blob: 1d2602aef137f4e80dcd581f976b24db97370083 [file] [log] [blame]
Chris Lattner2b383d2e2003-05-13 21:37:02 +00001//===-- Constants.cpp - Implement Constant nodes --------------------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner2f7c9632001-06-06 20:29:01 +00009//
Chris Lattnere17322b2011-02-07 20:03:14 +000010// This file implements the Constant* classes.
Chris Lattner2f7c9632001-06-06 20:29:01 +000011//
12//===----------------------------------------------------------------------===//
13
Chandler Carruth9fb823b2013-01-02 11:36:10 +000014#include "llvm/IR/Constants.h"
Chris Lattner33e93b82007-02-27 03:05:06 +000015#include "ConstantFold.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000016#include "LLVMContextImpl.h"
17#include "llvm/ADT/DenseMap.h"
18#include "llvm/ADT/FoldingSet.h"
19#include "llvm/ADT/STLExtras.h"
20#include "llvm/ADT/SmallVector.h"
21#include "llvm/ADT/StringExtras.h"
22#include "llvm/ADT/StringMap.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000023#include "llvm/IR/DerivedTypes.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000024#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000025#include "llvm/IR/GlobalValue.h"
26#include "llvm/IR/Instructions.h"
27#include "llvm/IR/Module.h"
28#include "llvm/IR/Operator.h"
Chris Lattner3d27be12006-08-27 12:54:02 +000029#include "llvm/Support/Compiler.h"
Bill Wendling6a462f12006-11-17 08:03:48 +000030#include "llvm/Support/Debug.h"
Torok Edwinccb29cd2009-07-11 13:10:19 +000031#include "llvm/Support/ErrorHandling.h"
Chris Lattner69edc982006-09-28 00:35:06 +000032#include "llvm/Support/ManagedStatic.h"
Bill Wendling6a462f12006-11-17 08:03:48 +000033#include "llvm/Support/MathExtras.h"
Chris Lattner78683a72009-08-23 04:02:03 +000034#include "llvm/Support/raw_ostream.h"
Chris Lattner2f7c9632001-06-06 20:29:01 +000035#include <algorithm>
Talin3a0a30d2011-02-28 23:53:27 +000036#include <cstdarg>
Chris Lattner189d19f2003-11-21 20:23:48 +000037using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000038
Chris Lattner2f7c9632001-06-06 20:29:01 +000039//===----------------------------------------------------------------------===//
Chris Lattner3462ae32001-12-03 22:26:30 +000040// Constant Class
Chris Lattner2f7c9632001-06-06 20:29:01 +000041//===----------------------------------------------------------------------===//
42
David Blaikiea379b1812011-12-20 02:50:00 +000043void Constant::anchor() { }
44
Chris Lattnerac5fb562011-07-15 05:58:04 +000045bool Constant::isNegativeZeroValue() const {
46 // Floating point values have an explicit -0.0 value.
47 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
48 return CFP->isZero() && CFP->isNegative();
Galina Kistanovafc259902012-07-13 01:25:27 +000049
David Tweed5493fee2013-03-18 11:54:44 +000050 // Equivalent for a vector of -0.0's.
51 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
52 if (ConstantFP *SplatCFP = dyn_cast_or_null<ConstantFP>(CV->getSplatValue()))
53 if (SplatCFP && SplatCFP->isZero() && SplatCFP->isNegative())
54 return true;
55
David Tweed298e4192013-03-19 10:16:40 +000056 // We've already handled true FP case; any other FP vectors can't represent -0.0.
57 if (getType()->isFPOrFPVectorTy())
58 return false;
David Tweed5493fee2013-03-18 11:54:44 +000059
Chris Lattnerac5fb562011-07-15 05:58:04 +000060 // Otherwise, just use +0.0.
61 return isNullValue();
62}
63
Shuxin Yang9ca562e2013-01-09 00:53:25 +000064// Return true iff this constant is positive zero (floating point), negative
65// zero (floating point), or a null value.
Shuxin Yangf0537ab2013-01-09 00:13:41 +000066bool Constant::isZeroValue() const {
67 // Floating point values have an explicit -0.0 value.
68 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
69 return CFP->isZero();
70
71 // Otherwise, just use +0.0.
72 return isNullValue();
73}
74
Chris Lattnerbe6610c2011-07-15 06:14:08 +000075bool Constant::isNullValue() const {
76 // 0 is null.
77 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
78 return CI->isZero();
Galina Kistanovafc259902012-07-13 01:25:27 +000079
Chris Lattnerbe6610c2011-07-15 06:14:08 +000080 // +0.0 is null.
81 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
82 return CFP->isZero() && !CFP->isNegative();
83
84 // constant zero is zero for aggregates and cpnull is null for pointers.
85 return isa<ConstantAggregateZero>(this) || isa<ConstantPointerNull>(this);
86}
87
Nadav Rotem365af6f2011-08-24 20:18:38 +000088bool Constant::isAllOnesValue() const {
89 // Check for -1 integers
90 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
91 return CI->isMinusOne();
92
93 // Check for FP which are bitcasted from -1 integers
94 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
95 return CFP->getValueAPF().bitcastToAPInt().isAllOnesValue();
96
Benjamin Kramer42d098e2011-11-14 19:12:20 +000097 // Check for constant vectors which are splats of -1 values.
Nadav Rotem365af6f2011-08-24 20:18:38 +000098 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
Benjamin Kramer42d098e2011-11-14 19:12:20 +000099 if (Constant *Splat = CV->getSplatValue())
100 return Splat->isAllOnesValue();
Nadav Rotem365af6f2011-08-24 20:18:38 +0000101
Chris Lattnerf14a67f2012-01-26 02:31:22 +0000102 // Check for constant vectors which are splats of -1 values.
103 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
104 if (Constant *Splat = CV->getSplatValue())
105 return Splat->isAllOnesValue();
106
Nadav Rotem365af6f2011-08-24 20:18:38 +0000107 return false;
108}
Benjamin Kramer42d098e2011-11-14 19:12:20 +0000109
David Majnemer1a0bbc82014-08-16 09:23:42 +0000110bool Constant::isOneValue() const {
111 // Check for 1 integers
112 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
113 return CI->isOne();
114
115 // Check for FP which are bitcasted from 1 integers
116 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
117 return CFP->getValueAPF().bitcastToAPInt() == 1;
118
119 // Check for constant vectors which are splats of 1 values.
120 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
121 if (Constant *Splat = CV->getSplatValue())
122 return Splat->isOneValue();
123
124 // Check for constant vectors which are splats of 1 values.
125 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
126 if (Constant *Splat = CV->getSplatValue())
127 return Splat->isOneValue();
128
129 return false;
130}
131
David Majnemerbdeef602014-07-02 06:07:09 +0000132bool Constant::isMinSignedValue() const {
133 // Check for INT_MIN integers
134 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
135 return CI->isMinValue(/*isSigned=*/true);
136
137 // Check for FP which are bitcasted from INT_MIN integers
138 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
139 return CFP->getValueAPF().bitcastToAPInt().isMinSignedValue();
140
141 // Check for constant vectors which are splats of INT_MIN values.
142 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
143 if (Constant *Splat = CV->getSplatValue())
144 return Splat->isMinSignedValue();
145
146 // Check for constant vectors which are splats of INT_MIN values.
147 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
148 if (Constant *Splat = CV->getSplatValue())
149 return Splat->isMinSignedValue();
150
151 return false;
152}
153
David Majnemer0e6c9862014-08-22 16:41:23 +0000154bool Constant::isNotMinSignedValue() const {
155 // Check for INT_MIN integers
156 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
157 return !CI->isMinValue(/*isSigned=*/true);
158
159 // Check for FP which are bitcasted from INT_MIN integers
160 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
161 return !CFP->getValueAPF().bitcastToAPInt().isMinSignedValue();
162
163 // Check for constant vectors which are splats of INT_MIN values.
164 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
165 if (Constant *Splat = CV->getSplatValue())
166 return Splat->isNotMinSignedValue();
167
168 // Check for constant vectors which are splats of INT_MIN values.
169 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
170 if (Constant *Splat = CV->getSplatValue())
171 return Splat->isNotMinSignedValue();
172
173 // It *may* contain INT_MIN, we can't tell.
174 return false;
175}
176
Owen Anderson5a1acd92009-07-31 20:28:14 +0000177// Constructor to create a '0' constant of arbitrary type...
Chris Lattner229907c2011-07-18 04:54:35 +0000178Constant *Constant::getNullValue(Type *Ty) {
Owen Anderson5a1acd92009-07-31 20:28:14 +0000179 switch (Ty->getTypeID()) {
180 case Type::IntegerTyID:
181 return ConstantInt::get(Ty, 0);
Dan Gohman518cda42011-12-17 00:04:22 +0000182 case Type::HalfTyID:
183 return ConstantFP::get(Ty->getContext(),
184 APFloat::getZero(APFloat::IEEEhalf));
Owen Anderson5a1acd92009-07-31 20:28:14 +0000185 case Type::FloatTyID:
Benjamin Kramer8ceebfa2010-12-04 14:22:24 +0000186 return ConstantFP::get(Ty->getContext(),
187 APFloat::getZero(APFloat::IEEEsingle));
Owen Anderson5a1acd92009-07-31 20:28:14 +0000188 case Type::DoubleTyID:
Benjamin Kramer8ceebfa2010-12-04 14:22:24 +0000189 return ConstantFP::get(Ty->getContext(),
190 APFloat::getZero(APFloat::IEEEdouble));
Owen Anderson5a1acd92009-07-31 20:28:14 +0000191 case Type::X86_FP80TyID:
Benjamin Kramer8ceebfa2010-12-04 14:22:24 +0000192 return ConstantFP::get(Ty->getContext(),
193 APFloat::getZero(APFloat::x87DoubleExtended));
Owen Anderson5a1acd92009-07-31 20:28:14 +0000194 case Type::FP128TyID:
195 return ConstantFP::get(Ty->getContext(),
Benjamin Kramer8ceebfa2010-12-04 14:22:24 +0000196 APFloat::getZero(APFloat::IEEEquad));
Owen Anderson5a1acd92009-07-31 20:28:14 +0000197 case Type::PPC_FP128TyID:
Benjamin Kramer8ceebfa2010-12-04 14:22:24 +0000198 return ConstantFP::get(Ty->getContext(),
Tim Northover29178a32013-01-22 09:46:31 +0000199 APFloat(APFloat::PPCDoubleDouble,
200 APInt::getNullValue(128)));
Owen Anderson5a1acd92009-07-31 20:28:14 +0000201 case Type::PointerTyID:
202 return ConstantPointerNull::get(cast<PointerType>(Ty));
203 case Type::StructTyID:
204 case Type::ArrayTyID:
205 case Type::VectorTyID:
206 return ConstantAggregateZero::get(Ty);
207 default:
208 // Function, Label, or Opaque type?
Craig Topperc514b542012-02-05 22:14:15 +0000209 llvm_unreachable("Cannot create a null constant of that type!");
Owen Anderson5a1acd92009-07-31 20:28:14 +0000210 }
211}
212
Chris Lattner229907c2011-07-18 04:54:35 +0000213Constant *Constant::getIntegerValue(Type *Ty, const APInt &V) {
214 Type *ScalarTy = Ty->getScalarType();
Dan Gohmanf011f5a2009-08-03 22:07:33 +0000215
216 // Create the base integer constant.
217 Constant *C = ConstantInt::get(Ty->getContext(), V);
218
219 // Convert an integer to a pointer, if necessary.
Chris Lattner229907c2011-07-18 04:54:35 +0000220 if (PointerType *PTy = dyn_cast<PointerType>(ScalarTy))
Dan Gohmanf011f5a2009-08-03 22:07:33 +0000221 C = ConstantExpr::getIntToPtr(C, PTy);
222
223 // Broadcast a scalar to a vector, if necessary.
Chris Lattner229907c2011-07-18 04:54:35 +0000224 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
Chris Lattnere9eed292012-01-25 05:19:54 +0000225 C = ConstantVector::getSplat(VTy->getNumElements(), C);
Dan Gohmanf011f5a2009-08-03 22:07:33 +0000226
227 return C;
228}
229
Chris Lattner229907c2011-07-18 04:54:35 +0000230Constant *Constant::getAllOnesValue(Type *Ty) {
231 if (IntegerType *ITy = dyn_cast<IntegerType>(Ty))
Owen Anderson5a1acd92009-07-31 20:28:14 +0000232 return ConstantInt::get(Ty->getContext(),
233 APInt::getAllOnesValue(ITy->getBitWidth()));
Nadav Rotem7cc6d122011-02-17 21:22:27 +0000234
235 if (Ty->isFloatingPointTy()) {
236 APFloat FL = APFloat::getAllOnesValue(Ty->getPrimitiveSizeInBits(),
237 !Ty->isPPC_FP128Ty());
238 return ConstantFP::get(Ty->getContext(), FL);
239 }
240
Chris Lattner229907c2011-07-18 04:54:35 +0000241 VectorType *VTy = cast<VectorType>(Ty);
Chris Lattnere9eed292012-01-25 05:19:54 +0000242 return ConstantVector::getSplat(VTy->getNumElements(),
243 getAllOnesValue(VTy->getElementType()));
Owen Anderson5a1acd92009-07-31 20:28:14 +0000244}
245
Chris Lattner7e683d12012-01-25 06:16:32 +0000246/// getAggregateElement - For aggregates (struct/array/vector) return the
247/// constant that corresponds to the specified element if possible, or null if
248/// not. This can return null if the element index is a ConstantExpr, or if
249/// 'this' is a constant expr.
250Constant *Constant::getAggregateElement(unsigned Elt) const {
251 if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(this))
Craig Topperc6207612014-04-09 06:08:46 +0000252 return Elt < CS->getNumOperands() ? CS->getOperand(Elt) : nullptr;
Galina Kistanovafc259902012-07-13 01:25:27 +0000253
Chris Lattner7e683d12012-01-25 06:16:32 +0000254 if (const ConstantArray *CA = dyn_cast<ConstantArray>(this))
Craig Topperc6207612014-04-09 06:08:46 +0000255 return Elt < CA->getNumOperands() ? CA->getOperand(Elt) : nullptr;
Galina Kistanovafc259902012-07-13 01:25:27 +0000256
Chris Lattner7e683d12012-01-25 06:16:32 +0000257 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
Craig Topperc6207612014-04-09 06:08:46 +0000258 return Elt < CV->getNumOperands() ? CV->getOperand(Elt) : nullptr;
Galina Kistanovafc259902012-07-13 01:25:27 +0000259
Chris Lattner7e683d12012-01-25 06:16:32 +0000260 if (const ConstantAggregateZero *CAZ =dyn_cast<ConstantAggregateZero>(this))
261 return CAZ->getElementValue(Elt);
Galina Kistanovafc259902012-07-13 01:25:27 +0000262
Chris Lattner7e683d12012-01-25 06:16:32 +0000263 if (const UndefValue *UV = dyn_cast<UndefValue>(this))
264 return UV->getElementValue(Elt);
Galina Kistanovafc259902012-07-13 01:25:27 +0000265
Chris Lattner8326bd82012-01-26 00:42:34 +0000266 if (const ConstantDataSequential *CDS =dyn_cast<ConstantDataSequential>(this))
Craig Topperc6207612014-04-09 06:08:46 +0000267 return Elt < CDS->getNumElements() ? CDS->getElementAsConstant(Elt)
268 : nullptr;
269 return nullptr;
Chris Lattner7e683d12012-01-25 06:16:32 +0000270}
271
272Constant *Constant::getAggregateElement(Constant *Elt) const {
273 assert(isa<IntegerType>(Elt->getType()) && "Index must be an integer");
274 if (ConstantInt *CI = dyn_cast<ConstantInt>(Elt))
275 return getAggregateElement(CI->getZExtValue());
Craig Topperc6207612014-04-09 06:08:46 +0000276 return nullptr;
Chris Lattner7e683d12012-01-25 06:16:32 +0000277}
278
279
Chris Lattner3462ae32001-12-03 22:26:30 +0000280void Constant::destroyConstantImpl() {
281 // When a Constant is destroyed, there may be lingering
Chris Lattnerd7a73302001-10-13 06:57:33 +0000282 // references to the constant by other constants in the constant pool. These
Misha Brukmanbe372b92003-08-21 22:14:26 +0000283 // constants are implicitly dependent on the module that is being deleted,
Chris Lattnerd7a73302001-10-13 06:57:33 +0000284 // but they don't know that. Because we only find out when the CPV is
285 // deleted, we must now notify all of our users (that should only be
Chris Lattner3462ae32001-12-03 22:26:30 +0000286 // Constants) that they are, in fact, invalid now and should be deleted.
Chris Lattnerd7a73302001-10-13 06:57:33 +0000287 //
288 while (!use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000289 Value *V = user_back();
Chris Lattnerd7a73302001-10-13 06:57:33 +0000290#ifndef NDEBUG // Only in -g mode...
Chris Lattner78683a72009-08-23 04:02:03 +0000291 if (!isa<Constant>(V)) {
David Greene1e27a132010-01-05 01:29:19 +0000292 dbgs() << "While deleting: " << *this
Chris Lattner78683a72009-08-23 04:02:03 +0000293 << "\n\nUse still stuck around after Def is destroyed: "
294 << *V << "\n\n";
295 }
Chris Lattnerd7a73302001-10-13 06:57:33 +0000296#endif
Vikram S. Adve4e537b22002-07-14 23:13:17 +0000297 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
Chris Lattner8326bd82012-01-26 00:42:34 +0000298 cast<Constant>(V)->destroyConstant();
Chris Lattnerd7a73302001-10-13 06:57:33 +0000299
300 // The constant should remove itself from our use list...
Chandler Carruthcdf47882014-03-09 03:16:01 +0000301 assert((use_empty() || user_back() != V) && "Constant not removed!");
Chris Lattnerd7a73302001-10-13 06:57:33 +0000302 }
303
304 // Value has no outstanding references it is safe to delete it now...
305 delete this;
Chris Lattner38569342001-10-01 20:11:19 +0000306}
Chris Lattner2f7c9632001-06-06 20:29:01 +0000307
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +0000308static bool canTrapImpl(const Constant *C,
Craig Topper71b7b682014-08-21 05:55:13 +0000309 SmallPtrSetImpl<const ConstantExpr *> &NonTrappingOps) {
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +0000310 assert(C->getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
Chris Lattner23dd1f62006-10-20 00:27:06 +0000311 // The only thing that could possibly trap are constant exprs.
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +0000312 const ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
313 if (!CE)
314 return false;
Galina Kistanovafc259902012-07-13 01:25:27 +0000315
316 // ConstantExpr traps if any operands can trap.
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +0000317 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) {
318 if (ConstantExpr *Op = dyn_cast<ConstantExpr>(CE->getOperand(i))) {
David Blaikie70573dc2014-11-19 07:49:26 +0000319 if (NonTrappingOps.insert(Op).second && canTrapImpl(Op, NonTrappingOps))
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +0000320 return true;
321 }
322 }
Chris Lattner23dd1f62006-10-20 00:27:06 +0000323
324 // Otherwise, only specific operations can trap.
325 switch (CE->getOpcode()) {
326 default:
327 return false;
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000328 case Instruction::UDiv:
329 case Instruction::SDiv:
330 case Instruction::FDiv:
Reid Spencer7eb55b32006-11-02 01:53:59 +0000331 case Instruction::URem:
332 case Instruction::SRem:
333 case Instruction::FRem:
Chris Lattner23dd1f62006-10-20 00:27:06 +0000334 // Div and rem can trap if the RHS is not known to be non-zero.
Chris Lattnera91a5632009-10-28 05:14:34 +0000335 if (!isa<ConstantInt>(CE->getOperand(1)) ||CE->getOperand(1)->isNullValue())
Chris Lattner23dd1f62006-10-20 00:27:06 +0000336 return true;
337 return false;
338 }
339}
340
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +0000341/// canTrap - Return true if evaluation of this constant could trap. This is
342/// true for things like constant expressions that could divide by zero.
343bool Constant::canTrap() const {
344 SmallPtrSet<const ConstantExpr *, 4> NonTrappingOps;
345 return canTrapImpl(this, NonTrappingOps);
346}
347
Hans Wennborg4dc89512014-06-20 00:38:12 +0000348/// Check if C contains a GlobalValue for which Predicate is true.
349static bool
350ConstHasGlobalValuePredicate(const Constant *C,
351 bool (*Predicate)(const GlobalValue *)) {
352 SmallPtrSet<const Constant *, 8> Visited;
353 SmallVector<const Constant *, 8> WorkList;
354 WorkList.push_back(C);
355 Visited.insert(C);
Hans Wennborg709e0152012-11-15 11:40:00 +0000356
357 while (!WorkList.empty()) {
Hans Wennborg4dc89512014-06-20 00:38:12 +0000358 const Constant *WorkItem = WorkList.pop_back_val();
359 if (const auto *GV = dyn_cast<GlobalValue>(WorkItem))
360 if (Predicate(GV))
Hans Wennborg709e0152012-11-15 11:40:00 +0000361 return true;
Hans Wennborg4dc89512014-06-20 00:38:12 +0000362 for (const Value *Op : WorkItem->operands()) {
363 const Constant *ConstOp = dyn_cast<Constant>(Op);
364 if (!ConstOp)
Hans Wennborg18aa12402012-11-16 10:33:25 +0000365 continue;
David Blaikie70573dc2014-11-19 07:49:26 +0000366 if (Visited.insert(ConstOp).second)
Hans Wennborg4dc89512014-06-20 00:38:12 +0000367 WorkList.push_back(ConstOp);
Hans Wennborg709e0152012-11-15 11:40:00 +0000368 }
369 }
Hans Wennborg709e0152012-11-15 11:40:00 +0000370 return false;
371}
372
Hans Wennborg4dc89512014-06-20 00:38:12 +0000373/// Return true if the value can vary between threads.
374bool Constant::isThreadDependent() const {
375 auto DLLImportPredicate = [](const GlobalValue *GV) {
376 return GV->isThreadLocal();
377 };
378 return ConstHasGlobalValuePredicate(this, DLLImportPredicate);
379}
380
381bool Constant::isDLLImportDependent() const {
382 auto DLLImportPredicate = [](const GlobalValue *GV) {
383 return GV->hasDLLImportStorageClass();
384 };
385 return ConstHasGlobalValuePredicate(this, DLLImportPredicate);
386}
387
388/// Return true if the constant has users other than constant exprs and other
389/// dangling things.
Chris Lattner253bc772009-11-01 18:11:50 +0000390bool Constant::isConstantUsed() const {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000391 for (const User *U : users()) {
392 const Constant *UC = dyn_cast<Constant>(U);
Craig Topperc6207612014-04-09 06:08:46 +0000393 if (!UC || isa<GlobalValue>(UC))
Chris Lattner253bc772009-11-01 18:11:50 +0000394 return true;
Galina Kistanovafc259902012-07-13 01:25:27 +0000395
Chris Lattner253bc772009-11-01 18:11:50 +0000396 if (UC->isConstantUsed())
397 return true;
398 }
399 return false;
400}
401
402
Chris Lattner4565ef52009-07-22 00:05:44 +0000403
404/// getRelocationInfo - This method classifies the entry according to
405/// whether or not it may generate a relocation entry. This must be
406/// conservative, so if it might codegen to a relocatable entry, it should say
407/// so. The return values are:
408///
Chris Lattner5cd4dd32009-07-24 03:27:21 +0000409/// NoRelocation: This constant pool entry is guaranteed to never have a
410/// relocation applied to it (because it holds a simple constant like
411/// '4').
412/// LocalRelocation: This entry has relocations, but the entries are
413/// guaranteed to be resolvable by the static linker, so the dynamic
414/// linker will never see them.
415/// GlobalRelocations: This entry may have arbitrary relocations.
Chris Lattner4565ef52009-07-22 00:05:44 +0000416///
Chandler Carruthef860a22013-01-02 09:10:48 +0000417/// FIXME: This really should not be in IR.
Chris Lattner5cd4dd32009-07-24 03:27:21 +0000418Constant::PossibleRelocationsTy Constant::getRelocationInfo() const {
419 if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
Chris Lattner4565ef52009-07-22 00:05:44 +0000420 if (GV->hasLocalLinkage() || GV->hasHiddenVisibility())
Chris Lattner5cd4dd32009-07-24 03:27:21 +0000421 return LocalRelocation; // Local to this file/library.
422 return GlobalRelocations; // Global reference.
Anton Korobeynikov7437b592009-03-29 17:13:18 +0000423 }
Chris Lattner4565ef52009-07-22 00:05:44 +0000424
Chris Lattner2cb85b42009-10-28 04:12:16 +0000425 if (const BlockAddress *BA = dyn_cast<BlockAddress>(this))
426 return BA->getFunction()->getRelocationInfo();
427
Chris Lattnera7cfc432010-01-03 18:09:40 +0000428 // While raw uses of blockaddress need to be relocated, differences between
429 // two of them don't when they are for labels in the same function. This is a
430 // common idiom when creating a table for the indirect goto extension, so we
431 // handle it efficiently here.
432 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(this))
433 if (CE->getOpcode() == Instruction::Sub) {
434 ConstantExpr *LHS = dyn_cast<ConstantExpr>(CE->getOperand(0));
435 ConstantExpr *RHS = dyn_cast<ConstantExpr>(CE->getOperand(1));
436 if (LHS && RHS &&
437 LHS->getOpcode() == Instruction::PtrToInt &&
438 RHS->getOpcode() == Instruction::PtrToInt &&
439 isa<BlockAddress>(LHS->getOperand(0)) &&
440 isa<BlockAddress>(RHS->getOperand(0)) &&
441 cast<BlockAddress>(LHS->getOperand(0))->getFunction() ==
442 cast<BlockAddress>(RHS->getOperand(0))->getFunction())
443 return NoRelocation;
444 }
Galina Kistanovafc259902012-07-13 01:25:27 +0000445
Chris Lattner5cd4dd32009-07-24 03:27:21 +0000446 PossibleRelocationsTy Result = NoRelocation;
Evan Chengf9e003b2007-03-08 00:59:12 +0000447 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
Chris Lattnera91a5632009-10-28 05:14:34 +0000448 Result = std::max(Result,
449 cast<Constant>(getOperand(i))->getRelocationInfo());
Galina Kistanovafc259902012-07-13 01:25:27 +0000450
Chris Lattner4565ef52009-07-22 00:05:44 +0000451 return Result;
Evan Chengf9e003b2007-03-08 00:59:12 +0000452}
453
Chris Lattner84886402011-02-18 04:41:42 +0000454/// removeDeadUsersOfConstant - If the specified constantexpr is dead, remove
455/// it. This involves recursively eliminating any dead users of the
456/// constantexpr.
457static bool removeDeadUsersOfConstant(const Constant *C) {
458 if (isa<GlobalValue>(C)) return false; // Cannot remove this
Galina Kistanovafc259902012-07-13 01:25:27 +0000459
Chris Lattner84886402011-02-18 04:41:42 +0000460 while (!C->use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000461 const Constant *User = dyn_cast<Constant>(C->user_back());
Chris Lattner84886402011-02-18 04:41:42 +0000462 if (!User) return false; // Non-constant usage;
463 if (!removeDeadUsersOfConstant(User))
464 return false; // Constant wasn't dead
465 }
Galina Kistanovafc259902012-07-13 01:25:27 +0000466
Chris Lattner84886402011-02-18 04:41:42 +0000467 const_cast<Constant*>(C)->destroyConstant();
468 return true;
469}
470
471
472/// removeDeadConstantUsers - If there are any dead constant users dangling
473/// off of this constant, remove them. This method is useful for clients
474/// that want to check to see if a global is unused, but don't want to deal
475/// with potentially dead constants hanging off of the globals.
476void Constant::removeDeadConstantUsers() const {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000477 Value::const_user_iterator I = user_begin(), E = user_end();
478 Value::const_user_iterator LastNonDeadUser = E;
Chris Lattner84886402011-02-18 04:41:42 +0000479 while (I != E) {
480 const Constant *User = dyn_cast<Constant>(*I);
Craig Topperc6207612014-04-09 06:08:46 +0000481 if (!User) {
Chris Lattner84886402011-02-18 04:41:42 +0000482 LastNonDeadUser = I;
483 ++I;
484 continue;
485 }
Galina Kistanovafc259902012-07-13 01:25:27 +0000486
Chris Lattner84886402011-02-18 04:41:42 +0000487 if (!removeDeadUsersOfConstant(User)) {
488 // If the constant wasn't dead, remember that this was the last live use
489 // and move on to the next constant.
490 LastNonDeadUser = I;
491 ++I;
492 continue;
493 }
Galina Kistanovafc259902012-07-13 01:25:27 +0000494
Chris Lattner84886402011-02-18 04:41:42 +0000495 // If the constant was dead, then the iterator is invalidated.
496 if (LastNonDeadUser == E) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000497 I = user_begin();
Chris Lattner84886402011-02-18 04:41:42 +0000498 if (I == E) break;
499 } else {
500 I = LastNonDeadUser;
501 ++I;
502 }
503 }
504}
505
506
Chris Lattner2105d662008-07-10 00:28:11 +0000507
Chris Lattner2f7c9632001-06-06 20:29:01 +0000508//===----------------------------------------------------------------------===//
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000509// ConstantInt
Chris Lattner2f7c9632001-06-06 20:29:01 +0000510//===----------------------------------------------------------------------===//
511
David Blaikiea379b1812011-12-20 02:50:00 +0000512void ConstantInt::anchor() { }
513
Chris Lattner229907c2011-07-18 04:54:35 +0000514ConstantInt::ConstantInt(IntegerType *Ty, const APInt& V)
Craig Topperc6207612014-04-09 06:08:46 +0000515 : Constant(Ty, ConstantIntVal, nullptr, 0), Val(V) {
Reid Spencerb31bffe2007-02-26 23:54:03 +0000516 assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
Chris Lattner2f7c9632001-06-06 20:29:01 +0000517}
518
Nick Lewycky92db8e82011-03-06 03:36:19 +0000519ConstantInt *ConstantInt::getTrue(LLVMContext &Context) {
Owen Anderson23a204d2009-07-31 17:39:07 +0000520 LLVMContextImpl *pImpl = Context.pImpl;
Benjamin Kramerddd1b7b2010-11-20 18:43:35 +0000521 if (!pImpl->TheTrueVal)
522 pImpl->TheTrueVal = ConstantInt::get(Type::getInt1Ty(Context), 1);
523 return pImpl->TheTrueVal;
Owen Anderson23a204d2009-07-31 17:39:07 +0000524}
525
Nick Lewycky92db8e82011-03-06 03:36:19 +0000526ConstantInt *ConstantInt::getFalse(LLVMContext &Context) {
Owen Anderson23a204d2009-07-31 17:39:07 +0000527 LLVMContextImpl *pImpl = Context.pImpl;
Benjamin Kramerddd1b7b2010-11-20 18:43:35 +0000528 if (!pImpl->TheFalseVal)
529 pImpl->TheFalseVal = ConstantInt::get(Type::getInt1Ty(Context), 0);
530 return pImpl->TheFalseVal;
Owen Anderson23a204d2009-07-31 17:39:07 +0000531}
532
Chris Lattner229907c2011-07-18 04:54:35 +0000533Constant *ConstantInt::getTrue(Type *Ty) {
534 VectorType *VTy = dyn_cast<VectorType>(Ty);
Nick Lewycky92db8e82011-03-06 03:36:19 +0000535 if (!VTy) {
536 assert(Ty->isIntegerTy(1) && "True must be i1 or vector of i1.");
537 return ConstantInt::getTrue(Ty->getContext());
538 }
539 assert(VTy->getElementType()->isIntegerTy(1) &&
540 "True must be vector of i1 or i1.");
Chris Lattnere9eed292012-01-25 05:19:54 +0000541 return ConstantVector::getSplat(VTy->getNumElements(),
542 ConstantInt::getTrue(Ty->getContext()));
Nick Lewycky92db8e82011-03-06 03:36:19 +0000543}
544
Chris Lattner229907c2011-07-18 04:54:35 +0000545Constant *ConstantInt::getFalse(Type *Ty) {
546 VectorType *VTy = dyn_cast<VectorType>(Ty);
Nick Lewycky92db8e82011-03-06 03:36:19 +0000547 if (!VTy) {
548 assert(Ty->isIntegerTy(1) && "False must be i1 or vector of i1.");
549 return ConstantInt::getFalse(Ty->getContext());
550 }
551 assert(VTy->getElementType()->isIntegerTy(1) &&
552 "False must be vector of i1 or i1.");
Chris Lattnere9eed292012-01-25 05:19:54 +0000553 return ConstantVector::getSplat(VTy->getNumElements(),
554 ConstantInt::getFalse(Ty->getContext()));
Nick Lewycky92db8e82011-03-06 03:36:19 +0000555}
556
Benjamin Kramer8e5dc532014-12-06 13:12:56 +0000557// Get a ConstantInt from an APInt.
Nick Lewycky92db8e82011-03-06 03:36:19 +0000558ConstantInt *ConstantInt::get(LLVMContext &Context, const APInt &V) {
Owen Andersonedb4a702009-07-24 23:12:02 +0000559 // get an existing value or the insertion position
Benjamin Kramer320682f2013-06-01 17:51:03 +0000560 LLVMContextImpl *pImpl = Context.pImpl;
Benjamin Kramer8e5dc532014-12-06 13:12:56 +0000561 ConstantInt *&Slot = pImpl->IntConstants[V];
562 if (!Slot) {
563 // Get the corresponding integer type for the bit width of the value.
564 IntegerType *ITy = IntegerType::get(Context, V.getBitWidth());
NAKAMURA Takumifc3062f2014-12-06 05:57:06 +0000565 Slot = new ConstantInt(ITy, V);
Benjamin Kramer8e5dc532014-12-06 13:12:56 +0000566 }
567 assert(Slot->getType() == IntegerType::get(Context, V.getBitWidth()));
Owen Anderson5dab84c2009-10-19 20:11:52 +0000568 return Slot;
Owen Andersonedb4a702009-07-24 23:12:02 +0000569}
570
Chris Lattner229907c2011-07-18 04:54:35 +0000571Constant *ConstantInt::get(Type *Ty, uint64_t V, bool isSigned) {
Nick Lewycky92db8e82011-03-06 03:36:19 +0000572 Constant *C = get(cast<IntegerType>(Ty->getScalarType()), V, isSigned);
Owen Andersonedb4a702009-07-24 23:12:02 +0000573
574 // For vectors, broadcast the value.
Chris Lattner229907c2011-07-18 04:54:35 +0000575 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
Chris Lattnere9eed292012-01-25 05:19:54 +0000576 return ConstantVector::getSplat(VTy->getNumElements(), C);
Owen Andersonedb4a702009-07-24 23:12:02 +0000577
578 return C;
579}
580
Chris Lattner0256be92012-01-27 03:08:05 +0000581ConstantInt *ConstantInt::get(IntegerType *Ty, uint64_t V,
Owen Andersonedb4a702009-07-24 23:12:02 +0000582 bool isSigned) {
583 return get(Ty->getContext(), APInt(Ty->getBitWidth(), V, isSigned));
584}
585
Chris Lattner0256be92012-01-27 03:08:05 +0000586ConstantInt *ConstantInt::getSigned(IntegerType *Ty, int64_t V) {
Owen Andersonedb4a702009-07-24 23:12:02 +0000587 return get(Ty, V, true);
588}
589
Chris Lattner229907c2011-07-18 04:54:35 +0000590Constant *ConstantInt::getSigned(Type *Ty, int64_t V) {
Owen Andersonedb4a702009-07-24 23:12:02 +0000591 return get(Ty, V, true);
592}
593
Chris Lattner0256be92012-01-27 03:08:05 +0000594Constant *ConstantInt::get(Type *Ty, const APInt& V) {
Owen Andersonedb4a702009-07-24 23:12:02 +0000595 ConstantInt *C = get(Ty->getContext(), V);
596 assert(C->getType() == Ty->getScalarType() &&
597 "ConstantInt type doesn't match the type implied by its value!");
598
599 // For vectors, broadcast the value.
Chris Lattner229907c2011-07-18 04:54:35 +0000600 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
Chris Lattnere9eed292012-01-25 05:19:54 +0000601 return ConstantVector::getSplat(VTy->getNumElements(), C);
Owen Andersonedb4a702009-07-24 23:12:02 +0000602
603 return C;
604}
605
Chris Lattner0256be92012-01-27 03:08:05 +0000606ConstantInt *ConstantInt::get(IntegerType* Ty, StringRef Str,
Erick Tryzelaarfc2280d2009-08-16 23:36:33 +0000607 uint8_t radix) {
608 return get(Ty->getContext(), APInt(Ty->getBitWidth(), Str, radix));
609}
610
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000611//===----------------------------------------------------------------------===//
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000612// ConstantFP
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000613//===----------------------------------------------------------------------===//
614
Chris Lattner229907c2011-07-18 04:54:35 +0000615static const fltSemantics *TypeToFloatSemantics(Type *Ty) {
Dan Gohman518cda42011-12-17 00:04:22 +0000616 if (Ty->isHalfTy())
617 return &APFloat::IEEEhalf;
Chris Lattnerfdd87902009-10-05 05:54:46 +0000618 if (Ty->isFloatTy())
Rafael Espindolaf5d53d42009-07-15 17:40:42 +0000619 return &APFloat::IEEEsingle;
Chris Lattnerfdd87902009-10-05 05:54:46 +0000620 if (Ty->isDoubleTy())
Rafael Espindolaf5d53d42009-07-15 17:40:42 +0000621 return &APFloat::IEEEdouble;
Chris Lattnerfdd87902009-10-05 05:54:46 +0000622 if (Ty->isX86_FP80Ty())
Rafael Espindolaf5d53d42009-07-15 17:40:42 +0000623 return &APFloat::x87DoubleExtended;
Chris Lattnerfdd87902009-10-05 05:54:46 +0000624 else if (Ty->isFP128Ty())
Rafael Espindolaf5d53d42009-07-15 17:40:42 +0000625 return &APFloat::IEEEquad;
Galina Kistanovafc259902012-07-13 01:25:27 +0000626
Chris Lattnerfdd87902009-10-05 05:54:46 +0000627 assert(Ty->isPPC_FP128Ty() && "Unknown FP format");
Rafael Espindolaf5d53d42009-07-15 17:40:42 +0000628 return &APFloat::PPCDoubleDouble;
629}
630
David Blaikiea379b1812011-12-20 02:50:00 +0000631void ConstantFP::anchor() { }
632
Owen Anderson69c464d2009-07-27 20:59:43 +0000633/// get() - This returns a constant fp for the specified value in the
634/// specified type. This should only be used for simple constant values like
635/// 2.0/1.0 etc, that are known-valid both as double and as the target format.
Chris Lattner0256be92012-01-27 03:08:05 +0000636Constant *ConstantFP::get(Type *Ty, double V) {
Owen Anderson69c464d2009-07-27 20:59:43 +0000637 LLVMContext &Context = Ty->getContext();
Galina Kistanovafc259902012-07-13 01:25:27 +0000638
Owen Anderson69c464d2009-07-27 20:59:43 +0000639 APFloat FV(V);
640 bool ignored;
641 FV.convert(*TypeToFloatSemantics(Ty->getScalarType()),
642 APFloat::rmNearestTiesToEven, &ignored);
643 Constant *C = get(Context, FV);
644
645 // For vectors, broadcast the value.
Chris Lattner229907c2011-07-18 04:54:35 +0000646 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
Chris Lattnere9eed292012-01-25 05:19:54 +0000647 return ConstantVector::getSplat(VTy->getNumElements(), C);
Owen Anderson69c464d2009-07-27 20:59:43 +0000648
649 return C;
650}
651
Erick Tryzelaarfc2280d2009-08-16 23:36:33 +0000652
Chris Lattner0256be92012-01-27 03:08:05 +0000653Constant *ConstantFP::get(Type *Ty, StringRef Str) {
Erick Tryzelaarfc2280d2009-08-16 23:36:33 +0000654 LLVMContext &Context = Ty->getContext();
655
656 APFloat FV(*TypeToFloatSemantics(Ty->getScalarType()), Str);
657 Constant *C = get(Context, FV);
658
659 // For vectors, broadcast the value.
Chris Lattner229907c2011-07-18 04:54:35 +0000660 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
Chris Lattnere9eed292012-01-25 05:19:54 +0000661 return ConstantVector::getSplat(VTy->getNumElements(), C);
Erick Tryzelaarfc2280d2009-08-16 23:36:33 +0000662
663 return C;
664}
665
Benjamin Kramer5d2ff222014-01-18 16:43:06 +0000666Constant *ConstantFP::getNegativeZero(Type *Ty) {
667 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
668 APFloat NegZero = APFloat::getZero(Semantics, /*Negative=*/true);
669 Constant *C = get(Ty->getContext(), NegZero);
Erick Tryzelaarfc2280d2009-08-16 23:36:33 +0000670
Benjamin Kramer5d2ff222014-01-18 16:43:06 +0000671 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
672 return ConstantVector::getSplat(VTy->getNumElements(), C);
673
674 return C;
Owen Anderson69c464d2009-07-27 20:59:43 +0000675}
676
677
Chris Lattnere9eed292012-01-25 05:19:54 +0000678Constant *ConstantFP::getZeroValueForNegation(Type *Ty) {
Benjamin Kramer5d2ff222014-01-18 16:43:06 +0000679 if (Ty->isFPOrFPVectorTy())
680 return getNegativeZero(Ty);
Owen Anderson69c464d2009-07-27 20:59:43 +0000681
Owen Anderson5a1acd92009-07-31 20:28:14 +0000682 return Constant::getNullValue(Ty);
Owen Anderson69c464d2009-07-27 20:59:43 +0000683}
684
685
686// ConstantFP accessors.
687ConstantFP* ConstantFP::get(LLVMContext &Context, const APFloat& V) {
Owen Anderson69c464d2009-07-27 20:59:43 +0000688 LLVMContextImpl* pImpl = Context.pImpl;
Galina Kistanovafc259902012-07-13 01:25:27 +0000689
Benjamin Kramer8e5dc532014-12-06 13:12:56 +0000690 ConstantFP *&Slot = pImpl->FPConstants[V];
Galina Kistanovafc259902012-07-13 01:25:27 +0000691
Owen Anderson69c464d2009-07-27 20:59:43 +0000692 if (!Slot) {
Chris Lattner229907c2011-07-18 04:54:35 +0000693 Type *Ty;
Dan Gohman518cda42011-12-17 00:04:22 +0000694 if (&V.getSemantics() == &APFloat::IEEEhalf)
695 Ty = Type::getHalfTy(Context);
696 else if (&V.getSemantics() == &APFloat::IEEEsingle)
Owen Anderson5dab84c2009-10-19 20:11:52 +0000697 Ty = Type::getFloatTy(Context);
698 else if (&V.getSemantics() == &APFloat::IEEEdouble)
699 Ty = Type::getDoubleTy(Context);
700 else if (&V.getSemantics() == &APFloat::x87DoubleExtended)
701 Ty = Type::getX86_FP80Ty(Context);
702 else if (&V.getSemantics() == &APFloat::IEEEquad)
703 Ty = Type::getFP128Ty(Context);
704 else {
705 assert(&V.getSemantics() == &APFloat::PPCDoubleDouble &&
706 "Unknown FP format");
707 Ty = Type::getPPC_FP128Ty(Context);
Owen Anderson69c464d2009-07-27 20:59:43 +0000708 }
Owen Anderson5dab84c2009-10-19 20:11:52 +0000709 Slot = new ConstantFP(Ty, V);
Owen Anderson69c464d2009-07-27 20:59:43 +0000710 }
Galina Kistanovafc259902012-07-13 01:25:27 +0000711
Owen Anderson69c464d2009-07-27 20:59:43 +0000712 return Slot;
713}
714
Benjamin Kramer5d2ff222014-01-18 16:43:06 +0000715Constant *ConstantFP::getInfinity(Type *Ty, bool Negative) {
716 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
717 Constant *C = get(Ty->getContext(), APFloat::getInf(Semantics, Negative));
718
719 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
720 return ConstantVector::getSplat(VTy->getNumElements(), C);
721
722 return C;
Dan Gohmanfeb50212009-09-25 23:00:48 +0000723}
724
Chris Lattner229907c2011-07-18 04:54:35 +0000725ConstantFP::ConstantFP(Type *Ty, const APFloat& V)
Craig Topperc6207612014-04-09 06:08:46 +0000726 : Constant(Ty, ConstantFPVal, nullptr, 0), Val(V) {
Chris Lattner98bd9392008-04-09 06:38:30 +0000727 assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
728 "FP type Mismatch");
Chris Lattner2f7c9632001-06-06 20:29:01 +0000729}
730
Chris Lattnerbe6610c2011-07-15 06:14:08 +0000731bool ConstantFP::isExactlyValue(const APFloat &V) const {
Dale Johannesend246b2c2007-08-30 00:23:21 +0000732 return Val.bitwiseIsEqual(V);
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000733}
734
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000735//===----------------------------------------------------------------------===//
Chris Lattner030af792012-01-24 05:42:11 +0000736// ConstantAggregateZero Implementation
737//===----------------------------------------------------------------------===//
738
739/// getSequentialElement - If this CAZ has array or vector type, return a zero
740/// with the right element type.
Chris Lattner7e683d12012-01-25 06:16:32 +0000741Constant *ConstantAggregateZero::getSequentialElement() const {
Chris Lattner8326bd82012-01-26 00:42:34 +0000742 return Constant::getNullValue(getType()->getSequentialElementType());
Chris Lattner030af792012-01-24 05:42:11 +0000743}
744
745/// getStructElement - If this CAZ has struct type, return a zero with the
746/// right element type for the specified element.
Chris Lattner7e683d12012-01-25 06:16:32 +0000747Constant *ConstantAggregateZero::getStructElement(unsigned Elt) const {
Chris Lattner8326bd82012-01-26 00:42:34 +0000748 return Constant::getNullValue(getType()->getStructElementType(Elt));
Chris Lattner030af792012-01-24 05:42:11 +0000749}
750
751/// getElementValue - Return a zero of the right value for the specified GEP
752/// index if we can, otherwise return null (e.g. if C is a ConstantExpr).
Chris Lattner7e683d12012-01-25 06:16:32 +0000753Constant *ConstantAggregateZero::getElementValue(Constant *C) const {
Chris Lattner030af792012-01-24 05:42:11 +0000754 if (isa<SequentialType>(getType()))
755 return getSequentialElement();
756 return getStructElement(cast<ConstantInt>(C)->getZExtValue());
757}
758
Chris Lattnerf7eb5432012-01-24 07:54:10 +0000759/// getElementValue - Return a zero of the right value for the specified GEP
760/// index.
Chris Lattner7e683d12012-01-25 06:16:32 +0000761Constant *ConstantAggregateZero::getElementValue(unsigned Idx) const {
Chris Lattnerf7eb5432012-01-24 07:54:10 +0000762 if (isa<SequentialType>(getType()))
763 return getSequentialElement();
764 return getStructElement(Idx);
765}
766
767
Chris Lattner030af792012-01-24 05:42:11 +0000768//===----------------------------------------------------------------------===//
769// UndefValue Implementation
770//===----------------------------------------------------------------------===//
771
772/// getSequentialElement - If this undef has array or vector type, return an
773/// undef with the right element type.
Chris Lattner7e683d12012-01-25 06:16:32 +0000774UndefValue *UndefValue::getSequentialElement() const {
Chris Lattner8326bd82012-01-26 00:42:34 +0000775 return UndefValue::get(getType()->getSequentialElementType());
Chris Lattner030af792012-01-24 05:42:11 +0000776}
777
778/// getStructElement - If this undef has struct type, return a zero with the
779/// right element type for the specified element.
Chris Lattner7e683d12012-01-25 06:16:32 +0000780UndefValue *UndefValue::getStructElement(unsigned Elt) const {
Chris Lattner8326bd82012-01-26 00:42:34 +0000781 return UndefValue::get(getType()->getStructElementType(Elt));
Chris Lattner030af792012-01-24 05:42:11 +0000782}
783
784/// getElementValue - Return an undef of the right value for the specified GEP
785/// index if we can, otherwise return null (e.g. if C is a ConstantExpr).
Chris Lattner7e683d12012-01-25 06:16:32 +0000786UndefValue *UndefValue::getElementValue(Constant *C) const {
Chris Lattner030af792012-01-24 05:42:11 +0000787 if (isa<SequentialType>(getType()))
788 return getSequentialElement();
789 return getStructElement(cast<ConstantInt>(C)->getZExtValue());
790}
791
Chris Lattnerf7eb5432012-01-24 07:54:10 +0000792/// getElementValue - Return an undef of the right value for the specified GEP
793/// index.
Chris Lattner7e683d12012-01-25 06:16:32 +0000794UndefValue *UndefValue::getElementValue(unsigned Idx) const {
Chris Lattnerf7eb5432012-01-24 07:54:10 +0000795 if (isa<SequentialType>(getType()))
796 return getSequentialElement();
797 return getStructElement(Idx);
798}
799
800
Chris Lattner030af792012-01-24 05:42:11 +0000801
802//===----------------------------------------------------------------------===//
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000803// ConstantXXX Classes
804//===----------------------------------------------------------------------===//
805
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000806template <typename ItTy, typename EltTy>
807static bool rangeOnlyContains(ItTy Start, ItTy End, EltTy Elt) {
808 for (; Start != End; ++Start)
809 if (*Start != Elt)
810 return false;
811 return true;
812}
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000813
Jay Foad89d9b812011-07-25 10:14:44 +0000814ConstantArray::ConstantArray(ArrayType *T, ArrayRef<Constant *> V)
Gabor Greiff6caff662008-05-10 08:32:32 +0000815 : Constant(T, ConstantArrayVal,
816 OperandTraits<ConstantArray>::op_end(this) - V.size(),
817 V.size()) {
Alkis Evlogimenos0507ffe2004-09-15 02:32:15 +0000818 assert(V.size() == T->getNumElements() &&
819 "Invalid initializer vector for constant array");
Jay Foad89d9b812011-07-25 10:14:44 +0000820 for (unsigned i = 0, e = V.size(); i != e; ++i)
821 assert(V[i]->getType() == T->getElementType() &&
Alkis Evlogimenoscb031d92004-09-10 04:16:59 +0000822 "Initializer for array element doesn't match array element type!");
Jay Foad89d9b812011-07-25 10:14:44 +0000823 std::copy(V.begin(), V.end(), op_begin());
Chris Lattner2f7c9632001-06-06 20:29:01 +0000824}
825
Chris Lattner229907c2011-07-18 04:54:35 +0000826Constant *ConstantArray::get(ArrayType *Ty, ArrayRef<Constant*> V) {
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +0000827 if (Constant *C = getImpl(Ty, V))
828 return C;
829 return Ty->getContext().pImpl->ArrayConstants.getOrCreate(Ty, V);
830}
831Constant *ConstantArray::getImpl(ArrayType *Ty, ArrayRef<Constant*> V) {
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000832 // Empty arrays are canonicalized to ConstantAggregateZero.
833 if (V.empty())
834 return ConstantAggregateZero::get(Ty);
835
Jeffrey Yasskin8ce67f82009-09-30 21:08:08 +0000836 for (unsigned i = 0, e = V.size(); i != e; ++i) {
837 assert(V[i]->getType() == Ty->getElementType() &&
838 "Wrong type in array element initializer");
839 }
Galina Kistanovafc259902012-07-13 01:25:27 +0000840
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000841 // If this is an all-zero array, return a ConstantAggregateZero object. If
842 // all undef, return an UndefValue, if "all simple", then return a
843 // ConstantDataArray.
844 Constant *C = V[0];
845 if (isa<UndefValue>(C) && rangeOnlyContains(V.begin(), V.end(), C))
846 return UndefValue::get(Ty);
Chris Lattnerf14a67f2012-01-26 02:31:22 +0000847
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000848 if (C->isNullValue() && rangeOnlyContains(V.begin(), V.end(), C))
849 return ConstantAggregateZero::get(Ty);
850
851 // Check to see if all of the elements are ConstantFP or ConstantInt and if
852 // the element type is compatible with ConstantDataVector. If so, use it.
853 if (ConstantDataSequential::isElementTypeCompatible(C->getType())) {
854 // We speculatively build the elements here even if it turns out that there
855 // is a constantexpr or something else weird in the array, since it is so
856 // uncommon for that to happen.
857 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
858 if (CI->getType()->isIntegerTy(8)) {
859 SmallVector<uint8_t, 16> Elts;
860 for (unsigned i = 0, e = V.size(); i != e; ++i)
861 if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
862 Elts.push_back(CI->getZExtValue());
863 else
864 break;
865 if (Elts.size() == V.size())
866 return ConstantDataArray::get(C->getContext(), Elts);
867 } else if (CI->getType()->isIntegerTy(16)) {
868 SmallVector<uint16_t, 16> Elts;
869 for (unsigned i = 0, e = V.size(); i != e; ++i)
870 if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
871 Elts.push_back(CI->getZExtValue());
872 else
873 break;
874 if (Elts.size() == V.size())
875 return ConstantDataArray::get(C->getContext(), Elts);
876 } else if (CI->getType()->isIntegerTy(32)) {
877 SmallVector<uint32_t, 16> Elts;
878 for (unsigned i = 0, e = V.size(); i != e; ++i)
879 if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
880 Elts.push_back(CI->getZExtValue());
881 else
882 break;
883 if (Elts.size() == V.size())
884 return ConstantDataArray::get(C->getContext(), Elts);
885 } else if (CI->getType()->isIntegerTy(64)) {
886 SmallVector<uint64_t, 16> Elts;
887 for (unsigned i = 0, e = V.size(); i != e; ++i)
888 if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
889 Elts.push_back(CI->getZExtValue());
890 else
891 break;
892 if (Elts.size() == V.size())
893 return ConstantDataArray::get(C->getContext(), Elts);
894 }
895 }
Galina Kistanovafc259902012-07-13 01:25:27 +0000896
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000897 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
898 if (CFP->getType()->isFloatTy()) {
899 SmallVector<float, 16> Elts;
900 for (unsigned i = 0, e = V.size(); i != e; ++i)
901 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V[i]))
902 Elts.push_back(CFP->getValueAPF().convertToFloat());
903 else
904 break;
905 if (Elts.size() == V.size())
906 return ConstantDataArray::get(C->getContext(), Elts);
907 } else if (CFP->getType()->isDoubleTy()) {
908 SmallVector<double, 16> Elts;
909 for (unsigned i = 0, e = V.size(); i != e; ++i)
910 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V[i]))
911 Elts.push_back(CFP->getValueAPF().convertToDouble());
912 else
913 break;
914 if (Elts.size() == V.size())
915 return ConstantDataArray::get(C->getContext(), Elts);
916 }
917 }
Owen Andersonc2c79322009-07-28 18:32:17 +0000918 }
Chris Lattnerf14a67f2012-01-26 02:31:22 +0000919
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000920 // Otherwise, we really do want to create a ConstantArray.
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +0000921 return nullptr;
Owen Andersonc2c79322009-07-28 18:32:17 +0000922}
923
Chris Lattnercc19efa2011-06-20 04:01:31 +0000924/// getTypeForElements - Return an anonymous struct type to use for a constant
925/// with the specified set of elements. The list must not be empty.
926StructType *ConstantStruct::getTypeForElements(LLVMContext &Context,
927 ArrayRef<Constant*> V,
928 bool Packed) {
Bill Wendling3ae7dd32012-02-07 01:27:51 +0000929 unsigned VecSize = V.size();
930 SmallVector<Type*, 16> EltTypes(VecSize);
931 for (unsigned i = 0; i != VecSize; ++i)
932 EltTypes[i] = V[i]->getType();
Galina Kistanovafc259902012-07-13 01:25:27 +0000933
Chris Lattnercc19efa2011-06-20 04:01:31 +0000934 return StructType::get(Context, EltTypes, Packed);
935}
936
937
938StructType *ConstantStruct::getTypeForElements(ArrayRef<Constant*> V,
939 bool Packed) {
940 assert(!V.empty() &&
941 "ConstantStruct::getTypeForElements cannot be called on empty list");
942 return getTypeForElements(V[0]->getContext(), V, Packed);
943}
944
945
Jay Foad89d9b812011-07-25 10:14:44 +0000946ConstantStruct::ConstantStruct(StructType *T, ArrayRef<Constant *> V)
Gabor Greiff6caff662008-05-10 08:32:32 +0000947 : Constant(T, ConstantStructVal,
948 OperandTraits<ConstantStruct>::op_end(this) - V.size(),
949 V.size()) {
Chris Lattnerc3e74cd2011-08-07 04:18:48 +0000950 assert(V.size() == T->getNumElements() &&
Vikram S. Adve4e537b22002-07-14 23:13:17 +0000951 "Invalid initializer vector for constant structure");
Jay Foad89d9b812011-07-25 10:14:44 +0000952 for (unsigned i = 0, e = V.size(); i != e; ++i)
953 assert((T->isOpaque() || V[i]->getType() == T->getElementType(i)) &&
Chris Lattner93c8f142003-06-02 17:42:47 +0000954 "Initializer for struct element doesn't match struct element type!");
Jay Foad89d9b812011-07-25 10:14:44 +0000955 std::copy(V.begin(), V.end(), op_begin());
Chris Lattner2f7c9632001-06-06 20:29:01 +0000956}
957
Owen Anderson45308b52009-07-27 22:29:26 +0000958// ConstantStruct accessors.
Chris Lattner229907c2011-07-18 04:54:35 +0000959Constant *ConstantStruct::get(StructType *ST, ArrayRef<Constant*> V) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000960 assert((ST->isOpaque() || ST->getNumElements() == V.size()) &&
961 "Incorrect # elements specified to ConstantStruct::get");
Chris Lattnerf14a67f2012-01-26 02:31:22 +0000962
963 // Create a ConstantAggregateZero value if all elements are zeros.
964 bool isZero = true;
965 bool isUndef = false;
966
967 if (!V.empty()) {
968 isUndef = isa<UndefValue>(V[0]);
969 isZero = V[0]->isNullValue();
970 if (isUndef || isZero) {
971 for (unsigned i = 0, e = V.size(); i != e; ++i) {
972 if (!V[i]->isNullValue())
973 isZero = false;
974 if (!isa<UndefValue>(V[i]))
975 isUndef = false;
976 }
977 }
Galina Kistanovafc259902012-07-13 01:25:27 +0000978 }
Chris Lattnerf14a67f2012-01-26 02:31:22 +0000979 if (isZero)
980 return ConstantAggregateZero::get(ST);
981 if (isUndef)
982 return UndefValue::get(ST);
Galina Kistanovafc259902012-07-13 01:25:27 +0000983
Chris Lattnerf14a67f2012-01-26 02:31:22 +0000984 return ST->getContext().pImpl->StructConstants.getOrCreate(ST, V);
Owen Anderson45308b52009-07-27 22:29:26 +0000985}
986
Chris Lattnerc3e74cd2011-08-07 04:18:48 +0000987Constant *ConstantStruct::get(StructType *T, ...) {
Talin3a0a30d2011-02-28 23:53:27 +0000988 va_list ap;
Chris Lattnercc19efa2011-06-20 04:01:31 +0000989 SmallVector<Constant*, 8> Values;
990 va_start(ap, T);
991 while (Constant *Val = va_arg(ap, llvm::Constant*))
Talin3a0a30d2011-02-28 23:53:27 +0000992 Values.push_back(Val);
Talinde422be2011-03-01 18:00:49 +0000993 va_end(ap);
Chris Lattnercc19efa2011-06-20 04:01:31 +0000994 return get(T, Values);
Talin3a0a30d2011-02-28 23:53:27 +0000995}
996
Jay Foad89d9b812011-07-25 10:14:44 +0000997ConstantVector::ConstantVector(VectorType *T, ArrayRef<Constant *> V)
Gabor Greiff6caff662008-05-10 08:32:32 +0000998 : Constant(T, ConstantVectorVal,
999 OperandTraits<ConstantVector>::op_end(this) - V.size(),
1000 V.size()) {
Jay Foad89d9b812011-07-25 10:14:44 +00001001 for (size_t i = 0, e = V.size(); i != e; i++)
1002 assert(V[i]->getType() == T->getElementType() &&
Dan Gohman30978072007-05-24 14:36:04 +00001003 "Initializer for vector element doesn't match vector element type!");
Jay Foad89d9b812011-07-25 10:14:44 +00001004 std::copy(V.begin(), V.end(), op_begin());
Brian Gaeke02209042004-08-20 06:00:58 +00001005}
1006
Owen Anderson4aa32952009-07-28 21:19:26 +00001007// ConstantVector accessors.
Jay Foadb8a8bed32011-06-22 09:10:19 +00001008Constant *ConstantVector::get(ArrayRef<Constant*> V) {
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00001009 if (Constant *C = getImpl(V))
1010 return C;
1011 VectorType *Ty = VectorType::get(V.front()->getType(), V.size());
1012 return Ty->getContext().pImpl->VectorConstants.getOrCreate(Ty, V);
1013}
1014Constant *ConstantVector::getImpl(ArrayRef<Constant*> V) {
Jay Foad9f32cfd2011-01-27 14:44:55 +00001015 assert(!V.empty() && "Vectors can't be empty");
Chris Lattner229907c2011-07-18 04:54:35 +00001016 VectorType *T = VectorType::get(V.front()->getType(), V.size());
Jay Foad9f32cfd2011-01-27 14:44:55 +00001017
Chris Lattner69229312011-02-15 00:14:00 +00001018 // If this is an all-undef or all-zero vector, return a
Owen Anderson4aa32952009-07-28 21:19:26 +00001019 // ConstantAggregateZero or UndefValue.
1020 Constant *C = V[0];
1021 bool isZero = C->isNullValue();
1022 bool isUndef = isa<UndefValue>(C);
1023
1024 if (isZero || isUndef) {
1025 for (unsigned i = 1, e = V.size(); i != e; ++i)
1026 if (V[i] != C) {
1027 isZero = isUndef = false;
1028 break;
1029 }
1030 }
Galina Kistanovafc259902012-07-13 01:25:27 +00001031
Owen Anderson4aa32952009-07-28 21:19:26 +00001032 if (isZero)
Owen Andersonb292b8c2009-07-30 23:03:37 +00001033 return ConstantAggregateZero::get(T);
Owen Anderson4aa32952009-07-28 21:19:26 +00001034 if (isUndef)
Owen Andersonb292b8c2009-07-30 23:03:37 +00001035 return UndefValue::get(T);
Galina Kistanovafc259902012-07-13 01:25:27 +00001036
Chris Lattner978fe0c2012-01-30 06:21:21 +00001037 // Check to see if all of the elements are ConstantFP or ConstantInt and if
1038 // the element type is compatible with ConstantDataVector. If so, use it.
Chris Lattnercf9e8f62012-02-05 02:29:43 +00001039 if (ConstantDataSequential::isElementTypeCompatible(C->getType())) {
Chris Lattner978fe0c2012-01-30 06:21:21 +00001040 // We speculatively build the elements here even if it turns out that there
1041 // is a constantexpr or something else weird in the array, since it is so
1042 // uncommon for that to happen.
1043 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
1044 if (CI->getType()->isIntegerTy(8)) {
1045 SmallVector<uint8_t, 16> Elts;
1046 for (unsigned i = 0, e = V.size(); i != e; ++i)
1047 if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
1048 Elts.push_back(CI->getZExtValue());
1049 else
1050 break;
1051 if (Elts.size() == V.size())
1052 return ConstantDataVector::get(C->getContext(), Elts);
1053 } else if (CI->getType()->isIntegerTy(16)) {
1054 SmallVector<uint16_t, 16> Elts;
1055 for (unsigned i = 0, e = V.size(); i != e; ++i)
1056 if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
1057 Elts.push_back(CI->getZExtValue());
1058 else
1059 break;
1060 if (Elts.size() == V.size())
1061 return ConstantDataVector::get(C->getContext(), Elts);
1062 } else if (CI->getType()->isIntegerTy(32)) {
1063 SmallVector<uint32_t, 16> Elts;
1064 for (unsigned i = 0, e = V.size(); i != e; ++i)
1065 if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
1066 Elts.push_back(CI->getZExtValue());
1067 else
1068 break;
1069 if (Elts.size() == V.size())
1070 return ConstantDataVector::get(C->getContext(), Elts);
1071 } else if (CI->getType()->isIntegerTy(64)) {
1072 SmallVector<uint64_t, 16> Elts;
1073 for (unsigned i = 0, e = V.size(); i != e; ++i)
1074 if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
1075 Elts.push_back(CI->getZExtValue());
1076 else
1077 break;
1078 if (Elts.size() == V.size())
1079 return ConstantDataVector::get(C->getContext(), Elts);
1080 }
1081 }
Galina Kistanovafc259902012-07-13 01:25:27 +00001082
Chris Lattner978fe0c2012-01-30 06:21:21 +00001083 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
1084 if (CFP->getType()->isFloatTy()) {
1085 SmallVector<float, 16> Elts;
1086 for (unsigned i = 0, e = V.size(); i != e; ++i)
1087 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V[i]))
1088 Elts.push_back(CFP->getValueAPF().convertToFloat());
1089 else
1090 break;
1091 if (Elts.size() == V.size())
1092 return ConstantDataVector::get(C->getContext(), Elts);
1093 } else if (CFP->getType()->isDoubleTy()) {
1094 SmallVector<double, 16> Elts;
1095 for (unsigned i = 0, e = V.size(); i != e; ++i)
1096 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V[i]))
1097 Elts.push_back(CFP->getValueAPF().convertToDouble());
1098 else
1099 break;
1100 if (Elts.size() == V.size())
1101 return ConstantDataVector::get(C->getContext(), Elts);
1102 }
1103 }
1104 }
Galina Kistanovafc259902012-07-13 01:25:27 +00001105
Chris Lattner978fe0c2012-01-30 06:21:21 +00001106 // Otherwise, the element type isn't compatible with ConstantDataVector, or
1107 // the operand list constants a ConstantExpr or something else strange.
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00001108 return nullptr;
Owen Anderson4aa32952009-07-28 21:19:26 +00001109}
1110
Chris Lattnere9eed292012-01-25 05:19:54 +00001111Constant *ConstantVector::getSplat(unsigned NumElts, Constant *V) {
Chris Lattner978fe0c2012-01-30 06:21:21 +00001112 // If this splat is compatible with ConstantDataVector, use it instead of
1113 // ConstantVector.
1114 if ((isa<ConstantFP>(V) || isa<ConstantInt>(V)) &&
1115 ConstantDataSequential::isElementTypeCompatible(V->getType()))
1116 return ConstantDataVector::getSplat(NumElts, V);
Galina Kistanovafc259902012-07-13 01:25:27 +00001117
Chris Lattnere9eed292012-01-25 05:19:54 +00001118 SmallVector<Constant*, 32> Elts(NumElts, V);
1119 return get(Elts);
1120}
1121
1122
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001123// Utility function for determining if a ConstantExpr is a CastOp or not. This
1124// can't be inline because we don't want to #include Instruction.h into
1125// Constant.h
1126bool ConstantExpr::isCast() const {
1127 return Instruction::isCast(getOpcode());
1128}
1129
Reid Spenceree3c9912006-12-04 05:19:50 +00001130bool ConstantExpr::isCompare() const {
Nick Lewyckya21d3da2009-07-08 03:04:38 +00001131 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
Reid Spenceree3c9912006-12-04 05:19:50 +00001132}
1133
Dan Gohman7190d482009-09-10 23:37:55 +00001134bool ConstantExpr::isGEPWithNoNotionalOverIndexing() const {
1135 if (getOpcode() != Instruction::GetElementPtr) return false;
1136
1137 gep_type_iterator GEPI = gep_type_begin(this), E = gep_type_end(this);
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001138 User::const_op_iterator OI = std::next(this->op_begin());
Dan Gohman7190d482009-09-10 23:37:55 +00001139
1140 // Skip the first index, as it has no static limit.
1141 ++GEPI;
1142 ++OI;
1143
1144 // The remaining indices must be compile-time known integers within the
1145 // bounds of the corresponding notional static array types.
1146 for (; GEPI != E; ++GEPI, ++OI) {
1147 ConstantInt *CI = dyn_cast<ConstantInt>(*OI);
1148 if (!CI) return false;
Chris Lattner229907c2011-07-18 04:54:35 +00001149 if (ArrayType *ATy = dyn_cast<ArrayType>(*GEPI))
Dan Gohman7190d482009-09-10 23:37:55 +00001150 if (CI->getValue().getActiveBits() > 64 ||
1151 CI->getZExtValue() >= ATy->getNumElements())
1152 return false;
1153 }
1154
1155 // All the indices checked out.
1156 return true;
1157}
1158
Dan Gohman1ecaf452008-05-31 00:58:22 +00001159bool ConstantExpr::hasIndices() const {
1160 return getOpcode() == Instruction::ExtractValue ||
1161 getOpcode() == Instruction::InsertValue;
1162}
1163
Jay Foad0091fe82011-04-13 15:22:40 +00001164ArrayRef<unsigned> ConstantExpr::getIndices() const {
Dan Gohman1ecaf452008-05-31 00:58:22 +00001165 if (const ExtractValueConstantExpr *EVCE =
1166 dyn_cast<ExtractValueConstantExpr>(this))
1167 return EVCE->Indices;
Dan Gohmana469bdb2008-06-23 16:39:44 +00001168
1169 return cast<InsertValueConstantExpr>(this)->Indices;
Dan Gohman1ecaf452008-05-31 00:58:22 +00001170}
1171
Reid Spencer10fbf0e2006-12-03 05:48:19 +00001172unsigned ConstantExpr::getPredicate() const {
Chris Lattnerd04e32d2011-07-17 06:01:30 +00001173 assert(isCompare());
Chris Lattneref650092007-10-18 16:26:24 +00001174 return ((const CompareConstantExpr*)this)->predicate;
Reid Spencer10fbf0e2006-12-03 05:48:19 +00001175}
Chris Lattner60e0dd72001-10-03 06:12:09 +00001176
Chris Lattner7c1018a2006-07-14 19:37:40 +00001177/// getWithOperandReplaced - Return a constant expression identical to this
1178/// one, but with the specified operand set to the specified value.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001179Constant *
1180ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
Chris Lattner7c1018a2006-07-14 19:37:40 +00001181 assert(Op->getType() == getOperand(OpNo)->getType() &&
1182 "Replacing operand with value of different type!");
Chris Lattner227816342006-07-14 22:20:01 +00001183 if (getOperand(OpNo) == Op)
1184 return const_cast<ConstantExpr*>(this);
Chris Lattner37e38352012-01-26 20:37:11 +00001185
1186 SmallVector<Constant*, 8> NewOps;
1187 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1188 NewOps.push_back(i == OpNo ? Op : getOperand(i));
Galina Kistanovafc259902012-07-13 01:25:27 +00001189
Chris Lattner37e38352012-01-26 20:37:11 +00001190 return getWithOperands(NewOps);
Chris Lattner227816342006-07-14 22:20:01 +00001191}
1192
1193/// getWithOperands - This returns the current constant expression with the
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001194/// operands replaced with the specified values. The specified array must
1195/// have the same number of operands as our current one.
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001196Constant *ConstantExpr::getWithOperands(ArrayRef<Constant *> Ops, Type *Ty,
1197 bool OnlyIfReduced) const {
Jay Foad5c984e562011-04-13 13:46:01 +00001198 assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001199 bool AnyChange = Ty != getType();
1200 for (unsigned i = 0; i != Ops.size(); ++i)
Chris Lattner227816342006-07-14 22:20:01 +00001201 AnyChange |= Ops[i] != getOperand(i);
Galina Kistanovafc259902012-07-13 01:25:27 +00001202
Chris Lattner227816342006-07-14 22:20:01 +00001203 if (!AnyChange) // No operands changed, return self.
1204 return const_cast<ConstantExpr*>(this);
1205
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001206 Type *OnlyIfReducedTy = OnlyIfReduced ? Ty : nullptr;
Chris Lattner227816342006-07-14 22:20:01 +00001207 switch (getOpcode()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001208 case Instruction::Trunc:
1209 case Instruction::ZExt:
1210 case Instruction::SExt:
1211 case Instruction::FPTrunc:
1212 case Instruction::FPExt:
1213 case Instruction::UIToFP:
1214 case Instruction::SIToFP:
1215 case Instruction::FPToUI:
1216 case Instruction::FPToSI:
1217 case Instruction::PtrToInt:
1218 case Instruction::IntToPtr:
1219 case Instruction::BitCast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00001220 case Instruction::AddrSpaceCast:
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001221 return ConstantExpr::getCast(getOpcode(), Ops[0], Ty, OnlyIfReduced);
Chris Lattner227816342006-07-14 22:20:01 +00001222 case Instruction::Select:
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001223 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2], OnlyIfReducedTy);
Chris Lattner227816342006-07-14 22:20:01 +00001224 case Instruction::InsertElement:
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001225 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2],
1226 OnlyIfReducedTy);
Chris Lattner227816342006-07-14 22:20:01 +00001227 case Instruction::ExtractElement:
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001228 return ConstantExpr::getExtractElement(Ops[0], Ops[1], OnlyIfReducedTy);
Chris Lattner37e38352012-01-26 20:37:11 +00001229 case Instruction::InsertValue:
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001230 return ConstantExpr::getInsertValue(Ops[0], Ops[1], getIndices(),
1231 OnlyIfReducedTy);
Chris Lattner37e38352012-01-26 20:37:11 +00001232 case Instruction::ExtractValue:
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001233 return ConstantExpr::getExtractValue(Ops[0], getIndices(), OnlyIfReducedTy);
Chris Lattner227816342006-07-14 22:20:01 +00001234 case Instruction::ShuffleVector:
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001235 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2],
1236 OnlyIfReducedTy);
Chris Lattnerb5d70302007-02-19 20:01:23 +00001237 case Instruction::GetElementPtr:
Chris Lattner37e38352012-01-26 20:37:11 +00001238 return ConstantExpr::getGetElementPtr(Ops[0], Ops.slice(1),
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001239 cast<GEPOperator>(this)->isInBounds(),
1240 OnlyIfReducedTy);
Reid Spencer266e42b2006-12-23 06:05:41 +00001241 case Instruction::ICmp:
1242 case Instruction::FCmp:
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001243 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1],
1244 OnlyIfReducedTy);
Chris Lattner227816342006-07-14 22:20:01 +00001245 default:
1246 assert(getNumOperands() == 2 && "Must be binary operator?");
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001247 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1], SubclassOptionalData,
1248 OnlyIfReducedTy);
Chris Lattner7c1018a2006-07-14 19:37:40 +00001249 }
1250}
1251
Chris Lattner2f7c9632001-06-06 20:29:01 +00001252
1253//===----------------------------------------------------------------------===//
Chris Lattner2f7c9632001-06-06 20:29:01 +00001254// isValueValidForType implementations
1255
Chris Lattner229907c2011-07-18 04:54:35 +00001256bool ConstantInt::isValueValidForType(Type *Ty, uint64_t Val) {
Chris Lattner8326bd82012-01-26 00:42:34 +00001257 unsigned NumBits = Ty->getIntegerBitWidth(); // assert okay
1258 if (Ty->isIntegerTy(1))
Reid Spencer7a9c62b2007-01-12 07:05:14 +00001259 return Val == 0 || Val == 1;
Reid Spencerd7a00d72007-02-05 23:47:56 +00001260 if (NumBits >= 64)
Reid Spencer7a9c62b2007-01-12 07:05:14 +00001261 return true; // always true, has to fit in largest type
1262 uint64_t Max = (1ll << NumBits) - 1;
1263 return Val <= Max;
Reid Spencere7334722006-12-19 01:28:19 +00001264}
1265
Chris Lattner229907c2011-07-18 04:54:35 +00001266bool ConstantInt::isValueValidForType(Type *Ty, int64_t Val) {
Chris Lattner8326bd82012-01-26 00:42:34 +00001267 unsigned NumBits = Ty->getIntegerBitWidth();
1268 if (Ty->isIntegerTy(1))
Reid Spencera94d3942007-01-19 21:13:56 +00001269 return Val == 0 || Val == 1 || Val == -1;
Reid Spencerd7a00d72007-02-05 23:47:56 +00001270 if (NumBits >= 64)
Reid Spencer7a9c62b2007-01-12 07:05:14 +00001271 return true; // always true, has to fit in largest type
1272 int64_t Min = -(1ll << (NumBits-1));
1273 int64_t Max = (1ll << (NumBits-1)) - 1;
1274 return (Val >= Min && Val <= Max);
Chris Lattner2f7c9632001-06-06 20:29:01 +00001275}
1276
Chris Lattner229907c2011-07-18 04:54:35 +00001277bool ConstantFP::isValueValidForType(Type *Ty, const APFloat& Val) {
Dale Johannesend246b2c2007-08-30 00:23:21 +00001278 // convert modifies in place, so make a copy.
1279 APFloat Val2 = APFloat(Val);
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001280 bool losesInfo;
Chris Lattner6b727592004-06-17 18:19:28 +00001281 switch (Ty->getTypeID()) {
Chris Lattner2f7c9632001-06-06 20:29:01 +00001282 default:
1283 return false; // These can't be represented as floating point!
1284
Dale Johannesend246b2c2007-08-30 00:23:21 +00001285 // FIXME rounding mode needs to be more flexible
Dan Gohman518cda42011-12-17 00:04:22 +00001286 case Type::HalfTyID: {
1287 if (&Val2.getSemantics() == &APFloat::IEEEhalf)
1288 return true;
1289 Val2.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven, &losesInfo);
1290 return !losesInfo;
1291 }
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001292 case Type::FloatTyID: {
1293 if (&Val2.getSemantics() == &APFloat::IEEEsingle)
1294 return true;
1295 Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &losesInfo);
1296 return !losesInfo;
1297 }
1298 case Type::DoubleTyID: {
Dan Gohman518cda42011-12-17 00:04:22 +00001299 if (&Val2.getSemantics() == &APFloat::IEEEhalf ||
1300 &Val2.getSemantics() == &APFloat::IEEEsingle ||
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001301 &Val2.getSemantics() == &APFloat::IEEEdouble)
1302 return true;
1303 Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &losesInfo);
1304 return !losesInfo;
1305 }
Dale Johannesenbdad8092007-08-09 22:51:36 +00001306 case Type::X86_FP80TyID:
Dan Gohman518cda42011-12-17 00:04:22 +00001307 return &Val2.getSemantics() == &APFloat::IEEEhalf ||
1308 &Val2.getSemantics() == &APFloat::IEEEsingle ||
Dale Johannesen028084e2007-09-12 03:30:33 +00001309 &Val2.getSemantics() == &APFloat::IEEEdouble ||
1310 &Val2.getSemantics() == &APFloat::x87DoubleExtended;
Dale Johannesenbdad8092007-08-09 22:51:36 +00001311 case Type::FP128TyID:
Dan Gohman518cda42011-12-17 00:04:22 +00001312 return &Val2.getSemantics() == &APFloat::IEEEhalf ||
1313 &Val2.getSemantics() == &APFloat::IEEEsingle ||
Dale Johannesen028084e2007-09-12 03:30:33 +00001314 &Val2.getSemantics() == &APFloat::IEEEdouble ||
1315 &Val2.getSemantics() == &APFloat::IEEEquad;
Dale Johannesen007aa372007-10-11 18:07:22 +00001316 case Type::PPC_FP128TyID:
Dan Gohman518cda42011-12-17 00:04:22 +00001317 return &Val2.getSemantics() == &APFloat::IEEEhalf ||
1318 &Val2.getSemantics() == &APFloat::IEEEsingle ||
Dale Johannesen007aa372007-10-11 18:07:22 +00001319 &Val2.getSemantics() == &APFloat::IEEEdouble ||
1320 &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
Chris Lattner2f7c9632001-06-06 20:29:01 +00001321 }
Chris Lattneraa2372562006-05-24 17:04:05 +00001322}
Chris Lattner9655e542001-07-20 19:16:02 +00001323
Chris Lattner030af792012-01-24 05:42:11 +00001324
Chris Lattner49d855c2001-09-07 16:46:31 +00001325//===----------------------------------------------------------------------===//
Chris Lattner49d855c2001-09-07 16:46:31 +00001326// Factory Function Implementation
1327
Chris Lattnerc7f9fd42012-01-23 15:20:12 +00001328ConstantAggregateZero *ConstantAggregateZero::get(Type *Ty) {
Chris Lattner13ee7952010-08-28 04:09:24 +00001329 assert((Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()) &&
Owen Andersonb292b8c2009-07-30 23:03:37 +00001330 "Cannot create an aggregate zero of non-aggregate type!");
David Blaikiecb2818f2014-11-25 02:26:22 +00001331
1332 ConstantAggregateZero *&Entry = Ty->getContext().pImpl->CAZConstants[Ty];
David Blaikie899b85a2014-11-25 02:13:54 +00001333 if (!Entry)
David Blaikiecb2818f2014-11-25 02:26:22 +00001334 Entry = new ConstantAggregateZero(Ty);
David Blaikie899b85a2014-11-25 02:13:54 +00001335
David Blaikiecb2818f2014-11-25 02:26:22 +00001336 return Entry;
Owen Andersonb292b8c2009-07-30 23:03:37 +00001337}
1338
Chris Lattner030af792012-01-24 05:42:11 +00001339/// destroyConstant - Remove the constant from the constant table.
Dan Gohman92b551b2009-03-03 02:55:14 +00001340///
Owen Anderson0d2de8c2009-06-20 00:24:58 +00001341void ConstantAggregateZero::destroyConstant() {
Chris Lattnerc7f9fd42012-01-23 15:20:12 +00001342 getContext().pImpl->CAZConstants.erase(getType());
Chris Lattner9fba3da2004-02-15 05:53:04 +00001343 destroyConstantImpl();
1344}
1345
Dan Gohman92b551b2009-03-03 02:55:14 +00001346/// destroyConstant - Remove the constant from the constant table...
1347///
Owen Anderson0d2de8c2009-06-20 00:24:58 +00001348void ConstantArray::destroyConstant() {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001349 getType()->getContext().pImpl->ArrayConstants.remove(this);
Chris Lattner98fa07b2003-05-23 20:03:32 +00001350 destroyConstantImpl();
1351}
1352
Chris Lattner81fabb02002-08-26 17:53:56 +00001353
Chris Lattner3462ae32001-12-03 22:26:30 +00001354//---- ConstantStruct::get() implementation...
Chris Lattner49d855c2001-09-07 16:46:31 +00001355//
Chris Lattnerb50d1352003-10-05 00:17:43 +00001356
Chris Lattnerd7a73302001-10-13 06:57:33 +00001357// destroyConstant - Remove the constant from the constant table...
Chris Lattner883ad0b2001-10-03 15:39:36 +00001358//
Owen Anderson0d2de8c2009-06-20 00:24:58 +00001359void ConstantStruct::destroyConstant() {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001360 getType()->getContext().pImpl->StructConstants.remove(this);
Chris Lattnerd7a73302001-10-13 06:57:33 +00001361 destroyConstantImpl();
1362}
Chris Lattner883ad0b2001-10-03 15:39:36 +00001363
Brian Gaeke02209042004-08-20 06:00:58 +00001364// destroyConstant - Remove the constant from the constant table...
1365//
Owen Anderson0d2de8c2009-06-20 00:24:58 +00001366void ConstantVector::destroyConstant() {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001367 getType()->getContext().pImpl->VectorConstants.remove(this);
Brian Gaeke02209042004-08-20 06:00:58 +00001368 destroyConstantImpl();
1369}
1370
Duncan Sandse6beec62012-11-13 12:59:33 +00001371/// getSplatValue - If this is a splat vector constant, meaning that all of
1372/// the elements have the same value, return that value. Otherwise return 0.
1373Constant *Constant::getSplatValue() const {
1374 assert(this->getType()->isVectorTy() && "Only valid for vectors!");
1375 if (isa<ConstantAggregateZero>(this))
1376 return getNullValue(this->getType()->getVectorElementType());
1377 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
1378 return CV->getSplatValue();
1379 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
1380 return CV->getSplatValue();
Craig Topperc6207612014-04-09 06:08:46 +00001381 return nullptr;
Duncan Sandse6beec62012-11-13 12:59:33 +00001382}
1383
Dan Gohman07159202007-10-17 17:51:30 +00001384/// getSplatValue - If this is a splat constant, where all of the
1385/// elements have the same value, return that value. Otherwise return null.
Duncan Sandscf0ff032011-02-01 08:39:12 +00001386Constant *ConstantVector::getSplatValue() const {
Dan Gohman07159202007-10-17 17:51:30 +00001387 // Check out first element.
1388 Constant *Elt = getOperand(0);
1389 // Then make sure all remaining elements point to the same value.
1390 for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
Chris Lattnerd04e32d2011-07-17 06:01:30 +00001391 if (getOperand(I) != Elt)
Craig Topperc6207612014-04-09 06:08:46 +00001392 return nullptr;
Dan Gohman07159202007-10-17 17:51:30 +00001393 return Elt;
1394}
1395
Duncan Sandse6beec62012-11-13 12:59:33 +00001396/// If C is a constant integer then return its value, otherwise C must be a
1397/// vector of constant integers, all equal, and the common value is returned.
1398const APInt &Constant::getUniqueInteger() const {
1399 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
1400 return CI->getValue();
1401 assert(this->getSplatValue() && "Doesn't contain a unique integer!");
1402 const Constant *C = this->getAggregateElement(0U);
1403 assert(C && isa<ConstantInt>(C) && "Not a vector of numbers!");
1404 return cast<ConstantInt>(C)->getValue();
1405}
1406
1407
Chris Lattner31b132c2009-10-28 00:01:44 +00001408//---- ConstantPointerNull::get() implementation.
Chris Lattnerd7a73302001-10-13 06:57:33 +00001409//
Chris Lattner98fa07b2003-05-23 20:03:32 +00001410
Chris Lattner229907c2011-07-18 04:54:35 +00001411ConstantPointerNull *ConstantPointerNull::get(PointerType *Ty) {
Chris Lattnerc7f9fd42012-01-23 15:20:12 +00001412 ConstantPointerNull *&Entry = Ty->getContext().pImpl->CPNConstants[Ty];
Craig Topperc6207612014-04-09 06:08:46 +00001413 if (!Entry)
Chris Lattnerc7f9fd42012-01-23 15:20:12 +00001414 Entry = new ConstantPointerNull(Ty);
Galina Kistanovafc259902012-07-13 01:25:27 +00001415
Chris Lattnerc7f9fd42012-01-23 15:20:12 +00001416 return Entry;
Chris Lattner883ad0b2001-10-03 15:39:36 +00001417}
1418
Chris Lattner0c6e0b92002-08-18 00:40:04 +00001419// destroyConstant - Remove the constant from the constant table...
1420//
Owen Anderson0d2de8c2009-06-20 00:24:58 +00001421void ConstantPointerNull::destroyConstant() {
Chris Lattnerc7f9fd42012-01-23 15:20:12 +00001422 getContext().pImpl->CPNConstants.erase(getType());
1423 // Free the constant and any dangling references to it.
Chris Lattner0c6e0b92002-08-18 00:40:04 +00001424 destroyConstantImpl();
1425}
1426
1427
Chris Lattner31b132c2009-10-28 00:01:44 +00001428//---- UndefValue::get() implementation.
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001429//
1430
Chris Lattner229907c2011-07-18 04:54:35 +00001431UndefValue *UndefValue::get(Type *Ty) {
Chris Lattnerc7f9fd42012-01-23 15:20:12 +00001432 UndefValue *&Entry = Ty->getContext().pImpl->UVConstants[Ty];
Craig Topperc6207612014-04-09 06:08:46 +00001433 if (!Entry)
Chris Lattnerc7f9fd42012-01-23 15:20:12 +00001434 Entry = new UndefValue(Ty);
Galina Kistanovafc259902012-07-13 01:25:27 +00001435
Chris Lattnerc7f9fd42012-01-23 15:20:12 +00001436 return Entry;
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001437}
1438
1439// destroyConstant - Remove the constant from the constant table.
1440//
Owen Anderson0d2de8c2009-06-20 00:24:58 +00001441void UndefValue::destroyConstant() {
Chris Lattnerc7f9fd42012-01-23 15:20:12 +00001442 // Free the constant and any dangling references to it.
1443 getContext().pImpl->UVConstants.erase(getType());
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001444 destroyConstantImpl();
1445}
1446
Chris Lattner31b132c2009-10-28 00:01:44 +00001447//---- BlockAddress::get() implementation.
1448//
1449
1450BlockAddress *BlockAddress::get(BasicBlock *BB) {
Craig Topper2617dcc2014-04-15 06:32:26 +00001451 assert(BB->getParent() && "Block must have a parent");
Chris Lattner31b132c2009-10-28 00:01:44 +00001452 return get(BB->getParent(), BB);
1453}
1454
1455BlockAddress *BlockAddress::get(Function *F, BasicBlock *BB) {
1456 BlockAddress *&BA =
1457 F->getContext().pImpl->BlockAddresses[std::make_pair(F, BB)];
Craig Topperc6207612014-04-09 06:08:46 +00001458 if (!BA)
Chris Lattner31b132c2009-10-28 00:01:44 +00001459 BA = new BlockAddress(F, BB);
Galina Kistanovafc259902012-07-13 01:25:27 +00001460
Chris Lattner31b132c2009-10-28 00:01:44 +00001461 assert(BA->getFunction() == F && "Basic block moved between functions");
1462 return BA;
1463}
1464
1465BlockAddress::BlockAddress(Function *F, BasicBlock *BB)
1466: Constant(Type::getInt8PtrTy(F->getContext()), Value::BlockAddressVal,
1467 &Op<0>(), 2) {
Chris Lattnerc559a9f2009-11-01 03:03:03 +00001468 setOperand(0, F);
1469 setOperand(1, BB);
Chris Lattneraa99c942009-11-01 01:27:45 +00001470 BB->AdjustBlockAddressRefCount(1);
Chris Lattner31b132c2009-10-28 00:01:44 +00001471}
1472
Chandler Carruth6a936922014-01-19 02:13:50 +00001473BlockAddress *BlockAddress::lookup(const BasicBlock *BB) {
1474 if (!BB->hasAddressTaken())
Craig Topperc6207612014-04-09 06:08:46 +00001475 return nullptr;
Chandler Carruth6a936922014-01-19 02:13:50 +00001476
1477 const Function *F = BB->getParent();
Craig Topper2617dcc2014-04-15 06:32:26 +00001478 assert(F && "Block must have a parent");
Chandler Carruth6a936922014-01-19 02:13:50 +00001479 BlockAddress *BA =
1480 F->getContext().pImpl->BlockAddresses.lookup(std::make_pair(F, BB));
1481 assert(BA && "Refcount and block address map disagree!");
1482 return BA;
1483}
Chris Lattner31b132c2009-10-28 00:01:44 +00001484
1485// destroyConstant - Remove the constant from the constant table.
1486//
1487void BlockAddress::destroyConstant() {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001488 getFunction()->getType()->getContext().pImpl
Chris Lattner31b132c2009-10-28 00:01:44 +00001489 ->BlockAddresses.erase(std::make_pair(getFunction(), getBasicBlock()));
Chris Lattneraa99c942009-11-01 01:27:45 +00001490 getBasicBlock()->AdjustBlockAddressRefCount(-1);
Chris Lattner31b132c2009-10-28 00:01:44 +00001491 destroyConstantImpl();
1492}
1493
1494void BlockAddress::replaceUsesOfWithOnConstant(Value *From, Value *To, Use *U) {
1495 // This could be replacing either the Basic Block or the Function. In either
1496 // case, we have to remove the map entry.
1497 Function *NewF = getFunction();
1498 BasicBlock *NewBB = getBasicBlock();
Galina Kistanovafc259902012-07-13 01:25:27 +00001499
Chris Lattner31b132c2009-10-28 00:01:44 +00001500 if (U == &Op<0>())
Derek Schuffec9dc012013-06-13 19:51:17 +00001501 NewF = cast<Function>(To->stripPointerCasts());
Chris Lattner31b132c2009-10-28 00:01:44 +00001502 else
1503 NewBB = cast<BasicBlock>(To);
Galina Kistanovafc259902012-07-13 01:25:27 +00001504
Chris Lattner31b132c2009-10-28 00:01:44 +00001505 // See if the 'new' entry already exists, if not, just update this in place
1506 // and return early.
1507 BlockAddress *&NewBA =
1508 getContext().pImpl->BlockAddresses[std::make_pair(NewF, NewBB)];
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00001509 if (NewBA) {
1510 replaceUsesOfWithOnConstantImpl(NewBA);
Chris Lattner31b132c2009-10-28 00:01:44 +00001511 return;
1512 }
1513
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00001514 getBasicBlock()->AdjustBlockAddressRefCount(-1);
Galina Kistanovafc259902012-07-13 01:25:27 +00001515
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00001516 // Remove the old entry, this can't cause the map to rehash (just a
1517 // tombstone will get added).
1518 getContext().pImpl->BlockAddresses.erase(std::make_pair(getFunction(),
1519 getBasicBlock()));
1520 NewBA = this;
1521 setOperand(0, NewF);
1522 setOperand(1, NewBB);
1523 getBasicBlock()->AdjustBlockAddressRefCount(1);
Chris Lattner31b132c2009-10-28 00:01:44 +00001524}
1525
1526//---- ConstantExpr::get() implementations.
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001527//
Reid Spencer8d9336d2006-12-31 05:26:44 +00001528
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001529/// This is a utility function to handle folding of casts and lookup of the
Duncan Sands7d6c8ae2008-03-30 19:38:55 +00001530/// cast in the ExprConstants map. It is used by the various get* methods below.
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001531static Constant *getFoldedCast(Instruction::CastOps opc, Constant *C, Type *Ty,
1532 bool OnlyIfReduced = false) {
Chris Lattner815ae2b2003-10-07 22:19:19 +00001533 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001534 // Fold a few common cases
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00001535 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001536 return FC;
Chris Lattneracdbe712003-04-17 19:24:48 +00001537
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001538 if (OnlyIfReduced)
1539 return nullptr;
1540
Owen Anderson1584a292009-08-04 20:25:11 +00001541 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
1542
Nadav Rotem88330432013-03-07 01:30:40 +00001543 // Look up the constant in the table first to ensure uniqueness.
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00001544 ConstantExprKeyType Key(opc, C);
Galina Kistanovafc259902012-07-13 01:25:27 +00001545
Owen Anderson1584a292009-08-04 20:25:11 +00001546 return pImpl->ExprConstants.getOrCreate(Ty, Key);
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001547}
Galina Kistanovafc259902012-07-13 01:25:27 +00001548
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001549Constant *ConstantExpr::getCast(unsigned oc, Constant *C, Type *Ty,
1550 bool OnlyIfReduced) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001551 Instruction::CastOps opc = Instruction::CastOps(oc);
1552 assert(Instruction::isCast(opc) && "opcode out of range");
1553 assert(C && Ty && "Null arguments to getCast");
Chris Lattner37bc78a2010-01-26 21:51:43 +00001554 assert(CastInst::castIsValid(opc, C, Ty) && "Invalid constantexpr cast!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001555
1556 switch (opc) {
Chris Lattner37bc78a2010-01-26 21:51:43 +00001557 default:
1558 llvm_unreachable("Invalid cast opcode");
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001559 case Instruction::Trunc:
1560 return getTrunc(C, Ty, OnlyIfReduced);
1561 case Instruction::ZExt:
1562 return getZExt(C, Ty, OnlyIfReduced);
1563 case Instruction::SExt:
1564 return getSExt(C, Ty, OnlyIfReduced);
1565 case Instruction::FPTrunc:
1566 return getFPTrunc(C, Ty, OnlyIfReduced);
1567 case Instruction::FPExt:
1568 return getFPExtend(C, Ty, OnlyIfReduced);
1569 case Instruction::UIToFP:
1570 return getUIToFP(C, Ty, OnlyIfReduced);
1571 case Instruction::SIToFP:
1572 return getSIToFP(C, Ty, OnlyIfReduced);
1573 case Instruction::FPToUI:
1574 return getFPToUI(C, Ty, OnlyIfReduced);
1575 case Instruction::FPToSI:
1576 return getFPToSI(C, Ty, OnlyIfReduced);
1577 case Instruction::PtrToInt:
1578 return getPtrToInt(C, Ty, OnlyIfReduced);
1579 case Instruction::IntToPtr:
1580 return getIntToPtr(C, Ty, OnlyIfReduced);
1581 case Instruction::BitCast:
1582 return getBitCast(C, Ty, OnlyIfReduced);
1583 case Instruction::AddrSpaceCast:
1584 return getAddrSpaceCast(C, Ty, OnlyIfReduced);
Chris Lattner1ece6f82005-01-01 15:59:57 +00001585 }
Galina Kistanovafc259902012-07-13 01:25:27 +00001586}
Reid Spencerf37dc652006-12-05 19:14:13 +00001587
Chris Lattner229907c2011-07-18 04:54:35 +00001588Constant *ConstantExpr::getZExtOrBitCast(Constant *C, Type *Ty) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001589 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
Dan Gohman3cdcc3f2010-04-12 22:12:29 +00001590 return getBitCast(C, Ty);
1591 return getZExt(C, Ty);
Reid Spencer5c140882006-12-04 20:17:56 +00001592}
1593
Chris Lattner229907c2011-07-18 04:54:35 +00001594Constant *ConstantExpr::getSExtOrBitCast(Constant *C, Type *Ty) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001595 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
Dan Gohman3cdcc3f2010-04-12 22:12:29 +00001596 return getBitCast(C, Ty);
1597 return getSExt(C, Ty);
Reid Spencer5c140882006-12-04 20:17:56 +00001598}
1599
Chris Lattner229907c2011-07-18 04:54:35 +00001600Constant *ConstantExpr::getTruncOrBitCast(Constant *C, Type *Ty) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001601 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
Dan Gohman3cdcc3f2010-04-12 22:12:29 +00001602 return getBitCast(C, Ty);
1603 return getTrunc(C, Ty);
Reid Spencer5c140882006-12-04 20:17:56 +00001604}
1605
Chris Lattner229907c2011-07-18 04:54:35 +00001606Constant *ConstantExpr::getPointerCast(Constant *S, Type *Ty) {
Evgeniy Stepanov23382642013-01-16 14:41:46 +00001607 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
1608 assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
1609 "Invalid cast");
Reid Spencerbc245a02006-12-05 03:25:26 +00001610
Evgeniy Stepanov23382642013-01-16 14:41:46 +00001611 if (Ty->isIntOrIntVectorTy())
Dan Gohman3cdcc3f2010-04-12 22:12:29 +00001612 return getPtrToInt(S, Ty);
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00001613
1614 unsigned SrcAS = S->getType()->getPointerAddressSpace();
1615 if (Ty->isPtrOrPtrVectorTy() && SrcAS != Ty->getPointerAddressSpace())
1616 return getAddrSpaceCast(S, Ty);
1617
Dan Gohman3cdcc3f2010-04-12 22:12:29 +00001618 return getBitCast(S, Ty);
Reid Spencerbc245a02006-12-05 03:25:26 +00001619}
1620
Matt Arsenault21f38f42013-12-07 02:58:41 +00001621Constant *ConstantExpr::getPointerBitCastOrAddrSpaceCast(Constant *S,
1622 Type *Ty) {
1623 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
1624 assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast");
1625
1626 if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace())
1627 return getAddrSpaceCast(S, Ty);
1628
1629 return getBitCast(S, Ty);
1630}
1631
1632Constant *ConstantExpr::getIntegerCast(Constant *C, Type *Ty,
Reid Spencer56521c42006-12-12 00:51:07 +00001633 bool isSigned) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00001634 assert(C->getType()->isIntOrIntVectorTy() &&
1635 Ty->isIntOrIntVectorTy() && "Invalid cast");
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001636 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1637 unsigned DstBits = Ty->getScalarSizeInBits();
Reid Spencer56521c42006-12-12 00:51:07 +00001638 Instruction::CastOps opcode =
1639 (SrcBits == DstBits ? Instruction::BitCast :
1640 (SrcBits > DstBits ? Instruction::Trunc :
1641 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1642 return getCast(opcode, C, Ty);
1643}
1644
Chris Lattner229907c2011-07-18 04:54:35 +00001645Constant *ConstantExpr::getFPCast(Constant *C, Type *Ty) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00001646 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
Reid Spencer56521c42006-12-12 00:51:07 +00001647 "Invalid cast");
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001648 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1649 unsigned DstBits = Ty->getScalarSizeInBits();
Reid Spencerca104e82006-12-12 05:38:50 +00001650 if (SrcBits == DstBits)
1651 return C; // Avoid a useless cast
Reid Spencer56521c42006-12-12 00:51:07 +00001652 Instruction::CastOps opcode =
Jay Foad9f32cfd2011-01-27 14:44:55 +00001653 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
Reid Spencer56521c42006-12-12 00:51:07 +00001654 return getCast(opcode, C, Ty);
1655}
1656
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001657Constant *ConstantExpr::getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001658#ifndef NDEBUG
1659 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1660 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1661#endif
1662 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001663 assert(C->getType()->isIntOrIntVectorTy() && "Trunc operand must be integer");
1664 assert(Ty->isIntOrIntVectorTy() && "Trunc produces only integral");
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001665 assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001666 "SrcTy must be larger than DestTy for Trunc!");
1667
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001668 return getFoldedCast(Instruction::Trunc, C, Ty, OnlyIfReduced);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001669}
1670
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001671Constant *ConstantExpr::getSExt(Constant *C, Type *Ty, bool OnlyIfReduced) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001672#ifndef NDEBUG
1673 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1674 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1675#endif
1676 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001677 assert(C->getType()->isIntOrIntVectorTy() && "SExt operand must be integral");
1678 assert(Ty->isIntOrIntVectorTy() && "SExt produces only integer");
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001679 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001680 "SrcTy must be smaller than DestTy for SExt!");
1681
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001682 return getFoldedCast(Instruction::SExt, C, Ty, OnlyIfReduced);
Chris Lattnerdd284742004-04-04 23:20:30 +00001683}
1684
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001685Constant *ConstantExpr::getZExt(Constant *C, Type *Ty, bool OnlyIfReduced) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001686#ifndef NDEBUG
1687 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1688 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1689#endif
1690 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001691 assert(C->getType()->isIntOrIntVectorTy() && "ZEXt operand must be integral");
1692 assert(Ty->isIntOrIntVectorTy() && "ZExt produces only integer");
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001693 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001694 "SrcTy must be smaller than DestTy for ZExt!");
1695
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001696 return getFoldedCast(Instruction::ZExt, C, Ty, OnlyIfReduced);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001697}
1698
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001699Constant *ConstantExpr::getFPTrunc(Constant *C, Type *Ty, bool OnlyIfReduced) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001700#ifndef NDEBUG
1701 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1702 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1703#endif
1704 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001705 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001706 C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001707 "This is an illegal floating point truncation!");
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001708 return getFoldedCast(Instruction::FPTrunc, C, Ty, OnlyIfReduced);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001709}
1710
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001711Constant *ConstantExpr::getFPExtend(Constant *C, Type *Ty, bool OnlyIfReduced) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001712#ifndef NDEBUG
1713 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1714 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1715#endif
1716 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001717 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001718 C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001719 "This is an illegal floating point extension!");
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001720 return getFoldedCast(Instruction::FPExt, C, Ty, OnlyIfReduced);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001721}
1722
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001723Constant *ConstantExpr::getUIToFP(Constant *C, Type *Ty, bool OnlyIfReduced) {
Devang Pateld26344d2008-11-03 23:20:04 +00001724#ifndef NDEBUG
Nate Begemand4d45c22007-11-17 03:58:34 +00001725 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1726 bool toVec = Ty->getTypeID() == Type::VectorTyID;
Devang Pateld26344d2008-11-03 23:20:04 +00001727#endif
Nate Begemand4d45c22007-11-17 03:58:34 +00001728 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001729 assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
Nate Begemand4d45c22007-11-17 03:58:34 +00001730 "This is an illegal uint to floating point cast!");
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001731 return getFoldedCast(Instruction::UIToFP, C, Ty, OnlyIfReduced);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001732}
1733
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001734Constant *ConstantExpr::getSIToFP(Constant *C, Type *Ty, bool OnlyIfReduced) {
Devang Pateld26344d2008-11-03 23:20:04 +00001735#ifndef NDEBUG
Nate Begemand4d45c22007-11-17 03:58:34 +00001736 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1737 bool toVec = Ty->getTypeID() == Type::VectorTyID;
Devang Pateld26344d2008-11-03 23:20:04 +00001738#endif
Nate Begemand4d45c22007-11-17 03:58:34 +00001739 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001740 assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001741 "This is an illegal sint to floating point cast!");
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001742 return getFoldedCast(Instruction::SIToFP, C, Ty, OnlyIfReduced);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001743}
1744
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001745Constant *ConstantExpr::getFPToUI(Constant *C, Type *Ty, bool OnlyIfReduced) {
Devang Pateld26344d2008-11-03 23:20:04 +00001746#ifndef NDEBUG
Nate Begemand4d45c22007-11-17 03:58:34 +00001747 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1748 bool toVec = Ty->getTypeID() == Type::VectorTyID;
Devang Pateld26344d2008-11-03 23:20:04 +00001749#endif
Nate Begemand4d45c22007-11-17 03:58:34 +00001750 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001751 assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
Nate Begemand4d45c22007-11-17 03:58:34 +00001752 "This is an illegal floating point to uint cast!");
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001753 return getFoldedCast(Instruction::FPToUI, C, Ty, OnlyIfReduced);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001754}
1755
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001756Constant *ConstantExpr::getFPToSI(Constant *C, Type *Ty, bool OnlyIfReduced) {
Devang Pateld26344d2008-11-03 23:20:04 +00001757#ifndef NDEBUG
Nate Begemand4d45c22007-11-17 03:58:34 +00001758 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1759 bool toVec = Ty->getTypeID() == Type::VectorTyID;
Devang Pateld26344d2008-11-03 23:20:04 +00001760#endif
Nate Begemand4d45c22007-11-17 03:58:34 +00001761 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001762 assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
Nate Begemand4d45c22007-11-17 03:58:34 +00001763 "This is an illegal floating point to sint cast!");
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001764 return getFoldedCast(Instruction::FPToSI, C, Ty, OnlyIfReduced);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001765}
1766
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001767Constant *ConstantExpr::getPtrToInt(Constant *C, Type *DstTy,
1768 bool OnlyIfReduced) {
Nadav Rotem3924cb02011-12-05 06:29:09 +00001769 assert(C->getType()->getScalarType()->isPointerTy() &&
1770 "PtrToInt source must be pointer or pointer vector");
1771 assert(DstTy->getScalarType()->isIntegerTy() &&
1772 "PtrToInt destination must be integer or integer vector");
Chris Lattner8a3df542012-01-25 01:32:59 +00001773 assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
Nick Lewyckyff509622012-01-25 03:20:12 +00001774 if (isa<VectorType>(C->getType()))
Chris Lattner8326bd82012-01-26 00:42:34 +00001775 assert(C->getType()->getVectorNumElements()==DstTy->getVectorNumElements()&&
Chris Lattner8a3df542012-01-25 01:32:59 +00001776 "Invalid cast between a different number of vector elements");
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001777 return getFoldedCast(Instruction::PtrToInt, C, DstTy, OnlyIfReduced);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001778}
1779
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001780Constant *ConstantExpr::getIntToPtr(Constant *C, Type *DstTy,
1781 bool OnlyIfReduced) {
Nadav Rotem3924cb02011-12-05 06:29:09 +00001782 assert(C->getType()->getScalarType()->isIntegerTy() &&
1783 "IntToPtr source must be integer or integer vector");
1784 assert(DstTy->getScalarType()->isPointerTy() &&
1785 "IntToPtr destination must be a pointer or pointer vector");
Chris Lattner8a3df542012-01-25 01:32:59 +00001786 assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
Nick Lewyckyff509622012-01-25 03:20:12 +00001787 if (isa<VectorType>(C->getType()))
Chris Lattner8326bd82012-01-26 00:42:34 +00001788 assert(C->getType()->getVectorNumElements()==DstTy->getVectorNumElements()&&
Chris Lattner8a3df542012-01-25 01:32:59 +00001789 "Invalid cast between a different number of vector elements");
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001790 return getFoldedCast(Instruction::IntToPtr, C, DstTy, OnlyIfReduced);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001791}
1792
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001793Constant *ConstantExpr::getBitCast(Constant *C, Type *DstTy,
1794 bool OnlyIfReduced) {
Chris Lattner37bc78a2010-01-26 21:51:43 +00001795 assert(CastInst::castIsValid(Instruction::BitCast, C, DstTy) &&
1796 "Invalid constantexpr bitcast!");
Galina Kistanovafc259902012-07-13 01:25:27 +00001797
Chris Lattnercbeda872009-03-21 06:55:54 +00001798 // It is common to ask for a bitcast of a value to its own type, handle this
1799 // speedily.
1800 if (C->getType() == DstTy) return C;
Galina Kistanovafc259902012-07-13 01:25:27 +00001801
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001802 return getFoldedCast(Instruction::BitCast, C, DstTy, OnlyIfReduced);
Chris Lattnerdd284742004-04-04 23:20:30 +00001803}
1804
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001805Constant *ConstantExpr::getAddrSpaceCast(Constant *C, Type *DstTy,
1806 bool OnlyIfReduced) {
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00001807 assert(CastInst::castIsValid(Instruction::AddrSpaceCast, C, DstTy) &&
1808 "Invalid constantexpr addrspacecast!");
1809
Jingyue Wubaabe502014-06-15 21:40:57 +00001810 // Canonicalize addrspacecasts between different pointer types by first
1811 // bitcasting the pointer type and then converting the address space.
1812 PointerType *SrcScalarTy = cast<PointerType>(C->getType()->getScalarType());
1813 PointerType *DstScalarTy = cast<PointerType>(DstTy->getScalarType());
1814 Type *DstElemTy = DstScalarTy->getElementType();
1815 if (SrcScalarTy->getElementType() != DstElemTy) {
1816 Type *MidTy = PointerType::get(DstElemTy, SrcScalarTy->getAddressSpace());
1817 if (VectorType *VT = dyn_cast<VectorType>(DstTy)) {
1818 // Handle vectors of pointers.
1819 MidTy = VectorType::get(MidTy, VT->getNumElements());
1820 }
1821 C = getBitCast(C, MidTy);
1822 }
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001823 return getFoldedCast(Instruction::AddrSpaceCast, C, DstTy, OnlyIfReduced);
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00001824}
1825
Chris Lattner887ecac2011-07-09 18:23:52 +00001826Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2,
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001827 unsigned Flags, Type *OnlyIfReducedTy) {
Chris Lattner887ecac2011-07-09 18:23:52 +00001828 // Check the operands for consistency first.
Reid Spencer7eb55b32006-11-02 01:53:59 +00001829 assert(Opcode >= Instruction::BinaryOpsBegin &&
1830 Opcode < Instruction::BinaryOpsEnd &&
Chris Lattner38a9bcd2003-05-21 17:49:25 +00001831 "Invalid opcode in binary constant expression");
1832 assert(C1->getType() == C2->getType() &&
1833 "Operand types in binary constant expression should match");
Galina Kistanovafc259902012-07-13 01:25:27 +00001834
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001835#ifndef NDEBUG
1836 switch (Opcode) {
Dan Gohmana5b96452009-06-04 22:49:04 +00001837 case Instruction::Add:
Reid Spencer7eb55b32006-11-02 01:53:59 +00001838 case Instruction::Sub:
Dan Gohmana5b96452009-06-04 22:49:04 +00001839 case Instruction::Mul:
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001840 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001841 assert(C1->getType()->isIntOrIntVectorTy() &&
Dan Gohmana5b96452009-06-04 22:49:04 +00001842 "Tried to create an integer operation on a non-integer type!");
1843 break;
1844 case Instruction::FAdd:
1845 case Instruction::FSub:
1846 case Instruction::FMul:
1847 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001848 assert(C1->getType()->isFPOrFPVectorTy() &&
Dan Gohmana5b96452009-06-04 22:49:04 +00001849 "Tried to create a floating-point operation on a "
1850 "non-floating-point type!");
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001851 break;
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001852 case Instruction::UDiv:
1853 case Instruction::SDiv:
1854 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001855 assert(C1->getType()->isIntOrIntVectorTy() &&
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001856 "Tried to create an arithmetic operation on a non-arithmetic type!");
1857 break;
1858 case Instruction::FDiv:
1859 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001860 assert(C1->getType()->isFPOrFPVectorTy() &&
Dan Gohman7889f2b2009-06-15 22:25:12 +00001861 "Tried to create an arithmetic operation on a non-arithmetic type!");
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001862 break;
Reid Spencer7eb55b32006-11-02 01:53:59 +00001863 case Instruction::URem:
1864 case Instruction::SRem:
1865 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001866 assert(C1->getType()->isIntOrIntVectorTy() &&
Reid Spencer7eb55b32006-11-02 01:53:59 +00001867 "Tried to create an arithmetic operation on a non-arithmetic type!");
1868 break;
1869 case Instruction::FRem:
1870 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001871 assert(C1->getType()->isFPOrFPVectorTy() &&
Dan Gohman7889f2b2009-06-15 22:25:12 +00001872 "Tried to create an arithmetic operation on a non-arithmetic type!");
Reid Spencer7eb55b32006-11-02 01:53:59 +00001873 break;
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001874 case Instruction::And:
1875 case Instruction::Or:
1876 case Instruction::Xor:
1877 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001878 assert(C1->getType()->isIntOrIntVectorTy() &&
Misha Brukman3852f652005-01-27 06:46:38 +00001879 "Tried to create a logical operation on a non-integral type!");
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001880 break;
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001881 case Instruction::Shl:
Reid Spencerfdff9382006-11-08 06:47:33 +00001882 case Instruction::LShr:
1883 case Instruction::AShr:
Reid Spencer2341c222007-02-02 02:16:23 +00001884 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001885 assert(C1->getType()->isIntOrIntVectorTy() &&
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001886 "Tried to create a shift operation on a non-integer type!");
1887 break;
1888 default:
1889 break;
1890 }
1891#endif
1892
Chris Lattner887ecac2011-07-09 18:23:52 +00001893 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1894 return FC; // Fold a few common cases.
Galina Kistanovafc259902012-07-13 01:25:27 +00001895
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001896 if (OnlyIfReducedTy == C1->getType())
1897 return nullptr;
1898
Benjamin Kramer324322b2013-03-07 20:53:34 +00001899 Constant *ArgVec[] = { C1, C2 };
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00001900 ConstantExprKeyType Key(Opcode, ArgVec, 0, Flags);
Galina Kistanovafc259902012-07-13 01:25:27 +00001901
Chris Lattner887ecac2011-07-09 18:23:52 +00001902 LLVMContextImpl *pImpl = C1->getContext().pImpl;
1903 return pImpl->ExprConstants.getOrCreate(C1->getType(), Key);
Reid Spencera009d0d2006-12-04 21:35:24 +00001904}
1905
Chris Lattner229907c2011-07-18 04:54:35 +00001906Constant *ConstantExpr::getSizeOf(Type* Ty) {
Owen Anderson487375e2009-07-29 18:55:55 +00001907 // sizeof is implemented as: (i64) gep (Ty*)null, 1
1908 // Note that a non-inbounds gep is used, as null isn't within any object.
Owen Anderson55f1c092009-08-13 21:58:54 +00001909 Constant *GEPIdx = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
Owen Anderson487375e2009-07-29 18:55:55 +00001910 Constant *GEP = getGetElementPtr(
Jay Foaded8db7d2011-07-21 14:31:17 +00001911 Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx);
Dan Gohman3cdcc3f2010-04-12 22:12:29 +00001912 return getPtrToInt(GEP,
1913 Type::getInt64Ty(Ty->getContext()));
Owen Anderson487375e2009-07-29 18:55:55 +00001914}
1915
Chris Lattner229907c2011-07-18 04:54:35 +00001916Constant *ConstantExpr::getAlignOf(Type* Ty) {
Dan Gohmancf913832010-01-28 02:15:55 +00001917 // alignof is implemented as: (i64) gep ({i1,Ty}*)null, 0, 1
Dan Gohman50c09d02009-08-11 17:57:01 +00001918 // Note that a non-inbounds gep is used, as null isn't within any object.
Chris Lattner229907c2011-07-18 04:54:35 +00001919 Type *AligningTy =
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001920 StructType::get(Type::getInt1Ty(Ty->getContext()), Ty, nullptr);
Matt Arsenaultbe558882014-04-23 20:58:57 +00001921 Constant *NullPtr = Constant::getNullValue(AligningTy->getPointerTo(0));
Dan Gohmana9be7392010-01-28 02:43:22 +00001922 Constant *Zero = ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0);
Owen Anderson55f1c092009-08-13 21:58:54 +00001923 Constant *One = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
Owen Anderson487375e2009-07-29 18:55:55 +00001924 Constant *Indices[2] = { Zero, One };
Jay Foaded8db7d2011-07-21 14:31:17 +00001925 Constant *GEP = getGetElementPtr(NullPtr, Indices);
Dan Gohman3cdcc3f2010-04-12 22:12:29 +00001926 return getPtrToInt(GEP,
1927 Type::getInt64Ty(Ty->getContext()));
Owen Anderson487375e2009-07-29 18:55:55 +00001928}
1929
Chris Lattner229907c2011-07-18 04:54:35 +00001930Constant *ConstantExpr::getOffsetOf(StructType* STy, unsigned FieldNo) {
Dan Gohmanede94e62010-02-01 16:37:38 +00001931 return getOffsetOf(STy, ConstantInt::get(Type::getInt32Ty(STy->getContext()),
1932 FieldNo));
1933}
1934
Chris Lattner229907c2011-07-18 04:54:35 +00001935Constant *ConstantExpr::getOffsetOf(Type* Ty, Constant *FieldNo) {
Dan Gohmanff3af7252009-08-16 21:26:11 +00001936 // offsetof is implemented as: (i64) gep (Ty*)null, 0, FieldNo
1937 // Note that a non-inbounds gep is used, as null isn't within any object.
1938 Constant *GEPIdx[] = {
Dan Gohmanede94e62010-02-01 16:37:38 +00001939 ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0),
1940 FieldNo
Dan Gohmanff3af7252009-08-16 21:26:11 +00001941 };
1942 Constant *GEP = getGetElementPtr(
Jay Foaded8db7d2011-07-21 14:31:17 +00001943 Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx);
Dan Gohman3cdcc3f2010-04-12 22:12:29 +00001944 return getPtrToInt(GEP,
1945 Type::getInt64Ty(Ty->getContext()));
Dan Gohmanff3af7252009-08-16 21:26:11 +00001946}
Owen Anderson487375e2009-07-29 18:55:55 +00001947
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001948Constant *ConstantExpr::getCompare(unsigned short Predicate, Constant *C1,
1949 Constant *C2, bool OnlyIfReduced) {
Reid Spencera009d0d2006-12-04 21:35:24 +00001950 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Galina Kistanovafc259902012-07-13 01:25:27 +00001951
Chris Lattner887ecac2011-07-09 18:23:52 +00001952 switch (Predicate) {
1953 default: llvm_unreachable("Invalid CmpInst predicate");
1954 case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
1955 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
1956 case CmpInst::FCMP_ONE: case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
1957 case CmpInst::FCMP_UEQ: case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
1958 case CmpInst::FCMP_ULT: case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
1959 case CmpInst::FCMP_TRUE:
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001960 return getFCmp(Predicate, C1, C2, OnlyIfReduced);
Galina Kistanovafc259902012-07-13 01:25:27 +00001961
Chris Lattner887ecac2011-07-09 18:23:52 +00001962 case CmpInst::ICMP_EQ: case CmpInst::ICMP_NE: case CmpInst::ICMP_UGT:
1963 case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
1964 case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
1965 case CmpInst::ICMP_SLE:
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001966 return getICmp(Predicate, C1, C2, OnlyIfReduced);
Chris Lattner887ecac2011-07-09 18:23:52 +00001967 }
Chris Lattner29ca2c62004-08-04 18:50:09 +00001968}
1969
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001970Constant *ConstantExpr::getSelect(Constant *C, Constant *V1, Constant *V2,
1971 Type *OnlyIfReducedTy) {
Chris Lattner41632132008-12-29 00:16:12 +00001972 assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
Chris Lattner6e415c02004-03-12 05:54:04 +00001973
Chris Lattner887ecac2011-07-09 18:23:52 +00001974 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1975 return SC; // Fold common cases
Chris Lattner6e415c02004-03-12 05:54:04 +00001976
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001977 if (OnlyIfReducedTy == V1->getType())
1978 return nullptr;
1979
Benjamin Kramer324322b2013-03-07 20:53:34 +00001980 Constant *ArgVec[] = { C, V1, V2 };
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00001981 ConstantExprKeyType Key(Instruction::Select, ArgVec);
Galina Kistanovafc259902012-07-13 01:25:27 +00001982
Chris Lattner887ecac2011-07-09 18:23:52 +00001983 LLVMContextImpl *pImpl = C->getContext().pImpl;
1984 return pImpl->ExprConstants.getOrCreate(V1->getType(), Key);
Chris Lattner6e415c02004-03-12 05:54:04 +00001985}
1986
Jay Foaded8db7d2011-07-21 14:31:17 +00001987Constant *ConstantExpr::getGetElementPtr(Constant *C, ArrayRef<Value *> Idxs,
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001988 bool InBounds, Type *OnlyIfReducedTy) {
Duncan Sandse6beec62012-11-13 12:59:33 +00001989 assert(C->getType()->isPtrOrPtrVectorTy() &&
1990 "Non-pointer type for constant GetElementPtr expression");
1991
Jay Foaded8db7d2011-07-21 14:31:17 +00001992 if (Constant *FC = ConstantFoldGetElementPtr(C, InBounds, Idxs))
Chris Lattner94c8d292011-02-11 05:34:33 +00001993 return FC; // Fold a few common cases.
Dan Gohman1b849082009-09-07 23:54:19 +00001994
Chris Lattner887ecac2011-07-09 18:23:52 +00001995 // Get the result type of the getelementptr!
Jay Foadd1b78492011-07-25 09:48:08 +00001996 Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), Idxs);
Chris Lattner887ecac2011-07-09 18:23:52 +00001997 assert(Ty && "GEP indices invalid!");
Chris Lattner8326bd82012-01-26 00:42:34 +00001998 unsigned AS = C->getType()->getPointerAddressSpace();
Chris Lattner887ecac2011-07-09 18:23:52 +00001999 Type *ReqTy = Ty->getPointerTo(AS);
Duncan Sandse6beec62012-11-13 12:59:33 +00002000 if (VectorType *VecTy = dyn_cast<VectorType>(C->getType()))
2001 ReqTy = VectorType::get(ReqTy, VecTy->getNumElements());
Galina Kistanovafc259902012-07-13 01:25:27 +00002002
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002003 if (OnlyIfReducedTy == ReqTy)
2004 return nullptr;
2005
Dan Gohman1b849082009-09-07 23:54:19 +00002006 // Look up the constant in the table first to ensure uniqueness
2007 std::vector<Constant*> ArgVec;
Jay Foaded8db7d2011-07-21 14:31:17 +00002008 ArgVec.reserve(1 + Idxs.size());
Dan Gohman1b849082009-09-07 23:54:19 +00002009 ArgVec.push_back(C);
Duncan Sandse6beec62012-11-13 12:59:33 +00002010 for (unsigned i = 0, e = Idxs.size(); i != e; ++i) {
2011 assert(Idxs[i]->getType()->isVectorTy() == ReqTy->isVectorTy() &&
2012 "getelementptr index type missmatch");
2013 assert((!Idxs[i]->getType()->isVectorTy() ||
2014 ReqTy->getVectorNumElements() ==
2015 Idxs[i]->getType()->getVectorNumElements()) &&
2016 "getelementptr index type missmatch");
Dan Gohman1b849082009-09-07 23:54:19 +00002017 ArgVec.push_back(cast<Constant>(Idxs[i]));
Duncan Sandse6beec62012-11-13 12:59:33 +00002018 }
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002019 const ConstantExprKeyType Key(Instruction::GetElementPtr, ArgVec, 0,
2020 InBounds ? GEPOperator::IsInBounds : 0);
Galina Kistanovafc259902012-07-13 01:25:27 +00002021
Chris Lattner887ecac2011-07-09 18:23:52 +00002022 LLVMContextImpl *pImpl = C->getContext().pImpl;
Dan Gohman1b849082009-09-07 23:54:19 +00002023 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
2024}
2025
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002026Constant *ConstantExpr::getICmp(unsigned short pred, Constant *LHS,
2027 Constant *RHS, bool OnlyIfReduced) {
Reid Spenceree3c9912006-12-04 05:19:50 +00002028 assert(LHS->getType() == RHS->getType());
2029 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
2030 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
2031
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00002032 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
Reid Spenceree3c9912006-12-04 05:19:50 +00002033 return FC; // Fold a few common cases...
2034
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002035 if (OnlyIfReduced)
2036 return nullptr;
2037
Reid Spenceree3c9912006-12-04 05:19:50 +00002038 // Look up the constant in the table first to ensure uniqueness
Benjamin Kramer324322b2013-03-07 20:53:34 +00002039 Constant *ArgVec[] = { LHS, RHS };
Reid Spencerb1537492006-12-24 18:42:29 +00002040 // Get the key type with both the opcode and predicate
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002041 const ConstantExprKeyType Key(Instruction::ICmp, ArgVec, pred);
Owen Anderson61794042009-06-17 20:10:08 +00002042
Chris Lattner229907c2011-07-18 04:54:35 +00002043 Type *ResultTy = Type::getInt1Ty(LHS->getContext());
2044 if (VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
Nick Lewycky9e26c1c2010-01-21 07:03:21 +00002045 ResultTy = VectorType::get(ResultTy, VT->getNumElements());
2046
Owen Anderson1584a292009-08-04 20:25:11 +00002047 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
Nick Lewycky9e26c1c2010-01-21 07:03:21 +00002048 return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
Reid Spenceree3c9912006-12-04 05:19:50 +00002049}
2050
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002051Constant *ConstantExpr::getFCmp(unsigned short pred, Constant *LHS,
2052 Constant *RHS, bool OnlyIfReduced) {
Reid Spenceree3c9912006-12-04 05:19:50 +00002053 assert(LHS->getType() == RHS->getType());
2054 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
2055
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00002056 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
Reid Spenceree3c9912006-12-04 05:19:50 +00002057 return FC; // Fold a few common cases...
2058
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002059 if (OnlyIfReduced)
2060 return nullptr;
2061
Reid Spenceree3c9912006-12-04 05:19:50 +00002062 // Look up the constant in the table first to ensure uniqueness
Benjamin Kramer324322b2013-03-07 20:53:34 +00002063 Constant *ArgVec[] = { LHS, RHS };
Reid Spencerb1537492006-12-24 18:42:29 +00002064 // Get the key type with both the opcode and predicate
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002065 const ConstantExprKeyType Key(Instruction::FCmp, ArgVec, pred);
Nick Lewycky9e26c1c2010-01-21 07:03:21 +00002066
Chris Lattner229907c2011-07-18 04:54:35 +00002067 Type *ResultTy = Type::getInt1Ty(LHS->getContext());
2068 if (VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
Nick Lewycky9e26c1c2010-01-21 07:03:21 +00002069 ResultTy = VectorType::get(ResultTy, VT->getNumElements());
2070
Owen Anderson1584a292009-08-04 20:25:11 +00002071 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
Nick Lewycky9e26c1c2010-01-21 07:03:21 +00002072 return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
Reid Spenceree3c9912006-12-04 05:19:50 +00002073}
2074
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002075Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx,
2076 Type *OnlyIfReducedTy) {
Duncan Sands19d0b472010-02-16 11:11:14 +00002077 assert(Val->getType()->isVectorTy() &&
Reid Spencer09575ba2007-02-15 03:39:18 +00002078 "Tried to create extractelement operation on non-vector type!");
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002079 assert(Idx->getType()->isIntegerTy() &&
2080 "Extractelement index must be an integer type!");
Galina Kistanovafc259902012-07-13 01:25:27 +00002081
Chris Lattner887ecac2011-07-09 18:23:52 +00002082 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
Chris Lattner09660c92009-12-30 20:25:09 +00002083 return FC; // Fold a few common cases.
Galina Kistanovafc259902012-07-13 01:25:27 +00002084
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002085 Type *ReqTy = Val->getType()->getVectorElementType();
2086 if (OnlyIfReducedTy == ReqTy)
2087 return nullptr;
2088
Robert Bocchinoca27f032006-01-17 20:07:22 +00002089 // Look up the constant in the table first to ensure uniqueness
Benjamin Kramer324322b2013-03-07 20:53:34 +00002090 Constant *ArgVec[] = { Val, Idx };
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002091 const ConstantExprKeyType Key(Instruction::ExtractElement, ArgVec);
Galina Kistanovafc259902012-07-13 01:25:27 +00002092
Chris Lattner887ecac2011-07-09 18:23:52 +00002093 LLVMContextImpl *pImpl = Val->getContext().pImpl;
Owen Anderson1584a292009-08-04 20:25:11 +00002094 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
Robert Bocchinoca27f032006-01-17 20:07:22 +00002095}
2096
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002097Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
2098 Constant *Idx, Type *OnlyIfReducedTy) {
Duncan Sands19d0b472010-02-16 11:11:14 +00002099 assert(Val->getType()->isVectorTy() &&
Reid Spencer09575ba2007-02-15 03:39:18 +00002100 "Tried to create insertelement operation on non-vector type!");
Chris Lattner8326bd82012-01-26 00:42:34 +00002101 assert(Elt->getType() == Val->getType()->getVectorElementType() &&
2102 "Insertelement types must match!");
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002103 assert(Idx->getType()->isIntegerTy() &&
Reid Spencer2546b762007-01-26 07:37:34 +00002104 "Insertelement index must be i32 type!");
Robert Bocchinoca27f032006-01-17 20:07:22 +00002105
Chris Lattner887ecac2011-07-09 18:23:52 +00002106 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
2107 return FC; // Fold a few common cases.
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002108
2109 if (OnlyIfReducedTy == Val->getType())
2110 return nullptr;
2111
Chris Lattnerbbe0a422006-04-08 01:18:18 +00002112 // Look up the constant in the table first to ensure uniqueness
Benjamin Kramer324322b2013-03-07 20:53:34 +00002113 Constant *ArgVec[] = { Val, Elt, Idx };
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002114 const ConstantExprKeyType Key(Instruction::InsertElement, ArgVec);
Galina Kistanovafc259902012-07-13 01:25:27 +00002115
Chris Lattner887ecac2011-07-09 18:23:52 +00002116 LLVMContextImpl *pImpl = Val->getContext().pImpl;
2117 return pImpl->ExprConstants.getOrCreate(Val->getType(), Key);
Chris Lattnerbbe0a422006-04-08 01:18:18 +00002118}
2119
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002120Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
2121 Constant *Mask, Type *OnlyIfReducedTy) {
Chris Lattnerbbe0a422006-04-08 01:18:18 +00002122 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
2123 "Invalid shuffle vector constant expr operands!");
Nate Begeman94aa38d2009-02-12 21:28:33 +00002124
Chris Lattner887ecac2011-07-09 18:23:52 +00002125 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
2126 return FC; // Fold a few common cases.
2127
Chris Lattner8326bd82012-01-26 00:42:34 +00002128 unsigned NElts = Mask->getType()->getVectorNumElements();
2129 Type *EltTy = V1->getType()->getVectorElementType();
Chris Lattner229907c2011-07-18 04:54:35 +00002130 Type *ShufTy = VectorType::get(EltTy, NElts);
Chris Lattner887ecac2011-07-09 18:23:52 +00002131
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002132 if (OnlyIfReducedTy == ShufTy)
2133 return nullptr;
2134
Chris Lattner887ecac2011-07-09 18:23:52 +00002135 // Look up the constant in the table first to ensure uniqueness
Benjamin Kramer324322b2013-03-07 20:53:34 +00002136 Constant *ArgVec[] = { V1, V2, Mask };
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002137 const ConstantExprKeyType Key(Instruction::ShuffleVector, ArgVec);
Galina Kistanovafc259902012-07-13 01:25:27 +00002138
Chris Lattner887ecac2011-07-09 18:23:52 +00002139 LLVMContextImpl *pImpl = ShufTy->getContext().pImpl;
2140 return pImpl->ExprConstants.getOrCreate(ShufTy, Key);
Chris Lattnerbbe0a422006-04-08 01:18:18 +00002141}
2142
Chris Lattner887ecac2011-07-09 18:23:52 +00002143Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002144 ArrayRef<unsigned> Idxs,
2145 Type *OnlyIfReducedTy) {
Hal Finkelb31366d2013-07-10 22:51:01 +00002146 assert(Agg->getType()->isFirstClassType() &&
2147 "Non-first-class type for constant insertvalue expression");
2148
Jay Foad57aa6362011-07-13 10:26:04 +00002149 assert(ExtractValueInst::getIndexedType(Agg->getType(),
2150 Idxs) == Val->getType() &&
Dan Gohman12fce772008-05-15 19:50:34 +00002151 "insertvalue indices invalid!");
Hal Finkelb31366d2013-07-10 22:51:01 +00002152 Type *ReqTy = Val->getType();
2153
2154 if (Constant *FC = ConstantFoldInsertValueInstruction(Agg, Val, Idxs))
2155 return FC;
2156
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002157 if (OnlyIfReducedTy == ReqTy)
2158 return nullptr;
2159
Hal Finkelb31366d2013-07-10 22:51:01 +00002160 Constant *ArgVec[] = { Agg, Val };
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002161 const ConstantExprKeyType Key(Instruction::InsertValue, ArgVec, 0, 0, Idxs);
Hal Finkelb31366d2013-07-10 22:51:01 +00002162
2163 LLVMContextImpl *pImpl = Agg->getContext().pImpl;
2164 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
Dan Gohman12fce772008-05-15 19:50:34 +00002165}
2166
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002167Constant *ConstantExpr::getExtractValue(Constant *Agg, ArrayRef<unsigned> Idxs,
2168 Type *OnlyIfReducedTy) {
Dan Gohman0752bff2008-05-23 00:36:11 +00002169 assert(Agg->getType()->isFirstClassType() &&
Chris Lattner887ecac2011-07-09 18:23:52 +00002170 "Tried to create extractelement operation on non-first-class type!");
Dan Gohman12fce772008-05-15 19:50:34 +00002171
Chris Lattner229907c2011-07-18 04:54:35 +00002172 Type *ReqTy = ExtractValueInst::getIndexedType(Agg->getType(), Idxs);
Chandler Carruth9db56b82011-07-10 09:45:35 +00002173 (void)ReqTy;
Chris Lattner887ecac2011-07-09 18:23:52 +00002174 assert(ReqTy && "extractvalue indices invalid!");
Galina Kistanovafc259902012-07-13 01:25:27 +00002175
Dan Gohman0752bff2008-05-23 00:36:11 +00002176 assert(Agg->getType()->isFirstClassType() &&
2177 "Non-first-class type for constant extractvalue expression");
Hal Finkelb31366d2013-07-10 22:51:01 +00002178 if (Constant *FC = ConstantFoldExtractValueInstruction(Agg, Idxs))
2179 return FC;
2180
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002181 if (OnlyIfReducedTy == ReqTy)
2182 return nullptr;
2183
Hal Finkelb31366d2013-07-10 22:51:01 +00002184 Constant *ArgVec[] = { Agg };
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002185 const ConstantExprKeyType Key(Instruction::ExtractValue, ArgVec, 0, 0, Idxs);
Hal Finkelb31366d2013-07-10 22:51:01 +00002186
2187 LLVMContextImpl *pImpl = Agg->getContext().pImpl;
2188 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
Dan Gohman12fce772008-05-15 19:50:34 +00002189}
2190
Chris Lattnere9b4ad72011-02-10 07:01:55 +00002191Constant *ConstantExpr::getNeg(Constant *C, bool HasNUW, bool HasNSW) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00002192 assert(C->getType()->isIntOrIntVectorTy() &&
Owen Anderson487375e2009-07-29 18:55:55 +00002193 "Cannot NEG a nonintegral value!");
Chris Lattnere9b4ad72011-02-10 07:01:55 +00002194 return getSub(ConstantFP::getZeroValueForNegation(C->getType()),
2195 C, HasNUW, HasNSW);
Owen Anderson487375e2009-07-29 18:55:55 +00002196}
2197
Chris Lattnera676c0f2011-02-07 16:40:21 +00002198Constant *ConstantExpr::getFNeg(Constant *C) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00002199 assert(C->getType()->isFPOrFPVectorTy() &&
Owen Anderson487375e2009-07-29 18:55:55 +00002200 "Cannot FNEG a non-floating-point value!");
Chris Lattnere9b4ad72011-02-10 07:01:55 +00002201 return getFSub(ConstantFP::getZeroValueForNegation(C->getType()), C);
Owen Anderson487375e2009-07-29 18:55:55 +00002202}
2203
Chris Lattnera676c0f2011-02-07 16:40:21 +00002204Constant *ConstantExpr::getNot(Constant *C) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00002205 assert(C->getType()->isIntOrIntVectorTy() &&
Owen Anderson487375e2009-07-29 18:55:55 +00002206 "Cannot NOT a nonintegral value!");
Owen Anderson5a1acd92009-07-31 20:28:14 +00002207 return get(Instruction::Xor, C, Constant::getAllOnesValue(C->getType()));
Owen Anderson487375e2009-07-29 18:55:55 +00002208}
2209
Chris Lattnere9b4ad72011-02-10 07:01:55 +00002210Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2,
2211 bool HasNUW, bool HasNSW) {
2212 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2213 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2214 return get(Instruction::Add, C1, C2, Flags);
Owen Anderson487375e2009-07-29 18:55:55 +00002215}
2216
Chris Lattnera676c0f2011-02-07 16:40:21 +00002217Constant *ConstantExpr::getFAdd(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002218 return get(Instruction::FAdd, C1, C2);
2219}
2220
Chris Lattnere9b4ad72011-02-10 07:01:55 +00002221Constant *ConstantExpr::getSub(Constant *C1, Constant *C2,
2222 bool HasNUW, bool HasNSW) {
2223 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2224 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2225 return get(Instruction::Sub, C1, C2, Flags);
Owen Anderson487375e2009-07-29 18:55:55 +00002226}
2227
Chris Lattnera676c0f2011-02-07 16:40:21 +00002228Constant *ConstantExpr::getFSub(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002229 return get(Instruction::FSub, C1, C2);
2230}
2231
Chris Lattnere9b4ad72011-02-10 07:01:55 +00002232Constant *ConstantExpr::getMul(Constant *C1, Constant *C2,
2233 bool HasNUW, bool HasNSW) {
2234 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2235 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2236 return get(Instruction::Mul, C1, C2, Flags);
Owen Anderson487375e2009-07-29 18:55:55 +00002237}
2238
Chris Lattnera676c0f2011-02-07 16:40:21 +00002239Constant *ConstantExpr::getFMul(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002240 return get(Instruction::FMul, C1, C2);
2241}
2242
Chris Lattner0d75eac2011-02-09 16:43:07 +00002243Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2, bool isExact) {
2244 return get(Instruction::UDiv, C1, C2,
2245 isExact ? PossiblyExactOperator::IsExact : 0);
Owen Anderson487375e2009-07-29 18:55:55 +00002246}
2247
Chris Lattner0d75eac2011-02-09 16:43:07 +00002248Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2, bool isExact) {
2249 return get(Instruction::SDiv, C1, C2,
2250 isExact ? PossiblyExactOperator::IsExact : 0);
Owen Anderson487375e2009-07-29 18:55:55 +00002251}
2252
Chris Lattnera676c0f2011-02-07 16:40:21 +00002253Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002254 return get(Instruction::FDiv, C1, C2);
2255}
2256
Chris Lattnera676c0f2011-02-07 16:40:21 +00002257Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002258 return get(Instruction::URem, C1, C2);
2259}
2260
Chris Lattnera676c0f2011-02-07 16:40:21 +00002261Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002262 return get(Instruction::SRem, C1, C2);
2263}
2264
Chris Lattnera676c0f2011-02-07 16:40:21 +00002265Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002266 return get(Instruction::FRem, C1, C2);
2267}
2268
Chris Lattnera676c0f2011-02-07 16:40:21 +00002269Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002270 return get(Instruction::And, C1, C2);
2271}
2272
Chris Lattnera676c0f2011-02-07 16:40:21 +00002273Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002274 return get(Instruction::Or, C1, C2);
2275}
2276
Chris Lattnera676c0f2011-02-07 16:40:21 +00002277Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002278 return get(Instruction::Xor, C1, C2);
2279}
2280
Chris Lattnere9b4ad72011-02-10 07:01:55 +00002281Constant *ConstantExpr::getShl(Constant *C1, Constant *C2,
2282 bool HasNUW, bool HasNSW) {
2283 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2284 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2285 return get(Instruction::Shl, C1, C2, Flags);
Owen Anderson487375e2009-07-29 18:55:55 +00002286}
2287
Chris Lattner0d75eac2011-02-09 16:43:07 +00002288Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2, bool isExact) {
2289 return get(Instruction::LShr, C1, C2,
2290 isExact ? PossiblyExactOperator::IsExact : 0);
Owen Anderson487375e2009-07-29 18:55:55 +00002291}
2292
Chris Lattner0d75eac2011-02-09 16:43:07 +00002293Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2, bool isExact) {
2294 return get(Instruction::AShr, C1, C2,
2295 isExact ? PossiblyExactOperator::IsExact : 0);
Owen Anderson487375e2009-07-29 18:55:55 +00002296}
2297
Duncan Sandsd7aeefe2012-06-12 14:33:56 +00002298/// getBinOpIdentity - Return the identity for the given binary operation,
2299/// i.e. a constant C such that X op C = X and C op X = X for every X. It
Duncan Sands318a89d2012-06-13 09:42:13 +00002300/// returns null if the operator doesn't have an identity.
Duncan Sandsd7aeefe2012-06-12 14:33:56 +00002301Constant *ConstantExpr::getBinOpIdentity(unsigned Opcode, Type *Ty) {
2302 switch (Opcode) {
2303 default:
Duncan Sands318a89d2012-06-13 09:42:13 +00002304 // Doesn't have an identity.
Craig Topperc6207612014-04-09 06:08:46 +00002305 return nullptr;
Duncan Sands318a89d2012-06-13 09:42:13 +00002306
Duncan Sandsd7aeefe2012-06-12 14:33:56 +00002307 case Instruction::Add:
2308 case Instruction::Or:
2309 case Instruction::Xor:
2310 return Constant::getNullValue(Ty);
2311
2312 case Instruction::Mul:
2313 return ConstantInt::get(Ty, 1);
2314
2315 case Instruction::And:
2316 return Constant::getAllOnesValue(Ty);
2317 }
2318}
2319
Duncan Sands318a89d2012-06-13 09:42:13 +00002320/// getBinOpAbsorber - Return the absorbing element for the given binary
2321/// operation, i.e. a constant C such that X op C = C and C op X = C for
2322/// every X. For example, this returns zero for integer multiplication.
2323/// It returns null if the operator doesn't have an absorbing element.
2324Constant *ConstantExpr::getBinOpAbsorber(unsigned Opcode, Type *Ty) {
2325 switch (Opcode) {
2326 default:
2327 // Doesn't have an absorber.
Craig Topperc6207612014-04-09 06:08:46 +00002328 return nullptr;
Duncan Sands318a89d2012-06-13 09:42:13 +00002329
2330 case Instruction::Or:
2331 return Constant::getAllOnesValue(Ty);
2332
2333 case Instruction::And:
2334 case Instruction::Mul:
2335 return Constant::getNullValue(Ty);
2336 }
2337}
2338
Vikram S. Adve4c485332002-07-15 18:19:33 +00002339// destroyConstant - Remove the constant from the constant table...
2340//
Owen Anderson0d2de8c2009-06-20 00:24:58 +00002341void ConstantExpr::destroyConstant() {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002342 getType()->getContext().pImpl->ExprConstants.remove(this);
Vikram S. Adve4c485332002-07-15 18:19:33 +00002343 destroyConstantImpl();
Vikram S. Adve4e537b22002-07-14 23:13:17 +00002344}
2345
Chris Lattner3cd8c562002-07-30 18:54:25 +00002346const char *ConstantExpr::getOpcodeName() const {
2347 return Instruction::getOpcodeName(getOpcode());
Vikram S. Adve4e537b22002-07-14 23:13:17 +00002348}
Reid Spencer1ebe1ab2004-07-17 23:48:33 +00002349
Chris Lattnera3b94ba2010-03-30 20:48:48 +00002350
2351
2352GetElementPtrConstantExpr::
Chris Lattnera474bb22012-01-26 20:40:56 +00002353GetElementPtrConstantExpr(Constant *C, ArrayRef<Constant*> IdxList,
Chris Lattner229907c2011-07-18 04:54:35 +00002354 Type *DestTy)
Chris Lattnera3b94ba2010-03-30 20:48:48 +00002355 : ConstantExpr(DestTy, Instruction::GetElementPtr,
2356 OperandTraits<GetElementPtrConstantExpr>::op_end(this)
2357 - (IdxList.size()+1), IdxList.size()+1) {
2358 OperandList[0] = C;
2359 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
2360 OperandList[i+1] = IdxList[i];
2361}
2362
Chris Lattner3756b912012-01-23 22:57:10 +00002363//===----------------------------------------------------------------------===//
2364// ConstantData* implementations
2365
2366void ConstantDataArray::anchor() {}
2367void ConstantDataVector::anchor() {}
2368
Chris Lattnere4f3f102012-01-24 04:43:41 +00002369/// getElementType - Return the element type of the array/vector.
2370Type *ConstantDataSequential::getElementType() const {
2371 return getType()->getElementType();
2372}
2373
Chris Lattner5d4497b2012-01-24 09:31:43 +00002374StringRef ConstantDataSequential::getRawDataValues() const {
Chris Lattner00245f42012-01-24 13:41:11 +00002375 return StringRef(DataElements, getNumElements()*getElementByteSize());
Chris Lattner5d4497b2012-01-24 09:31:43 +00002376}
2377
Chris Lattner030af792012-01-24 05:42:11 +00002378/// isElementTypeCompatible - Return true if a ConstantDataSequential can be
2379/// formed with a vector or array of the specified element type.
2380/// ConstantDataArray only works with normal float and int types that are
2381/// stored densely in memory, not with things like i42 or x86_f80.
2382bool ConstantDataSequential::isElementTypeCompatible(const Type *Ty) {
Chris Lattnere4f3f102012-01-24 04:43:41 +00002383 if (Ty->isFloatTy() || Ty->isDoubleTy()) return true;
2384 if (const IntegerType *IT = dyn_cast<IntegerType>(Ty)) {
2385 switch (IT->getBitWidth()) {
2386 case 8:
2387 case 16:
2388 case 32:
2389 case 64:
2390 return true;
2391 default: break;
2392 }
2393 }
2394 return false;
2395}
2396
Chris Lattner00245f42012-01-24 13:41:11 +00002397/// getNumElements - Return the number of elements in the array or vector.
2398unsigned ConstantDataSequential::getNumElements() const {
Chris Lattner8a3df542012-01-25 01:32:59 +00002399 if (ArrayType *AT = dyn_cast<ArrayType>(getType()))
2400 return AT->getNumElements();
Chris Lattner8326bd82012-01-26 00:42:34 +00002401 return getType()->getVectorNumElements();
Chris Lattner00245f42012-01-24 13:41:11 +00002402}
2403
2404
Chris Lattnere4f3f102012-01-24 04:43:41 +00002405/// getElementByteSize - Return the size in bytes of the elements in the data.
2406uint64_t ConstantDataSequential::getElementByteSize() const {
2407 return getElementType()->getPrimitiveSizeInBits()/8;
2408}
2409
2410/// getElementPointer - Return the start of the specified element.
2411const char *ConstantDataSequential::getElementPointer(unsigned Elt) const {
Chris Lattner00245f42012-01-24 13:41:11 +00002412 assert(Elt < getNumElements() && "Invalid Elt");
Chris Lattnere4f3f102012-01-24 04:43:41 +00002413 return DataElements+Elt*getElementByteSize();
2414}
2415
2416
Chris Lattner3756b912012-01-23 22:57:10 +00002417/// isAllZeros - return true if the array is empty or all zeros.
2418static bool isAllZeros(StringRef Arr) {
2419 for (StringRef::iterator I = Arr.begin(), E = Arr.end(); I != E; ++I)
2420 if (*I != 0)
2421 return false;
2422 return true;
2423}
Chris Lattner030af792012-01-24 05:42:11 +00002424
Chris Lattner3756b912012-01-23 22:57:10 +00002425/// getImpl - This is the underlying implementation of all of the
2426/// ConstantDataSequential::get methods. They all thunk down to here, providing
Chris Lattnerf06039b2012-01-30 18:19:30 +00002427/// the correct element type. We take the bytes in as a StringRef because
Chris Lattner3756b912012-01-23 22:57:10 +00002428/// we *want* an underlying "char*" to avoid TBAA type punning violations.
2429Constant *ConstantDataSequential::getImpl(StringRef Elements, Type *Ty) {
Chris Lattner8326bd82012-01-26 00:42:34 +00002430 assert(isElementTypeCompatible(Ty->getSequentialElementType()));
Chris Lattner139822f2012-01-24 14:17:05 +00002431 // If the elements are all zero or there are no elements, return a CAZ, which
2432 // is more dense and canonical.
Chris Lattner3756b912012-01-23 22:57:10 +00002433 if (isAllZeros(Elements))
2434 return ConstantAggregateZero::get(Ty);
2435
2436 // Do a lookup to see if we have already formed one of these.
David Blaikie5106ce72014-11-19 05:49:42 +00002437 auto &Slot =
2438 *Ty->getContext()
2439 .pImpl->CDSConstants.insert(std::make_pair(Elements, nullptr))
2440 .first;
Galina Kistanovafc259902012-07-13 01:25:27 +00002441
Chris Lattner3756b912012-01-23 22:57:10 +00002442 // The bucket can point to a linked list of different CDS's that have the same
2443 // body but different types. For example, 0,0,0,1 could be a 4 element array
2444 // of i8, or a 1-element array of i32. They'll both end up in the same
2445 /// StringMap bucket, linked up by their Next pointers. Walk the list.
David Blaikie5106ce72014-11-19 05:49:42 +00002446 ConstantDataSequential **Entry = &Slot.second;
Craig Topperc6207612014-04-09 06:08:46 +00002447 for (ConstantDataSequential *Node = *Entry; Node;
Chris Lattner3756b912012-01-23 22:57:10 +00002448 Entry = &Node->Next, Node = *Entry)
2449 if (Node->getType() == Ty)
2450 return Node;
Galina Kistanovafc259902012-07-13 01:25:27 +00002451
Chris Lattner3756b912012-01-23 22:57:10 +00002452 // Okay, we didn't get a hit. Create a node of the right class, link it in,
2453 // and return it.
2454 if (isa<ArrayType>(Ty))
David Blaikie5106ce72014-11-19 05:49:42 +00002455 return *Entry = new ConstantDataArray(Ty, Slot.first().data());
Chris Lattner3756b912012-01-23 22:57:10 +00002456
2457 assert(isa<VectorType>(Ty));
David Blaikie5106ce72014-11-19 05:49:42 +00002458 return *Entry = new ConstantDataVector(Ty, Slot.first().data());
Chris Lattner3756b912012-01-23 22:57:10 +00002459}
2460
2461void ConstantDataSequential::destroyConstant() {
Chris Lattner3756b912012-01-23 22:57:10 +00002462 // Remove the constant from the StringMap.
2463 StringMap<ConstantDataSequential*> &CDSConstants =
2464 getType()->getContext().pImpl->CDSConstants;
Galina Kistanovafc259902012-07-13 01:25:27 +00002465
Chris Lattner3756b912012-01-23 22:57:10 +00002466 StringMap<ConstantDataSequential*>::iterator Slot =
Chris Lattner5d4497b2012-01-24 09:31:43 +00002467 CDSConstants.find(getRawDataValues());
Chris Lattner3756b912012-01-23 22:57:10 +00002468
2469 assert(Slot != CDSConstants.end() && "CDS not found in uniquing table");
2470
2471 ConstantDataSequential **Entry = &Slot->getValue();
2472
2473 // Remove the entry from the hash table.
Craig Topperc6207612014-04-09 06:08:46 +00002474 if (!(*Entry)->Next) {
Chris Lattner3756b912012-01-23 22:57:10 +00002475 // If there is only one value in the bucket (common case) it must be this
2476 // entry, and removing the entry should remove the bucket completely.
2477 assert((*Entry) == this && "Hash mismatch in ConstantDataSequential");
2478 getContext().pImpl->CDSConstants.erase(Slot);
2479 } else {
2480 // Otherwise, there are multiple entries linked off the bucket, unlink the
2481 // node we care about but keep the bucket around.
2482 for (ConstantDataSequential *Node = *Entry; ;
2483 Entry = &Node->Next, Node = *Entry) {
2484 assert(Node && "Didn't find entry in its uniquing hash table!");
2485 // If we found our entry, unlink it from the list and we're done.
2486 if (Node == this) {
2487 *Entry = Node->Next;
2488 break;
2489 }
2490 }
2491 }
Galina Kistanovafc259902012-07-13 01:25:27 +00002492
Chris Lattner3756b912012-01-23 22:57:10 +00002493 // If we were part of a list, make sure that we don't delete the list that is
2494 // still owned by the uniquing map.
Craig Topperc6207612014-04-09 06:08:46 +00002495 Next = nullptr;
Galina Kistanovafc259902012-07-13 01:25:27 +00002496
Chris Lattner3756b912012-01-23 22:57:10 +00002497 // Finally, actually delete it.
2498 destroyConstantImpl();
2499}
2500
2501/// get() constructors - Return a constant with array type with an element
2502/// count and element type matching the ArrayRef passed in. Note that this
2503/// can return a ConstantAggregateZero object.
Chris Lattner20683932012-01-24 14:04:40 +00002504Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint8_t> Elts) {
Chris Lattner3756b912012-01-23 22:57:10 +00002505 Type *Ty = ArrayType::get(Type::getInt8Ty(Context), Elts.size());
Galina Kistanovafc259902012-07-13 01:25:27 +00002506 const char *Data = reinterpret_cast<const char *>(Elts.data());
2507 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*1), Ty);
Chris Lattner3756b912012-01-23 22:57:10 +00002508}
Chris Lattner20683932012-01-24 14:04:40 +00002509Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint16_t> Elts){
Chris Lattner3756b912012-01-23 22:57:10 +00002510 Type *Ty = ArrayType::get(Type::getInt16Ty(Context), Elts.size());
Galina Kistanovafc259902012-07-13 01:25:27 +00002511 const char *Data = reinterpret_cast<const char *>(Elts.data());
2512 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*2), Ty);
Chris Lattner3756b912012-01-23 22:57:10 +00002513}
Chris Lattner20683932012-01-24 14:04:40 +00002514Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint32_t> Elts){
Chris Lattner3756b912012-01-23 22:57:10 +00002515 Type *Ty = ArrayType::get(Type::getInt32Ty(Context), Elts.size());
Galina Kistanovafc259902012-07-13 01:25:27 +00002516 const char *Data = reinterpret_cast<const char *>(Elts.data());
2517 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*4), Ty);
Chris Lattner3756b912012-01-23 22:57:10 +00002518}
Chris Lattner20683932012-01-24 14:04:40 +00002519Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint64_t> Elts){
Chris Lattner3756b912012-01-23 22:57:10 +00002520 Type *Ty = ArrayType::get(Type::getInt64Ty(Context), Elts.size());
Galina Kistanovafc259902012-07-13 01:25:27 +00002521 const char *Data = reinterpret_cast<const char *>(Elts.data());
2522 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*8), Ty);
Chris Lattner3756b912012-01-23 22:57:10 +00002523}
Chris Lattner20683932012-01-24 14:04:40 +00002524Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<float> Elts) {
Chris Lattner3756b912012-01-23 22:57:10 +00002525 Type *Ty = ArrayType::get(Type::getFloatTy(Context), Elts.size());
Galina Kistanovafc259902012-07-13 01:25:27 +00002526 const char *Data = reinterpret_cast<const char *>(Elts.data());
2527 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*4), Ty);
Chris Lattner3756b912012-01-23 22:57:10 +00002528}
Chris Lattner20683932012-01-24 14:04:40 +00002529Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<double> Elts) {
Chris Lattner3756b912012-01-23 22:57:10 +00002530 Type *Ty = ArrayType::get(Type::getDoubleTy(Context), Elts.size());
Galina Kistanovafc259902012-07-13 01:25:27 +00002531 const char *Data = reinterpret_cast<const char *>(Elts.data());
2532 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*8), Ty);
Chris Lattner3756b912012-01-23 22:57:10 +00002533}
2534
Chris Lattner20683932012-01-24 14:04:40 +00002535/// getString - This method constructs a CDS and initializes it with a text
2536/// string. The default behavior (AddNull==true) causes a null terminator to
2537/// be placed at the end of the array (increasing the length of the string by
2538/// one more than the StringRef would normally indicate. Pass AddNull=false
2539/// to disable this behavior.
2540Constant *ConstantDataArray::getString(LLVMContext &Context,
2541 StringRef Str, bool AddNull) {
Galina Kistanovafc259902012-07-13 01:25:27 +00002542 if (!AddNull) {
2543 const uint8_t *Data = reinterpret_cast<const uint8_t *>(Str.data());
Craig Toppere1d12942014-08-27 05:25:25 +00002544 return get(Context, makeArrayRef(const_cast<uint8_t *>(Data),
Galina Kistanovafc259902012-07-13 01:25:27 +00002545 Str.size()));
2546 }
2547
Chris Lattner20683932012-01-24 14:04:40 +00002548 SmallVector<uint8_t, 64> ElementVals;
2549 ElementVals.append(Str.begin(), Str.end());
2550 ElementVals.push_back(0);
2551 return get(Context, ElementVals);
2552}
Chris Lattner3756b912012-01-23 22:57:10 +00002553
2554/// get() constructors - Return a constant with vector type with an element
2555/// count and element type matching the ArrayRef passed in. Note that this
2556/// can return a ConstantAggregateZero object.
Chris Lattner20683932012-01-24 14:04:40 +00002557Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint8_t> Elts){
Chris Lattner3756b912012-01-23 22:57:10 +00002558 Type *Ty = VectorType::get(Type::getInt8Ty(Context), Elts.size());
Galina Kistanovafc259902012-07-13 01:25:27 +00002559 const char *Data = reinterpret_cast<const char *>(Elts.data());
2560 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*1), Ty);
Chris Lattner3756b912012-01-23 22:57:10 +00002561}
Chris Lattner20683932012-01-24 14:04:40 +00002562Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint16_t> Elts){
Chris Lattner3756b912012-01-23 22:57:10 +00002563 Type *Ty = VectorType::get(Type::getInt16Ty(Context), Elts.size());
Galina Kistanovafc259902012-07-13 01:25:27 +00002564 const char *Data = reinterpret_cast<const char *>(Elts.data());
2565 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*2), Ty);
Chris Lattner3756b912012-01-23 22:57:10 +00002566}
Chris Lattner20683932012-01-24 14:04:40 +00002567Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint32_t> Elts){
Chris Lattner3756b912012-01-23 22:57:10 +00002568 Type *Ty = VectorType::get(Type::getInt32Ty(Context), Elts.size());
Galina Kistanovafc259902012-07-13 01:25:27 +00002569 const char *Data = reinterpret_cast<const char *>(Elts.data());
2570 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*4), Ty);
Chris Lattner3756b912012-01-23 22:57:10 +00002571}
Chris Lattner20683932012-01-24 14:04:40 +00002572Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint64_t> Elts){
Chris Lattner3756b912012-01-23 22:57:10 +00002573 Type *Ty = VectorType::get(Type::getInt64Ty(Context), Elts.size());
Galina Kistanovafc259902012-07-13 01:25:27 +00002574 const char *Data = reinterpret_cast<const char *>(Elts.data());
2575 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*8), Ty);
Chris Lattner3756b912012-01-23 22:57:10 +00002576}
Chris Lattner20683932012-01-24 14:04:40 +00002577Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<float> Elts) {
Chris Lattner3756b912012-01-23 22:57:10 +00002578 Type *Ty = VectorType::get(Type::getFloatTy(Context), Elts.size());
Galina Kistanovafc259902012-07-13 01:25:27 +00002579 const char *Data = reinterpret_cast<const char *>(Elts.data());
2580 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*4), Ty);
Chris Lattner3756b912012-01-23 22:57:10 +00002581}
Chris Lattner20683932012-01-24 14:04:40 +00002582Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<double> Elts) {
Chris Lattner3756b912012-01-23 22:57:10 +00002583 Type *Ty = VectorType::get(Type::getDoubleTy(Context), Elts.size());
Galina Kistanovafc259902012-07-13 01:25:27 +00002584 const char *Data = reinterpret_cast<const char *>(Elts.data());
2585 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*8), Ty);
Chris Lattner3756b912012-01-23 22:57:10 +00002586}
2587
Chris Lattnere9eed292012-01-25 05:19:54 +00002588Constant *ConstantDataVector::getSplat(unsigned NumElts, Constant *V) {
2589 assert(isElementTypeCompatible(V->getType()) &&
2590 "Element type not compatible with ConstantData");
2591 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
2592 if (CI->getType()->isIntegerTy(8)) {
2593 SmallVector<uint8_t, 16> Elts(NumElts, CI->getZExtValue());
2594 return get(V->getContext(), Elts);
2595 }
2596 if (CI->getType()->isIntegerTy(16)) {
2597 SmallVector<uint16_t, 16> Elts(NumElts, CI->getZExtValue());
2598 return get(V->getContext(), Elts);
2599 }
2600 if (CI->getType()->isIntegerTy(32)) {
2601 SmallVector<uint32_t, 16> Elts(NumElts, CI->getZExtValue());
2602 return get(V->getContext(), Elts);
2603 }
2604 assert(CI->getType()->isIntegerTy(64) && "Unsupported ConstantData type");
2605 SmallVector<uint64_t, 16> Elts(NumElts, CI->getZExtValue());
2606 return get(V->getContext(), Elts);
2607 }
2608
Chris Lattner978fe0c2012-01-30 06:21:21 +00002609 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
2610 if (CFP->getType()->isFloatTy()) {
2611 SmallVector<float, 16> Elts(NumElts, CFP->getValueAPF().convertToFloat());
2612 return get(V->getContext(), Elts);
2613 }
2614 if (CFP->getType()->isDoubleTy()) {
2615 SmallVector<double, 16> Elts(NumElts,
2616 CFP->getValueAPF().convertToDouble());
2617 return get(V->getContext(), Elts);
2618 }
Chris Lattnere9eed292012-01-25 05:19:54 +00002619 }
Chris Lattner978fe0c2012-01-30 06:21:21 +00002620 return ConstantVector::getSplat(NumElts, V);
Chris Lattnere9eed292012-01-25 05:19:54 +00002621}
2622
2623
Chris Lattnere4f3f102012-01-24 04:43:41 +00002624/// getElementAsInteger - If this is a sequential container of integers (of
2625/// any size), return the specified element in the low bits of a uint64_t.
2626uint64_t ConstantDataSequential::getElementAsInteger(unsigned Elt) const {
2627 assert(isa<IntegerType>(getElementType()) &&
2628 "Accessor can only be used when element is an integer");
2629 const char *EltPtr = getElementPointer(Elt);
Galina Kistanovafc259902012-07-13 01:25:27 +00002630
Chris Lattnere4f3f102012-01-24 04:43:41 +00002631 // The data is stored in host byte order, make sure to cast back to the right
2632 // type to load with the right endianness.
Chris Lattner8326bd82012-01-26 00:42:34 +00002633 switch (getElementType()->getIntegerBitWidth()) {
Craig Topperc514b542012-02-05 22:14:15 +00002634 default: llvm_unreachable("Invalid bitwidth for CDS");
Galina Kistanovafc259902012-07-13 01:25:27 +00002635 case 8:
2636 return *const_cast<uint8_t *>(reinterpret_cast<const uint8_t *>(EltPtr));
2637 case 16:
2638 return *const_cast<uint16_t *>(reinterpret_cast<const uint16_t *>(EltPtr));
2639 case 32:
2640 return *const_cast<uint32_t *>(reinterpret_cast<const uint32_t *>(EltPtr));
2641 case 64:
2642 return *const_cast<uint64_t *>(reinterpret_cast<const uint64_t *>(EltPtr));
Chris Lattnere4f3f102012-01-24 04:43:41 +00002643 }
2644}
2645
2646/// getElementAsAPFloat - If this is a sequential container of floating point
2647/// type, return the specified element as an APFloat.
2648APFloat ConstantDataSequential::getElementAsAPFloat(unsigned Elt) const {
2649 const char *EltPtr = getElementPointer(Elt);
2650
2651 switch (getElementType()->getTypeID()) {
Nick Lewyckyff509622012-01-25 03:20:12 +00002652 default:
Craig Topperc514b542012-02-05 22:14:15 +00002653 llvm_unreachable("Accessor can only be used when element is float/double!");
Galina Kistanovafc259902012-07-13 01:25:27 +00002654 case Type::FloatTyID: {
2655 const float *FloatPrt = reinterpret_cast<const float *>(EltPtr);
2656 return APFloat(*const_cast<float *>(FloatPrt));
2657 }
2658 case Type::DoubleTyID: {
2659 const double *DoublePtr = reinterpret_cast<const double *>(EltPtr);
2660 return APFloat(*const_cast<double *>(DoublePtr));
2661 }
Chris Lattnere4f3f102012-01-24 04:43:41 +00002662 }
2663}
2664
2665/// getElementAsFloat - If this is an sequential container of floats, return
2666/// the specified element as a float.
2667float ConstantDataSequential::getElementAsFloat(unsigned Elt) const {
2668 assert(getElementType()->isFloatTy() &&
2669 "Accessor can only be used when element is a 'float'");
Galina Kistanovafc259902012-07-13 01:25:27 +00002670 const float *EltPtr = reinterpret_cast<const float *>(getElementPointer(Elt));
2671 return *const_cast<float *>(EltPtr);
Chris Lattnere4f3f102012-01-24 04:43:41 +00002672}
2673
2674/// getElementAsDouble - If this is an sequential container of doubles, return
2675/// the specified element as a float.
2676double ConstantDataSequential::getElementAsDouble(unsigned Elt) const {
2677 assert(getElementType()->isDoubleTy() &&
2678 "Accessor can only be used when element is a 'float'");
Galina Kistanovafc259902012-07-13 01:25:27 +00002679 const double *EltPtr =
2680 reinterpret_cast<const double *>(getElementPointer(Elt));
2681 return *const_cast<double *>(EltPtr);
Chris Lattnere4f3f102012-01-24 04:43:41 +00002682}
2683
2684/// getElementAsConstant - Return a Constant for a specified index's element.
2685/// Note that this has to compute a new constant to return, so it isn't as
2686/// efficient as getElementAsInteger/Float/Double.
2687Constant *ConstantDataSequential::getElementAsConstant(unsigned Elt) const {
2688 if (getElementType()->isFloatTy() || getElementType()->isDoubleTy())
2689 return ConstantFP::get(getContext(), getElementAsAPFloat(Elt));
Galina Kistanovafc259902012-07-13 01:25:27 +00002690
Chris Lattnere4f3f102012-01-24 04:43:41 +00002691 return ConstantInt::get(getElementType(), getElementAsInteger(Elt));
2692}
2693
Chris Lattner5dd4d872012-01-24 09:01:07 +00002694/// isString - This method returns true if this is an array of i8.
2695bool ConstantDataSequential::isString() const {
2696 return isa<ArrayType>(getType()) && getElementType()->isIntegerTy(8);
2697}
Chris Lattner3756b912012-01-23 22:57:10 +00002698
Chris Lattner5dd4d872012-01-24 09:01:07 +00002699/// isCString - This method returns true if the array "isString", ends with a
2700/// nul byte, and does not contains any other nul bytes.
2701bool ConstantDataSequential::isCString() const {
2702 if (!isString())
2703 return false;
Galina Kistanovafc259902012-07-13 01:25:27 +00002704
Chris Lattner5dd4d872012-01-24 09:01:07 +00002705 StringRef Str = getAsString();
Galina Kistanovafc259902012-07-13 01:25:27 +00002706
Chris Lattner5dd4d872012-01-24 09:01:07 +00002707 // The last value must be nul.
2708 if (Str.back() != 0) return false;
Galina Kistanovafc259902012-07-13 01:25:27 +00002709
Chris Lattner5dd4d872012-01-24 09:01:07 +00002710 // Other elements must be non-nul.
2711 return Str.drop_back().find(0) == StringRef::npos;
2712}
Chris Lattner3756b912012-01-23 22:57:10 +00002713
Chris Lattnerf14a67f2012-01-26 02:31:22 +00002714/// getSplatValue - If this is a splat constant, meaning that all of the
Reid Kleckner971c3ea2014-11-13 22:55:19 +00002715/// elements have the same value, return that value. Otherwise return nullptr.
Chris Lattnerf14a67f2012-01-26 02:31:22 +00002716Constant *ConstantDataVector::getSplatValue() const {
2717 const char *Base = getRawDataValues().data();
Galina Kistanovafc259902012-07-13 01:25:27 +00002718
Chris Lattnerf14a67f2012-01-26 02:31:22 +00002719 // Compare elements 1+ to the 0'th element.
2720 unsigned EltSize = getElementByteSize();
2721 for (unsigned i = 1, e = getNumElements(); i != e; ++i)
2722 if (memcmp(Base, Base+i*EltSize, EltSize))
Craig Topperc6207612014-04-09 06:08:46 +00002723 return nullptr;
Galina Kistanovafc259902012-07-13 01:25:27 +00002724
Chris Lattnerf14a67f2012-01-26 02:31:22 +00002725 // If they're all the same, return the 0th one as a representative.
2726 return getElementAsConstant(0);
2727}
Chris Lattnera3b94ba2010-03-30 20:48:48 +00002728
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002729//===----------------------------------------------------------------------===//
2730// replaceUsesOfWithOnConstant implementations
2731
Chris Lattner913849b2007-08-21 00:55:23 +00002732/// replaceUsesOfWithOnConstant - Update this constant array to change uses of
2733/// 'From' to be uses of 'To'. This must update the uniquing data structures
2734/// etc.
2735///
2736/// Note that we intentionally replace all uses of From with To here. Consider
2737/// a large array that uses 'From' 1000 times. By handling this case all here,
2738/// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
2739/// single invocation handles all 1000 uses. Handling them one at a time would
2740/// work, but would be really slow because it would have to unique each updated
2741/// array instance.
Chris Lattner31b132c2009-10-28 00:01:44 +00002742///
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002743void Constant::replaceUsesOfWithOnConstantImpl(Constant *Replacement) {
2744 // I do need to replace this with an existing value.
2745 assert(Replacement != this && "I didn't contain From!");
2746
2747 // Everyone using this now uses the replacement.
2748 replaceAllUsesWith(Replacement);
2749
2750 // Delete the old constant!
2751 destroyConstant();
2752}
2753
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002754void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
Chris Lattner7a1450d2005-10-04 18:13:04 +00002755 Use *U) {
Owen Andersonc2c79322009-07-28 18:32:17 +00002756 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2757 Constant *ToC = cast<Constant>(To);
2758
Talin46e9b442012-02-05 20:54:10 +00002759 SmallVector<Constant*, 8> Values;
Owen Andersonc2c79322009-07-28 18:32:17 +00002760 Values.reserve(getNumOperands()); // Build replacement array.
2761
Galina Kistanovafc259902012-07-13 01:25:27 +00002762 // Fill values with the modified operands of the constant array. Also,
Owen Andersonc2c79322009-07-28 18:32:17 +00002763 // compute whether this turns into an all-zeros array.
Owen Andersonc2c79322009-07-28 18:32:17 +00002764 unsigned NumUpdated = 0;
Galina Kistanovafc259902012-07-13 01:25:27 +00002765
Chris Lattnerf14a67f2012-01-26 02:31:22 +00002766 // Keep track of whether all the values in the array are "ToC".
2767 bool AllSame = true;
2768 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2769 Constant *Val = cast<Constant>(O->get());
2770 if (Val == From) {
2771 Val = ToC;
2772 ++NumUpdated;
Owen Andersonc2c79322009-07-28 18:32:17 +00002773 }
Chris Lattnerf14a67f2012-01-26 02:31:22 +00002774 Values.push_back(Val);
Talin46e9b442012-02-05 20:54:10 +00002775 AllSame &= Val == ToC;
Owen Andersonc2c79322009-07-28 18:32:17 +00002776 }
Galina Kistanovafc259902012-07-13 01:25:27 +00002777
Chris Lattnerf14a67f2012-01-26 02:31:22 +00002778 if (AllSame && ToC->isNullValue()) {
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002779 replaceUsesOfWithOnConstantImpl(ConstantAggregateZero::get(getType()));
2780 return;
2781 }
2782 if (AllSame && isa<UndefValue>(ToC)) {
2783 replaceUsesOfWithOnConstantImpl(UndefValue::get(getType()));
2784 return;
Duncan P. N. Exon Smithd8c60542014-08-19 02:16:51 +00002785 }
Aaron Ballmane4b91dc2014-08-19 14:59:02 +00002786
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002787 // Check for any other type of constant-folding.
2788 if (Constant *C = getImpl(getType(), Values)) {
2789 replaceUsesOfWithOnConstantImpl(C);
2790 return;
2791 }
Aaron Ballmane4b91dc2014-08-19 14:59:02 +00002792
Duncan P. N. Exon Smith909620a2014-08-19 19:13:30 +00002793 // Update to the new value.
2794 if (Constant *C = getContext().pImpl->ArrayConstants.replaceOperandsInPlace(
2795 Values, this, From, ToC, NumUpdated, U - OperandList))
2796 replaceUsesOfWithOnConstantImpl(C);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002797}
2798
2799void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
Chris Lattner7a1450d2005-10-04 18:13:04 +00002800 Use *U) {
Owen Anderson45308b52009-07-27 22:29:26 +00002801 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2802 Constant *ToC = cast<Constant>(To);
2803
2804 unsigned OperandToUpdate = U-OperandList;
2805 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
2806
Talin46e9b442012-02-05 20:54:10 +00002807 SmallVector<Constant*, 8> Values;
Owen Anderson45308b52009-07-27 22:29:26 +00002808 Values.reserve(getNumOperands()); // Build replacement struct.
Galina Kistanovafc259902012-07-13 01:25:27 +00002809
2810 // Fill values with the modified operands of the constant struct. Also,
Owen Anderson45308b52009-07-27 22:29:26 +00002811 // compute whether this turns into an all-zeros struct.
2812 bool isAllZeros = false;
Chris Lattnerf14a67f2012-01-26 02:31:22 +00002813 bool isAllUndef = false;
2814 if (ToC->isNullValue()) {
Owen Anderson45308b52009-07-27 22:29:26 +00002815 isAllZeros = true;
2816 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2817 Constant *Val = cast<Constant>(O->get());
2818 Values.push_back(Val);
2819 if (isAllZeros) isAllZeros = Val->isNullValue();
2820 }
Chris Lattnerf14a67f2012-01-26 02:31:22 +00002821 } else if (isa<UndefValue>(ToC)) {
2822 isAllUndef = true;
2823 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2824 Constant *Val = cast<Constant>(O->get());
2825 Values.push_back(Val);
2826 if (isAllUndef) isAllUndef = isa<UndefValue>(Val);
2827 }
2828 } else {
2829 for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O)
2830 Values.push_back(cast<Constant>(O->get()));
Owen Anderson45308b52009-07-27 22:29:26 +00002831 }
2832 Values[OperandToUpdate] = ToC;
Galina Kistanovafc259902012-07-13 01:25:27 +00002833
Owen Anderson45308b52009-07-27 22:29:26 +00002834 if (isAllZeros) {
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002835 replaceUsesOfWithOnConstantImpl(ConstantAggregateZero::get(getType()));
2836 return;
2837 }
2838 if (isAllUndef) {
2839 replaceUsesOfWithOnConstantImpl(UndefValue::get(getType()));
2840 return;
Duncan P. N. Exon Smithd8c60542014-08-19 02:16:51 +00002841 }
Galina Kistanovafc259902012-07-13 01:25:27 +00002842
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002843 // Update to the new value.
Duncan P. N. Exon Smith909620a2014-08-19 19:13:30 +00002844 if (Constant *C = getContext().pImpl->StructConstants.replaceOperandsInPlace(
2845 Values, this, From, ToC))
2846 replaceUsesOfWithOnConstantImpl(C);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002847}
2848
Reid Spencerd84d35b2007-02-15 02:26:10 +00002849void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
Chris Lattner7a1450d2005-10-04 18:13:04 +00002850 Use *U) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002851 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002852 Constant *ToC = cast<Constant>(To);
Galina Kistanovafc259902012-07-13 01:25:27 +00002853
Chris Lattnera474bb22012-01-26 20:40:56 +00002854 SmallVector<Constant*, 8> Values;
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002855 Values.reserve(getNumOperands()); // Build replacement array...
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002856 unsigned NumUpdated = 0;
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002857 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2858 Constant *Val = getOperand(i);
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002859 if (Val == From) {
2860 ++NumUpdated;
2861 Val = ToC;
2862 }
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002863 Values.push_back(Val);
2864 }
Galina Kistanovafc259902012-07-13 01:25:27 +00002865
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002866 if (Constant *C = getImpl(Values)) {
2867 replaceUsesOfWithOnConstantImpl(C);
2868 return;
2869 }
Duncan P. N. Exon Smith687744d2014-08-19 02:24:46 +00002870
Duncan P. N. Exon Smith909620a2014-08-19 19:13:30 +00002871 // Update to the new value.
2872 if (Constant *C = getContext().pImpl->VectorConstants.replaceOperandsInPlace(
2873 Values, this, From, ToC, NumUpdated, U - OperandList))
2874 replaceUsesOfWithOnConstantImpl(C);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002875}
2876
2877void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
Chris Lattner7a1450d2005-10-04 18:13:04 +00002878 Use *U) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002879 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2880 Constant *To = cast<Constant>(ToV);
Galina Kistanovafc259902012-07-13 01:25:27 +00002881
Chris Lattner37e38352012-01-26 20:37:11 +00002882 SmallVector<Constant*, 8> NewOps;
Duncan P. N. Exon Smith33de00c2014-08-19 20:03:35 +00002883 unsigned NumUpdated = 0;
Chris Lattner37e38352012-01-26 20:37:11 +00002884 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2885 Constant *Op = getOperand(i);
Duncan P. N. Exon Smith33de00c2014-08-19 20:03:35 +00002886 if (Op == From) {
2887 ++NumUpdated;
2888 Op = To;
2889 }
2890 NewOps.push_back(Op);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002891 }
Duncan P. N. Exon Smith33de00c2014-08-19 20:03:35 +00002892 assert(NumUpdated && "I didn't contain From!");
Galina Kistanovafc259902012-07-13 01:25:27 +00002893
Duncan P. N. Exon Smith33de00c2014-08-19 20:03:35 +00002894 if (Constant *C = getWithOperands(NewOps, getType(), true)) {
2895 replaceUsesOfWithOnConstantImpl(C);
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002896 return;
2897 }
2898
Duncan P. N. Exon Smith33de00c2014-08-19 20:03:35 +00002899 // Update to the new value.
2900 if (Constant *C = getContext().pImpl->ExprConstants.replaceOperandsInPlace(
2901 NewOps, this, From, To, NumUpdated, U - OperandList))
2902 replaceUsesOfWithOnConstantImpl(C);
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002903}
2904
James Molloyce545682012-11-17 17:56:30 +00002905Instruction *ConstantExpr::getAsInstruction() {
2906 SmallVector<Value*,4> ValueOperands;
2907 for (op_iterator I = op_begin(), E = op_end(); I != E; ++I)
2908 ValueOperands.push_back(cast<Value>(I));
2909
2910 ArrayRef<Value*> Ops(ValueOperands);
2911
2912 switch (getOpcode()) {
2913 case Instruction::Trunc:
2914 case Instruction::ZExt:
2915 case Instruction::SExt:
2916 case Instruction::FPTrunc:
2917 case Instruction::FPExt:
2918 case Instruction::UIToFP:
2919 case Instruction::SIToFP:
2920 case Instruction::FPToUI:
2921 case Instruction::FPToSI:
2922 case Instruction::PtrToInt:
2923 case Instruction::IntToPtr:
2924 case Instruction::BitCast:
Eli Bendersky157a97a2014-01-18 22:54:33 +00002925 case Instruction::AddrSpaceCast:
James Molloyce545682012-11-17 17:56:30 +00002926 return CastInst::Create((Instruction::CastOps)getOpcode(),
2927 Ops[0], getType());
2928 case Instruction::Select:
2929 return SelectInst::Create(Ops[0], Ops[1], Ops[2]);
2930 case Instruction::InsertElement:
2931 return InsertElementInst::Create(Ops[0], Ops[1], Ops[2]);
2932 case Instruction::ExtractElement:
2933 return ExtractElementInst::Create(Ops[0], Ops[1]);
2934 case Instruction::InsertValue:
2935 return InsertValueInst::Create(Ops[0], Ops[1], getIndices());
2936 case Instruction::ExtractValue:
2937 return ExtractValueInst::Create(Ops[0], getIndices());
2938 case Instruction::ShuffleVector:
2939 return new ShuffleVectorInst(Ops[0], Ops[1], Ops[2]);
2940
2941 case Instruction::GetElementPtr:
2942 if (cast<GEPOperator>(this)->isInBounds())
2943 return GetElementPtrInst::CreateInBounds(Ops[0], Ops.slice(1));
2944 else
2945 return GetElementPtrInst::Create(Ops[0], Ops.slice(1));
2946
2947 case Instruction::ICmp:
2948 case Instruction::FCmp:
2949 return CmpInst::Create((Instruction::OtherOps)getOpcode(),
2950 getPredicate(), Ops[0], Ops[1]);
2951
2952 default:
2953 assert(getNumOperands() == 2 && "Must be binary operator?");
2954 BinaryOperator *BO =
2955 BinaryOperator::Create((Instruction::BinaryOps)getOpcode(),
2956 Ops[0], Ops[1]);
2957 if (isa<OverflowingBinaryOperator>(BO)) {
2958 BO->setHasNoUnsignedWrap(SubclassOptionalData &
2959 OverflowingBinaryOperator::NoUnsignedWrap);
2960 BO->setHasNoSignedWrap(SubclassOptionalData &
2961 OverflowingBinaryOperator::NoSignedWrap);
2962 }
2963 if (isa<PossiblyExactOperator>(BO))
2964 BO->setIsExact(SubclassOptionalData & PossiblyExactOperator::IsExact);
2965 return BO;
2966 }
2967}