LLVM  9.0.0svn
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 "ConstantFold.h"
15 #include "LLVMContextImpl.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/ADT/StringMap.h"
19 #include "llvm/IR/DerivedTypes.h"
21 #include "llvm/IR/GlobalValue.h"
22 #include "llvm/IR/Instructions.h"
23 #include "llvm/IR/Module.h"
24 #include "llvm/IR/Operator.h"
25 #include "llvm/Support/Debug.h"
30 #include <algorithm>
31 
32 using namespace llvm;
33 
34 //===----------------------------------------------------------------------===//
35 // Constant Class
36 //===----------------------------------------------------------------------===//
37 
39  // Floating point values have an explicit -0.0 value.
40  if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
41  return CFP->isZero() && CFP->isNegative();
42 
43  // Equivalent for a vector of -0.0's.
44  if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
45  if (CV->getElementType()->isFloatingPointTy() && CV->isSplat())
46  if (CV->getElementAsAPFloat(0).isNegZero())
47  return true;
48 
49  if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
50  if (ConstantFP *SplatCFP = dyn_cast_or_null<ConstantFP>(CV->getSplatValue()))
51  if (SplatCFP && SplatCFP->isZero() && SplatCFP->isNegative())
52  return true;
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 
62 // Return true iff this constant is positive zero (floating point), negative
63 // zero (floating point), or a null value.
64 bool Constant::isZeroValue() const {
65  // Floating point values have an explicit -0.0 value.
66  if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
67  return CFP->isZero();
68 
69  // Equivalent for a vector of -0.0's.
70  if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
71  if (CV->getElementType()->isFloatingPointTy() && CV->isSplat())
72  if (CV->getElementAsAPFloat(0).isZero())
73  return true;
74 
75  if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
76  if (ConstantFP *SplatCFP = dyn_cast_or_null<ConstantFP>(CV->getSplatValue()))
77  if (SplatCFP && SplatCFP->isZero())
78  return true;
79 
80  // Otherwise, just use +0.0.
81  return isNullValue();
82 }
83 
84 bool Constant::isNullValue() const {
85  // 0 is null.
86  if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
87  return CI->isZero();
88 
89  // +0.0 is null.
90  if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
91  return CFP->isZero() && !CFP->isNegative();
92 
93  // constant zero is zero for aggregates, cpnull is null for pointers, none for
94  // tokens.
95  return isa<ConstantAggregateZero>(this) || isa<ConstantPointerNull>(this) ||
96  isa<ConstantTokenNone>(this);
97 }
98 
100  // Check for -1 integers
101  if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
102  return CI->isMinusOne();
103 
104  // Check for FP which are bitcasted from -1 integers
105  if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
106  return CFP->getValueAPF().bitcastToAPInt().isAllOnesValue();
107 
108  // Check for constant vectors which are splats of -1 values.
109  if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
110  if (Constant *Splat = CV->getSplatValue())
111  return Splat->isAllOnesValue();
112 
113  // Check for constant vectors which are splats of -1 values.
114  if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this)) {
115  if (CV->isSplat()) {
116  if (CV->getElementType()->isFloatingPointTy())
117  return CV->getElementAsAPFloat(0).bitcastToAPInt().isAllOnesValue();
118  return CV->getElementAsAPInt(0).isAllOnesValue();
119  }
120  }
121 
122  return false;
123 }
124 
125 bool Constant::isOneValue() const {
126  // Check for 1 integers
127  if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
128  return CI->isOne();
129 
130  // Check for FP which are bitcasted from 1 integers
131  if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
132  return CFP->getValueAPF().bitcastToAPInt().isOneValue();
133 
134  // Check for constant vectors which are splats of 1 values.
135  if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
136  if (Constant *Splat = CV->getSplatValue())
137  return Splat->isOneValue();
138 
139  // Check for constant vectors which are splats of 1 values.
140  if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this)) {
141  if (CV->isSplat()) {
142  if (CV->getElementType()->isFloatingPointTy())
143  return CV->getElementAsAPFloat(0).bitcastToAPInt().isOneValue();
144  return CV->getElementAsAPInt(0).isOneValue();
145  }
146  }
147 
148  return false;
149 }
150 
152  // Check for INT_MIN integers
153  if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
154  return CI->isMinValue(/*isSigned=*/true);
155 
156  // Check for FP which are bitcasted from INT_MIN integers
157  if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
158  return CFP->getValueAPF().bitcastToAPInt().isMinSignedValue();
159 
160  // Check for constant vectors which are splats of INT_MIN values.
161  if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
162  if (Constant *Splat = CV->getSplatValue())
163  return Splat->isMinSignedValue();
164 
165  // Check for constant vectors which are splats of INT_MIN values.
166  if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this)) {
167  if (CV->isSplat()) {
168  if (CV->getElementType()->isFloatingPointTy())
169  return CV->getElementAsAPFloat(0).bitcastToAPInt().isMinSignedValue();
170  return CV->getElementAsAPInt(0).isMinSignedValue();
171  }
172  }
173 
174  return false;
175 }
176 
178  // Check for INT_MIN integers
179  if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
180  return !CI->isMinValue(/*isSigned=*/true);
181 
182  // Check for FP which are bitcasted from INT_MIN integers
183  if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
184  return !CFP->getValueAPF().bitcastToAPInt().isMinSignedValue();
185 
186  // Check that vectors don't contain INT_MIN
187  if (this->getType()->isVectorTy()) {
188  unsigned NumElts = this->getType()->getVectorNumElements();
189  for (unsigned i = 0; i != NumElts; ++i) {
190  Constant *Elt = this->getAggregateElement(i);
191  if (!Elt || !Elt->isNotMinSignedValue())
192  return false;
193  }
194  return true;
195  }
196 
197  // It *may* contain INT_MIN, we can't tell.
198  return false;
199 }
200 
202  if (auto *CFP = dyn_cast<ConstantFP>(this))
203  return CFP->getValueAPF().isFiniteNonZero();
204  if (!getType()->isVectorTy())
205  return false;
206  for (unsigned i = 0, e = getType()->getVectorNumElements(); i != e; ++i) {
207  auto *CFP = dyn_cast_or_null<ConstantFP>(this->getAggregateElement(i));
208  if (!CFP || !CFP->getValueAPF().isFiniteNonZero())
209  return false;
210  }
211  return true;
212 }
213 
214 bool Constant::isNormalFP() const {
215  if (auto *CFP = dyn_cast<ConstantFP>(this))
216  return CFP->getValueAPF().isNormal();
217  if (!getType()->isVectorTy())
218  return false;
219  for (unsigned i = 0, e = getType()->getVectorNumElements(); i != e; ++i) {
220  auto *CFP = dyn_cast_or_null<ConstantFP>(this->getAggregateElement(i));
221  if (!CFP || !CFP->getValueAPF().isNormal())
222  return false;
223  }
224  return true;
225 }
226 
228  if (auto *CFP = dyn_cast<ConstantFP>(this))
229  return CFP->getValueAPF().getExactInverse(nullptr);
230  if (!getType()->isVectorTy())
231  return false;
232  for (unsigned i = 0, e = getType()->getVectorNumElements(); i != e; ++i) {
233  auto *CFP = dyn_cast_or_null<ConstantFP>(this->getAggregateElement(i));
234  if (!CFP || !CFP->getValueAPF().getExactInverse(nullptr))
235  return false;
236  }
237  return true;
238 }
239 
240 bool Constant::isNaN() const {
241  if (auto *CFP = dyn_cast<ConstantFP>(this))
242  return CFP->isNaN();
243  if (!getType()->isVectorTy())
244  return false;
245  for (unsigned i = 0, e = getType()->getVectorNumElements(); i != e; ++i) {
246  auto *CFP = dyn_cast_or_null<ConstantFP>(this->getAggregateElement(i));
247  if (!CFP || !CFP->isNaN())
248  return false;
249  }
250  return true;
251 }
252 
254  if (!getType()->isVectorTy())
255  return false;
256  for (unsigned i = 0, e = getType()->getVectorNumElements(); i != e; ++i)
257  if (isa<UndefValue>(getAggregateElement(i)))
258  return true;
259 
260  return false;
261 }
262 
263 /// Constructor to create a '0' constant of arbitrary type.
265  switch (Ty->getTypeID()) {
266  case Type::IntegerTyID:
267  return ConstantInt::get(Ty, 0);
268  case Type::HalfTyID:
269  return ConstantFP::get(Ty->getContext(),
271  case Type::FloatTyID:
272  return ConstantFP::get(Ty->getContext(),
274  case Type::DoubleTyID:
275  return ConstantFP::get(Ty->getContext(),
277  case Type::X86_FP80TyID:
278  return ConstantFP::get(Ty->getContext(),
280  case Type::FP128TyID:
281  return ConstantFP::get(Ty->getContext(),
283  case Type::PPC_FP128TyID:
284  return ConstantFP::get(Ty->getContext(),
286  APInt::getNullValue(128)));
287  case Type::PointerTyID:
288  return ConstantPointerNull::get(cast<PointerType>(Ty));
289  case Type::StructTyID:
290  case Type::ArrayTyID:
291  case Type::VectorTyID:
292  return ConstantAggregateZero::get(Ty);
293  case Type::TokenTyID:
294  return ConstantTokenNone::get(Ty->getContext());
295  default:
296  // Function, Label, or Opaque type?
297  llvm_unreachable("Cannot create a null constant of that type!");
298  }
299 }
300 
302  Type *ScalarTy = Ty->getScalarType();
303 
304  // Create the base integer constant.
305  Constant *C = ConstantInt::get(Ty->getContext(), V);
306 
307  // Convert an integer to a pointer, if necessary.
308  if (PointerType *PTy = dyn_cast<PointerType>(ScalarTy))
309  C = ConstantExpr::getIntToPtr(C, PTy);
310 
311  // Broadcast a scalar to a vector, if necessary.
312  if (VectorType *VTy = dyn_cast<VectorType>(Ty))
313  C = ConstantVector::getSplat(VTy->getNumElements(), C);
314 
315  return C;
316 }
317 
319  if (IntegerType *ITy = dyn_cast<IntegerType>(Ty))
320  return ConstantInt::get(Ty->getContext(),
321  APInt::getAllOnesValue(ITy->getBitWidth()));
322 
323  if (Ty->isFloatingPointTy()) {
325  !Ty->isPPC_FP128Ty());
326  return ConstantFP::get(Ty->getContext(), FL);
327  }
328 
329  VectorType *VTy = cast<VectorType>(Ty);
330  return ConstantVector::getSplat(VTy->getNumElements(),
331  getAllOnesValue(VTy->getElementType()));
332 }
333 
335  if (const ConstantAggregate *CC = dyn_cast<ConstantAggregate>(this))
336  return Elt < CC->getNumOperands() ? CC->getOperand(Elt) : nullptr;
337 
338  if (const ConstantAggregateZero *CAZ = dyn_cast<ConstantAggregateZero>(this))
339  return Elt < CAZ->getNumElements() ? CAZ->getElementValue(Elt) : nullptr;
340 
341  if (const UndefValue *UV = dyn_cast<UndefValue>(this))
342  return Elt < UV->getNumElements() ? UV->getElementValue(Elt) : nullptr;
343 
344  if (const ConstantDataSequential *CDS =dyn_cast<ConstantDataSequential>(this))
345  return Elt < CDS->getNumElements() ? CDS->getElementAsConstant(Elt)
346  : nullptr;
347  return nullptr;
348 }
349 
351  assert(isa<IntegerType>(Elt->getType()) && "Index must be an integer");
352  if (ConstantInt *CI = dyn_cast<ConstantInt>(Elt)) {
353  // Check if the constant fits into an uint64_t.
354  if (CI->getValue().getActiveBits() > 64)
355  return nullptr;
356  return getAggregateElement(CI->getZExtValue());
357  }
358  return nullptr;
359 }
360 
362  /// First call destroyConstantImpl on the subclass. This gives the subclass
363  /// a chance to remove the constant from any maps/pools it's contained in.
364  switch (getValueID()) {
365  default:
366  llvm_unreachable("Not a constant!");
367 #define HANDLE_CONSTANT(Name) \
368  case Value::Name##Val: \
369  cast<Name>(this)->destroyConstantImpl(); \
370  break;
371 #include "llvm/IR/Value.def"
372  }
373 
374  // When a Constant is destroyed, there may be lingering
375  // references to the constant by other constants in the constant pool. These
376  // constants are implicitly dependent on the module that is being deleted,
377  // but they don't know that. Because we only find out when the CPV is
378  // deleted, we must now notify all of our users (that should only be
379  // Constants) that they are, in fact, invalid now and should be deleted.
380  //
381  while (!use_empty()) {
382  Value *V = user_back();
383 #ifndef NDEBUG // Only in -g mode...
384  if (!isa<Constant>(V)) {
385  dbgs() << "While deleting: " << *this
386  << "\n\nUse still stuck around after Def is destroyed: " << *V
387  << "\n\n";
388  }
389 #endif
390  assert(isa<Constant>(V) && "References remain to Constant being destroyed");
391  cast<Constant>(V)->destroyConstant();
392 
393  // The constant should remove itself from our use list...
394  assert((use_empty() || user_back() != V) && "Constant not removed!");
395  }
396 
397  // Value has no outstanding references it is safe to delete it now...
398  delete this;
399 }
400 
401 static bool canTrapImpl(const Constant *C,
402  SmallPtrSetImpl<const ConstantExpr *> &NonTrappingOps) {
403  assert(C->getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
404  // The only thing that could possibly trap are constant exprs.
405  const ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
406  if (!CE)
407  return false;
408 
409  // ConstantExpr traps if any operands can trap.
410  for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) {
411  if (ConstantExpr *Op = dyn_cast<ConstantExpr>(CE->getOperand(i))) {
412  if (NonTrappingOps.insert(Op).second && canTrapImpl(Op, NonTrappingOps))
413  return true;
414  }
415  }
416 
417  // Otherwise, only specific operations can trap.
418  switch (CE->getOpcode()) {
419  default:
420  return false;
421  case Instruction::UDiv:
422  case Instruction::SDiv:
423  case Instruction::URem:
424  case Instruction::SRem:
425  // Div and rem can trap if the RHS is not known to be non-zero.
426  if (!isa<ConstantInt>(CE->getOperand(1)) ||CE->getOperand(1)->isNullValue())
427  return true;
428  return false;
429  }
430 }
431 
432 bool Constant::canTrap() const {
434  return canTrapImpl(this, NonTrappingOps);
435 }
436 
437 /// Check if C contains a GlobalValue for which Predicate is true.
438 static bool
440  bool (*Predicate)(const GlobalValue *)) {
443  WorkList.push_back(C);
444  Visited.insert(C);
445 
446  while (!WorkList.empty()) {
447  const Constant *WorkItem = WorkList.pop_back_val();
448  if (const auto *GV = dyn_cast<GlobalValue>(WorkItem))
449  if (Predicate(GV))
450  return true;
451  for (const Value *Op : WorkItem->operands()) {
452  const Constant *ConstOp = dyn_cast<Constant>(Op);
453  if (!ConstOp)
454  continue;
455  if (Visited.insert(ConstOp).second)
456  WorkList.push_back(ConstOp);
457  }
458  }
459  return false;
460 }
461 
463  auto DLLImportPredicate = [](const GlobalValue *GV) {
464  return GV->isThreadLocal();
465  };
466  return ConstHasGlobalValuePredicate(this, DLLImportPredicate);
467 }
468 
470  auto DLLImportPredicate = [](const GlobalValue *GV) {
471  return GV->hasDLLImportStorageClass();
472  };
473  return ConstHasGlobalValuePredicate(this, DLLImportPredicate);
474 }
475 
477  for (const User *U : users()) {
478  const Constant *UC = dyn_cast<Constant>(U);
479  if (!UC || isa<GlobalValue>(UC))
480  return true;
481 
482  if (UC->isConstantUsed())
483  return true;
484  }
485  return false;
486 }
487 
489  if (isa<GlobalValue>(this))
490  return true; // Global reference.
491 
492  if (const BlockAddress *BA = dyn_cast<BlockAddress>(this))
493  return BA->getFunction()->needsRelocation();
494 
495  // While raw uses of blockaddress need to be relocated, differences between
496  // two of them don't when they are for labels in the same function. This is a
497  // common idiom when creating a table for the indirect goto extension, so we
498  // handle it efficiently here.
499  if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(this))
500  if (CE->getOpcode() == Instruction::Sub) {
501  ConstantExpr *LHS = dyn_cast<ConstantExpr>(CE->getOperand(0));
502  ConstantExpr *RHS = dyn_cast<ConstantExpr>(CE->getOperand(1));
503  if (LHS && RHS && LHS->getOpcode() == Instruction::PtrToInt &&
504  RHS->getOpcode() == Instruction::PtrToInt &&
505  isa<BlockAddress>(LHS->getOperand(0)) &&
506  isa<BlockAddress>(RHS->getOperand(0)) &&
507  cast<BlockAddress>(LHS->getOperand(0))->getFunction() ==
508  cast<BlockAddress>(RHS->getOperand(0))->getFunction())
509  return false;
510  }
511 
512  bool Result = false;
513  for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
514  Result |= cast<Constant>(getOperand(i))->needsRelocation();
515 
516  return Result;
517 }
518 
519 /// If the specified constantexpr is dead, remove it. This involves recursively
520 /// eliminating any dead users of the constantexpr.
521 static bool removeDeadUsersOfConstant(const Constant *C) {
522  if (isa<GlobalValue>(C)) return false; // Cannot remove this
523 
524  while (!C->use_empty()) {
525  const Constant *User = dyn_cast<Constant>(C->user_back());
526  if (!User) return false; // Non-constant usage;
527  if (!removeDeadUsersOfConstant(User))
528  return false; // Constant wasn't dead
529  }
530 
531  const_cast<Constant*>(C)->destroyConstant();
532  return true;
533 }
534 
535 
538  Value::const_user_iterator LastNonDeadUser = E;
539  while (I != E) {
540  const Constant *User = dyn_cast<Constant>(*I);
541  if (!User) {
542  LastNonDeadUser = I;
543  ++I;
544  continue;
545  }
546 
547  if (!removeDeadUsersOfConstant(User)) {
548  // If the constant wasn't dead, remember that this was the last live use
549  // and move on to the next constant.
550  LastNonDeadUser = I;
551  ++I;
552  continue;
553  }
554 
555  // If the constant was dead, then the iterator is invalidated.
556  if (LastNonDeadUser == E) {
557  I = user_begin();
558  if (I == E) break;
559  } else {
560  I = LastNonDeadUser;
561  ++I;
562  }
563  }
564 }
565 
566 
567 
568 //===----------------------------------------------------------------------===//
569 // ConstantInt
570 //===----------------------------------------------------------------------===//
571 
572 ConstantInt::ConstantInt(IntegerType *Ty, const APInt &V)
573  : ConstantData(Ty, ConstantIntVal), Val(V) {
574  assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
575 }
576 
578  LLVMContextImpl *pImpl = Context.pImpl;
579  if (!pImpl->TheTrueVal)
580  pImpl->TheTrueVal = ConstantInt::get(Type::getInt1Ty(Context), 1);
581  return pImpl->TheTrueVal;
582 }
583 
585  LLVMContextImpl *pImpl = Context.pImpl;
586  if (!pImpl->TheFalseVal)
587  pImpl->TheFalseVal = ConstantInt::get(Type::getInt1Ty(Context), 0);
588  return pImpl->TheFalseVal;
589 }
590 
592  assert(Ty->isIntOrIntVectorTy(1) && "Type not i1 or vector of i1.");
594  if (auto *VTy = dyn_cast<VectorType>(Ty))
595  return ConstantVector::getSplat(VTy->getNumElements(), TrueC);
596  return TrueC;
597 }
598 
600  assert(Ty->isIntOrIntVectorTy(1) && "Type not i1 or vector of i1.");
602  if (auto *VTy = dyn_cast<VectorType>(Ty))
603  return ConstantVector::getSplat(VTy->getNumElements(), FalseC);
604  return FalseC;
605 }
606 
607 // Get a ConstantInt from an APInt.
609  // get an existing value or the insertion position
610  LLVMContextImpl *pImpl = Context.pImpl;
611  std::unique_ptr<ConstantInt> &Slot = pImpl->IntConstants[V];
612  if (!Slot) {
613  // Get the corresponding integer type for the bit width of the value.
614  IntegerType *ITy = IntegerType::get(Context, V.getBitWidth());
615  Slot.reset(new ConstantInt(ITy, V));
616  }
617  assert(Slot->getType() == IntegerType::get(Context, V.getBitWidth()));
618  return Slot.get();
619 }
620 
621 Constant *ConstantInt::get(Type *Ty, uint64_t V, bool isSigned) {
622  Constant *C = get(cast<IntegerType>(Ty->getScalarType()), V, isSigned);
623 
624  // For vectors, broadcast the value.
625  if (VectorType *VTy = dyn_cast<VectorType>(Ty))
626  return ConstantVector::getSplat(VTy->getNumElements(), C);
627 
628  return C;
629 }
630 
631 ConstantInt *ConstantInt::get(IntegerType *Ty, uint64_t V, bool isSigned) {
632  return get(Ty->getContext(), APInt(Ty->getBitWidth(), V, isSigned));
633 }
634 
636  return get(Ty, V, true);
637 }
638 
640  return get(Ty, V, true);
641 }
642 
644  ConstantInt *C = get(Ty->getContext(), V);
645  assert(C->getType() == Ty->getScalarType() &&
646  "ConstantInt type doesn't match the type implied by its value!");
647 
648  // For vectors, broadcast the value.
649  if (VectorType *VTy = dyn_cast<VectorType>(Ty))
650  return ConstantVector::getSplat(VTy->getNumElements(), C);
651 
652  return C;
653 }
654 
656  return get(Ty->getContext(), APInt(Ty->getBitWidth(), Str, radix));
657 }
658 
659 /// Remove the constant from the constant table.
660 void ConstantInt::destroyConstantImpl() {
661  llvm_unreachable("You can't ConstantInt->destroyConstantImpl()!");
662 }
663 
664 //===----------------------------------------------------------------------===//
665 // ConstantFP
666 //===----------------------------------------------------------------------===//
667 
669  if (Ty->isHalfTy())
670  return &APFloat::IEEEhalf();
671  if (Ty->isFloatTy())
672  return &APFloat::IEEEsingle();
673  if (Ty->isDoubleTy())
674  return &APFloat::IEEEdouble();
675  if (Ty->isX86_FP80Ty())
676  return &APFloat::x87DoubleExtended();
677  else if (Ty->isFP128Ty())
678  return &APFloat::IEEEquad();
679 
680  assert(Ty->isPPC_FP128Ty() && "Unknown FP format");
681  return &APFloat::PPCDoubleDouble();
682 }
683 
684 Constant *ConstantFP::get(Type *Ty, double V) {
685  LLVMContext &Context = Ty->getContext();
686 
687  APFloat FV(V);
688  bool ignored;
690  APFloat::rmNearestTiesToEven, &ignored);
691  Constant *C = get(Context, FV);
692 
693  // For vectors, broadcast the value.
694  if (VectorType *VTy = dyn_cast<VectorType>(Ty))
695  return ConstantVector::getSplat(VTy->getNumElements(), C);
696 
697  return C;
698 }
699 
701  ConstantFP *C = get(Ty->getContext(), V);
702  assert(C->getType() == Ty->getScalarType() &&
703  "ConstantFP type doesn't match the type implied by its value!");
704 
705  // For vectors, broadcast the value.
706  if (auto *VTy = dyn_cast<VectorType>(Ty))
707  return ConstantVector::getSplat(VTy->getNumElements(), C);
708 
709  return C;
710 }
711 
713  LLVMContext &Context = Ty->getContext();
714 
715  APFloat FV(*TypeToFloatSemantics(Ty->getScalarType()), Str);
716  Constant *C = get(Context, FV);
717 
718  // For vectors, broadcast the value.
719  if (VectorType *VTy = dyn_cast<VectorType>(Ty))
720  return ConstantVector::getSplat(VTy->getNumElements(), C);
721 
722  return C;
723 }
724 
725 Constant *ConstantFP::getNaN(Type *Ty, bool Negative, uint64_t Payload) {
726  const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
727  APFloat NaN = APFloat::getNaN(Semantics, Negative, Payload);
728  Constant *C = get(Ty->getContext(), NaN);
729 
730  if (VectorType *VTy = dyn_cast<VectorType>(Ty))
731  return ConstantVector::getSplat(VTy->getNumElements(), C);
732 
733  return C;
734 }
735 
736 Constant *ConstantFP::getQNaN(Type *Ty, bool Negative, APInt *Payload) {
737  const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
738  APFloat NaN = APFloat::getQNaN(Semantics, Negative, Payload);
739  Constant *C = get(Ty->getContext(), NaN);
740 
741  if (VectorType *VTy = dyn_cast<VectorType>(Ty))
742  return ConstantVector::getSplat(VTy->getNumElements(), C);
743 
744  return C;
745 }
746 
747 Constant *ConstantFP::getSNaN(Type *Ty, bool Negative, APInt *Payload) {
748  const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
749  APFloat NaN = APFloat::getSNaN(Semantics, Negative, Payload);
750  Constant *C = get(Ty->getContext(), NaN);
751 
752  if (VectorType *VTy = dyn_cast<VectorType>(Ty))
753  return ConstantVector::getSplat(VTy->getNumElements(), C);
754 
755  return C;
756 }
757 
759  const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
760  APFloat NegZero = APFloat::getZero(Semantics, /*Negative=*/true);
761  Constant *C = get(Ty->getContext(), NegZero);
762 
763  if (VectorType *VTy = dyn_cast<VectorType>(Ty))
764  return ConstantVector::getSplat(VTy->getNumElements(), C);
765 
766  return C;
767 }
768 
769 
771  if (Ty->isFPOrFPVectorTy())
772  return getNegativeZero(Ty);
773 
774  return Constant::getNullValue(Ty);
775 }
776 
777 
778 // ConstantFP accessors.
780  LLVMContextImpl* pImpl = Context.pImpl;
781 
782  std::unique_ptr<ConstantFP> &Slot = pImpl->FPConstants[V];
783 
784  if (!Slot) {
785  Type *Ty;
786  if (&V.getSemantics() == &APFloat::IEEEhalf())
787  Ty = Type::getHalfTy(Context);
788  else if (&V.getSemantics() == &APFloat::IEEEsingle())
789  Ty = Type::getFloatTy(Context);
790  else if (&V.getSemantics() == &APFloat::IEEEdouble())
791  Ty = Type::getDoubleTy(Context);
792  else if (&V.getSemantics() == &APFloat::x87DoubleExtended())
793  Ty = Type::getX86_FP80Ty(Context);
794  else if (&V.getSemantics() == &APFloat::IEEEquad())
795  Ty = Type::getFP128Ty(Context);
796  else {
798  "Unknown FP format");
799  Ty = Type::getPPC_FP128Ty(Context);
800  }
801  Slot.reset(new ConstantFP(Ty, V));
802  }
803 
804  return Slot.get();
805 }
806 
807 Constant *ConstantFP::getInfinity(Type *Ty, bool Negative) {
808  const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
809  Constant *C = get(Ty->getContext(), APFloat::getInf(Semantics, Negative));
810 
811  if (VectorType *VTy = dyn_cast<VectorType>(Ty))
812  return ConstantVector::getSplat(VTy->getNumElements(), C);
813 
814  return C;
815 }
816 
817 ConstantFP::ConstantFP(Type *Ty, const APFloat &V)
818  : ConstantData(Ty, ConstantFPVal), Val(V) {
820  "FP type Mismatch");
821 }
822 
823 bool ConstantFP::isExactlyValue(const APFloat &V) const {
824  return Val.bitwiseIsEqual(V);
825 }
826 
827 /// Remove the constant from the constant table.
828 void ConstantFP::destroyConstantImpl() {
829  llvm_unreachable("You can't ConstantFP->destroyConstantImpl()!");
830 }
831 
832 //===----------------------------------------------------------------------===//
833 // ConstantAggregateZero Implementation
834 //===----------------------------------------------------------------------===//
835 
837  return Constant::getNullValue(getType()->getSequentialElementType());
838 }
839 
841  return Constant::getNullValue(getType()->getStructElementType(Elt));
842 }
843 
845  if (isa<SequentialType>(getType()))
846  return getSequentialElement();
847  return getStructElement(cast<ConstantInt>(C)->getZExtValue());
848 }
849 
851  if (isa<SequentialType>(getType()))
852  return getSequentialElement();
853  return getStructElement(Idx);
854 }
855 
857  Type *Ty = getType();
858  if (auto *AT = dyn_cast<ArrayType>(Ty))
859  return AT->getNumElements();
860  if (auto *VT = dyn_cast<VectorType>(Ty))
861  return VT->getNumElements();
862  return Ty->getStructNumElements();
863 }
864 
865 //===----------------------------------------------------------------------===//
866 // UndefValue Implementation
867 //===----------------------------------------------------------------------===//
868 
870  return UndefValue::get(getType()->getSequentialElementType());
871 }
872 
874  return UndefValue::get(getType()->getStructElementType(Elt));
875 }
876 
878  if (isa<SequentialType>(getType()))
879  return getSequentialElement();
880  return getStructElement(cast<ConstantInt>(C)->getZExtValue());
881 }
882 
884  if (isa<SequentialType>(getType()))
885  return getSequentialElement();
886  return getStructElement(Idx);
887 }
888 
889 unsigned UndefValue::getNumElements() const {
890  Type *Ty = getType();
891  if (auto *ST = dyn_cast<SequentialType>(Ty))
892  return ST->getNumElements();
893  return Ty->getStructNumElements();
894 }
895 
896 //===----------------------------------------------------------------------===//
897 // ConstantXXX Classes
898 //===----------------------------------------------------------------------===//
899 
900 template <typename ItTy, typename EltTy>
901 static bool rangeOnlyContains(ItTy Start, ItTy End, EltTy Elt) {
902  for (; Start != End; ++Start)
903  if (*Start != Elt)
904  return false;
905  return true;
906 }
907 
908 template <typename SequentialTy, typename ElementTy>
910  assert(!V.empty() && "Cannot get empty int sequence.");
911 
913  for (Constant *C : V)
914  if (auto *CI = dyn_cast<ConstantInt>(C))
915  Elts.push_back(CI->getZExtValue());
916  else
917  return nullptr;
918  return SequentialTy::get(V[0]->getContext(), Elts);
919 }
920 
921 template <typename SequentialTy, typename ElementTy>
923  assert(!V.empty() && "Cannot get empty FP sequence.");
924 
926  for (Constant *C : V)
927  if (auto *CFP = dyn_cast<ConstantFP>(C))
928  Elts.push_back(CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
929  else
930  return nullptr;
931  return SequentialTy::getFP(V[0]->getContext(), Elts);
932 }
933 
934 template <typename SequenceTy>
937  // We speculatively build the elements here even if it turns out that there is
938  // a constantexpr or something else weird, since it is so uncommon for that to
939  // happen.
940  if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
941  if (CI->getType()->isIntegerTy(8))
942  return getIntSequenceIfElementsMatch<SequenceTy, uint8_t>(V);
943  else if (CI->getType()->isIntegerTy(16))
944  return getIntSequenceIfElementsMatch<SequenceTy, uint16_t>(V);
945  else if (CI->getType()->isIntegerTy(32))
946  return getIntSequenceIfElementsMatch<SequenceTy, uint32_t>(V);
947  else if (CI->getType()->isIntegerTy(64))
948  return getIntSequenceIfElementsMatch<SequenceTy, uint64_t>(V);
949  } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
950  if (CFP->getType()->isHalfTy())
951  return getFPSequenceIfElementsMatch<SequenceTy, uint16_t>(V);
952  else if (CFP->getType()->isFloatTy())
953  return getFPSequenceIfElementsMatch<SequenceTy, uint32_t>(V);
954  else if (CFP->getType()->isDoubleTy())
955  return getFPSequenceIfElementsMatch<SequenceTy, uint64_t>(V);
956  }
957 
958  return nullptr;
959 }
960 
963  : Constant(T, VT, OperandTraits<ConstantAggregate>::op_end(this) - V.size(),
964  V.size()) {
965  llvm::copy(V, op_begin());
966 
967  // Check that types match, unless this is an opaque struct.
968  if (auto *ST = dyn_cast<StructType>(T))
969  if (ST->isOpaque())
970  return;
971  for (unsigned I = 0, E = V.size(); I != E; ++I)
972  assert(V[I]->getType() == T->getTypeAtIndex(I) &&
973  "Initializer for composite element doesn't match!");
974 }
975 
976 ConstantArray::ConstantArray(ArrayType *T, ArrayRef<Constant *> V)
977  : ConstantAggregate(T, ConstantArrayVal, V) {
978  assert(V.size() == T->getNumElements() &&
979  "Invalid initializer for constant array");
980 }
981 
983  if (Constant *C = getImpl(Ty, V))
984  return C;
985  return Ty->getContext().pImpl->ArrayConstants.getOrCreate(Ty, V);
986 }
987 
989  // Empty arrays are canonicalized to ConstantAggregateZero.
990  if (V.empty())
991  return ConstantAggregateZero::get(Ty);
992 
993  for (unsigned i = 0, e = V.size(); i != e; ++i) {
994  assert(V[i]->getType() == Ty->getElementType() &&
995  "Wrong type in array element initializer");
996  }
997 
998  // If this is an all-zero array, return a ConstantAggregateZero object. If
999  // all undef, return an UndefValue, if "all simple", then return a
1000  // ConstantDataArray.
1001  Constant *C = V[0];
1002  if (isa<UndefValue>(C) && rangeOnlyContains(V.begin(), V.end(), C))
1003  return UndefValue::get(Ty);
1004 
1005  if (C->isNullValue() && rangeOnlyContains(V.begin(), V.end(), C))
1006  return ConstantAggregateZero::get(Ty);
1007 
1008  // Check to see if all of the elements are ConstantFP or ConstantInt and if
1009  // the element type is compatible with ConstantDataVector. If so, use it.
1011  return getSequenceIfElementsMatch<ConstantDataArray>(C, V);
1012 
1013  // Otherwise, we really do want to create a ConstantArray.
1014  return nullptr;
1015 }
1016 
1019  bool Packed) {
1020  unsigned VecSize = V.size();
1021  SmallVector<Type*, 16> EltTypes(VecSize);
1022  for (unsigned i = 0; i != VecSize; ++i)
1023  EltTypes[i] = V[i]->getType();
1024 
1025  return StructType::get(Context, EltTypes, Packed);
1026 }
1027 
1028 
1030  bool Packed) {
1031  assert(!V.empty() &&
1032  "ConstantStruct::getTypeForElements cannot be called on empty list");
1033  return getTypeForElements(V[0]->getContext(), V, Packed);
1034 }
1035 
1036 ConstantStruct::ConstantStruct(StructType *T, ArrayRef<Constant *> V)
1037  : ConstantAggregate(T, ConstantStructVal, V) {
1038  assert((T->isOpaque() || V.size() == T->getNumElements()) &&
1039  "Invalid initializer for constant struct");
1040 }
1041 
1042 // ConstantStruct accessors.
1044  assert((ST->isOpaque() || ST->getNumElements() == V.size()) &&
1045  "Incorrect # elements specified to ConstantStruct::get");
1046 
1047  // Create a ConstantAggregateZero value if all elements are zeros.
1048  bool isZero = true;
1049  bool isUndef = false;
1050 
1051  if (!V.empty()) {
1052  isUndef = isa<UndefValue>(V[0]);
1053  isZero = V[0]->isNullValue();
1054  if (isUndef || isZero) {
1055  for (unsigned i = 0, e = V.size(); i != e; ++i) {
1056  if (!V[i]->isNullValue())
1057  isZero = false;
1058  if (!isa<UndefValue>(V[i]))
1059  isUndef = false;
1060  }
1061  }
1062  }
1063  if (isZero)
1064  return ConstantAggregateZero::get(ST);
1065  if (isUndef)
1066  return UndefValue::get(ST);
1067 
1068  return ST->getContext().pImpl->StructConstants.getOrCreate(ST, V);
1069 }
1070 
1071 ConstantVector::ConstantVector(VectorType *T, ArrayRef<Constant *> V)
1072  : ConstantAggregate(T, ConstantVectorVal, V) {
1073  assert(V.size() == T->getNumElements() &&
1074  "Invalid initializer for constant vector");
1075 }
1076 
1077 // ConstantVector accessors.
1079  if (Constant *C = getImpl(V))
1080  return C;
1081  VectorType *Ty = VectorType::get(V.front()->getType(), V.size());
1082  return Ty->getContext().pImpl->VectorConstants.getOrCreate(Ty, V);
1083 }
1084 
1086  assert(!V.empty() && "Vectors can't be empty");
1087  VectorType *T = VectorType::get(V.front()->getType(), V.size());
1088 
1089  // If this is an all-undef or all-zero vector, return a
1090  // ConstantAggregateZero or UndefValue.
1091  Constant *C = V[0];
1092  bool isZero = C->isNullValue();
1093  bool isUndef = isa<UndefValue>(C);
1094 
1095  if (isZero || isUndef) {
1096  for (unsigned i = 1, e = V.size(); i != e; ++i)
1097  if (V[i] != C) {
1098  isZero = isUndef = false;
1099  break;
1100  }
1101  }
1102 
1103  if (isZero)
1104  return ConstantAggregateZero::get(T);
1105  if (isUndef)
1106  return UndefValue::get(T);
1107 
1108  // Check to see if all of the elements are ConstantFP or ConstantInt and if
1109  // the element type is compatible with ConstantDataVector. If so, use it.
1111  return getSequenceIfElementsMatch<ConstantDataVector>(C, V);
1112 
1113  // Otherwise, the element type isn't compatible with ConstantDataVector, or
1114  // the operand list contains a ConstantExpr or something else strange.
1115  return nullptr;
1116 }
1117 
1119  // If this splat is compatible with ConstantDataVector, use it instead of
1120  // ConstantVector.
1121  if ((isa<ConstantFP>(V) || isa<ConstantInt>(V)) &&
1123  return ConstantDataVector::getSplat(NumElts, V);
1124 
1125  SmallVector<Constant*, 32> Elts(NumElts, V);
1126  return get(Elts);
1127 }
1128 
1130  LLVMContextImpl *pImpl = Context.pImpl;
1131  if (!pImpl->TheNoneToken)
1132  pImpl->TheNoneToken.reset(new ConstantTokenNone(Context));
1133  return pImpl->TheNoneToken.get();
1134 }
1135 
1136 /// Remove the constant from the constant table.
1137 void ConstantTokenNone::destroyConstantImpl() {
1138  llvm_unreachable("You can't ConstantTokenNone->destroyConstantImpl()!");
1139 }
1140 
1141 // Utility function for determining if a ConstantExpr is a CastOp or not. This
1142 // can't be inline because we don't want to #include Instruction.h into
1143 // Constant.h
1144 bool ConstantExpr::isCast() const {
1145  return Instruction::isCast(getOpcode());
1146 }
1147 
1149  return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
1150 }
1151 
1153  if (getOpcode() != Instruction::GetElementPtr) return false;
1154 
1155  gep_type_iterator GEPI = gep_type_begin(this), E = gep_type_end(this);
1156  User::const_op_iterator OI = std::next(this->op_begin());
1157 
1158  // The remaining indices may be compile-time known integers within the bounds
1159  // of the corresponding notional static array types.
1160  for (; GEPI != E; ++GEPI, ++OI) {
1161  if (isa<UndefValue>(*OI))
1162  continue;
1163  auto *CI = dyn_cast<ConstantInt>(*OI);
1164  if (!CI || (GEPI.isBoundedSequential() &&
1165  (CI->getValue().getActiveBits() > 64 ||
1166  CI->getZExtValue() >= GEPI.getSequentialNumElements())))
1167  return false;
1168  }
1169 
1170  // All the indices checked out.
1171  return true;
1172 }
1173 
1175  return getOpcode() == Instruction::ExtractValue ||
1176  getOpcode() == Instruction::InsertValue;
1177 }
1178 
1180  if (const ExtractValueConstantExpr *EVCE =
1181  dyn_cast<ExtractValueConstantExpr>(this))
1182  return EVCE->Indices;
1183 
1184  return cast<InsertValueConstantExpr>(this)->Indices;
1185 }
1186 
1187 unsigned ConstantExpr::getPredicate() const {
1188  return cast<CompareConstantExpr>(this)->predicate;
1189 }
1190 
1191 Constant *
1193  assert(Op->getType() == getOperand(OpNo)->getType() &&
1194  "Replacing operand with value of different type!");
1195  if (getOperand(OpNo) == Op)
1196  return const_cast<ConstantExpr*>(this);
1197 
1199  for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1200  NewOps.push_back(i == OpNo ? Op : getOperand(i));
1201 
1202  return getWithOperands(NewOps);
1203 }
1204 
1206  bool OnlyIfReduced, Type *SrcTy) const {
1207  assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
1208 
1209  // If no operands changed return self.
1210  if (Ty == getType() && std::equal(Ops.begin(), Ops.end(), op_begin()))
1211  return const_cast<ConstantExpr*>(this);
1212 
1213  Type *OnlyIfReducedTy = OnlyIfReduced ? Ty : nullptr;
1214  switch (getOpcode()) {
1215  case Instruction::Trunc:
1216  case Instruction::ZExt:
1217  case Instruction::SExt:
1218  case Instruction::FPTrunc:
1219  case Instruction::FPExt:
1220  case Instruction::UIToFP:
1221  case Instruction::SIToFP:
1222  case Instruction::FPToUI:
1223  case Instruction::FPToSI:
1224  case Instruction::PtrToInt:
1225  case Instruction::IntToPtr:
1226  case Instruction::BitCast:
1227  case Instruction::AddrSpaceCast:
1228  return ConstantExpr::getCast(getOpcode(), Ops[0], Ty, OnlyIfReduced);
1229  case Instruction::Select:
1230  return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2], OnlyIfReducedTy);
1231  case Instruction::InsertElement:
1232  return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2],
1233  OnlyIfReducedTy);
1234  case Instruction::ExtractElement:
1235  return ConstantExpr::getExtractElement(Ops[0], Ops[1], OnlyIfReducedTy);
1236  case Instruction::InsertValue:
1237  return ConstantExpr::getInsertValue(Ops[0], Ops[1], getIndices(),
1238  OnlyIfReducedTy);
1239  case Instruction::ExtractValue:
1240  return ConstantExpr::getExtractValue(Ops[0], getIndices(), OnlyIfReducedTy);
1241  case Instruction::ShuffleVector:
1242  return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2],
1243  OnlyIfReducedTy);
1244  case Instruction::GetElementPtr: {
1245  auto *GEPO = cast<GEPOperator>(this);
1246  assert(SrcTy || (Ops[0]->getType() == getOperand(0)->getType()));
1248  SrcTy ? SrcTy : GEPO->getSourceElementType(), Ops[0], Ops.slice(1),
1249  GEPO->isInBounds(), GEPO->getInRangeIndex(), OnlyIfReducedTy);
1250  }
1251  case Instruction::ICmp:
1252  case Instruction::FCmp:
1253  return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1],
1254  OnlyIfReducedTy);
1255  default:
1256  assert(getNumOperands() == 2 && "Must be binary operator?");
1257  return ConstantExpr::get(getOpcode(), Ops[0], Ops[1], SubclassOptionalData,
1258  OnlyIfReducedTy);
1259  }
1260 }
1261 
1262 
1263 //===----------------------------------------------------------------------===//
1264 // isValueValidForType implementations
1265 
1266 bool ConstantInt::isValueValidForType(Type *Ty, uint64_t Val) {
1267  unsigned NumBits = Ty->getIntegerBitWidth(); // assert okay
1268  if (Ty->isIntegerTy(1))
1269  return Val == 0 || Val == 1;
1270  return isUIntN(NumBits, Val);
1271 }
1272 
1273 bool ConstantInt::isValueValidForType(Type *Ty, int64_t Val) {
1274  unsigned NumBits = Ty->getIntegerBitWidth();
1275  if (Ty->isIntegerTy(1))
1276  return Val == 0 || Val == 1 || Val == -1;
1277  return isIntN(NumBits, Val);
1278 }
1279 
1281  // convert modifies in place, so make a copy.
1282  APFloat Val2 = APFloat(Val);
1283  bool losesInfo;
1284  switch (Ty->getTypeID()) {
1285  default:
1286  return false; // These can't be represented as floating point!
1287 
1288  // FIXME rounding mode needs to be more flexible
1289  case Type::HalfTyID: {
1290  if (&Val2.getSemantics() == &APFloat::IEEEhalf())
1291  return true;
1293  return !losesInfo;
1294  }
1295  case Type::FloatTyID: {
1296  if (&Val2.getSemantics() == &APFloat::IEEEsingle())
1297  return true;
1299  return !losesInfo;
1300  }
1301  case Type::DoubleTyID: {
1302  if (&Val2.getSemantics() == &APFloat::IEEEhalf() ||
1303  &Val2.getSemantics() == &APFloat::IEEEsingle() ||
1304  &Val2.getSemantics() == &APFloat::IEEEdouble())
1305  return true;
1307  return !losesInfo;
1308  }
1309  case Type::X86_FP80TyID:
1310  return &Val2.getSemantics() == &APFloat::IEEEhalf() ||
1311  &Val2.getSemantics() == &APFloat::IEEEsingle() ||
1312  &Val2.getSemantics() == &APFloat::IEEEdouble() ||
1314  case Type::FP128TyID:
1315  return &Val2.getSemantics() == &APFloat::IEEEhalf() ||
1316  &Val2.getSemantics() == &APFloat::IEEEsingle() ||
1317  &Val2.getSemantics() == &APFloat::IEEEdouble() ||
1318  &Val2.getSemantics() == &APFloat::IEEEquad();
1319  case Type::PPC_FP128TyID:
1320  return &Val2.getSemantics() == &APFloat::IEEEhalf() ||
1321  &Val2.getSemantics() == &APFloat::IEEEsingle() ||
1322  &Val2.getSemantics() == &APFloat::IEEEdouble() ||
1323  &Val2.getSemantics() == &APFloat::PPCDoubleDouble();
1324  }
1325 }
1326 
1327 
1328 //===----------------------------------------------------------------------===//
1329 // Factory Function Implementation
1330 
1332  assert((Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()) &&
1333  "Cannot create an aggregate zero of non-aggregate type!");
1334 
1335  std::unique_ptr<ConstantAggregateZero> &Entry =
1336  Ty->getContext().pImpl->CAZConstants[Ty];
1337  if (!Entry)
1338  Entry.reset(new ConstantAggregateZero(Ty));
1339 
1340  return Entry.get();
1341 }
1342 
1343 /// Remove the constant from the constant table.
1344 void ConstantAggregateZero::destroyConstantImpl() {
1345  getContext().pImpl->CAZConstants.erase(getType());
1346 }
1347 
1348 /// Remove the constant from the constant table.
1349 void ConstantArray::destroyConstantImpl() {
1351 }
1352 
1353 
1354 //---- ConstantStruct::get() implementation...
1355 //
1356 
1357 /// Remove the constant from the constant table.
1358 void ConstantStruct::destroyConstantImpl() {
1360 }
1361 
1362 /// Remove the constant from the constant table.
1363 void ConstantVector::destroyConstantImpl() {
1365 }
1366 
1368  assert(this->getType()->isVectorTy() && "Only valid for vectors!");
1369  if (isa<ConstantAggregateZero>(this))
1370  return getNullValue(this->getType()->getVectorElementType());
1371  if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
1372  return CV->getSplatValue();
1373  if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
1374  return CV->getSplatValue();
1375  return nullptr;
1376 }
1377 
1379  // Check out first element.
1380  Constant *Elt = getOperand(0);
1381  // Then make sure all remaining elements point to the same value.
1382  for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
1383  if (getOperand(I) != Elt)
1384  return nullptr;
1385  return Elt;
1386 }
1387 
1389  if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
1390  return CI->getValue();
1391  assert(this->getSplatValue() && "Doesn't contain a unique integer!");
1392  const Constant *C = this->getAggregateElement(0U);
1393  assert(C && isa<ConstantInt>(C) && "Not a vector of numbers!");
1394  return cast<ConstantInt>(C)->getValue();
1395 }
1396 
1397 //---- ConstantPointerNull::get() implementation.
1398 //
1399 
1401  std::unique_ptr<ConstantPointerNull> &Entry =
1402  Ty->getContext().pImpl->CPNConstants[Ty];
1403  if (!Entry)
1404  Entry.reset(new ConstantPointerNull(Ty));
1405 
1406  return Entry.get();
1407 }
1408 
1409 /// Remove the constant from the constant table.
1410 void ConstantPointerNull::destroyConstantImpl() {
1411  getContext().pImpl->CPNConstants.erase(getType());
1412 }
1413 
1415  std::unique_ptr<UndefValue> &Entry = Ty->getContext().pImpl->UVConstants[Ty];
1416  if (!Entry)
1417  Entry.reset(new UndefValue(Ty));
1418 
1419  return Entry.get();
1420 }
1421 
1422 /// Remove the constant from the constant table.
1423 void UndefValue::destroyConstantImpl() {
1424  // Free the constant and any dangling references to it.
1425  getContext().pImpl->UVConstants.erase(getType());
1426 }
1427 
1429  assert(BB->getParent() && "Block must have a parent");
1430  return get(BB->getParent(), BB);
1431 }
1432 
1434  BlockAddress *&BA =
1435  F->getContext().pImpl->BlockAddresses[std::make_pair(F, BB)];
1436  if (!BA)
1437  BA = new BlockAddress(F, BB);
1438 
1439  assert(BA->getFunction() == F && "Basic block moved between functions");
1440  return BA;
1441 }
1442 
1444 : Constant(Type::getInt8PtrTy(F->getContext()), Value::BlockAddressVal,
1445  &Op<0>(), 2) {
1446  setOperand(0, F);
1447  setOperand(1, BB);
1448  BB->AdjustBlockAddressRefCount(1);
1449 }
1450 
1452  if (!BB->hasAddressTaken())
1453  return nullptr;
1454 
1455  const Function *F = BB->getParent();
1456  assert(F && "Block must have a parent");
1457  BlockAddress *BA =
1458  F->getContext().pImpl->BlockAddresses.lookup(std::make_pair(F, BB));
1459  assert(BA && "Refcount and block address map disagree!");
1460  return BA;
1461 }
1462 
1463 /// Remove the constant from the constant table.
1464 void BlockAddress::destroyConstantImpl() {
1466  ->BlockAddresses.erase(std::make_pair(getFunction(), getBasicBlock()));
1467  getBasicBlock()->AdjustBlockAddressRefCount(-1);
1468 }
1469 
1470 Value *BlockAddress::handleOperandChangeImpl(Value *From, Value *To) {
1471  // This could be replacing either the Basic Block or the Function. In either
1472  // case, we have to remove the map entry.
1473  Function *NewF = getFunction();
1474  BasicBlock *NewBB = getBasicBlock();
1475 
1476  if (From == NewF)
1477  NewF = cast<Function>(To->stripPointerCasts());
1478  else {
1479  assert(From == NewBB && "From does not match any operand");
1480  NewBB = cast<BasicBlock>(To);
1481  }
1482 
1483  // See if the 'new' entry already exists, if not, just update this in place
1484  // and return early.
1485  BlockAddress *&NewBA =
1486  getContext().pImpl->BlockAddresses[std::make_pair(NewF, NewBB)];
1487  if (NewBA)
1488  return NewBA;
1489 
1490  getBasicBlock()->AdjustBlockAddressRefCount(-1);
1491 
1492  // Remove the old entry, this can't cause the map to rehash (just a
1493  // tombstone will get added).
1494  getContext().pImpl->BlockAddresses.erase(std::make_pair(getFunction(),
1495  getBasicBlock()));
1496  NewBA = this;
1497  setOperand(0, NewF);
1498  setOperand(1, NewBB);
1499  getBasicBlock()->AdjustBlockAddressRefCount(1);
1500 
1501  // If we just want to keep the existing value, then return null.
1502  // Callers know that this means we shouldn't delete this value.
1503  return nullptr;
1504 }
1505 
1506 //---- ConstantExpr::get() implementations.
1507 //
1508 
1509 /// This is a utility function to handle folding of casts and lookup of the
1510 /// cast in the ExprConstants map. It is used by the various get* methods below.
1512  bool OnlyIfReduced = false) {
1513  assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1514  // Fold a few common cases
1515  if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
1516  return FC;
1517 
1518  if (OnlyIfReduced)
1519  return nullptr;
1520 
1521  LLVMContextImpl *pImpl = Ty->getContext().pImpl;
1522 
1523  // Look up the constant in the table first to ensure uniqueness.
1524  ConstantExprKeyType Key(opc, C);
1525 
1526  return pImpl->ExprConstants.getOrCreate(Ty, Key);
1527 }
1528 
1530  bool OnlyIfReduced) {
1532  assert(Instruction::isCast(opc) && "opcode out of range");
1533  assert(C && Ty && "Null arguments to getCast");
1534  assert(CastInst::castIsValid(opc, C, Ty) && "Invalid constantexpr cast!");
1535 
1536  switch (opc) {
1537  default:
1538  llvm_unreachable("Invalid cast opcode");
1539  case Instruction::Trunc:
1540  return getTrunc(C, Ty, OnlyIfReduced);
1541  case Instruction::ZExt:
1542  return getZExt(C, Ty, OnlyIfReduced);
1543  case Instruction::SExt:
1544  return getSExt(C, Ty, OnlyIfReduced);
1545  case Instruction::FPTrunc:
1546  return getFPTrunc(C, Ty, OnlyIfReduced);
1547  case Instruction::FPExt:
1548  return getFPExtend(C, Ty, OnlyIfReduced);
1549  case Instruction::UIToFP:
1550  return getUIToFP(C, Ty, OnlyIfReduced);
1551  case Instruction::SIToFP:
1552  return getSIToFP(C, Ty, OnlyIfReduced);
1553  case Instruction::FPToUI:
1554  return getFPToUI(C, Ty, OnlyIfReduced);
1555  case Instruction::FPToSI:
1556  return getFPToSI(C, Ty, OnlyIfReduced);
1557  case Instruction::PtrToInt:
1558  return getPtrToInt(C, Ty, OnlyIfReduced);
1559  case Instruction::IntToPtr:
1560  return getIntToPtr(C, Ty, OnlyIfReduced);
1561  case Instruction::BitCast:
1562  return getBitCast(C, Ty, OnlyIfReduced);
1563  case Instruction::AddrSpaceCast:
1564  return getAddrSpaceCast(C, Ty, OnlyIfReduced);
1565  }
1566 }
1567 
1569  if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1570  return getBitCast(C, Ty);
1571  return getZExt(C, Ty);
1572 }
1573 
1575  if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1576  return getBitCast(C, Ty);
1577  return getSExt(C, Ty);
1578 }
1579 
1581  if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1582  return getBitCast(C, Ty);
1583  return getTrunc(C, Ty);
1584 }
1585 
1587  assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
1588  assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
1589  "Invalid cast");
1590 
1591  if (Ty->isIntOrIntVectorTy())
1592  return getPtrToInt(S, Ty);
1593 
1594  unsigned SrcAS = S->getType()->getPointerAddressSpace();
1595  if (Ty->isPtrOrPtrVectorTy() && SrcAS != Ty->getPointerAddressSpace())
1596  return getAddrSpaceCast(S, Ty);
1597 
1598  return getBitCast(S, Ty);
1599 }
1600 
1602  Type *Ty) {
1603  assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
1604  assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast");
1605 
1607  return getAddrSpaceCast(S, Ty);
1608 
1609  return getBitCast(S, Ty);
1610 }
1611 
1613  assert(C->getType()->isIntOrIntVectorTy() &&
1614  Ty->isIntOrIntVectorTy() && "Invalid cast");
1615  unsigned SrcBits = C->getType()->getScalarSizeInBits();
1616  unsigned DstBits = Ty->getScalarSizeInBits();
1617  Instruction::CastOps opcode =
1618  (SrcBits == DstBits ? Instruction::BitCast :
1619  (SrcBits > DstBits ? Instruction::Trunc :
1620  (isSigned ? Instruction::SExt : Instruction::ZExt)));
1621  return getCast(opcode, C, Ty);
1622 }
1623 
1625  assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
1626  "Invalid cast");
1627  unsigned SrcBits = C->getType()->getScalarSizeInBits();
1628  unsigned DstBits = Ty->getScalarSizeInBits();
1629  if (SrcBits == DstBits)
1630  return C; // Avoid a useless cast
1631  Instruction::CastOps opcode =
1632  (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
1633  return getCast(opcode, C, Ty);
1634 }
1635 
1636 Constant *ConstantExpr::getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced) {
1637 #ifndef NDEBUG
1638  bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1639  bool toVec = Ty->getTypeID() == Type::VectorTyID;
1640 #endif
1641  assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1642  assert(C->getType()->isIntOrIntVectorTy() && "Trunc operand must be integer");
1643  assert(Ty->isIntOrIntVectorTy() && "Trunc produces only integral");
1645  "SrcTy must be larger than DestTy for Trunc!");
1646 
1647  return getFoldedCast(Instruction::Trunc, C, Ty, OnlyIfReduced);
1648 }
1649 
1650 Constant *ConstantExpr::getSExt(Constant *C, Type *Ty, bool OnlyIfReduced) {
1651 #ifndef NDEBUG
1652  bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1653  bool toVec = Ty->getTypeID() == Type::VectorTyID;
1654 #endif
1655  assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1656  assert(C->getType()->isIntOrIntVectorTy() && "SExt operand must be integral");
1657  assert(Ty->isIntOrIntVectorTy() && "SExt produces only integer");
1659  "SrcTy must be smaller than DestTy for SExt!");
1660 
1661  return getFoldedCast(Instruction::SExt, C, Ty, OnlyIfReduced);
1662 }
1663 
1664 Constant *ConstantExpr::getZExt(Constant *C, Type *Ty, bool OnlyIfReduced) {
1665 #ifndef NDEBUG
1666  bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1667  bool toVec = Ty->getTypeID() == Type::VectorTyID;
1668 #endif
1669  assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1670  assert(C->getType()->isIntOrIntVectorTy() && "ZEXt operand must be integral");
1671  assert(Ty->isIntOrIntVectorTy() && "ZExt produces only integer");
1673  "SrcTy must be smaller than DestTy for ZExt!");
1674 
1675  return getFoldedCast(Instruction::ZExt, C, Ty, OnlyIfReduced);
1676 }
1677 
1678 Constant *ConstantExpr::getFPTrunc(Constant *C, Type *Ty, bool OnlyIfReduced) {
1679 #ifndef NDEBUG
1680  bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1681  bool toVec = Ty->getTypeID() == Type::VectorTyID;
1682 #endif
1683  assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1684  assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
1686  "This is an illegal floating point truncation!");
1687  return getFoldedCast(Instruction::FPTrunc, C, Ty, OnlyIfReduced);
1688 }
1689 
1690 Constant *ConstantExpr::getFPExtend(Constant *C, Type *Ty, bool OnlyIfReduced) {
1691 #ifndef NDEBUG
1692  bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1693  bool toVec = Ty->getTypeID() == Type::VectorTyID;
1694 #endif
1695  assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1696  assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
1698  "This is an illegal floating point extension!");
1699  return getFoldedCast(Instruction::FPExt, C, Ty, OnlyIfReduced);
1700 }
1701 
1702 Constant *ConstantExpr::getUIToFP(Constant *C, Type *Ty, bool OnlyIfReduced) {
1703 #ifndef NDEBUG
1704  bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1705  bool toVec = Ty->getTypeID() == Type::VectorTyID;
1706 #endif
1707  assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1709  "This is an illegal uint to floating point cast!");
1710  return getFoldedCast(Instruction::UIToFP, C, Ty, OnlyIfReduced);
1711 }
1712 
1713 Constant *ConstantExpr::getSIToFP(Constant *C, Type *Ty, bool OnlyIfReduced) {
1714 #ifndef NDEBUG
1715  bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1716  bool toVec = Ty->getTypeID() == Type::VectorTyID;
1717 #endif
1718  assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1720  "This is an illegal sint to floating point cast!");
1721  return getFoldedCast(Instruction::SIToFP, C, Ty, OnlyIfReduced);
1722 }
1723 
1724 Constant *ConstantExpr::getFPToUI(Constant *C, Type *Ty, bool OnlyIfReduced) {
1725 #ifndef NDEBUG
1726  bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1727  bool toVec = Ty->getTypeID() == Type::VectorTyID;
1728 #endif
1729  assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1731  "This is an illegal floating point to uint cast!");
1732  return getFoldedCast(Instruction::FPToUI, C, Ty, OnlyIfReduced);
1733 }
1734 
1735 Constant *ConstantExpr::getFPToSI(Constant *C, Type *Ty, bool OnlyIfReduced) {
1736 #ifndef NDEBUG
1737  bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1738  bool toVec = Ty->getTypeID() == Type::VectorTyID;
1739 #endif
1740  assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1742  "This is an illegal floating point to sint cast!");
1743  return getFoldedCast(Instruction::FPToSI, C, Ty, OnlyIfReduced);
1744 }
1745 
1747  bool OnlyIfReduced) {
1748  assert(C->getType()->isPtrOrPtrVectorTy() &&
1749  "PtrToInt source must be pointer or pointer vector");
1750  assert(DstTy->isIntOrIntVectorTy() &&
1751  "PtrToInt destination must be integer or integer vector");
1752  assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
1753  if (isa<VectorType>(C->getType()))
1755  "Invalid cast between a different number of vector elements");
1756  return getFoldedCast(Instruction::PtrToInt, C, DstTy, OnlyIfReduced);
1757 }
1758 
1760  bool OnlyIfReduced) {
1761  assert(C->getType()->isIntOrIntVectorTy() &&
1762  "IntToPtr source must be integer or integer vector");
1763  assert(DstTy->isPtrOrPtrVectorTy() &&
1764  "IntToPtr destination must be a pointer or pointer vector");
1765  assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
1766  if (isa<VectorType>(C->getType()))
1768  "Invalid cast between a different number of vector elements");
1769  return getFoldedCast(Instruction::IntToPtr, C, DstTy, OnlyIfReduced);
1770 }
1771 
1773  bool OnlyIfReduced) {
1774  assert(CastInst::castIsValid(Instruction::BitCast, C, DstTy) &&
1775  "Invalid constantexpr bitcast!");
1776 
1777  // It is common to ask for a bitcast of a value to its own type, handle this
1778  // speedily.
1779  if (C->getType() == DstTy) return C;
1780 
1781  return getFoldedCast(Instruction::BitCast, C, DstTy, OnlyIfReduced);
1782 }
1783 
1785  bool OnlyIfReduced) {
1786  assert(CastInst::castIsValid(Instruction::AddrSpaceCast, C, DstTy) &&
1787  "Invalid constantexpr addrspacecast!");
1788 
1789  // Canonicalize addrspacecasts between different pointer types by first
1790  // bitcasting the pointer type and then converting the address space.
1791  PointerType *SrcScalarTy = cast<PointerType>(C->getType()->getScalarType());
1792  PointerType *DstScalarTy = cast<PointerType>(DstTy->getScalarType());
1793  Type *DstElemTy = DstScalarTy->getElementType();
1794  if (SrcScalarTy->getElementType() != DstElemTy) {
1795  Type *MidTy = PointerType::get(DstElemTy, SrcScalarTy->getAddressSpace());
1796  if (VectorType *VT = dyn_cast<VectorType>(DstTy)) {
1797  // Handle vectors of pointers.
1798  MidTy = VectorType::get(MidTy, VT->getNumElements());
1799  }
1800  C = getBitCast(C, MidTy);
1801  }
1802  return getFoldedCast(Instruction::AddrSpaceCast, C, DstTy, OnlyIfReduced);
1803 }
1804 
1805 Constant *ConstantExpr::get(unsigned Opcode, Constant *C, unsigned Flags,
1806  Type *OnlyIfReducedTy) {
1807  // Check the operands for consistency first.
1808  assert(Instruction::isUnaryOp(Opcode) &&
1809  "Invalid opcode in unary constant expression");
1810 
1811 #ifndef NDEBUG
1812  switch (Opcode) {
1813  case Instruction::FNeg:
1814  assert(C->getType()->isFPOrFPVectorTy() &&
1815  "Tried to create a floating-point operation on a "
1816  "non-floating-point type!");
1817  break;
1818  default:
1819  break;
1820  }
1821 #endif
1822 
1823  // TODO: Try to constant fold operation.
1824 
1825  if (OnlyIfReducedTy == C->getType())
1826  return nullptr;
1827 
1828  Constant *ArgVec[] = { C };
1829  ConstantExprKeyType Key(Opcode, ArgVec, 0, Flags);
1830 
1831  LLVMContextImpl *pImpl = C->getContext().pImpl;
1832  return pImpl->ExprConstants.getOrCreate(C->getType(), Key);
1833 }
1834 
1835 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2,
1836  unsigned Flags, Type *OnlyIfReducedTy) {
1837  // Check the operands for consistency first.
1838  assert(Instruction::isBinaryOp(Opcode) &&
1839  "Invalid opcode in binary constant expression");
1840  assert(C1->getType() == C2->getType() &&
1841  "Operand types in binary constant expression should match");
1842 
1843 #ifndef NDEBUG
1844  switch (Opcode) {
1845  case Instruction::Add:
1846  case Instruction::Sub:
1847  case Instruction::Mul:
1848  assert(C1->getType() == C2->getType() && "Op types should be identical!");
1849  assert(C1->getType()->isIntOrIntVectorTy() &&
1850  "Tried to create an integer operation on a non-integer type!");
1851  break;
1852  case Instruction::FAdd:
1853  case Instruction::FSub:
1854  case Instruction::FMul:
1855  assert(C1->getType() == C2->getType() && "Op types should be identical!");
1856  assert(C1->getType()->isFPOrFPVectorTy() &&
1857  "Tried to create a floating-point operation on a "
1858  "non-floating-point type!");
1859  break;
1860  case Instruction::UDiv:
1861  case Instruction::SDiv:
1862  assert(C1->getType() == C2->getType() && "Op types should be identical!");
1863  assert(C1->getType()->isIntOrIntVectorTy() &&
1864  "Tried to create an arithmetic operation on a non-arithmetic type!");
1865  break;
1866  case Instruction::FDiv:
1867  assert(C1->getType() == C2->getType() && "Op types should be identical!");
1868  assert(C1->getType()->isFPOrFPVectorTy() &&
1869  "Tried to create an arithmetic operation on a non-arithmetic type!");
1870  break;
1871  case Instruction::URem:
1872  case Instruction::SRem:
1873  assert(C1->getType() == C2->getType() && "Op types should be identical!");
1874  assert(C1->getType()->isIntOrIntVectorTy() &&
1875  "Tried to create an arithmetic operation on a non-arithmetic type!");
1876  break;
1877  case Instruction::FRem:
1878  assert(C1->getType() == C2->getType() && "Op types should be identical!");
1879  assert(C1->getType()->isFPOrFPVectorTy() &&
1880  "Tried to create an arithmetic operation on a non-arithmetic type!");
1881  break;
1882  case Instruction::And:
1883  case Instruction::Or:
1884  case Instruction::Xor:
1885  assert(C1->getType() == C2->getType() && "Op types should be identical!");
1886  assert(C1->getType()->isIntOrIntVectorTy() &&
1887  "Tried to create a logical operation on a non-integral type!");
1888  break;
1889  case Instruction::Shl:
1890  case Instruction::LShr:
1891  case Instruction::AShr:
1892  assert(C1->getType() == C2->getType() && "Op types should be identical!");
1893  assert(C1->getType()->isIntOrIntVectorTy() &&
1894  "Tried to create a shift operation on a non-integer type!");
1895  break;
1896  default:
1897  break;
1898  }
1899 #endif
1900 
1901  if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1902  return FC; // Fold a few common cases.
1903 
1904  if (OnlyIfReducedTy == C1->getType())
1905  return nullptr;
1906 
1907  Constant *ArgVec[] = { C1, C2 };
1908  ConstantExprKeyType Key(Opcode, ArgVec, 0, Flags);
1909 
1910  LLVMContextImpl *pImpl = C1->getContext().pImpl;
1911  return pImpl->ExprConstants.getOrCreate(C1->getType(), Key);
1912 }
1913 
1915  // sizeof is implemented as: (i64) gep (Ty*)null, 1
1916  // Note that a non-inbounds gep is used, as null isn't within any object.
1918  Constant *GEP = getGetElementPtr(
1920  return getPtrToInt(GEP,
1921  Type::getInt64Ty(Ty->getContext()));
1922 }
1923 
1925  // alignof is implemented as: (i64) gep ({i1,Ty}*)null, 0, 1
1926  // Note that a non-inbounds gep is used, as null isn't within any object.
1927  Type *AligningTy = StructType::get(Type::getInt1Ty(Ty->getContext()), Ty);
1928  Constant *NullPtr = Constant::getNullValue(AligningTy->getPointerTo(0));
1931  Constant *Indices[2] = { Zero, One };
1932  Constant *GEP = getGetElementPtr(AligningTy, NullPtr, Indices);
1933  return getPtrToInt(GEP,
1934  Type::getInt64Ty(Ty->getContext()));
1935 }
1936 
1938  return getOffsetOf(STy, ConstantInt::get(Type::getInt32Ty(STy->getContext()),
1939  FieldNo));
1940 }
1941 
1943  // offsetof is implemented as: (i64) gep (Ty*)null, 0, FieldNo
1944  // Note that a non-inbounds gep is used, as null isn't within any object.
1945  Constant *GEPIdx[] = {
1947  FieldNo
1948  };
1949  Constant *GEP = getGetElementPtr(
1951  return getPtrToInt(GEP,
1952  Type::getInt64Ty(Ty->getContext()));
1953 }
1954 
1956  Constant *C2, bool OnlyIfReduced) {
1957  assert(C1->getType() == C2->getType() && "Op types should be identical!");
1958 
1959  switch (Predicate) {
1960  default: llvm_unreachable("Invalid CmpInst predicate");
1966  case CmpInst::FCMP_TRUE:
1967  return getFCmp(Predicate, C1, C2, OnlyIfReduced);
1968 
1972  case CmpInst::ICMP_SLE:
1973  return getICmp(Predicate, C1, C2, OnlyIfReduced);
1974  }
1975 }
1976 
1978  Type *OnlyIfReducedTy) {
1979  assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
1980 
1981  if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1982  return SC; // Fold common cases
1983 
1984  if (OnlyIfReducedTy == V1->getType())
1985  return nullptr;
1986 
1987  Constant *ArgVec[] = { C, V1, V2 };
1989 
1990  LLVMContextImpl *pImpl = C->getContext().pImpl;
1991  return pImpl->ExprConstants.getOrCreate(V1->getType(), Key);
1992 }
1993 
1995  ArrayRef<Value *> Idxs, bool InBounds,
1996  Optional<unsigned> InRangeIndex,
1997  Type *OnlyIfReducedTy) {
1998  if (!Ty)
1999  Ty = cast<PointerType>(C->getType()->getScalarType())->getElementType();
2000  else
2001  assert(Ty ==
2002  cast<PointerType>(C->getType()->getScalarType())->getElementType());
2003 
2004  if (Constant *FC =
2005  ConstantFoldGetElementPtr(Ty, C, InBounds, InRangeIndex, Idxs))
2006  return FC; // Fold a few common cases.
2007 
2008  // Get the result type of the getelementptr!
2009  Type *DestTy = GetElementPtrInst::getIndexedType(Ty, Idxs);
2010  assert(DestTy && "GEP indices invalid!");
2011  unsigned AS = C->getType()->getPointerAddressSpace();
2012  Type *ReqTy = DestTy->getPointerTo(AS);
2013 
2014  unsigned NumVecElts = 0;
2015  if (C->getType()->isVectorTy())
2016  NumVecElts = C->getType()->getVectorNumElements();
2017  else for (auto Idx : Idxs)
2018  if (Idx->getType()->isVectorTy())
2019  NumVecElts = Idx->getType()->getVectorNumElements();
2020 
2021  if (NumVecElts)
2022  ReqTy = VectorType::get(ReqTy, NumVecElts);
2023 
2024  if (OnlyIfReducedTy == ReqTy)
2025  return nullptr;
2026 
2027  // Look up the constant in the table first to ensure uniqueness
2028  std::vector<Constant*> ArgVec;
2029  ArgVec.reserve(1 + Idxs.size());
2030  ArgVec.push_back(C);
2031  for (unsigned i = 0, e = Idxs.size(); i != e; ++i) {
2032  assert((!Idxs[i]->getType()->isVectorTy() ||
2033  Idxs[i]->getType()->getVectorNumElements() == NumVecElts) &&
2034  "getelementptr index type missmatch");
2035 
2036  Constant *Idx = cast<Constant>(Idxs[i]);
2037  if (NumVecElts && !Idxs[i]->getType()->isVectorTy())
2038  Idx = ConstantVector::getSplat(NumVecElts, Idx);
2039  ArgVec.push_back(Idx);
2040  }
2041 
2042  unsigned SubClassOptionalData = InBounds ? GEPOperator::IsInBounds : 0;
2043  if (InRangeIndex && *InRangeIndex < 63)
2044  SubClassOptionalData |= (*InRangeIndex + 1) << 1;
2045  const ConstantExprKeyType Key(Instruction::GetElementPtr, ArgVec, 0,
2046  SubClassOptionalData, None, Ty);
2047 
2048  LLVMContextImpl *pImpl = C->getContext().pImpl;
2049  return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
2050 }
2051 
2053  Constant *RHS, bool OnlyIfReduced) {
2054  assert(LHS->getType() == RHS->getType());
2056  "Invalid ICmp Predicate");
2057 
2058  if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
2059  return FC; // Fold a few common cases...
2060 
2061  if (OnlyIfReduced)
2062  return nullptr;
2063 
2064  // Look up the constant in the table first to ensure uniqueness
2065  Constant *ArgVec[] = { LHS, RHS };
2066  // Get the key type with both the opcode and predicate
2067  const ConstantExprKeyType Key(Instruction::ICmp, ArgVec, pred);
2068 
2069  Type *ResultTy = Type::getInt1Ty(LHS->getContext());
2070  if (VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
2071  ResultTy = VectorType::get(ResultTy, VT->getNumElements());
2072 
2073  LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
2074  return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
2075 }
2076 
2078  Constant *RHS, bool OnlyIfReduced) {
2079  assert(LHS->getType() == RHS->getType());
2081  "Invalid FCmp Predicate");
2082 
2083  if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
2084  return FC; // Fold a few common cases...
2085 
2086  if (OnlyIfReduced)
2087  return nullptr;
2088 
2089  // Look up the constant in the table first to ensure uniqueness
2090  Constant *ArgVec[] = { LHS, RHS };
2091  // Get the key type with both the opcode and predicate
2092  const ConstantExprKeyType Key(Instruction::FCmp, ArgVec, pred);
2093 
2094  Type *ResultTy = Type::getInt1Ty(LHS->getContext());
2095  if (VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
2096  ResultTy = VectorType::get(ResultTy, VT->getNumElements());
2097 
2098  LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
2099  return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
2100 }
2101 
2103  Type *OnlyIfReducedTy) {
2104  assert(Val->getType()->isVectorTy() &&
2105  "Tried to create extractelement operation on non-vector type!");
2106  assert(Idx->getType()->isIntegerTy() &&
2107  "Extractelement index must be an integer type!");
2108 
2110  return FC; // Fold a few common cases.
2111 
2112  Type *ReqTy = Val->getType()->getVectorElementType();
2113  if (OnlyIfReducedTy == ReqTy)
2114  return nullptr;
2115 
2116  // Look up the constant in the table first to ensure uniqueness
2117  Constant *ArgVec[] = { Val, Idx };
2118  const ConstantExprKeyType Key(Instruction::ExtractElement, ArgVec);
2119 
2120  LLVMContextImpl *pImpl = Val->getContext().pImpl;
2121  return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
2122 }
2123 
2125  Constant *Idx, Type *OnlyIfReducedTy) {
2126  assert(Val->getType()->isVectorTy() &&
2127  "Tried to create insertelement operation on non-vector type!");
2128  assert(Elt->getType() == Val->getType()->getVectorElementType() &&
2129  "Insertelement types must match!");
2130  assert(Idx->getType()->isIntegerTy() &&
2131  "Insertelement index must be i32 type!");
2132 
2133  if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
2134  return FC; // Fold a few common cases.
2135 
2136  if (OnlyIfReducedTy == Val->getType())
2137  return nullptr;
2138 
2139  // Look up the constant in the table first to ensure uniqueness
2140  Constant *ArgVec[] = { Val, Elt, Idx };
2141  const ConstantExprKeyType Key(Instruction::InsertElement, ArgVec);
2142 
2143  LLVMContextImpl *pImpl = Val->getContext().pImpl;
2144  return pImpl->ExprConstants.getOrCreate(Val->getType(), Key);
2145 }
2146 
2148  Constant *Mask, Type *OnlyIfReducedTy) {
2150  "Invalid shuffle vector constant expr operands!");
2151 
2152  if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
2153  return FC; // Fold a few common cases.
2154 
2155  unsigned NElts = Mask->getType()->getVectorNumElements();
2156  Type *EltTy = V1->getType()->getVectorElementType();
2157  Type *ShufTy = VectorType::get(EltTy, NElts);
2158 
2159  if (OnlyIfReducedTy == ShufTy)
2160  return nullptr;
2161 
2162  // Look up the constant in the table first to ensure uniqueness
2163  Constant *ArgVec[] = { V1, V2, Mask };
2164  const ConstantExprKeyType Key(Instruction::ShuffleVector, ArgVec);
2165 
2166  LLVMContextImpl *pImpl = ShufTy->getContext().pImpl;
2167  return pImpl->ExprConstants.getOrCreate(ShufTy, Key);
2168 }
2169 
2171  ArrayRef<unsigned> Idxs,
2172  Type *OnlyIfReducedTy) {
2173  assert(Agg->getType()->isFirstClassType() &&
2174  "Non-first-class type for constant insertvalue expression");
2175 
2177  Idxs) == Val->getType() &&
2178  "insertvalue indices invalid!");
2179  Type *ReqTy = Val->getType();
2180 
2181  if (Constant *FC = ConstantFoldInsertValueInstruction(Agg, Val, Idxs))
2182  return FC;
2183 
2184  if (OnlyIfReducedTy == ReqTy)
2185  return nullptr;
2186 
2187  Constant *ArgVec[] = { Agg, Val };
2188  const ConstantExprKeyType Key(Instruction::InsertValue, ArgVec, 0, 0, Idxs);
2189 
2190  LLVMContextImpl *pImpl = Agg->getContext().pImpl;
2191  return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
2192 }
2193 
2195  Type *OnlyIfReducedTy) {
2196  assert(Agg->getType()->isFirstClassType() &&
2197  "Tried to create extractelement operation on non-first-class type!");
2198 
2199  Type *ReqTy = ExtractValueInst::getIndexedType(Agg->getType(), Idxs);
2200  (void)ReqTy;
2201  assert(ReqTy && "extractvalue indices invalid!");
2202 
2203  assert(Agg->getType()->isFirstClassType() &&
2204  "Non-first-class type for constant extractvalue expression");
2206  return FC;
2207 
2208  if (OnlyIfReducedTy == ReqTy)
2209  return nullptr;
2210 
2211  Constant *ArgVec[] = { Agg };
2212  const ConstantExprKeyType Key(Instruction::ExtractValue, ArgVec, 0, 0, Idxs);
2213 
2214  LLVMContextImpl *pImpl = Agg->getContext().pImpl;
2215  return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
2216 }
2217 
2218 Constant *ConstantExpr::getNeg(Constant *C, bool HasNUW, bool HasNSW) {
2219  assert(C->getType()->isIntOrIntVectorTy() &&
2220  "Cannot NEG a nonintegral value!");
2221  return getSub(ConstantFP::getZeroValueForNegation(C->getType()),
2222  C, HasNUW, HasNSW);
2223 }
2224 
2226  assert(C->getType()->isFPOrFPVectorTy() &&
2227  "Cannot FNEG a non-floating-point value!");
2228  return getFSub(ConstantFP::getZeroValueForNegation(C->getType()), C);
2229 }
2230 
2232  assert(C->getType()->isIntOrIntVectorTy() &&
2233  "Cannot NOT a nonintegral value!");
2234  return get(Instruction::Xor, C, Constant::getAllOnesValue(C->getType()));
2235 }
2236 
2238  bool HasNUW, bool HasNSW) {
2239  unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2241  return get(Instruction::Add, C1, C2, Flags);
2242 }
2243 
2245  return get(Instruction::FAdd, C1, C2);
2246 }
2247 
2249  bool HasNUW, bool HasNSW) {
2250  unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2252  return get(Instruction::Sub, C1, C2, Flags);
2253 }
2254 
2256  return get(Instruction::FSub, C1, C2);
2257 }
2258 
2260  bool HasNUW, bool HasNSW) {
2261  unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2263  return get(Instruction::Mul, C1, C2, Flags);
2264 }
2265 
2267  return get(Instruction::FMul, C1, C2);
2268 }
2269 
2271  return get(Instruction::UDiv, C1, C2,
2272  isExact ? PossiblyExactOperator::IsExact : 0);
2273 }
2274 
2276  return get(Instruction::SDiv, C1, C2,
2277  isExact ? PossiblyExactOperator::IsExact : 0);
2278 }
2279 
2281  return get(Instruction::FDiv, C1, C2);
2282 }
2283 
2285  return get(Instruction::URem, C1, C2);
2286 }
2287 
2289  return get(Instruction::SRem, C1, C2);
2290 }
2291 
2293  return get(Instruction::FRem, C1, C2);
2294 }
2295 
2297  return get(Instruction::And, C1, C2);
2298 }
2299 
2301  return get(Instruction::Or, C1, C2);
2302 }
2303 
2305  return get(Instruction::Xor, C1, C2);
2306 }
2307 
2309  bool HasNUW, bool HasNSW) {
2310  unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2312  return get(Instruction::Shl, C1, C2, Flags);
2313 }
2314 
2316  return get(Instruction::LShr, C1, C2,
2317  isExact ? PossiblyExactOperator::IsExact : 0);
2318 }
2319 
2321  return get(Instruction::AShr, C1, C2,
2322  isExact ? PossiblyExactOperator::IsExact : 0);
2323 }
2324 
2326  bool AllowRHSConstant) {
2327  assert(Instruction::isBinaryOp(Opcode) && "Only binops allowed");
2328 
2329  // Commutative opcodes: it does not matter if AllowRHSConstant is set.
2330  if (Instruction::isCommutative(Opcode)) {
2331  switch (Opcode) {
2332  case Instruction::Add: // X + 0 = X
2333  case Instruction::Or: // X | 0 = X
2334  case Instruction::Xor: // X ^ 0 = X
2335  return Constant::getNullValue(Ty);
2336  case Instruction::Mul: // X * 1 = X
2337  return ConstantInt::get(Ty, 1);
2338  case Instruction::And: // X & -1 = X
2339  return Constant::getAllOnesValue(Ty);
2340  case Instruction::FAdd: // X + -0.0 = X
2341  // TODO: If the fadd has 'nsz', should we return +0.0?
2342  return ConstantFP::getNegativeZero(Ty);
2343  case Instruction::FMul: // X * 1.0 = X
2344  return ConstantFP::get(Ty, 1.0);
2345  default:
2346  llvm_unreachable("Every commutative binop has an identity constant");
2347  }
2348  }
2349 
2350  // Non-commutative opcodes: AllowRHSConstant must be set.
2351  if (!AllowRHSConstant)
2352  return nullptr;
2353 
2354  switch (Opcode) {
2355  case Instruction::Sub: // X - 0 = X
2356  case Instruction::Shl: // X << 0 = X
2357  case Instruction::LShr: // X >>u 0 = X
2358  case Instruction::AShr: // X >> 0 = X
2359  case Instruction::FSub: // X - 0.0 = X
2360  return Constant::getNullValue(Ty);
2361  case Instruction::SDiv: // X / 1 = X
2362  case Instruction::UDiv: // X /u 1 = X
2363  return ConstantInt::get(Ty, 1);
2364  case Instruction::FDiv: // X / 1.0 = X
2365  return ConstantFP::get(Ty, 1.0);
2366  default:
2367  return nullptr;
2368  }
2369 }
2370 
2372  switch (Opcode) {
2373  default:
2374  // Doesn't have an absorber.
2375  return nullptr;
2376 
2377  case Instruction::Or:
2378  return Constant::getAllOnesValue(Ty);
2379 
2380  case Instruction::And:
2381  case Instruction::Mul:
2382  return Constant::getNullValue(Ty);
2383  }
2384 }
2385 
2386 /// Remove the constant from the constant table.
2387 void ConstantExpr::destroyConstantImpl() {
2388  getType()->getContext().pImpl->ExprConstants.remove(this);
2389 }
2390 
2391 const char *ConstantExpr::getOpcodeName() const {
2393 }
2394 
2395 GetElementPtrConstantExpr::GetElementPtrConstantExpr(
2396  Type *SrcElementTy, Constant *C, ArrayRef<Constant *> IdxList, Type *DestTy)
2397  : ConstantExpr(DestTy, Instruction::GetElementPtr,
2399  (IdxList.size() + 1),
2400  IdxList.size() + 1),
2401  SrcElementTy(SrcElementTy),
2402  ResElementTy(GetElementPtrInst::getIndexedType(SrcElementTy, IdxList)) {
2403  Op<0>() = C;
2404  Use *OperandList = getOperandList();
2405  for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
2406  OperandList[i+1] = IdxList[i];
2407 }
2408 
2410  return SrcElementTy;
2411 }
2412 
2414  return ResElementTy;
2415 }
2416 
2417 //===----------------------------------------------------------------------===//
2418 // ConstantData* implementations
2419 
2421  return getType()->getElementType();
2422 }
2423 
2425  return StringRef(DataElements, getNumElements()*getElementByteSize());
2426 }
2427 
2429  if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy()) return true;
2430  if (auto *IT = dyn_cast<IntegerType>(Ty)) {
2431  switch (IT->getBitWidth()) {
2432  case 8:
2433  case 16:
2434  case 32:
2435  case 64:
2436  return true;
2437  default: break;
2438  }
2439  }
2440  return false;
2441 }
2442 
2444  if (ArrayType *AT = dyn_cast<ArrayType>(getType()))
2445  return AT->getNumElements();
2446  return getType()->getVectorNumElements();
2447 }
2448 
2449 
2451  return getElementType()->getPrimitiveSizeInBits()/8;
2452 }
2453 
2454 /// Return the start of the specified element.
2455 const char *ConstantDataSequential::getElementPointer(unsigned Elt) const {
2456  assert(Elt < getNumElements() && "Invalid Elt");
2457  return DataElements+Elt*getElementByteSize();
2458 }
2459 
2460 
2461 /// Return true if the array is empty or all zeros.
2462 static bool isAllZeros(StringRef Arr) {
2463  for (char I : Arr)
2464  if (I != 0)
2465  return false;
2466  return true;
2467 }
2468 
2469 /// This is the underlying implementation of all of the
2470 /// ConstantDataSequential::get methods. They all thunk down to here, providing
2471 /// the correct element type. We take the bytes in as a StringRef because
2472 /// we *want* an underlying "char*" to avoid TBAA type punning violations.
2474  assert(isElementTypeCompatible(Ty->getSequentialElementType()));
2475  // If the elements are all zero or there are no elements, return a CAZ, which
2476  // is more dense and canonical.
2477  if (isAllZeros(Elements))
2478  return ConstantAggregateZero::get(Ty);
2479 
2480  // Do a lookup to see if we have already formed one of these.
2481  auto &Slot =
2482  *Ty->getContext()
2483  .pImpl->CDSConstants.insert(std::make_pair(Elements, nullptr))
2484  .first;
2485 
2486  // The bucket can point to a linked list of different CDS's that have the same
2487  // body but different types. For example, 0,0,0,1 could be a 4 element array
2488  // of i8, or a 1-element array of i32. They'll both end up in the same
2489  /// StringMap bucket, linked up by their Next pointers. Walk the list.
2490  ConstantDataSequential **Entry = &Slot.second;
2491  for (ConstantDataSequential *Node = *Entry; Node;
2492  Entry = &Node->Next, Node = *Entry)
2493  if (Node->getType() == Ty)
2494  return Node;
2495 
2496  // Okay, we didn't get a hit. Create a node of the right class, link it in,
2497  // and return it.
2498  if (isa<ArrayType>(Ty))
2499  return *Entry = new ConstantDataArray(Ty, Slot.first().data());
2500 
2501  assert(isa<VectorType>(Ty));
2502  return *Entry = new ConstantDataVector(Ty, Slot.first().data());
2503 }
2504 
2505 void ConstantDataSequential::destroyConstantImpl() {
2506  // Remove the constant from the StringMap.
2507  StringMap<ConstantDataSequential*> &CDSConstants =
2509 
2511  CDSConstants.find(getRawDataValues());
2512 
2513  assert(Slot != CDSConstants.end() && "CDS not found in uniquing table");
2514 
2515  ConstantDataSequential **Entry = &Slot->getValue();
2516 
2517  // Remove the entry from the hash table.
2518  if (!(*Entry)->Next) {
2519  // If there is only one value in the bucket (common case) it must be this
2520  // entry, and removing the entry should remove the bucket completely.
2521  assert((*Entry) == this && "Hash mismatch in ConstantDataSequential");
2522  getContext().pImpl->CDSConstants.erase(Slot);
2523  } else {
2524  // Otherwise, there are multiple entries linked off the bucket, unlink the
2525  // node we care about but keep the bucket around.
2526  for (ConstantDataSequential *Node = *Entry; ;
2527  Entry = &Node->Next, Node = *Entry) {
2528  assert(Node && "Didn't find entry in its uniquing hash table!");
2529  // If we found our entry, unlink it from the list and we're done.
2530  if (Node == this) {
2531  *Entry = Node->Next;
2532  break;
2533  }
2534  }
2535  }
2536 
2537  // If we were part of a list, make sure that we don't delete the list that is
2538  // still owned by the uniquing map.
2539  Next = nullptr;
2540 }
2541 
2542 /// getFP() constructors - Return a constant with array type with an element
2543 /// count and element type of float with precision matching the number of
2544 /// bits in the ArrayRef passed in. (i.e. half for 16bits, float for 32bits,
2545 /// double for 64bits) Note that this can return a ConstantAggregateZero
2546 /// object.
2548  ArrayRef<uint16_t> Elts) {
2549  Type *Ty = ArrayType::get(Type::getHalfTy(Context), Elts.size());
2550  const char *Data = reinterpret_cast<const char *>(Elts.data());
2551  return getImpl(StringRef(Data, Elts.size() * 2), Ty);
2552 }
2554  ArrayRef<uint32_t> Elts) {
2555  Type *Ty = ArrayType::get(Type::getFloatTy(Context), Elts.size());
2556  const char *Data = reinterpret_cast<const char *>(Elts.data());
2557  return getImpl(StringRef(Data, Elts.size() * 4), Ty);
2558 }
2560  ArrayRef<uint64_t> Elts) {
2561  Type *Ty = ArrayType::get(Type::getDoubleTy(Context), Elts.size());
2562  const char *Data = reinterpret_cast<const char *>(Elts.data());
2563  return getImpl(StringRef(Data, Elts.size() * 8), Ty);
2564 }
2565 
2567  StringRef Str, bool AddNull) {
2568  if (!AddNull) {
2569  const uint8_t *Data = reinterpret_cast<const uint8_t *>(Str.data());
2570  return get(Context, makeArrayRef(Data, Str.size()));
2571  }
2572 
2573  SmallVector<uint8_t, 64> ElementVals;
2574  ElementVals.append(Str.begin(), Str.end());
2575  ElementVals.push_back(0);
2576  return get(Context, ElementVals);
2577 }
2578 
2579 /// get() constructors - Return a constant with vector type with an element
2580 /// count and element type matching the ArrayRef passed in. Note that this
2581 /// can return a ConstantAggregateZero object.
2583  Type *Ty = VectorType::get(Type::getInt8Ty(Context), Elts.size());
2584  const char *Data = reinterpret_cast<const char *>(Elts.data());
2585  return getImpl(StringRef(Data, Elts.size() * 1), Ty);
2586 }
2588  Type *Ty = VectorType::get(Type::getInt16Ty(Context), Elts.size());
2589  const char *Data = reinterpret_cast<const char *>(Elts.data());
2590  return getImpl(StringRef(Data, Elts.size() * 2), Ty);
2591 }
2593  Type *Ty = VectorType::get(Type::getInt32Ty(Context), Elts.size());
2594  const char *Data = reinterpret_cast<const char *>(Elts.data());
2595  return getImpl(StringRef(Data, Elts.size() * 4), Ty);
2596 }
2598  Type *Ty = VectorType::get(Type::getInt64Ty(Context), Elts.size());
2599  const char *Data = reinterpret_cast<const char *>(Elts.data());
2600  return getImpl(StringRef(Data, Elts.size() * 8), Ty);
2601 }
2603  Type *Ty = VectorType::get(Type::getFloatTy(Context), Elts.size());
2604  const char *Data = reinterpret_cast<const char *>(Elts.data());
2605  return getImpl(StringRef(Data, Elts.size() * 4), Ty);
2606 }
2608  Type *Ty = VectorType::get(Type::getDoubleTy(Context), Elts.size());
2609  const char *Data = reinterpret_cast<const char *>(Elts.data());
2610  return getImpl(StringRef(Data, Elts.size() * 8), Ty);
2611 }
2612 
2613 /// getFP() constructors - Return a constant with vector type with an element
2614 /// count and element type of float with the precision matching the number of
2615 /// bits in the ArrayRef passed in. (i.e. half for 16bits, float for 32bits,
2616 /// double for 64bits) Note that this can return a ConstantAggregateZero
2617 /// object.
2619  ArrayRef<uint16_t> Elts) {
2620  Type *Ty = VectorType::get(Type::getHalfTy(Context), Elts.size());
2621  const char *Data = reinterpret_cast<const char *>(Elts.data());
2622  return getImpl(StringRef(Data, Elts.size() * 2), Ty);
2623 }
2625  ArrayRef<uint32_t> Elts) {
2626  Type *Ty = VectorType::get(Type::getFloatTy(Context), Elts.size());
2627  const char *Data = reinterpret_cast<const char *>(Elts.data());
2628  return getImpl(StringRef(Data, Elts.size() * 4), Ty);
2629 }
2631  ArrayRef<uint64_t> Elts) {
2632  Type *Ty = VectorType::get(Type::getDoubleTy(Context), Elts.size());
2633  const char *Data = reinterpret_cast<const char *>(Elts.data());
2634  return getImpl(StringRef(Data, Elts.size() * 8), Ty);
2635 }
2636 
2638  assert(isElementTypeCompatible(V->getType()) &&
2639  "Element type not compatible with ConstantData");
2640  if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
2641  if (CI->getType()->isIntegerTy(8)) {
2642  SmallVector<uint8_t, 16> Elts(NumElts, CI->getZExtValue());
2643  return get(V->getContext(), Elts);
2644  }
2645  if (CI->getType()->isIntegerTy(16)) {
2646  SmallVector<uint16_t, 16> Elts(NumElts, CI->getZExtValue());
2647  return get(V->getContext(), Elts);
2648  }
2649  if (CI->getType()->isIntegerTy(32)) {
2650  SmallVector<uint32_t, 16> Elts(NumElts, CI->getZExtValue());
2651  return get(V->getContext(), Elts);
2652  }
2653  assert(CI->getType()->isIntegerTy(64) && "Unsupported ConstantData type");
2654  SmallVector<uint64_t, 16> Elts(NumElts, CI->getZExtValue());
2655  return get(V->getContext(), Elts);
2656  }
2657 
2658  if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
2659  if (CFP->getType()->isHalfTy()) {
2661  NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
2662  return getFP(V->getContext(), Elts);
2663  }
2664  if (CFP->getType()->isFloatTy()) {
2666  NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
2667  return getFP(V->getContext(), Elts);
2668  }
2669  if (CFP->getType()->isDoubleTy()) {
2671  NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
2672  return getFP(V->getContext(), Elts);
2673  }
2674  }
2675  return ConstantVector::getSplat(NumElts, V);
2676 }
2677 
2678 
2679 uint64_t ConstantDataSequential::getElementAsInteger(unsigned Elt) const {
2680  assert(isa<IntegerType>(getElementType()) &&
2681  "Accessor can only be used when element is an integer");
2682  const char *EltPtr = getElementPointer(Elt);
2683 
2684  // The data is stored in host byte order, make sure to cast back to the right
2685  // type to load with the right endianness.
2686  switch (getElementType()->getIntegerBitWidth()) {
2687  default: llvm_unreachable("Invalid bitwidth for CDS");
2688  case 8:
2689  return *reinterpret_cast<const uint8_t *>(EltPtr);
2690  case 16:
2691  return *reinterpret_cast<const uint16_t *>(EltPtr);
2692  case 32:
2693  return *reinterpret_cast<const uint32_t *>(EltPtr);
2694  case 64:
2695  return *reinterpret_cast<const uint64_t *>(EltPtr);
2696  }
2697 }
2698 
2700  assert(isa<IntegerType>(getElementType()) &&
2701  "Accessor can only be used when element is an integer");
2702  const char *EltPtr = getElementPointer(Elt);
2703 
2704  // The data is stored in host byte order, make sure to cast back to the right
2705  // type to load with the right endianness.
2706  switch (getElementType()->getIntegerBitWidth()) {
2707  default: llvm_unreachable("Invalid bitwidth for CDS");
2708  case 8: {
2709  auto EltVal = *reinterpret_cast<const uint8_t *>(EltPtr);
2710  return APInt(8, EltVal);
2711  }
2712  case 16: {
2713  auto EltVal = *reinterpret_cast<const uint16_t *>(EltPtr);
2714  return APInt(16, EltVal);
2715  }
2716  case 32: {
2717  auto EltVal = *reinterpret_cast<const uint32_t *>(EltPtr);
2718  return APInt(32, EltVal);
2719  }
2720  case 64: {
2721  auto EltVal = *reinterpret_cast<const uint64_t *>(EltPtr);
2722  return APInt(64, EltVal);
2723  }
2724  }
2725 }
2726 
2728  const char *EltPtr = getElementPointer(Elt);
2729 
2730  switch (getElementType()->getTypeID()) {
2731  default:
2732  llvm_unreachable("Accessor can only be used when element is float/double!");
2733  case Type::HalfTyID: {
2734  auto EltVal = *reinterpret_cast<const uint16_t *>(EltPtr);
2735  return APFloat(APFloat::IEEEhalf(), APInt(16, EltVal));
2736  }
2737  case Type::FloatTyID: {
2738  auto EltVal = *reinterpret_cast<const uint32_t *>(EltPtr);
2739  return APFloat(APFloat::IEEEsingle(), APInt(32, EltVal));
2740  }
2741  case Type::DoubleTyID: {
2742  auto EltVal = *reinterpret_cast<const uint64_t *>(EltPtr);
2743  return APFloat(APFloat::IEEEdouble(), APInt(64, EltVal));
2744  }
2745  }
2746 }
2747 
2749  assert(getElementType()->isFloatTy() &&
2750  "Accessor can only be used when element is a 'float'");
2751  return *reinterpret_cast<const float *>(getElementPointer(Elt));
2752 }
2753 
2755  assert(getElementType()->isDoubleTy() &&
2756  "Accessor can only be used when element is a 'float'");
2757  return *reinterpret_cast<const double *>(getElementPointer(Elt));
2758 }
2759 
2761  if (getElementType()->isHalfTy() || getElementType()->isFloatTy() ||
2762  getElementType()->isDoubleTy())
2763  return ConstantFP::get(getContext(), getElementAsAPFloat(Elt));
2764 
2765  return ConstantInt::get(getElementType(), getElementAsInteger(Elt));
2766 }
2767 
2768 bool ConstantDataSequential::isString(unsigned CharSize) const {
2769  return isa<ArrayType>(getType()) && getElementType()->isIntegerTy(CharSize);
2770 }
2771 
2773  if (!isString())
2774  return false;
2775 
2776  StringRef Str = getAsString();
2777 
2778  // The last value must be nul.
2779  if (Str.back() != 0) return false;
2780 
2781  // Other elements must be non-nul.
2782  return Str.drop_back().find(0) == StringRef::npos;
2783 }
2784 
2786  const char *Base = getRawDataValues().data();
2787 
2788  // Compare elements 1+ to the 0'th element.
2789  unsigned EltSize = getElementByteSize();
2790  for (unsigned i = 1, e = getNumElements(); i != e; ++i)
2791  if (memcmp(Base, Base+i*EltSize, EltSize))
2792  return false;
2793 
2794  return true;
2795 }
2796 
2798  // If they're all the same, return the 0th one as a representative.
2799  return isSplat() ? getElementAsConstant(0) : nullptr;
2800 }
2801 
2802 //===----------------------------------------------------------------------===//
2803 // handleOperandChange implementations
2804 
2805 /// Update this constant array to change uses of
2806 /// 'From' to be uses of 'To'. This must update the uniquing data structures
2807 /// etc.
2808 ///
2809 /// Note that we intentionally replace all uses of From with To here. Consider
2810 /// a large array that uses 'From' 1000 times. By handling this case all here,
2811 /// ConstantArray::handleOperandChange is only invoked once, and that
2812 /// single invocation handles all 1000 uses. Handling them one at a time would
2813 /// work, but would be really slow because it would have to unique each updated
2814 /// array instance.
2815 ///
2817  Value *Replacement = nullptr;
2818  switch (getValueID()) {
2819  default:
2820  llvm_unreachable("Not a constant!");
2821 #define HANDLE_CONSTANT(Name) \
2822  case Value::Name##Val: \
2823  Replacement = cast<Name>(this)->handleOperandChangeImpl(From, To); \
2824  break;
2825 #include "llvm/IR/Value.def"
2826  }
2827 
2828  // If handleOperandChangeImpl returned nullptr, then it handled
2829  // replacing itself and we don't want to delete or replace anything else here.
2830  if (!Replacement)
2831  return;
2832 
2833  // I do need to replace this with an existing value.
2834  assert(Replacement != this && "I didn't contain From!");
2835 
2836  // Everyone using this now uses the replacement.
2837  replaceAllUsesWith(Replacement);
2838 
2839  // Delete the old constant!
2840  destroyConstant();
2841 }
2842 
2843 Value *ConstantArray::handleOperandChangeImpl(Value *From, Value *To) {
2844  assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2845  Constant *ToC = cast<Constant>(To);
2846 
2848  Values.reserve(getNumOperands()); // Build replacement array.
2849 
2850  // Fill values with the modified operands of the constant array. Also,
2851  // compute whether this turns into an all-zeros array.
2852  unsigned NumUpdated = 0;
2853 
2854  // Keep track of whether all the values in the array are "ToC".
2855  bool AllSame = true;
2856  Use *OperandList = getOperandList();
2857  unsigned OperandNo = 0;
2858  for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2859  Constant *Val = cast<Constant>(O->get());
2860  if (Val == From) {
2861  OperandNo = (O - OperandList);
2862  Val = ToC;
2863  ++NumUpdated;
2864  }
2865  Values.push_back(Val);
2866  AllSame &= Val == ToC;
2867  }
2868 
2869  if (AllSame && ToC->isNullValue())
2871 
2872  if (AllSame && isa<UndefValue>(ToC))
2873  return UndefValue::get(getType());
2874 
2875  // Check for any other type of constant-folding.
2876  if (Constant *C = getImpl(getType(), Values))
2877  return C;
2878 
2879  // Update to the new value.
2881  Values, this, From, ToC, NumUpdated, OperandNo);
2882 }
2883 
2884 Value *ConstantStruct::handleOperandChangeImpl(Value *From, Value *To) {
2885  assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2886  Constant *ToC = cast<Constant>(To);
2887 
2888  Use *OperandList = getOperandList();
2889 
2891  Values.reserve(getNumOperands()); // Build replacement struct.
2892 
2893  // Fill values with the modified operands of the constant struct. Also,
2894  // compute whether this turns into an all-zeros struct.
2895  unsigned NumUpdated = 0;
2896  bool AllSame = true;
2897  unsigned OperandNo = 0;
2898  for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O) {
2899  Constant *Val = cast<Constant>(O->get());
2900  if (Val == From) {
2901  OperandNo = (O - OperandList);
2902  Val = ToC;
2903  ++NumUpdated;
2904  }
2905  Values.push_back(Val);
2906  AllSame &= Val == ToC;
2907  }
2908 
2909  if (AllSame && ToC->isNullValue())
2911 
2912  if (AllSame && isa<UndefValue>(ToC))
2913  return UndefValue::get(getType());
2914 
2915  // Update to the new value.
2917  Values, this, From, ToC, NumUpdated, OperandNo);
2918 }
2919 
2920 Value *ConstantVector::handleOperandChangeImpl(Value *From, Value *To) {
2921  assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2922  Constant *ToC = cast<Constant>(To);
2923 
2925  Values.reserve(getNumOperands()); // Build replacement array...
2926  unsigned NumUpdated = 0;
2927  unsigned OperandNo = 0;
2928  for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2929  Constant *Val = getOperand(i);
2930  if (Val == From) {
2931  OperandNo = i;
2932  ++NumUpdated;
2933  Val = ToC;
2934  }
2935  Values.push_back(Val);
2936  }
2937 
2938  if (Constant *C = getImpl(Values))
2939  return C;
2940 
2941  // Update to the new value.
2943  Values, this, From, ToC, NumUpdated, OperandNo);
2944 }
2945 
2946 Value *ConstantExpr::handleOperandChangeImpl(Value *From, Value *ToV) {
2947  assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2948  Constant *To = cast<Constant>(ToV);
2949 
2951  unsigned NumUpdated = 0;
2952  unsigned OperandNo = 0;
2953  for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2954  Constant *Op = getOperand(i);
2955  if (Op == From) {
2956  OperandNo = i;
2957  ++NumUpdated;
2958  Op = To;
2959  }
2960  NewOps.push_back(Op);
2961  }
2962  assert(NumUpdated && "I didn't contain From!");
2963 
2964  if (Constant *C = getWithOperands(NewOps, getType(), true))
2965  return C;
2966 
2967  // Update to the new value.
2968  return getContext().pImpl->ExprConstants.replaceOperandsInPlace(
2969  NewOps, this, From, To, NumUpdated, OperandNo);
2970 }
2971 
2973  SmallVector<Value *, 4> ValueOperands(op_begin(), op_end());
2974  ArrayRef<Value*> Ops(ValueOperands);
2975 
2976  switch (getOpcode()) {
2977  case Instruction::Trunc:
2978  case Instruction::ZExt:
2979  case Instruction::SExt:
2980  case Instruction::FPTrunc:
2981  case Instruction::FPExt:
2982  case Instruction::UIToFP:
2983  case Instruction::SIToFP:
2984  case Instruction::FPToUI:
2985  case Instruction::FPToSI:
2986  case Instruction::PtrToInt:
2987  case Instruction::IntToPtr:
2988  case Instruction::BitCast:
2989  case Instruction::AddrSpaceCast:
2991  Ops[0], getType());
2992  case Instruction::Select:
2993  return SelectInst::Create(Ops[0], Ops[1], Ops[2]);
2994  case Instruction::InsertElement:
2995  return InsertElementInst::Create(Ops[0], Ops[1], Ops[2]);
2996  case Instruction::ExtractElement:
2997  return ExtractElementInst::Create(Ops[0], Ops[1]);
2998  case Instruction::InsertValue:
2999  return InsertValueInst::Create(Ops[0], Ops[1], getIndices());
3000  case Instruction::ExtractValue:
3001  return ExtractValueInst::Create(Ops[0], getIndices());
3002  case Instruction::ShuffleVector:
3003  return new ShuffleVectorInst(Ops[0], Ops[1], Ops[2]);
3004 
3005  case Instruction::GetElementPtr: {
3006  const auto *GO = cast<GEPOperator>(this);
3007  if (GO->isInBounds())
3008  return GetElementPtrInst::CreateInBounds(GO->getSourceElementType(),
3009  Ops[0], Ops.slice(1));
3010  return GetElementPtrInst::Create(GO->getSourceElementType(), Ops[0],
3011  Ops.slice(1));
3012  }
3013  case Instruction::ICmp:
3014  case Instruction::FCmp:
3016  (CmpInst::Predicate)getPredicate(), Ops[0], Ops[1]);
3017 
3018  default:
3019  assert(getNumOperands() == 2 && "Must be binary operator?");
3020  BinaryOperator *BO =
3022  Ops[0], Ops[1]);
3023  if (isa<OverflowingBinaryOperator>(BO)) {
3028  }
3029  if (isa<PossiblyExactOperator>(BO))
3031  return BO;
3032  }
3033 }
bool isFPPredicate() const
Definition: InstrTypes.h:738
const T & front() const
front - Get the first element.
Definition: ArrayRef.h:151
static Constant * getFPTrunc(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:1678
Type * getVectorElementType() const
Definition: Type.h:370
static bool isValueValidForType(Type *Ty, uint64_t V)
This static method returns true if the type Ty is big enough to represent the value V...
Definition: Constants.cpp:1266
A vector constant whose element type is a simple 1/2/4/8-byte integer or float/double, and whose elements are just simple data values (i.e.
Definition: Constants.h:761
static APFloat getNaN(const fltSemantics &Sem, bool Negative=false, uint64_t payload=0)
Factory for NaN values.
Definition: APFloat.h:874
uint64_t CallInst * C
static const fltSemantics & IEEEquad() LLVM_READNONE
Definition: APFloat.cpp:125
IntegerType * getType() const
getType - Specialize the getType() method to always return an IntegerType, which reduces the amount o...
Definition: Constants.h:171
static ConstantInt * getFalse(LLVMContext &Context)
Definition: Constants.cpp:584
static Constant * getString(LLVMContext &Context, StringRef Initializer, bool AddNull=true)
This method constructs a CDS and initializes it with a text string.
Definition: Constants.cpp:2566
static bool rangeOnlyContains(ItTy Start, ItTy End, EltTy Elt)
Definition: Constants.cpp:901
static Type * getDoubleTy(LLVMContext &C)
Definition: Type.cpp:164
bool isAllOnesValue() const
Return true if this is the value that would be returned by getAllOnesValue.
Definition: Constants.cpp:99
static IntegerType * getInt1Ty(LLVMContext &C)
Definition: Type.cpp:172
static Constant * getFAdd(Constant *C1, Constant *C2)
Definition: Constants.cpp:2244
unsigned getOpcode() const
Return the opcode at the root of this constant expression.
Definition: Constants.h:1209
unsigned getNumElements() const
Return the number of elements in the array, vector, or struct.
Definition: Constants.cpp:856
static APInt getAllOnesValue(unsigned numBits)
Get the all-ones value.
Definition: APInt.h:561
unsigned getValueID() const
Return an ID for the concrete type of this object.
Definition: Value.h:463
LLVMContext & Context
bool isNaN() const
Return true if this is a floating-point NaN constant or a vector floating-point constant with all NaN...
Definition: Constants.cpp:240
static Constant * getPointerBitCastOrAddrSpaceCast(Constant *C, Type *Ty)
Create a BitCast or AddrSpaceCast for a pointer type depending on the address space.
Definition: Constants.cpp:1601
This class represents lattice values for constants.
Definition: AllocatorList.h:23
Constant * getElementAsConstant(unsigned i) const
Return a Constant for a specified index&#39;s element.
Definition: Constants.cpp:2760
DenseMap< std::pair< const Function *, const BasicBlock * >, BlockAddress * > BlockAddresses
static Constant * getGetElementPtr(Type *Ty, Constant *C, ArrayRef< Constant *> IdxList, bool InBounds=false, Optional< unsigned > InRangeIndex=None, Type *OnlyIfReducedTy=nullptr)
Getelementptr form.
Definition: Constants.h:1153
iterator begin() const
Definition: ArrayRef.h:136
static Constant * getInfinity(Type *Ty, bool Negative=false)
Definition: Constants.cpp:807
2: 32-bit floating point type
Definition: Type.h:58
bool needsRelocation() const
This method classifies the entry according to whether or not it may generate a relocation entry...
Definition: Constants.cpp:488
bool isConstantUsed() const
Return true if the constant has users other than constant expressions and other dangling things...
Definition: Constants.cpp:476
unsigned getNumElements() const
Random access to the elements.
Definition: DerivedTypes.h:344
static Constant * getAddrSpaceCast(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:1784
static ConstantAggregateZero * get(Type *Ty)
Definition: Constants.cpp:1331
ExtractValueConstantExpr - This class is private to Constants.cpp, and is used behind the scenes to i...
APInt getElementAsAPInt(unsigned i) const
If this is a sequential container of integers (of any size), return the specified element as an APInt...
Definition: Constants.cpp:2699
bool isFP128Ty() const
Return true if this is &#39;fp128&#39;.
Definition: Type.h:155
static GetElementPtrInst * Create(Type *PointeeType, Value *Ptr, ArrayRef< Value *> IdxList, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
Definition: Instructions.h:899
Constant * ConstantFoldExtractElementInstruction(Constant *Val, Constant *Idx)
Attempt to constant fold an extractelement instruction with the specified operands and indices...
static PointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space...
Definition: Type.cpp:629
gep_type_iterator gep_type_end(const User *GEP)
unsigned less or equal
Definition: InstrTypes.h:672
unsigned less than
Definition: InstrTypes.h:671
Constant * ConstantFoldCastInstruction(unsigned opcode, Constant *V, Type *DestTy)
static Constant * getIntToPtr(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:1759
uint64_t getElementByteSize() const
Return the size (in bytes) of each element in the array/vector.
Definition: Constants.cpp:2450
static Constant * getExtractElement(Constant *Vec, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
Definition: Constants.cpp:2102
0 1 0 0 True if ordered and less than
Definition: InstrTypes.h:652
iterator find(StringRef Key)
Definition: StringMap.h:332
static Constant * getFoldedCast(Instruction::CastOps opc, Constant *C, Type *Ty, bool OnlyIfReduced=false)
This is a utility function to handle folding of casts and lookup of the cast in the ExprConstants map...
Definition: Constants.cpp:1511
This instruction constructs a fixed permutation of two input vectors.
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", Instruction *InsertBefore=nullptr, Instruction *MDFrom=nullptr)
LLVMContext & getContext() const
All values hold a context through their type.
Definition: Value.cpp:705
1 1 1 0 True if unordered or not equal
Definition: InstrTypes.h:662
const APInt & getUniqueInteger() const
If C is a constant integer then return its value, otherwise C must be a vector of constant integers...
Definition: Constants.cpp:1388
13: Structures
Definition: Type.h:72
F(f)
4: 80-bit floating point type (X87)
Definition: Type.h:60
const fltSemantics & getSemantics() const
Definition: APFloat.h:1154
unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
Definition: DerivedTypes.h:534
static APFloat getZero(const fltSemantics &Sem, bool Negative=false)
Factory for Positive and Negative Zero.
Definition: APFloat.h:854
1: 16-bit floating point type
Definition: Type.h:57
static IntegerType * getInt64Ty(LLVMContext &C)
Definition: Type.cpp:176
bool isOpaque() const
Return true if this is a type with an identity that has no body specified yet.
Definition: DerivedTypes.h:300
static Constant * getCompare(unsigned short pred, Constant *C1, Constant *C2, bool OnlyIfReduced=false)
Return an ICmp or FCmp comparison operator constant expression.
Definition: Constants.cpp:1955
Hexagon Common GEP
static Constant * getSub(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
Definition: Constants.cpp:2248
bool isVectorTy() const
True if this is an instance of VectorType.
Definition: Type.h:229
15: Pointers
Definition: Type.h:74
void reserve(size_type N)
Definition: SmallVector.h:368
static IntegerType * getInt16Ty(LLVMContext &C)
Definition: Type.cpp:174
unsigned getPredicate() const
Return the ICMP or FCMP predicate value.
Definition: Constants.cpp:1187
bool isPPC_FP128Ty() const
Return true if this is powerpc long double.
Definition: Type.h:158
op_iterator op_begin()
Definition: User.h:229
static Type * getX86_FP80Ty(LLVMContext &C)
Definition: Type.cpp:167
static Constant * get(ArrayType *T, ArrayRef< Constant *> V)
Definition: Constants.cpp:982
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition: APInt.h:1508
Constant * getElementValue(Constant *C) const
Return a zero of the right value for the specified GEP index if we can, otherwise return null (e...
Definition: Constants.cpp:844
static Constant * getInsertElement(Constant *Vec, Constant *Elt, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
Definition: Constants.cpp:2124
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition: Type.h:129
static Constant * getNullValue(Type *Ty)
Constructor to create a &#39;0&#39; constant of arbitrary type.
Definition: Constants.cpp:264
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
Definition: SmallPtrSet.h:343
static Constant * getAdd(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
Definition: Constants.cpp:2237
static Constant * getFMul(Constant *C1, Constant *C2)
Definition: Constants.cpp:2266
static Constant * getFPSequenceIfElementsMatch(ArrayRef< Constant *> V)
Definition: Constants.cpp:922
Function * getFunction() const
Definition: Constants.h:865
ConstantClass * replaceOperandsInPlace(ArrayRef< Constant *> Operands, ConstantClass *CP, Value *From, Constant *To, unsigned NumUpdated=0, unsigned OperandNo=~0u)
1 0 0 1 True if unordered or equal
Definition: InstrTypes.h:657
The address of a basic block.
Definition: Constants.h:839
static InsertElementInst * Create(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
1 0 0 0 True if unordered: isnan(X) | isnan(Y)
Definition: InstrTypes.h:656
static Constant * getIntegerCast(Constant *C, Type *Ty, bool isSigned)
Create a ZExt, Bitcast or Trunc for integer -> integer casts.
Definition: Constants.cpp:1612
static bool castIsValid(Instruction::CastOps op, Value *S, Type *DstTy)
This method can be used to determine if a cast from S to DstTy using Opcode op is valid or not...
static Type * getIndexedType(Type *Agg, ArrayRef< unsigned > Idxs)
Returns the type of the element that would be extracted with an extractvalue instruction with the spe...
static Type * getFloatTy(LLVMContext &C)
Definition: Type.cpp:163
static Constant * getNegativeZero(Type *Ty)
Definition: Constants.cpp:758
ArrayRef< T > makeArrayRef(const T &OneElt)
Construct an ArrayRef from a single element.
Definition: ArrayRef.h:450
TypeID getTypeID() const
Return the type id for the type.
Definition: Type.h:137
bool isFloatingPointTy() const
Return true if this is one of the six floating-point types.
Definition: Type.h:161
&#39;undef&#39; values are things that do not have specified contents.
Definition: Constants.h:1285
static APFloat getAllOnesValue(unsigned BitWidth, bool isIEEE=false)
Returns a float which is bitcasted from an all one value int.
Definition: APFloat.cpp:4468
StringRef getRawDataValues() const
Return the raw, underlying, bytes of this data.
Definition: Constants.cpp:2424
Class to represent struct types.
Definition: DerivedTypes.h:232
A Use represents the edge between a Value definition and its users.
Definition: Use.h:55
static Constant * getLShr(Constant *C1, Constant *C2, bool isExact=false)
Definition: Constants.cpp:2315
PointerType * getPointerTo(unsigned AddrSpace=0) const
Return a pointer to the current type.
Definition: Type.cpp:651
static Optional< unsigned > getOpcode(ArrayRef< VPValue *> Values)
Returns the opcode of Values or ~0 if they do not all agree.
Definition: VPlanSLP.cpp:196
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition: Type.h:196
0 1 0 1 True if ordered and less than or equal
Definition: InstrTypes.h:653
static Constant * getSExt(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:1650
Instruction * getAsInstruction()
Returns an Instruction which implements the same operation as this ConstantExpr.
Definition: Constants.cpp:2972
UndefValue * getElementValue(Constant *C) const
Return an undef of the right value for the specified GEP index if we can, otherwise return null (e...
Definition: Constants.cpp:877
uint64_t getNumElements() const
Definition: DerivedTypes.h:390
void remove(ConstantClass *CP)
Remove this constant from the map.
static Type * getPPC_FP128Ty(LLVMContext &C)
Definition: Type.cpp:169
static StructType * get(LLVMContext &Context, ArrayRef< Type *> Elements, bool isPacked=false)
This static method is the primary way to create a literal StructType.
Definition: Type.cpp:341
All zero aggregate value.
Definition: Constants.h:340
static Constant * getSequenceIfElementsMatch(Constant *C, ArrayRef< Constant *> V)
Definition: Constants.cpp:935
static bool isValidOperands(const Value *V1, const Value *V2, const Value *Mask)
Return true if a shufflevector instruction can be formed with the specified operands.
static Constant * getZExt(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:1664
Key
PAL metadata keys.
static Constant * getSizeOf(Type *Ty)
getSizeOf constant expr - computes the (alloc) size of a type (in address-units, not bits) in a targe...
Definition: Constants.cpp:1914
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
Definition: Constants.cpp:84
A constant value that is initialized with an expression using other constant values.
Definition: Constants.h:888
void setIsExact(bool b=true)
Set or clear the exact flag on this instruction, which must be an operator which supports this flag...
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:244
bool canTrap() const
Return true if evaluation of this constant could trap.
Definition: Constants.cpp:432
bool isFirstClassType() const
Return true if the type is "first class", meaning it is a valid type for a Value. ...
Definition: Type.h:243
opStatus convert(const fltSemantics &ToSemantics, roundingMode RM, bool *losesInfo)
Definition: APFloat.cpp:4443
static Constant * getFPCast(Constant *C, Type *Ty)
Create a FPExt, Bitcast or FPTrunc for fp -> fp casts.
Definition: Constants.cpp:1624
ConstantDataSequential - A vector or array constant whose element type is a simple 1/2/4/8-byte integ...
Definition: Constants.h:573
static Constant * getAShr(Constant *C1, Constant *C2, bool isExact=false)
Definition: Constants.cpp:2320
Class to represent array types.
Definition: DerivedTypes.h:400
static Constant * getSelect(Constant *C, Constant *V1, Constant *V2, Type *OnlyIfReducedTy=nullptr)
Select constant expr.
Definition: Constants.cpp:1977
std::unique_ptr< ConstantTokenNone > TheNoneToken
static CmpInst * Create(OtherOps Op, Predicate predicate, Value *S1, Value *S2, const Twine &Name="", Instruction *InsertBefore=nullptr)
Construct a compare instruction, given the opcode, the predicate and the two operands.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: APInt.h:32
LLVM_NODISCARD size_t size() const
size - Get the string size.
Definition: StringRef.h:130
bool isGEPWithNoNotionalOverIndexing() const
Return true if this is a getelementptr expression and all the index operands are compile-time known i...
Definition: Constants.cpp:1152
ArrayConstantsTy ArrayConstants
bool isFiniteNonZeroFP() const
Return true if this is a finite and non-zero floating-point scalar constant or a vector constant with...
Definition: Constants.cpp:201
Constant * ConstantFoldInsertValueInstruction(Constant *Agg, Constant *Val, ArrayRef< unsigned > Idxs)
ConstantFoldInsertValueInstruction - Attempt to constant fold an insertvalue instruction with the spe...
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition: Type.h:202
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition: Value.cpp:429
static const fltSemantics & IEEEdouble() LLVM_READNONE
Definition: APFloat.cpp:122
static Constant * getUDiv(Constant *C1, Constant *C2, bool isExact=false)
Definition: Constants.cpp:2270
static Function * getFunction(Constant *C)
Definition: Evaluator.cpp:220
unsigned getBitWidth() const
Get the number of bits in this IntegerType.
Definition: DerivedTypes.h:65
Constant(Type *ty, ValueTy vty, Use *Ops, unsigned NumOps)
Definition: Constant.h:43
bool isMinSignedValue() const
Return true if the value is the smallest signed value.
Definition: Constants.cpp:151
static Constant * getFDiv(Constant *C1, Constant *C2)
Definition: Constants.cpp:2280
static APFloat getInf(const fltSemantics &Sem, bool Negative=false)
Factory for Positive and Negative Infinity.
Definition: APFloat.h:863
Type * getElementType() const
Return the element type of the array/vector.
Definition: Constants.cpp:2420
Value * getOperand(unsigned i) const
Definition: User.h:169
void removeDeadConstantUsers() const
If there are any dead constant users dangling off of this constant, remove them.
Definition: Constants.cpp:536
Class to represent pointers.
Definition: DerivedTypes.h:498
Constant * getAggregateElement(unsigned Elt) const
For aggregates (struct/array/vector) return the constant that corresponds to the specified element if...
Definition: Constants.cpp:334
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return &#39;this&#39;.
Definition: Type.h:303
bool isZeroValue() const
Return true if the value is negative zero or null value.
Definition: Constants.cpp:64
11: Arbitrary bit width integers
Definition: Type.h:70
static Constant * getBitCast(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:1772
static bool removeDeadUsersOfConstant(const Constant *C)
If the specified constantexpr is dead, remove it.
Definition: Constants.cpp:521
bool isFloatTy() const
Return true if this is &#39;float&#39;, a 32-bit IEEE fp type.
Definition: Type.h:146
bool isThreadDependent() const
Return true if the value can vary between threads.
Definition: Constants.cpp:462
DenseMap< PointerType *, std::unique_ptr< ConstantPointerNull > > CPNConstants
static Constant * getInsertValue(Constant *Agg, Constant *Val, ArrayRef< unsigned > Idxs, Type *OnlyIfReducedTy=nullptr)
Definition: Constants.cpp:2170
static bool ConstHasGlobalValuePredicate(const Constant *C, bool(*Predicate)(const GlobalValue *))
Check if C contains a GlobalValue for which Predicate is true.
Definition: Constants.cpp:439
Constant * ConstantFoldShuffleVectorInstruction(Constant *V1, Constant *V2, Constant *Mask)
Attempt to constant fold a shufflevector instruction with the specified operands and indices...
static Constant * getFNeg(Constant *C)
Definition: Constants.cpp:2225
static Constant * getFRem(Constant *C1, Constant *C2)
Definition: Constants.cpp:2292
const Use * getOperandList() const
Definition: User.h:162
static Constant * getImpl(StringRef Bytes, Type *Ty)
This is the underlying implementation of all of the ConstantDataSequential::get methods.
Definition: Constants.cpp:2473
static ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
Definition: Constants.cpp:1400
An array constant whose element type is a simple 1/2/4/8-byte integer or float/double, and whose elements are just simple data values (i.e.
Definition: Constants.h:689
LLVM Basic Block Representation.
Definition: BasicBlock.h:57
Constant * getSplatValue() const
If this is a splat constant, meaning that all of the elements have the same value, return that value.
Definition: Constants.cpp:2797
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:45
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:68
static Constant * getFP(LLVMContext &Context, ArrayRef< uint16_t > Elts)
getFP() constructors - Return a constant with array type with an element count and element type of fl...
Definition: Constants.cpp:2547
A constant token which is empty.
Definition: Constants.h:817
Constant * getWithOperandReplaced(unsigned OpNo, Constant *Op) const
Return a constant expression identical to this one, but with the specified operand set to the specifi...
Definition: Constants.cpp:1192
static ExtractValueInst * Create(Value *Agg, ArrayRef< unsigned > Idxs, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
static BlockAddress * get(Function *F, BasicBlock *BB)
Return a BlockAddress for the specified function and basic block.
Definition: Constants.cpp:1433
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:148
const char * getOpcodeName() const
Definition: Instruction.h:127
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This is an important base class in LLVM.
Definition: Constant.h:41
This file contains the declarations for the subclasses of Constant, which represent the different fla...
10: Tokens
Definition: Type.h:66
static Constant * getFP(LLVMContext &Context, ArrayRef< uint16_t > Elts)
getFP() constructors - Return a constant with vector type with an element count and element type of f...
Definition: Constants.cpp:2618
static Constant * getAnd(Constant *C1, Constant *C2)
Definition: Constants.cpp:2296
bool hasIndices() const
Return true if this is an insertvalue or extractvalue expression, and the getIndices() method may be ...
Definition: Constants.cpp:1174
ConstantFP - Floating Point Values [float, double].
Definition: Constants.h:263
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:370
static Constant * getSExtOrBitCast(Constant *C, Type *Ty)
Definition: Constants.cpp:1574
float getElementAsFloat(unsigned i) const
If this is an sequential container of floats, return the specified element as a float.
Definition: Constants.cpp:2748
LLVM_NODISCARD size_t find(char C, size_t From=0) const
Search for the first character C in the string.
Definition: StringRef.h:285
bool isDLLImportDependent() const
Return true if the value is dependent on a dllimport variable.
Definition: Constants.cpp:469
static Constant * getShuffleVector(Constant *V1, Constant *V2, Constant *Mask, Type *OnlyIfReducedTy=nullptr)
Definition: Constants.cpp:2147
op_iterator op_end()
Definition: User.h:231
const char * getOpcodeName() const
Return a string representation for an opcode.
Definition: Constants.cpp:2391
bool isHalfTy() const
Return true if this is &#39;half&#39;, a 16-bit IEEE fp type.
Definition: Type.h:143
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition: InstrTypes.h:646
bool isBinaryOp() const
Definition: Instruction.h:130
static Constant * getBinOpIdentity(unsigned Opcode, Type *Ty, bool AllowRHSConstant=false)
Return the identity constant for a binary opcode.
Definition: Constants.cpp:2325
6: 128-bit floating point type (two 64-bits, PowerPC)
Definition: Type.h:62
static Constant * get(StructType *T, ArrayRef< Constant *> V)
Definition: Constants.cpp:1043
op_range operands()
Definition: User.h:237
0 1 1 1 True if ordered (no nans)
Definition: InstrTypes.h:655
unsigned getStructNumElements() const
Definition: DerivedTypes.h:360
static bool isValueValidForType(Type *Ty, const APFloat &V)
Return true if Ty is big enough to represent V.
Definition: Constants.cpp:1280
unsigned getAddressSpace() const
Return the address space of the Pointer type.
Definition: DerivedTypes.h:526
static Constant * getICmp(unsigned short pred, Constant *LHS, Constant *RHS, bool OnlyIfReduced=false)
get* - Return some common constants without having to specify the full Instruction::OPCODE identifier...
Definition: Constants.cpp:2052
static const fltSemantics & x87DoubleExtended() LLVM_READNONE
Definition: APFloat.cpp:128
Class to represent integer types.
Definition: DerivedTypes.h:39
Constant Vector Declarations.
Definition: Constants.h:499
bool isNegativeZeroValue() const
Return true if the value is what would be returned by getZeroValueForNegation.
Definition: Constants.cpp:38
static Constant * getQNaN(Type *Ty, bool Negative=false, APInt *Payload=nullptr)
Definition: Constants.cpp:736
static Constant * getSplat(unsigned NumElts, Constant *Elt)
Return a ConstantVector with the specified constant in each element.
Definition: Constants.cpp:2637
static Constant * getNot(Constant *C)
Definition: Constants.cpp:2231
static Constant * getAllOnesValue(Type *Ty)
Definition: Constants.cpp:318
1 1 1 1 Always true (always folded)
Definition: InstrTypes.h:663
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function. ...
Definition: Function.cpp:192
static bool isElementTypeCompatible(Type *Ty)
Return true if a ConstantDataSequential can be formed with a vector or array of the specified element...
Definition: Constants.cpp:2428
bool isIntN(unsigned N, int64_t x)
Checks if an signed integer fits into the given (dynamic) bit width.
Definition: MathExtras.h:397
static const fltSemantics * TypeToFloatSemantics(Type *Ty)
Definition: Constants.cpp:668
static UndefValue * get(Type *T)
Static factory methods - Return an &#39;undef&#39; object of the specified type.
Definition: Constants.cpp:1414
const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs, and aliases.
Definition: Value.cpp:529
bool isCast() const
Definition: Instruction.h:133
LLVM_NODISCARD char back() const
back - Get the last character in the string.
Definition: StringRef.h:141
static PointerType * getInt8PtrTy(LLVMContext &C, unsigned AS=0)
Definition: Type.cpp:219
Constant * getWithOperands(ArrayRef< Constant *> Ops) const
This returns the current constant expression with the operands replaced with the specified values...
Definition: Constants.h:1229
Constant * ConstantFoldBinaryInstruction(unsigned Opcode, Constant *V1, Constant *V2)
Constant * getSplatValue() const
If this is a splat vector constant, meaning that all of the elements have the same value...
Definition: Constants.cpp:1367
1 1 0 1 True if unordered, less than, or equal
Definition: InstrTypes.h:661
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
VectorConstantsTy VectorConstants
const T * data() const
Definition: ArrayRef.h:145
unsigned char SubclassOptionalData
Hold subclass data that can be dropped.
Definition: Value.h:90
LLVMContextImpl *const pImpl
Definition: LLVMContext.h:70
signed greater than
Definition: InstrTypes.h:673
static Type * getFP128Ty(LLVMContext &C)
Definition: Type.cpp:168
static Constant * getIntegerValue(Type *Ty, const APInt &V)
Return the value for an integer or pointer constant, or a vector thereof, with the given scalar value...
Definition: Constants.cpp:301
bool isNormalFP() const
Return true if this is a normal (as opposed to denormal) floating-point scalar constant or a vector c...
Definition: Constants.cpp:214
hexagon gen pred
14: Arrays
Definition: Type.h:73
static Constant * getFCmp(unsigned short pred, Constant *LHS, Constant *RHS, bool OnlyIfReduced=false)
Definition: Constants.cpp:2077
0 0 1 0 True if ordered and greater than
Definition: InstrTypes.h:650
static Constant * getPointerCast(Constant *C, Type *Ty)
Create a BitCast, AddrSpaceCast, or a PtrToInt cast constant expression.
Definition: Constants.cpp:1586
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches, switches, etc.
Definition: BasicBlock.h:391
static bool isUndef(ArrayRef< int > Mask)
static Constant * getSIToFP(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:1713
static Type * getHalfTy(LLVMContext &C)
Definition: Type.cpp:162
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
Definition: Type.h:226
static Constant * getSplat(unsigned NumElts, Constant *Elt)
Return a ConstantVector with the specified constant in each element.
Definition: Constants.cpp:1118
static IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition: Type.cpp:239
Type * getSequentialElementType() const
Definition: Type.h:357
void setHasNoSignedWrap(bool b=true)
Set or clear the nsw flag on this instruction, which must be an operator which supports this flag...
static const fltSemantics & IEEEsingle() LLVM_READNONE
Definition: APFloat.cpp:119
static bool isAllZeros(StringRef Arr)
Return true if the array is empty or all zeros.
Definition: Constants.cpp:2462
Predicate getPredicate(unsigned Condition, unsigned Hint)
Return predicate consisting of specified condition and hint bits.
Definition: PPCPredicates.h:87
unsigned getNumOperands() const
Definition: User.h:191
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
Definition: SmallPtrSet.h:417
static PointerType * getUnqual(Type *ElementType)
This constructs a pointer to an object of the specified type in the generic address space (address sp...
Definition: DerivedTypes.h:513
This is the shared class of boolean and integer constants.
Definition: Constants.h:83
auto size(R &&Range, typename std::enable_if< std::is_same< typename std::iterator_traits< decltype(Range.begin())>::iterator_category, std::random_access_iterator_tag >::value, void >::type *=nullptr) -> decltype(std::distance(Range.begin(), Range.end()))
Get the size of a range.
Definition: STLExtras.h:1166
BlockVerifier::State From
static const fltSemantics & IEEEhalf() LLVM_READNONE
Definition: APFloat.cpp:116
16: SIMD &#39;packed&#39; format, or other vector type
Definition: Type.h:75
static Constant * getSDiv(Constant *C1, Constant *C2, bool isExact=false)
Definition: Constants.cpp:2275
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type...
Definition: Type.cpp:129
bool containsUndefElement() const
Return true if this is a vector constant that includes any undefined elements.
Definition: Constants.cpp:253
1 1 0 0 True if unordered or less than
Definition: InstrTypes.h:660
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:839
uint64_t getElementAsInteger(unsigned i) const
If this is a sequential container of integers (of any size), return the specified element in the low ...
Definition: Constants.cpp:2679
Module.h This file contains the declarations for the Module class.
bool isCString() const
This method returns true if the array "isString", ends with a null byte, and does not contains any ot...
Definition: Constants.cpp:2772
A constant pointer value that points to null.
Definition: Constants.h:538
Predicate
Predicate - These are "(BI << 5) | BO" for various predicates.
Definition: PPCPredicates.h:26
iterator end() const
Definition: ArrayRef.h:137
signed less than
Definition: InstrTypes.h:675
LLVM_NODISCARD T pop_back_val()
Definition: SmallVector.h:373
CHAIN = SC CHAIN, Imm128 - System call.
static Constant * getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:1636
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
Definition: Constants.cpp:621
static ConstantInt * getSigned(IntegerType *Ty, int64_t V)
Return a ConstantInt with the specified value for the specified type.
Definition: Constants.cpp:635
static Constant * get(Type *Ty, double V)
This returns a ConstantFP, or a vector containing a splat of a ConstantFP, for the specified value in...
Definition: Constants.cpp:684
static ConstantInt * getTrue(LLVMContext &Context)
Definition: Constants.cpp:577
ValueTy
Concrete subclass of this.
Definition: Value.h:444
bool isCommutative() const
Return true if the instruction is commutative:
Definition: Instruction.h:491
void handleOperandChange(Value *, Value *)
This method is a special form of User::replaceUsesOfWith (which does not work on constants) that does...
Definition: Constants.cpp:2816
void setOperand(unsigned i, Value *Val)
Definition: User.h:174
static BlockAddress * lookup(const BasicBlock *BB)
Lookup an existing BlockAddress constant for the given BasicBlock.
Definition: Constants.cpp:1451
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
unsigned getVectorNumElements() const
Definition: DerivedTypes.h:493
bool isIntPredicate() const
Definition: InstrTypes.h:739
signed less or equal
Definition: InstrTypes.h:676
StringMap - This is an unconventional map that is specialized for handling keys that are "strings"...
Definition: StringMap.h:219
Class to represent vector types.
Definition: DerivedTypes.h:424
Class for arbitrary precision integers.
Definition: APInt.h:69
Constant * getSplatValue() const
If this is a splat constant, meaning that all of the elements have the same value, return that value.
Definition: Constants.cpp:1378
static APFloat getSNaN(const fltSemantics &Sem, bool Negative=false, const APInt *payload=nullptr)
Factory for SNaN values.
Definition: APFloat.h:893
bool isSplat() const
Returns true if this is a splat constant, meaning that all elements have the same value...
Definition: Constants.cpp:2785
static BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), Instruction *InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
iterator_range< user_iterator > users()
Definition: Value.h:399
static Constant * getFPToUI(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:1724
static Constant * getCast(unsigned ops, Constant *C, Type *Ty, bool OnlyIfReduced=false)
Convenience function for getting a Cast operation.
Definition: Constants.cpp:1529
static char getTypeID(Type *Ty)
ArrayRef< T > slice(size_t N, size_t M) const
slice(n, m) - Chop off the first N elements of the array, and keep M elements in the array...
Definition: ArrayRef.h:178
iterator begin() const
Definition: StringRef.h:101
static Constant * getZExtOrBitCast(Constant *C, Type *Ty)
Definition: Constants.cpp:1568
void append(in_iter in_start, in_iter in_end)
Add the specified range to the end of the SmallVector.
Definition: SmallVector.h:386
Common super class of ArrayType, StructType and VectorType.
Definition: DerivedTypes.h:193
bool isX86_FP80Ty() const
Return true if this is x86 long double.
Definition: Type.h:152
user_iterator_impl< const User > const_user_iterator
Definition: Value.h:369
static Constant * getFSub(Constant *C1, Constant *C2)
Definition: Constants.cpp:2255
static Constant * getTruncOrBitCast(Constant *C, Type *Ty)
Definition: Constants.cpp:1580
static cl::opt< ITMode > IT(cl::desc("IT block support"), cl::Hidden, cl::init(DefaultIT), cl::ZeroOrMore, cl::values(clEnumValN(DefaultIT, "arm-default-it", "Generate IT block based on arch"), clEnumValN(RestrictedIT, "arm-restrict-it", "Disallow deprecated IT based on ARMv8"), clEnumValN(NoRestrictedIT, "arm-no-restrict-it", "Allow IT blocks based on ARMv7")))
static Constant * getIntSequenceIfElementsMatch(ArrayRef< Constant *> V)
Definition: Constants.cpp:909
static const fltSemantics & PPCDoubleDouble() LLVM_READNONE
Definition: APFloat.cpp:134
static Constant * getNeg(Constant *C, bool HasNUW=false, bool HasNSW=false)
Definition: Constants.cpp:2218
Constant * ConstantFoldCompareInstruction(unsigned short predicate, Constant *C1, Constant *C2)
static CastInst * Create(Instruction::CastOps, Value *S, Type *Ty, const Twine &Name="", Instruction *InsertBefore=nullptr)
Provides a way to construct any of the CastInst subclasses using an opcode instead of the subclass&#39;s ...
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
Definition: Lint.cpp:545
Constant * ConstantFoldSelectInstruction(Constant *Cond, Constant *V1, Constant *V2)
Attempt to constant fold a select instruction with the specified operands.
static Constant * getNaN(Type *Ty, bool Negative=false, uint64_t Payload=0)
Definition: Constants.cpp:725
Merge contiguous icmps into a memcmp
Definition: MergeICmps.cpp:866
static const size_t npos
Definition: StringRef.h:50
APFloat getElementAsAPFloat(unsigned i) const
If this is a sequential container of floating point type, return the specified element as an APFloat...
Definition: Constants.cpp:2727
static Type * getIndexedType(Type *Ty, ArrayRef< Value *> IdxList)
Returns the type of the element that would be loaded with a load instruction with the specified param...
static IntegerType * getInt32Ty(LLVMContext &C)
Definition: Type.cpp:175
unsigned getIntegerBitWidth() const
Definition: DerivedTypes.h:96
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:55
static Constant * getOffsetOf(StructType *STy, unsigned FieldNo)
getOffsetOf constant expr - computes the offset of a struct field in a target independent way (Note: ...
Definition: Constants.cpp:1937
unsigned greater or equal
Definition: InstrTypes.h:670
static InsertValueInst * Create(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
double getElementAsDouble(unsigned i) const
If this is an sequential container of doubles, return the specified element as a double.
Definition: Constants.cpp:2754
const Function * getParent() const
Return the enclosing method, or null if none.
Definition: BasicBlock.h:106
static Constant * getPtrToInt(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:1746
#define I(x, y, z)
Definition: MD5.cpp:58
static Constant * getOr(Constant *C1, Constant *C2)
Definition: Constants.cpp:2300
static Constant * getZeroValueForNegation(Type *Ty)
Floating point negation must be implemented with f(x) = -0.0 - x.
Definition: Constants.cpp:770
Constant * ConstantFoldInsertElementInstruction(Constant *Val, Constant *Elt, Constant *Idx)
Attempt to constant fold an insertelement instruction with the specified operands and indices...
bool isCompare() const
Return true if this is a compare constant expression.
Definition: Constants.cpp:1148
0 1 1 0 True if ordered and operands are unequal
Definition: InstrTypes.h:654
static ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
Definition: Type.cpp:580
Compile-time customization of User operands.
Definition: User.h:42
DenseMap< Type *, std::unique_ptr< ConstantAggregateZero > > CAZConstants
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:322
static Constant * getShl(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
Definition: Constants.cpp:2308
void destroyConstant()
Called if some element of this constant is no longer valid.
Definition: Constants.cpp:361
static ConstantTokenNone * get(LLVMContext &Context)
Return the ConstantTokenNone.
Definition: Constants.cpp:1129
ConstantUniqueMap< ConstantExpr > ExprConstants
1 0 1 0 True if unordered or greater than
Definition: InstrTypes.h:658
Constant * ConstantFoldGetElementPtr(Type *Ty, Constant *C, bool InBounds, Optional< unsigned > InRangeIndex, ArrayRef< Value *> Idxs)
Constant * getStructElement(unsigned Elt) const
If this CAZ has struct type, return a zero with the right element type for the specified element...
Definition: Constants.cpp:840
ArrayRef< unsigned > getIndices() const
Assert that this is an insertvalue or exactvalue expression and return the list of indices...
Definition: Constants.cpp:1179
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
Definition: Type.h:184
bool isOneValue() const
Returns true if the value is one.
Definition: Constants.cpp:125
void setHasNoUnsignedWrap(bool b=true)
Set or clear the nuw flag on this instruction, which must be an operator which supports this flag...
3: 64-bit floating point type
Definition: Type.h:59
LLVM_NODISCARD const char * data() const
data - Get a pointer to the start of the string (which may not be null terminated).
Definition: StringRef.h:122
static GetElementPtrInst * CreateInBounds(Value *Ptr, ArrayRef< Value *> IdxList, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
Create an "inbounds" getelementptr.
Definition: Instructions.h:933
static Constant * getSNaN(Type *Ty, bool Negative=false, APInt *Payload=nullptr)
Definition: Constants.cpp:747
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
user_iterator user_begin()
Definition: Value.h:375
static Constant * getSRem(Constant *C1, Constant *C2)
Definition: Constants.cpp:2288
Base class for aggregate constants (with operands).
Definition: Constants.h:389
unsigned getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition: Type.cpp:114
0 0 0 1 True if ordered and equal
Definition: InstrTypes.h:649
StructConstantsTy StructConstants
LLVM Value Representation.
Definition: Value.h:72
1 0 1 1 True if unordered, greater than, or equal
Definition: InstrTypes.h:659
DenseMap< Type *, std::unique_ptr< UndefValue > > UVConstants
LLVM_NODISCARD StringRef drop_back(size_t N=1) const
Return a StringRef equal to &#39;this&#39; but with the last N elements dropped.
Definition: StringRef.h:628
static Constant * getURem(Constant *C1, Constant *C2)
Definition: Constants.cpp:2284
static VectorType * get(Type *ElementType, unsigned NumElements)
This static method is the primary way to construct an VectorType.
Definition: Type.cpp:605
static StructType * getTypeForElements(ArrayRef< Constant *> V, bool Packed=false)
Return an anonymous struct type to use for a constant with the specified set of elements.
Definition: Constants.cpp:1029
bool hasExactInverseFP() const
Return true if this scalar has an exact multiplicative inverse or this vector has an exact multiplica...
Definition: Constants.cpp:227
std::underlying_type< E >::type Mask()
Get a bitmask with 1s in all places up to the high-order bit of E&#39;s largest value.
Definition: BitmaskEnum.h:80
static Constant * getUIToFP(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:1702
static Constant * getFPToSI(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:1735
bool isCast() const
Return true if this is a convert constant expression.
Definition: Constants.cpp:1144
ConstantClass * getOrCreate(TypeClass *Ty, ValType V)
Return the specified constant from the map, creating it if necessary.
unsigned getNumElements() const
Return the number of elements in the array, vector, or struct.
Definition: Constants.cpp:889
Type * getElementType() const
Definition: DerivedTypes.h:391
bool isExactlyValue(const APFloat &V) const
We don&#39;t rely on operator== working on double values, as it returns true for things that are clearly ...
Definition: Constants.cpp:823
bool isNotMinSignedValue() const
Return true if the value is not the smallest signed value.
Definition: Constants.cpp:177
static Constant * getExtractValue(Constant *Agg, ArrayRef< unsigned > Idxs, Type *OnlyIfReducedTy=nullptr)
Definition: Constants.cpp:2194
unsigned greater than
Definition: InstrTypes.h:669
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:48
Constant * ConstantFoldExtractValueInstruction(Constant *Agg, ArrayRef< unsigned > Idxs)
Attempt to constant fold an extractvalue instruction with the specified operands and indices...
static bool isSplat(ArrayRef< Value *> VL)
Use & Op()
Definition: User.h:133
unsigned getNumElements() const
Return the number of elements in the array or vector.
Definition: Constants.cpp:2443
static APInt getNullValue(unsigned numBits)
Get the &#39;0&#39; value.
Definition: APInt.h:568
static Constant * getAlignOf(Type *Ty)
getAlignOf constant expr - computes the alignment of a type in a target independent way (Note: the re...
Definition: Constants.cpp:1924
static Constant * getMul(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
Definition: Constants.cpp:2259
static Constant * get(LLVMContext &Context, ArrayRef< uint8_t > Elts)
get() constructors - Return a constant with vector type with an element count and element type matchi...
Definition: Constants.cpp:2582
static LazyValueInfoImpl & getImpl(void *&PImpl, AssumptionCache *AC, const DataLayout *DL, DominatorTree *DT=nullptr)
This lazily constructs the LazyValueInfoImpl.
static bool canTrapImpl(const Constant *C, SmallPtrSetImpl< const ConstantExpr *> &NonTrappingOps)
Definition: Constants.cpp:401
static ExtractElementInst * Create(Value *Vec, Value *Idx, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
bool isUIntN(unsigned N, uint64_t x)
Checks if an unsigned integer fits into the given (dynamic) bit width.
Definition: MathExtras.h:392
OutputIt copy(R &&Range, OutputIt Out)
Definition: STLExtras.h:1237
0 0 1 1 True if ordered and greater than or equal
Definition: InstrTypes.h:651
iterator end() const
Definition: StringRef.h:103
static Constant * getFPExtend(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:1690
UndefValue * getStructElement(unsigned Elt) const
If this undef has struct type, return a undef with the right element type for the specified element...
Definition: Constants.cpp:873
Constant * getSequentialElement() const
If this CAZ has array or vector type, return a zero with the right element type.
Definition: Constants.cpp:836
bool isDoubleTy() const
Return true if this is &#39;double&#39;, a 64-bit IEEE fp type.
Definition: Type.h:149
StringMap< ConstantDataSequential * > CDSConstants
Base class for constants with no operands.
Definition: Constants.h:57
ConstantAggregate(CompositeType *T, ValueTy VT, ArrayRef< Constant *> V)
Definition: Constants.cpp:961
bool isUnaryOp() const
Definition: Instruction.h:129
static Constant * getBinOpAbsorber(unsigned Opcode, Type *Ty)
Return the absorbing element for the given binary operation, i.e.
Definition: Constants.cpp:2371
static IntegerType * getInt8Ty(LLVMContext &C)
Definition: Type.cpp:173
bool use_empty() const
Definition: Value.h:322
iterator end()
Definition: StringMap.h:317
static Constant * get(ArrayRef< Constant *> V)
Definition: Constants.cpp:1078
static APFloat getQNaN(const fltSemantics &Sem, bool Negative=false, const APInt *payload=nullptr)
Factory for QNaN values.
Definition: APFloat.h:885
Type * getElementType() const
Definition: DerivedTypes.h:517
UndefValue * getSequentialElement() const
If this Undef has array or vector type, return a undef with the right element type.
Definition: Constants.cpp:869
PointerType * getType() const
Global values are always pointers.
Definition: GlobalValue.h:273
0 0 0 0 Always false (always folded)
Definition: InstrTypes.h:648
bool isStructTy() const
True if this is an instance of StructType.
Definition: Type.h:217
signed greater or equal
Definition: InstrTypes.h:674
bool empty() const
empty - Check if the array is empty.
Definition: ArrayRef.h:143
User * user_back()
Definition: Value.h:385
bool isArrayTy() const
True if this is an instance of ArrayType.
Definition: Type.h:220
Type * getTypeAtIndex(const Value *V) const
Given an index value into the type, return the type of the element.
Definition: Type.cpp:529
static Constant * getXor(Constant *C1, Constant *C2)
Definition: Constants.cpp:2304
5: 128-bit floating point type (112-bit mantissa)
Definition: Type.h:61
gep_type_iterator gep_type_begin(const User *GEP)
bool isString(unsigned CharSize=8) const
This method returns true if this is an array of CharSize integers.
Definition: Constants.cpp:2768
static Constant * get(unsigned Opcode, Constant *C1, unsigned Flags=0, Type *OnlyIfReducedTy=nullptr)
get - Return a unary operator constant expression, folding if possible.
Definition: Constants.cpp:1805
static const char * areInvalidOperands(Value *Cond, Value *True, Value *False)
Return a string if the specified operands are invalid for a select operation, otherwise return null...
user_iterator user_end()
Definition: Value.h:383