blob: ac80eae8e941464b967ee67fc7ac842dc8b6b87b [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
Owen Anderson8e851302015-11-20 22:34:48 +000056 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
57 if (ConstantFP *SplatCFP = dyn_cast_or_null<ConstantFP>(CV->getSplatValue()))
58 if (SplatCFP && SplatCFP->isZero() && SplatCFP->isNegative())
59 return true;
60
David Tweed298e4192013-03-19 10:16:40 +000061 // We've already handled true FP case; any other FP vectors can't represent -0.0.
62 if (getType()->isFPOrFPVectorTy())
63 return false;
David Tweed5493fee2013-03-18 11:54:44 +000064
Chris Lattnerac5fb562011-07-15 05:58:04 +000065 // Otherwise, just use +0.0.
66 return isNullValue();
67}
68
Shuxin Yang9ca562e2013-01-09 00:53:25 +000069// Return true iff this constant is positive zero (floating point), negative
70// zero (floating point), or a null value.
Shuxin Yangf0537ab2013-01-09 00:13:41 +000071bool Constant::isZeroValue() const {
72 // Floating point values have an explicit -0.0 value.
73 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
74 return CFP->isZero();
75
Owen Anderson630077e2015-11-20 08:16:13 +000076 // Equivalent for a vector of -0.0's.
77 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
78 if (ConstantFP *SplatCFP = dyn_cast_or_null<ConstantFP>(CV->getSplatValue()))
79 if (SplatCFP && SplatCFP->isZero())
80 return true;
81
Owen Anderson8e851302015-11-20 22:34:48 +000082 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
83 if (ConstantFP *SplatCFP = dyn_cast_or_null<ConstantFP>(CV->getSplatValue()))
84 if (SplatCFP && SplatCFP->isZero())
85 return true;
86
Shuxin Yangf0537ab2013-01-09 00:13:41 +000087 // Otherwise, just use +0.0.
88 return isNullValue();
89}
90
Chris Lattnerbe6610c2011-07-15 06:14:08 +000091bool Constant::isNullValue() const {
92 // 0 is null.
93 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
94 return CI->isZero();
Galina Kistanovafc259902012-07-13 01:25:27 +000095
Chris Lattnerbe6610c2011-07-15 06:14:08 +000096 // +0.0 is null.
97 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
98 return CFP->isZero() && !CFP->isNegative();
99
David Majnemerf0f224d2015-11-11 21:57:16 +0000100 // constant zero is zero for aggregates, cpnull is null for pointers, none for
101 // tokens.
102 return isa<ConstantAggregateZero>(this) || isa<ConstantPointerNull>(this) ||
103 isa<ConstantTokenNone>(this);
Chris Lattnerbe6610c2011-07-15 06:14:08 +0000104}
105
Nadav Rotem365af6f2011-08-24 20:18:38 +0000106bool Constant::isAllOnesValue() const {
107 // Check for -1 integers
108 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
109 return CI->isMinusOne();
110
111 // Check for FP which are bitcasted from -1 integers
112 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
113 return CFP->getValueAPF().bitcastToAPInt().isAllOnesValue();
114
Benjamin Kramer42d098e2011-11-14 19:12:20 +0000115 // Check for constant vectors which are splats of -1 values.
Nadav Rotem365af6f2011-08-24 20:18:38 +0000116 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
Benjamin Kramer42d098e2011-11-14 19:12:20 +0000117 if (Constant *Splat = CV->getSplatValue())
118 return Splat->isAllOnesValue();
Nadav Rotem365af6f2011-08-24 20:18:38 +0000119
Chris Lattnerf14a67f2012-01-26 02:31:22 +0000120 // Check for constant vectors which are splats of -1 values.
121 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
122 if (Constant *Splat = CV->getSplatValue())
123 return Splat->isAllOnesValue();
124
Nadav Rotem365af6f2011-08-24 20:18:38 +0000125 return false;
126}
Benjamin Kramer42d098e2011-11-14 19:12:20 +0000127
David Majnemer1a0bbc82014-08-16 09:23:42 +0000128bool Constant::isOneValue() const {
129 // Check for 1 integers
130 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
131 return CI->isOne();
132
133 // Check for FP which are bitcasted from 1 integers
134 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
135 return CFP->getValueAPF().bitcastToAPInt() == 1;
136
137 // Check for constant vectors which are splats of 1 values.
138 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
139 if (Constant *Splat = CV->getSplatValue())
140 return Splat->isOneValue();
141
142 // Check for constant vectors which are splats of 1 values.
143 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
144 if (Constant *Splat = CV->getSplatValue())
145 return Splat->isOneValue();
146
147 return false;
148}
149
David Majnemerbdeef602014-07-02 06:07:09 +0000150bool Constant::isMinSignedValue() const {
151 // Check for INT_MIN integers
152 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
153 return CI->isMinValue(/*isSigned=*/true);
154
155 // Check for FP which are bitcasted from INT_MIN integers
156 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
157 return CFP->getValueAPF().bitcastToAPInt().isMinSignedValue();
158
159 // Check for constant vectors which are splats of INT_MIN values.
160 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
161 if (Constant *Splat = CV->getSplatValue())
162 return Splat->isMinSignedValue();
163
164 // Check for constant vectors which are splats of INT_MIN values.
165 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
166 if (Constant *Splat = CV->getSplatValue())
167 return Splat->isMinSignedValue();
168
169 return false;
170}
171
David Majnemer0e6c9862014-08-22 16:41:23 +0000172bool Constant::isNotMinSignedValue() const {
173 // Check for INT_MIN integers
174 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
175 return !CI->isMinValue(/*isSigned=*/true);
176
177 // Check for FP which are bitcasted from INT_MIN integers
178 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
179 return !CFP->getValueAPF().bitcastToAPInt().isMinSignedValue();
180
181 // Check for constant vectors which are splats of INT_MIN values.
182 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
183 if (Constant *Splat = CV->getSplatValue())
184 return Splat->isNotMinSignedValue();
185
186 // Check for constant vectors which are splats of INT_MIN values.
187 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
188 if (Constant *Splat = CV->getSplatValue())
189 return Splat->isNotMinSignedValue();
190
191 // It *may* contain INT_MIN, we can't tell.
192 return false;
193}
194
Owen Anderson5a1acd92009-07-31 20:28:14 +0000195// Constructor to create a '0' constant of arbitrary type...
Chris Lattner229907c2011-07-18 04:54:35 +0000196Constant *Constant::getNullValue(Type *Ty) {
Owen Anderson5a1acd92009-07-31 20:28:14 +0000197 switch (Ty->getTypeID()) {
198 case Type::IntegerTyID:
199 return ConstantInt::get(Ty, 0);
Dan Gohman518cda42011-12-17 00:04:22 +0000200 case Type::HalfTyID:
201 return ConstantFP::get(Ty->getContext(),
202 APFloat::getZero(APFloat::IEEEhalf));
Owen Anderson5a1acd92009-07-31 20:28:14 +0000203 case Type::FloatTyID:
Benjamin Kramer8ceebfa2010-12-04 14:22:24 +0000204 return ConstantFP::get(Ty->getContext(),
205 APFloat::getZero(APFloat::IEEEsingle));
Owen Anderson5a1acd92009-07-31 20:28:14 +0000206 case Type::DoubleTyID:
Benjamin Kramer8ceebfa2010-12-04 14:22:24 +0000207 return ConstantFP::get(Ty->getContext(),
208 APFloat::getZero(APFloat::IEEEdouble));
Owen Anderson5a1acd92009-07-31 20:28:14 +0000209 case Type::X86_FP80TyID:
Benjamin Kramer8ceebfa2010-12-04 14:22:24 +0000210 return ConstantFP::get(Ty->getContext(),
211 APFloat::getZero(APFloat::x87DoubleExtended));
Owen Anderson5a1acd92009-07-31 20:28:14 +0000212 case Type::FP128TyID:
213 return ConstantFP::get(Ty->getContext(),
Benjamin Kramer8ceebfa2010-12-04 14:22:24 +0000214 APFloat::getZero(APFloat::IEEEquad));
Owen Anderson5a1acd92009-07-31 20:28:14 +0000215 case Type::PPC_FP128TyID:
Benjamin Kramer8ceebfa2010-12-04 14:22:24 +0000216 return ConstantFP::get(Ty->getContext(),
Tim Northover29178a32013-01-22 09:46:31 +0000217 APFloat(APFloat::PPCDoubleDouble,
218 APInt::getNullValue(128)));
Owen Anderson5a1acd92009-07-31 20:28:14 +0000219 case Type::PointerTyID:
220 return ConstantPointerNull::get(cast<PointerType>(Ty));
221 case Type::StructTyID:
222 case Type::ArrayTyID:
223 case Type::VectorTyID:
224 return ConstantAggregateZero::get(Ty);
David Majnemerf0f224d2015-11-11 21:57:16 +0000225 case Type::TokenTyID:
226 return ConstantTokenNone::get(Ty->getContext());
Owen Anderson5a1acd92009-07-31 20:28:14 +0000227 default:
228 // Function, Label, or Opaque type?
Craig Topperc514b542012-02-05 22:14:15 +0000229 llvm_unreachable("Cannot create a null constant of that type!");
Owen Anderson5a1acd92009-07-31 20:28:14 +0000230 }
231}
232
Chris Lattner229907c2011-07-18 04:54:35 +0000233Constant *Constant::getIntegerValue(Type *Ty, const APInt &V) {
234 Type *ScalarTy = Ty->getScalarType();
Dan Gohmanf011f5a2009-08-03 22:07:33 +0000235
236 // Create the base integer constant.
237 Constant *C = ConstantInt::get(Ty->getContext(), V);
238
239 // Convert an integer to a pointer, if necessary.
Chris Lattner229907c2011-07-18 04:54:35 +0000240 if (PointerType *PTy = dyn_cast<PointerType>(ScalarTy))
Dan Gohmanf011f5a2009-08-03 22:07:33 +0000241 C = ConstantExpr::getIntToPtr(C, PTy);
242
243 // Broadcast a scalar to a vector, if necessary.
Chris Lattner229907c2011-07-18 04:54:35 +0000244 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
Chris Lattnere9eed292012-01-25 05:19:54 +0000245 C = ConstantVector::getSplat(VTy->getNumElements(), C);
Dan Gohmanf011f5a2009-08-03 22:07:33 +0000246
247 return C;
248}
249
Chris Lattner229907c2011-07-18 04:54:35 +0000250Constant *Constant::getAllOnesValue(Type *Ty) {
251 if (IntegerType *ITy = dyn_cast<IntegerType>(Ty))
Owen Anderson5a1acd92009-07-31 20:28:14 +0000252 return ConstantInt::get(Ty->getContext(),
253 APInt::getAllOnesValue(ITy->getBitWidth()));
Nadav Rotem7cc6d122011-02-17 21:22:27 +0000254
255 if (Ty->isFloatingPointTy()) {
256 APFloat FL = APFloat::getAllOnesValue(Ty->getPrimitiveSizeInBits(),
257 !Ty->isPPC_FP128Ty());
258 return ConstantFP::get(Ty->getContext(), FL);
259 }
260
Chris Lattner229907c2011-07-18 04:54:35 +0000261 VectorType *VTy = cast<VectorType>(Ty);
Chris Lattnere9eed292012-01-25 05:19:54 +0000262 return ConstantVector::getSplat(VTy->getNumElements(),
263 getAllOnesValue(VTy->getElementType()));
Owen Anderson5a1acd92009-07-31 20:28:14 +0000264}
265
Chris Lattner7e683d12012-01-25 06:16:32 +0000266/// getAggregateElement - For aggregates (struct/array/vector) return the
267/// constant that corresponds to the specified element if possible, or null if
268/// not. This can return null if the element index is a ConstantExpr, or if
269/// 'this' is a constant expr.
270Constant *Constant::getAggregateElement(unsigned Elt) const {
271 if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(this))
Craig Topperc6207612014-04-09 06:08:46 +0000272 return Elt < CS->getNumOperands() ? CS->getOperand(Elt) : nullptr;
Galina Kistanovafc259902012-07-13 01:25:27 +0000273
Chris Lattner7e683d12012-01-25 06:16:32 +0000274 if (const ConstantArray *CA = dyn_cast<ConstantArray>(this))
Craig Topperc6207612014-04-09 06:08:46 +0000275 return Elt < CA->getNumOperands() ? CA->getOperand(Elt) : nullptr;
Galina Kistanovafc259902012-07-13 01:25:27 +0000276
Chris Lattner7e683d12012-01-25 06:16:32 +0000277 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
Craig Topperc6207612014-04-09 06:08:46 +0000278 return Elt < CV->getNumOperands() ? CV->getOperand(Elt) : nullptr;
Galina Kistanovafc259902012-07-13 01:25:27 +0000279
David Majnemer9b529a72015-02-16 04:02:09 +0000280 if (const ConstantAggregateZero *CAZ = dyn_cast<ConstantAggregateZero>(this))
281 return Elt < CAZ->getNumElements() ? CAZ->getElementValue(Elt) : nullptr;
Galina Kistanovafc259902012-07-13 01:25:27 +0000282
Chris Lattner7e683d12012-01-25 06:16:32 +0000283 if (const UndefValue *UV = dyn_cast<UndefValue>(this))
David Majnemer9b529a72015-02-16 04:02:09 +0000284 return Elt < UV->getNumElements() ? UV->getElementValue(Elt) : nullptr;
Galina Kistanovafc259902012-07-13 01:25:27 +0000285
Chris Lattner8326bd82012-01-26 00:42:34 +0000286 if (const ConstantDataSequential *CDS =dyn_cast<ConstantDataSequential>(this))
Craig Topperc6207612014-04-09 06:08:46 +0000287 return Elt < CDS->getNumElements() ? CDS->getElementAsConstant(Elt)
288 : nullptr;
289 return nullptr;
Chris Lattner7e683d12012-01-25 06:16:32 +0000290}
291
292Constant *Constant::getAggregateElement(Constant *Elt) const {
293 assert(isa<IntegerType>(Elt->getType()) && "Index must be an integer");
294 if (ConstantInt *CI = dyn_cast<ConstantInt>(Elt))
295 return getAggregateElement(CI->getZExtValue());
Craig Topperc6207612014-04-09 06:08:46 +0000296 return nullptr;
Chris Lattner7e683d12012-01-25 06:16:32 +0000297}
298
Pete Cooper86dd4cf2015-06-23 21:55:11 +0000299void Constant::destroyConstant() {
300 /// First call destroyConstantImpl on the subclass. This gives the subclass
301 /// a chance to remove the constant from any maps/pools it's contained in.
302 switch (getValueID()) {
303 default:
304 llvm_unreachable("Not a constant!");
305#define HANDLE_CONSTANT(Name) \
306 case Value::Name##Val: \
307 cast<Name>(this)->destroyConstantImpl(); \
308 break;
309#include "llvm/IR/Value.def"
310 }
Chris Lattner7e683d12012-01-25 06:16:32 +0000311
Chris Lattner3462ae32001-12-03 22:26:30 +0000312 // When a Constant is destroyed, there may be lingering
Chris Lattnerd7a73302001-10-13 06:57:33 +0000313 // references to the constant by other constants in the constant pool. These
Misha Brukmanbe372b92003-08-21 22:14:26 +0000314 // constants are implicitly dependent on the module that is being deleted,
Chris Lattnerd7a73302001-10-13 06:57:33 +0000315 // but they don't know that. Because we only find out when the CPV is
316 // deleted, we must now notify all of our users (that should only be
Chris Lattner3462ae32001-12-03 22:26:30 +0000317 // Constants) that they are, in fact, invalid now and should be deleted.
Chris Lattnerd7a73302001-10-13 06:57:33 +0000318 //
319 while (!use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000320 Value *V = user_back();
Pete Cooper86dd4cf2015-06-23 21:55:11 +0000321#ifndef NDEBUG // Only in -g mode...
Chris Lattner78683a72009-08-23 04:02:03 +0000322 if (!isa<Constant>(V)) {
David Greene1e27a132010-01-05 01:29:19 +0000323 dbgs() << "While deleting: " << *this
Pete Cooper86dd4cf2015-06-23 21:55:11 +0000324 << "\n\nUse still stuck around after Def is destroyed: " << *V
325 << "\n\n";
Chris Lattner78683a72009-08-23 04:02:03 +0000326 }
Chris Lattnerd7a73302001-10-13 06:57:33 +0000327#endif
Vikram S. Adve4e537b22002-07-14 23:13:17 +0000328 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
Chris Lattner8326bd82012-01-26 00:42:34 +0000329 cast<Constant>(V)->destroyConstant();
Chris Lattnerd7a73302001-10-13 06:57:33 +0000330
331 // The constant should remove itself from our use list...
Chandler Carruthcdf47882014-03-09 03:16:01 +0000332 assert((use_empty() || user_back() != V) && "Constant not removed!");
Chris Lattnerd7a73302001-10-13 06:57:33 +0000333 }
334
335 // Value has no outstanding references it is safe to delete it now...
336 delete this;
Chris Lattner38569342001-10-01 20:11:19 +0000337}
Chris Lattner2f7c9632001-06-06 20:29:01 +0000338
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +0000339static bool canTrapImpl(const Constant *C,
Craig Topper71b7b682014-08-21 05:55:13 +0000340 SmallPtrSetImpl<const ConstantExpr *> &NonTrappingOps) {
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +0000341 assert(C->getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
Chris Lattner23dd1f62006-10-20 00:27:06 +0000342 // The only thing that could possibly trap are constant exprs.
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +0000343 const ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
344 if (!CE)
345 return false;
Galina Kistanovafc259902012-07-13 01:25:27 +0000346
347 // ConstantExpr traps if any operands can trap.
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +0000348 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) {
349 if (ConstantExpr *Op = dyn_cast<ConstantExpr>(CE->getOperand(i))) {
David Blaikie70573dc2014-11-19 07:49:26 +0000350 if (NonTrappingOps.insert(Op).second && canTrapImpl(Op, NonTrappingOps))
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +0000351 return true;
352 }
353 }
Chris Lattner23dd1f62006-10-20 00:27:06 +0000354
355 // Otherwise, only specific operations can trap.
356 switch (CE->getOpcode()) {
357 default:
358 return false;
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000359 case Instruction::UDiv:
360 case Instruction::SDiv:
361 case Instruction::FDiv:
Reid Spencer7eb55b32006-11-02 01:53:59 +0000362 case Instruction::URem:
363 case Instruction::SRem:
364 case Instruction::FRem:
Chris Lattner23dd1f62006-10-20 00:27:06 +0000365 // Div and rem can trap if the RHS is not known to be non-zero.
Chris Lattnera91a5632009-10-28 05:14:34 +0000366 if (!isa<ConstantInt>(CE->getOperand(1)) ||CE->getOperand(1)->isNullValue())
Chris Lattner23dd1f62006-10-20 00:27:06 +0000367 return true;
368 return false;
369 }
370}
371
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +0000372/// canTrap - Return true if evaluation of this constant could trap. This is
373/// true for things like constant expressions that could divide by zero.
374bool Constant::canTrap() const {
375 SmallPtrSet<const ConstantExpr *, 4> NonTrappingOps;
376 return canTrapImpl(this, NonTrappingOps);
377}
378
Hans Wennborg4dc89512014-06-20 00:38:12 +0000379/// Check if C contains a GlobalValue for which Predicate is true.
380static bool
381ConstHasGlobalValuePredicate(const Constant *C,
382 bool (*Predicate)(const GlobalValue *)) {
383 SmallPtrSet<const Constant *, 8> Visited;
384 SmallVector<const Constant *, 8> WorkList;
385 WorkList.push_back(C);
386 Visited.insert(C);
Hans Wennborg709e0152012-11-15 11:40:00 +0000387
388 while (!WorkList.empty()) {
Hans Wennborg4dc89512014-06-20 00:38:12 +0000389 const Constant *WorkItem = WorkList.pop_back_val();
390 if (const auto *GV = dyn_cast<GlobalValue>(WorkItem))
391 if (Predicate(GV))
Hans Wennborg709e0152012-11-15 11:40:00 +0000392 return true;
Hans Wennborg4dc89512014-06-20 00:38:12 +0000393 for (const Value *Op : WorkItem->operands()) {
394 const Constant *ConstOp = dyn_cast<Constant>(Op);
395 if (!ConstOp)
Hans Wennborg18aa12402012-11-16 10:33:25 +0000396 continue;
David Blaikie70573dc2014-11-19 07:49:26 +0000397 if (Visited.insert(ConstOp).second)
Hans Wennborg4dc89512014-06-20 00:38:12 +0000398 WorkList.push_back(ConstOp);
Hans Wennborg709e0152012-11-15 11:40:00 +0000399 }
400 }
Hans Wennborg709e0152012-11-15 11:40:00 +0000401 return false;
402}
403
Hans Wennborg4dc89512014-06-20 00:38:12 +0000404/// Return true if the value can vary between threads.
405bool Constant::isThreadDependent() const {
406 auto DLLImportPredicate = [](const GlobalValue *GV) {
407 return GV->isThreadLocal();
408 };
409 return ConstHasGlobalValuePredicate(this, DLLImportPredicate);
410}
411
412bool Constant::isDLLImportDependent() const {
413 auto DLLImportPredicate = [](const GlobalValue *GV) {
414 return GV->hasDLLImportStorageClass();
415 };
416 return ConstHasGlobalValuePredicate(this, DLLImportPredicate);
417}
418
419/// Return true if the constant has users other than constant exprs and other
420/// dangling things.
Chris Lattner253bc772009-11-01 18:11:50 +0000421bool Constant::isConstantUsed() const {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000422 for (const User *U : users()) {
423 const Constant *UC = dyn_cast<Constant>(U);
Craig Topperc6207612014-04-09 06:08:46 +0000424 if (!UC || isa<GlobalValue>(UC))
Chris Lattner253bc772009-11-01 18:11:50 +0000425 return true;
Galina Kistanovafc259902012-07-13 01:25:27 +0000426
Chris Lattner253bc772009-11-01 18:11:50 +0000427 if (UC->isConstantUsed())
428 return true;
429 }
430 return false;
431}
432
Rafael Espindola65e49022015-11-17 00:51:23 +0000433bool Constant::needsRelocation() const {
434 if (isa<GlobalValue>(this))
435 return true; // Global reference.
436
Chris Lattner2cb85b42009-10-28 04:12:16 +0000437 if (const BlockAddress *BA = dyn_cast<BlockAddress>(this))
Rafael Espindola65e49022015-11-17 00:51:23 +0000438 return BA->getFunction()->needsRelocation();
439
Chris Lattnera7cfc432010-01-03 18:09:40 +0000440 // While raw uses of blockaddress need to be relocated, differences between
441 // two of them don't when they are for labels in the same function. This is a
442 // common idiom when creating a table for the indirect goto extension, so we
443 // handle it efficiently here.
444 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(this))
445 if (CE->getOpcode() == Instruction::Sub) {
446 ConstantExpr *LHS = dyn_cast<ConstantExpr>(CE->getOperand(0));
447 ConstantExpr *RHS = dyn_cast<ConstantExpr>(CE->getOperand(1));
Rafael Espindola65e49022015-11-17 00:51:23 +0000448 if (LHS && RHS && LHS->getOpcode() == Instruction::PtrToInt &&
Chris Lattnera7cfc432010-01-03 18:09:40 +0000449 RHS->getOpcode() == Instruction::PtrToInt &&
450 isa<BlockAddress>(LHS->getOperand(0)) &&
451 isa<BlockAddress>(RHS->getOperand(0)) &&
452 cast<BlockAddress>(LHS->getOperand(0))->getFunction() ==
Rafael Espindola65e49022015-11-17 00:51:23 +0000453 cast<BlockAddress>(RHS->getOperand(0))->getFunction())
454 return false;
Chris Lattnera7cfc432010-01-03 18:09:40 +0000455 }
Galina Kistanovafc259902012-07-13 01:25:27 +0000456
Rafael Espindola65e49022015-11-17 00:51:23 +0000457 bool Result = false;
Evan Chengf9e003b2007-03-08 00:59:12 +0000458 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
Rafael Espindola65e49022015-11-17 00:51:23 +0000459 Result |= cast<Constant>(getOperand(i))->needsRelocation();
Galina Kistanovafc259902012-07-13 01:25:27 +0000460
Chris Lattner4565ef52009-07-22 00:05:44 +0000461 return Result;
Evan Chengf9e003b2007-03-08 00:59:12 +0000462}
463
Chris Lattner84886402011-02-18 04:41:42 +0000464/// removeDeadUsersOfConstant - If the specified constantexpr is dead, remove
465/// it. This involves recursively eliminating any dead users of the
466/// constantexpr.
467static bool removeDeadUsersOfConstant(const Constant *C) {
468 if (isa<GlobalValue>(C)) return false; // Cannot remove this
Galina Kistanovafc259902012-07-13 01:25:27 +0000469
Chris Lattner84886402011-02-18 04:41:42 +0000470 while (!C->use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000471 const Constant *User = dyn_cast<Constant>(C->user_back());
Chris Lattner84886402011-02-18 04:41:42 +0000472 if (!User) return false; // Non-constant usage;
473 if (!removeDeadUsersOfConstant(User))
474 return false; // Constant wasn't dead
475 }
Galina Kistanovafc259902012-07-13 01:25:27 +0000476
Chris Lattner84886402011-02-18 04:41:42 +0000477 const_cast<Constant*>(C)->destroyConstant();
478 return true;
479}
480
481
482/// removeDeadConstantUsers - If there are any dead constant users dangling
483/// off of this constant, remove them. This method is useful for clients
484/// that want to check to see if a global is unused, but don't want to deal
485/// with potentially dead constants hanging off of the globals.
486void Constant::removeDeadConstantUsers() const {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000487 Value::const_user_iterator I = user_begin(), E = user_end();
488 Value::const_user_iterator LastNonDeadUser = E;
Chris Lattner84886402011-02-18 04:41:42 +0000489 while (I != E) {
490 const Constant *User = dyn_cast<Constant>(*I);
Craig Topperc6207612014-04-09 06:08:46 +0000491 if (!User) {
Chris Lattner84886402011-02-18 04:41:42 +0000492 LastNonDeadUser = I;
493 ++I;
494 continue;
495 }
Galina Kistanovafc259902012-07-13 01:25:27 +0000496
Chris Lattner84886402011-02-18 04:41:42 +0000497 if (!removeDeadUsersOfConstant(User)) {
498 // If the constant wasn't dead, remember that this was the last live use
499 // and move on to the next constant.
500 LastNonDeadUser = I;
501 ++I;
502 continue;
503 }
Galina Kistanovafc259902012-07-13 01:25:27 +0000504
Chris Lattner84886402011-02-18 04:41:42 +0000505 // If the constant was dead, then the iterator is invalidated.
506 if (LastNonDeadUser == E) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000507 I = user_begin();
Chris Lattner84886402011-02-18 04:41:42 +0000508 if (I == E) break;
509 } else {
510 I = LastNonDeadUser;
511 ++I;
512 }
513 }
514}
515
516
Chris Lattner2105d662008-07-10 00:28:11 +0000517
Chris Lattner2f7c9632001-06-06 20:29:01 +0000518//===----------------------------------------------------------------------===//
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000519// ConstantInt
Chris Lattner2f7c9632001-06-06 20:29:01 +0000520//===----------------------------------------------------------------------===//
521
David Blaikiea379b1812011-12-20 02:50:00 +0000522void ConstantInt::anchor() { }
523
Chris Lattner229907c2011-07-18 04:54:35 +0000524ConstantInt::ConstantInt(IntegerType *Ty, const APInt& V)
Craig Topperc6207612014-04-09 06:08:46 +0000525 : Constant(Ty, ConstantIntVal, nullptr, 0), Val(V) {
Reid Spencerb31bffe2007-02-26 23:54:03 +0000526 assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
Chris Lattner2f7c9632001-06-06 20:29:01 +0000527}
528
Nick Lewycky92db8e82011-03-06 03:36:19 +0000529ConstantInt *ConstantInt::getTrue(LLVMContext &Context) {
Owen Anderson23a204d2009-07-31 17:39:07 +0000530 LLVMContextImpl *pImpl = Context.pImpl;
Benjamin Kramerddd1b7b2010-11-20 18:43:35 +0000531 if (!pImpl->TheTrueVal)
532 pImpl->TheTrueVal = ConstantInt::get(Type::getInt1Ty(Context), 1);
533 return pImpl->TheTrueVal;
Owen Anderson23a204d2009-07-31 17:39:07 +0000534}
535
Nick Lewycky92db8e82011-03-06 03:36:19 +0000536ConstantInt *ConstantInt::getFalse(LLVMContext &Context) {
Owen Anderson23a204d2009-07-31 17:39:07 +0000537 LLVMContextImpl *pImpl = Context.pImpl;
Benjamin Kramerddd1b7b2010-11-20 18:43:35 +0000538 if (!pImpl->TheFalseVal)
539 pImpl->TheFalseVal = ConstantInt::get(Type::getInt1Ty(Context), 0);
540 return pImpl->TheFalseVal;
Owen Anderson23a204d2009-07-31 17:39:07 +0000541}
542
Chris Lattner229907c2011-07-18 04:54:35 +0000543Constant *ConstantInt::getTrue(Type *Ty) {
544 VectorType *VTy = dyn_cast<VectorType>(Ty);
Nick Lewycky92db8e82011-03-06 03:36:19 +0000545 if (!VTy) {
546 assert(Ty->isIntegerTy(1) && "True must be i1 or vector of i1.");
547 return ConstantInt::getTrue(Ty->getContext());
548 }
549 assert(VTy->getElementType()->isIntegerTy(1) &&
550 "True must be vector of i1 or i1.");
Chris Lattnere9eed292012-01-25 05:19:54 +0000551 return ConstantVector::getSplat(VTy->getNumElements(),
552 ConstantInt::getTrue(Ty->getContext()));
Nick Lewycky92db8e82011-03-06 03:36:19 +0000553}
554
Chris Lattner229907c2011-07-18 04:54:35 +0000555Constant *ConstantInt::getFalse(Type *Ty) {
556 VectorType *VTy = dyn_cast<VectorType>(Ty);
Nick Lewycky92db8e82011-03-06 03:36:19 +0000557 if (!VTy) {
558 assert(Ty->isIntegerTy(1) && "False must be i1 or vector of i1.");
559 return ConstantInt::getFalse(Ty->getContext());
560 }
561 assert(VTy->getElementType()->isIntegerTy(1) &&
562 "False must be vector of i1 or i1.");
Chris Lattnere9eed292012-01-25 05:19:54 +0000563 return ConstantVector::getSplat(VTy->getNumElements(),
564 ConstantInt::getFalse(Ty->getContext()));
Nick Lewycky92db8e82011-03-06 03:36:19 +0000565}
566
Benjamin Kramer8e5dc532014-12-06 13:12:56 +0000567// Get a ConstantInt from an APInt.
Nick Lewycky92db8e82011-03-06 03:36:19 +0000568ConstantInt *ConstantInt::get(LLVMContext &Context, const APInt &V) {
Owen Andersonedb4a702009-07-24 23:12:02 +0000569 // get an existing value or the insertion position
Benjamin Kramer320682f2013-06-01 17:51:03 +0000570 LLVMContextImpl *pImpl = Context.pImpl;
Benjamin Kramer8e5dc532014-12-06 13:12:56 +0000571 ConstantInt *&Slot = pImpl->IntConstants[V];
572 if (!Slot) {
573 // Get the corresponding integer type for the bit width of the value.
574 IntegerType *ITy = IntegerType::get(Context, V.getBitWidth());
NAKAMURA Takumifc3062f2014-12-06 05:57:06 +0000575 Slot = new ConstantInt(ITy, V);
Benjamin Kramer8e5dc532014-12-06 13:12:56 +0000576 }
577 assert(Slot->getType() == IntegerType::get(Context, V.getBitWidth()));
Owen Anderson5dab84c2009-10-19 20:11:52 +0000578 return Slot;
Owen Andersonedb4a702009-07-24 23:12:02 +0000579}
580
Chris Lattner229907c2011-07-18 04:54:35 +0000581Constant *ConstantInt::get(Type *Ty, uint64_t V, bool isSigned) {
Nick Lewycky92db8e82011-03-06 03:36:19 +0000582 Constant *C = get(cast<IntegerType>(Ty->getScalarType()), V, isSigned);
Owen Andersonedb4a702009-07-24 23:12:02 +0000583
584 // For vectors, broadcast the value.
Chris Lattner229907c2011-07-18 04:54:35 +0000585 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
Chris Lattnere9eed292012-01-25 05:19:54 +0000586 return ConstantVector::getSplat(VTy->getNumElements(), C);
Owen Andersonedb4a702009-07-24 23:12:02 +0000587
588 return C;
589}
590
Chris Lattner0256be92012-01-27 03:08:05 +0000591ConstantInt *ConstantInt::get(IntegerType *Ty, uint64_t V,
Owen Andersonedb4a702009-07-24 23:12:02 +0000592 bool isSigned) {
593 return get(Ty->getContext(), APInt(Ty->getBitWidth(), V, isSigned));
594}
595
Chris Lattner0256be92012-01-27 03:08:05 +0000596ConstantInt *ConstantInt::getSigned(IntegerType *Ty, int64_t V) {
Owen Andersonedb4a702009-07-24 23:12:02 +0000597 return get(Ty, V, true);
598}
599
Chris Lattner229907c2011-07-18 04:54:35 +0000600Constant *ConstantInt::getSigned(Type *Ty, int64_t V) {
Owen Andersonedb4a702009-07-24 23:12:02 +0000601 return get(Ty, V, true);
602}
603
Chris Lattner0256be92012-01-27 03:08:05 +0000604Constant *ConstantInt::get(Type *Ty, const APInt& V) {
Owen Andersonedb4a702009-07-24 23:12:02 +0000605 ConstantInt *C = get(Ty->getContext(), V);
606 assert(C->getType() == Ty->getScalarType() &&
607 "ConstantInt type doesn't match the type implied by its value!");
608
609 // For vectors, broadcast the value.
Chris Lattner229907c2011-07-18 04:54:35 +0000610 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
Chris Lattnere9eed292012-01-25 05:19:54 +0000611 return ConstantVector::getSplat(VTy->getNumElements(), C);
Owen Andersonedb4a702009-07-24 23:12:02 +0000612
613 return C;
614}
615
Chris Lattner0256be92012-01-27 03:08:05 +0000616ConstantInt *ConstantInt::get(IntegerType* Ty, StringRef Str,
Erick Tryzelaarfc2280d2009-08-16 23:36:33 +0000617 uint8_t radix) {
618 return get(Ty->getContext(), APInt(Ty->getBitWidth(), Str, radix));
619}
620
Pete Cooper86dd4cf2015-06-23 21:55:11 +0000621/// Remove the constant from the constant table.
622void ConstantInt::destroyConstantImpl() {
623 llvm_unreachable("You can't ConstantInt->destroyConstantImpl()!");
624}
625
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000626//===----------------------------------------------------------------------===//
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000627// ConstantFP
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000628//===----------------------------------------------------------------------===//
629
Chris Lattner229907c2011-07-18 04:54:35 +0000630static const fltSemantics *TypeToFloatSemantics(Type *Ty) {
Dan Gohman518cda42011-12-17 00:04:22 +0000631 if (Ty->isHalfTy())
632 return &APFloat::IEEEhalf;
Chris Lattnerfdd87902009-10-05 05:54:46 +0000633 if (Ty->isFloatTy())
Rafael Espindolaf5d53d42009-07-15 17:40:42 +0000634 return &APFloat::IEEEsingle;
Chris Lattnerfdd87902009-10-05 05:54:46 +0000635 if (Ty->isDoubleTy())
Rafael Espindolaf5d53d42009-07-15 17:40:42 +0000636 return &APFloat::IEEEdouble;
Chris Lattnerfdd87902009-10-05 05:54:46 +0000637 if (Ty->isX86_FP80Ty())
Rafael Espindolaf5d53d42009-07-15 17:40:42 +0000638 return &APFloat::x87DoubleExtended;
Chris Lattnerfdd87902009-10-05 05:54:46 +0000639 else if (Ty->isFP128Ty())
Rafael Espindolaf5d53d42009-07-15 17:40:42 +0000640 return &APFloat::IEEEquad;
Galina Kistanovafc259902012-07-13 01:25:27 +0000641
Chris Lattnerfdd87902009-10-05 05:54:46 +0000642 assert(Ty->isPPC_FP128Ty() && "Unknown FP format");
Rafael Espindolaf5d53d42009-07-15 17:40:42 +0000643 return &APFloat::PPCDoubleDouble;
644}
645
David Blaikiea379b1812011-12-20 02:50:00 +0000646void ConstantFP::anchor() { }
647
Owen Anderson69c464d2009-07-27 20:59:43 +0000648/// get() - This returns a constant fp for the specified value in the
649/// specified type. This should only be used for simple constant values like
650/// 2.0/1.0 etc, that are known-valid both as double and as the target format.
Chris Lattner0256be92012-01-27 03:08:05 +0000651Constant *ConstantFP::get(Type *Ty, double V) {
Owen Anderson69c464d2009-07-27 20:59:43 +0000652 LLVMContext &Context = Ty->getContext();
Galina Kistanovafc259902012-07-13 01:25:27 +0000653
Owen Anderson69c464d2009-07-27 20:59:43 +0000654 APFloat FV(V);
655 bool ignored;
656 FV.convert(*TypeToFloatSemantics(Ty->getScalarType()),
657 APFloat::rmNearestTiesToEven, &ignored);
658 Constant *C = get(Context, FV);
659
660 // For vectors, broadcast the value.
Chris Lattner229907c2011-07-18 04:54:35 +0000661 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
Chris Lattnere9eed292012-01-25 05:19:54 +0000662 return ConstantVector::getSplat(VTy->getNumElements(), C);
Owen Anderson69c464d2009-07-27 20:59:43 +0000663
664 return C;
665}
666
Erick Tryzelaarfc2280d2009-08-16 23:36:33 +0000667
Chris Lattner0256be92012-01-27 03:08:05 +0000668Constant *ConstantFP::get(Type *Ty, StringRef Str) {
Erick Tryzelaarfc2280d2009-08-16 23:36:33 +0000669 LLVMContext &Context = Ty->getContext();
670
671 APFloat FV(*TypeToFloatSemantics(Ty->getScalarType()), Str);
672 Constant *C = get(Context, FV);
673
674 // For vectors, broadcast the value.
Chris Lattner229907c2011-07-18 04:54:35 +0000675 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
Chris Lattnere9eed292012-01-25 05:19:54 +0000676 return ConstantVector::getSplat(VTy->getNumElements(), C);
Erick Tryzelaarfc2280d2009-08-16 23:36:33 +0000677
678 return C;
679}
680
Tom Stellard67246d12015-04-20 19:38:24 +0000681Constant *ConstantFP::getNaN(Type *Ty, bool Negative, unsigned Type) {
682 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
683 APFloat NaN = APFloat::getNaN(Semantics, Negative, Type);
684 Constant *C = get(Ty->getContext(), NaN);
685
686 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
687 return ConstantVector::getSplat(VTy->getNumElements(), C);
688
689 return C;
690}
691
Benjamin Kramer5d2ff222014-01-18 16:43:06 +0000692Constant *ConstantFP::getNegativeZero(Type *Ty) {
693 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
694 APFloat NegZero = APFloat::getZero(Semantics, /*Negative=*/true);
695 Constant *C = get(Ty->getContext(), NegZero);
Erick Tryzelaarfc2280d2009-08-16 23:36:33 +0000696
Benjamin Kramer5d2ff222014-01-18 16:43:06 +0000697 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
698 return ConstantVector::getSplat(VTy->getNumElements(), C);
699
700 return C;
Owen Anderson69c464d2009-07-27 20:59:43 +0000701}
702
703
Chris Lattnere9eed292012-01-25 05:19:54 +0000704Constant *ConstantFP::getZeroValueForNegation(Type *Ty) {
Benjamin Kramer5d2ff222014-01-18 16:43:06 +0000705 if (Ty->isFPOrFPVectorTy())
706 return getNegativeZero(Ty);
Owen Anderson69c464d2009-07-27 20:59:43 +0000707
Owen Anderson5a1acd92009-07-31 20:28:14 +0000708 return Constant::getNullValue(Ty);
Owen Anderson69c464d2009-07-27 20:59:43 +0000709}
710
711
712// ConstantFP accessors.
713ConstantFP* ConstantFP::get(LLVMContext &Context, const APFloat& V) {
Owen Anderson69c464d2009-07-27 20:59:43 +0000714 LLVMContextImpl* pImpl = Context.pImpl;
Galina Kistanovafc259902012-07-13 01:25:27 +0000715
Benjamin Kramer8e5dc532014-12-06 13:12:56 +0000716 ConstantFP *&Slot = pImpl->FPConstants[V];
Galina Kistanovafc259902012-07-13 01:25:27 +0000717
Owen Anderson69c464d2009-07-27 20:59:43 +0000718 if (!Slot) {
Chris Lattner229907c2011-07-18 04:54:35 +0000719 Type *Ty;
Dan Gohman518cda42011-12-17 00:04:22 +0000720 if (&V.getSemantics() == &APFloat::IEEEhalf)
721 Ty = Type::getHalfTy(Context);
722 else if (&V.getSemantics() == &APFloat::IEEEsingle)
Owen Anderson5dab84c2009-10-19 20:11:52 +0000723 Ty = Type::getFloatTy(Context);
724 else if (&V.getSemantics() == &APFloat::IEEEdouble)
725 Ty = Type::getDoubleTy(Context);
726 else if (&V.getSemantics() == &APFloat::x87DoubleExtended)
727 Ty = Type::getX86_FP80Ty(Context);
728 else if (&V.getSemantics() == &APFloat::IEEEquad)
729 Ty = Type::getFP128Ty(Context);
730 else {
731 assert(&V.getSemantics() == &APFloat::PPCDoubleDouble &&
732 "Unknown FP format");
733 Ty = Type::getPPC_FP128Ty(Context);
Owen Anderson69c464d2009-07-27 20:59:43 +0000734 }
Owen Anderson5dab84c2009-10-19 20:11:52 +0000735 Slot = new ConstantFP(Ty, V);
Owen Anderson69c464d2009-07-27 20:59:43 +0000736 }
Galina Kistanovafc259902012-07-13 01:25:27 +0000737
Owen Anderson69c464d2009-07-27 20:59:43 +0000738 return Slot;
739}
740
Benjamin Kramer5d2ff222014-01-18 16:43:06 +0000741Constant *ConstantFP::getInfinity(Type *Ty, bool Negative) {
742 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
743 Constant *C = get(Ty->getContext(), APFloat::getInf(Semantics, Negative));
744
745 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
746 return ConstantVector::getSplat(VTy->getNumElements(), C);
747
748 return C;
Dan Gohmanfeb50212009-09-25 23:00:48 +0000749}
750
Chris Lattner229907c2011-07-18 04:54:35 +0000751ConstantFP::ConstantFP(Type *Ty, const APFloat& V)
Craig Topperc6207612014-04-09 06:08:46 +0000752 : Constant(Ty, ConstantFPVal, nullptr, 0), Val(V) {
Chris Lattner98bd9392008-04-09 06:38:30 +0000753 assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
754 "FP type Mismatch");
Chris Lattner2f7c9632001-06-06 20:29:01 +0000755}
756
Chris Lattnerbe6610c2011-07-15 06:14:08 +0000757bool ConstantFP::isExactlyValue(const APFloat &V) const {
Dale Johannesend246b2c2007-08-30 00:23:21 +0000758 return Val.bitwiseIsEqual(V);
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000759}
760
Pete Cooper86dd4cf2015-06-23 21:55:11 +0000761/// Remove the constant from the constant table.
762void ConstantFP::destroyConstantImpl() {
763 llvm_unreachable("You can't ConstantInt->destroyConstantImpl()!");
764}
765
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000766//===----------------------------------------------------------------------===//
Chris Lattner030af792012-01-24 05:42:11 +0000767// ConstantAggregateZero Implementation
768//===----------------------------------------------------------------------===//
769
770/// getSequentialElement - If this CAZ has array or vector type, return a zero
771/// with the right element type.
Chris Lattner7e683d12012-01-25 06:16:32 +0000772Constant *ConstantAggregateZero::getSequentialElement() const {
Chris Lattner8326bd82012-01-26 00:42:34 +0000773 return Constant::getNullValue(getType()->getSequentialElementType());
Chris Lattner030af792012-01-24 05:42:11 +0000774}
775
776/// getStructElement - If this CAZ has struct type, return a zero with the
777/// right element type for the specified element.
Chris Lattner7e683d12012-01-25 06:16:32 +0000778Constant *ConstantAggregateZero::getStructElement(unsigned Elt) const {
Chris Lattner8326bd82012-01-26 00:42:34 +0000779 return Constant::getNullValue(getType()->getStructElementType(Elt));
Chris Lattner030af792012-01-24 05:42:11 +0000780}
781
782/// getElementValue - Return a zero of the right value for the specified GEP
783/// index if we can, otherwise return null (e.g. if C is a ConstantExpr).
Chris Lattner7e683d12012-01-25 06:16:32 +0000784Constant *ConstantAggregateZero::getElementValue(Constant *C) const {
Chris Lattner030af792012-01-24 05:42:11 +0000785 if (isa<SequentialType>(getType()))
786 return getSequentialElement();
787 return getStructElement(cast<ConstantInt>(C)->getZExtValue());
788}
789
Chris Lattnerf7eb5432012-01-24 07:54:10 +0000790/// getElementValue - Return a zero of the right value for the specified GEP
791/// index.
Chris Lattner7e683d12012-01-25 06:16:32 +0000792Constant *ConstantAggregateZero::getElementValue(unsigned Idx) const {
Chris Lattnerf7eb5432012-01-24 07:54:10 +0000793 if (isa<SequentialType>(getType()))
794 return getSequentialElement();
795 return getStructElement(Idx);
796}
797
David Majnemer9b529a72015-02-16 04:02:09 +0000798unsigned ConstantAggregateZero::getNumElements() const {
Craig Toppere3dcce92015-08-01 22:20:21 +0000799 Type *Ty = getType();
800 if (auto *AT = dyn_cast<ArrayType>(Ty))
David Majnemer9b529a72015-02-16 04:02:09 +0000801 return AT->getNumElements();
Craig Toppere3dcce92015-08-01 22:20:21 +0000802 if (auto *VT = dyn_cast<VectorType>(Ty))
David Majnemer9b529a72015-02-16 04:02:09 +0000803 return VT->getNumElements();
804 return Ty->getStructNumElements();
805}
Chris Lattnerf7eb5432012-01-24 07:54:10 +0000806
Chris Lattner030af792012-01-24 05:42:11 +0000807//===----------------------------------------------------------------------===//
808// UndefValue Implementation
809//===----------------------------------------------------------------------===//
810
811/// getSequentialElement - If this undef has array or vector type, return an
812/// undef with the right element type.
Chris Lattner7e683d12012-01-25 06:16:32 +0000813UndefValue *UndefValue::getSequentialElement() const {
Chris Lattner8326bd82012-01-26 00:42:34 +0000814 return UndefValue::get(getType()->getSequentialElementType());
Chris Lattner030af792012-01-24 05:42:11 +0000815}
816
817/// getStructElement - If this undef has struct type, return a zero with the
818/// right element type for the specified element.
Chris Lattner7e683d12012-01-25 06:16:32 +0000819UndefValue *UndefValue::getStructElement(unsigned Elt) const {
Chris Lattner8326bd82012-01-26 00:42:34 +0000820 return UndefValue::get(getType()->getStructElementType(Elt));
Chris Lattner030af792012-01-24 05:42:11 +0000821}
822
823/// getElementValue - Return an undef of the right value for the specified GEP
824/// index if we can, otherwise return null (e.g. if C is a ConstantExpr).
Chris Lattner7e683d12012-01-25 06:16:32 +0000825UndefValue *UndefValue::getElementValue(Constant *C) const {
Chris Lattner030af792012-01-24 05:42:11 +0000826 if (isa<SequentialType>(getType()))
827 return getSequentialElement();
828 return getStructElement(cast<ConstantInt>(C)->getZExtValue());
829}
830
Chris Lattnerf7eb5432012-01-24 07:54:10 +0000831/// getElementValue - Return an undef of the right value for the specified GEP
832/// index.
Chris Lattner7e683d12012-01-25 06:16:32 +0000833UndefValue *UndefValue::getElementValue(unsigned Idx) const {
Chris Lattnerf7eb5432012-01-24 07:54:10 +0000834 if (isa<SequentialType>(getType()))
835 return getSequentialElement();
836 return getStructElement(Idx);
837}
838
David Majnemer9b529a72015-02-16 04:02:09 +0000839unsigned UndefValue::getNumElements() const {
Craig Toppere3dcce92015-08-01 22:20:21 +0000840 Type *Ty = getType();
841 if (auto *AT = dyn_cast<ArrayType>(Ty))
David Majnemer9b529a72015-02-16 04:02:09 +0000842 return AT->getNumElements();
Craig Toppere3dcce92015-08-01 22:20:21 +0000843 if (auto *VT = dyn_cast<VectorType>(Ty))
David Majnemer9b529a72015-02-16 04:02:09 +0000844 return VT->getNumElements();
845 return Ty->getStructNumElements();
846}
Chris Lattner030af792012-01-24 05:42:11 +0000847
848//===----------------------------------------------------------------------===//
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000849// ConstantXXX Classes
850//===----------------------------------------------------------------------===//
851
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000852template <typename ItTy, typename EltTy>
853static bool rangeOnlyContains(ItTy Start, ItTy End, EltTy Elt) {
854 for (; Start != End; ++Start)
855 if (*Start != Elt)
856 return false;
857 return true;
858}
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000859
Justin Bogner909e1c02015-12-01 20:20:49 +0000860template <typename SequentialTy, typename ElementTy>
861static Constant *getIntSequenceIfElementsMatch(ArrayRef<Constant *> V) {
862 assert(!V.empty() && "Cannot get empty int sequence.");
863
864 SmallVector<ElementTy, 16> Elts;
865 for (Constant *C : V)
866 if (auto *CI = dyn_cast<ConstantInt>(C))
867 Elts.push_back(CI->getZExtValue());
868 else
869 return nullptr;
870 return SequentialTy::get(V[0]->getContext(), Elts);
871}
872
873template <typename SequentialTy, typename ElementTy>
874static Constant *getFPSequenceIfElementsMatch(ArrayRef<Constant *> V) {
875 assert(!V.empty() && "Cannot get empty FP sequence.");
876
877 SmallVector<ElementTy, 16> Elts;
878 for (Constant *C : V)
879 if (auto *CFP = dyn_cast<ConstantFP>(C))
880 Elts.push_back(CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
881 else
882 return nullptr;
883 return SequentialTy::getFP(V[0]->getContext(), Elts);
884}
885
886template <typename SequenceTy>
887static Constant *getSequenceIfElementsMatch(Constant *C,
888 ArrayRef<Constant *> V) {
889 // We speculatively build the elements here even if it turns out that there is
890 // a constantexpr or something else weird, since it is so uncommon for that to
891 // happen.
892 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
893 if (CI->getType()->isIntegerTy(8))
894 return getIntSequenceIfElementsMatch<SequenceTy, uint8_t>(V);
895 else if (CI->getType()->isIntegerTy(16))
896 return getIntSequenceIfElementsMatch<SequenceTy, uint16_t>(V);
897 else if (CI->getType()->isIntegerTy(32))
898 return getIntSequenceIfElementsMatch<SequenceTy, uint32_t>(V);
899 else if (CI->getType()->isIntegerTy(64))
900 return getIntSequenceIfElementsMatch<SequenceTy, uint64_t>(V);
901 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
Justin Bogner0ebc8602015-12-08 03:01:16 +0000902 if (CFP->getType()->isHalfTy())
903 return getFPSequenceIfElementsMatch<SequenceTy, uint16_t>(V);
904 else if (CFP->getType()->isFloatTy())
Justin Bogner909e1c02015-12-01 20:20:49 +0000905 return getFPSequenceIfElementsMatch<SequenceTy, uint32_t>(V);
906 else if (CFP->getType()->isDoubleTy())
907 return getFPSequenceIfElementsMatch<SequenceTy, uint64_t>(V);
908 }
909
910 return nullptr;
911}
912
Jay Foad89d9b812011-07-25 10:14:44 +0000913ConstantArray::ConstantArray(ArrayType *T, ArrayRef<Constant *> V)
Gabor Greiff6caff662008-05-10 08:32:32 +0000914 : Constant(T, ConstantArrayVal,
915 OperandTraits<ConstantArray>::op_end(this) - V.size(),
916 V.size()) {
Alkis Evlogimenos0507ffe2004-09-15 02:32:15 +0000917 assert(V.size() == T->getNumElements() &&
918 "Invalid initializer vector for constant array");
Jay Foad89d9b812011-07-25 10:14:44 +0000919 for (unsigned i = 0, e = V.size(); i != e; ++i)
920 assert(V[i]->getType() == T->getElementType() &&
Alkis Evlogimenoscb031d92004-09-10 04:16:59 +0000921 "Initializer for array element doesn't match array element type!");
Jay Foad89d9b812011-07-25 10:14:44 +0000922 std::copy(V.begin(), V.end(), op_begin());
Chris Lattner2f7c9632001-06-06 20:29:01 +0000923}
924
Chris Lattner229907c2011-07-18 04:54:35 +0000925Constant *ConstantArray::get(ArrayType *Ty, ArrayRef<Constant*> V) {
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +0000926 if (Constant *C = getImpl(Ty, V))
927 return C;
928 return Ty->getContext().pImpl->ArrayConstants.getOrCreate(Ty, V);
929}
Justin Bogner909e1c02015-12-01 20:20:49 +0000930
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +0000931Constant *ConstantArray::getImpl(ArrayType *Ty, ArrayRef<Constant*> V) {
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000932 // Empty arrays are canonicalized to ConstantAggregateZero.
933 if (V.empty())
934 return ConstantAggregateZero::get(Ty);
935
Jeffrey Yasskin8ce67f82009-09-30 21:08:08 +0000936 for (unsigned i = 0, e = V.size(); i != e; ++i) {
937 assert(V[i]->getType() == Ty->getElementType() &&
938 "Wrong type in array element initializer");
939 }
Galina Kistanovafc259902012-07-13 01:25:27 +0000940
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000941 // If this is an all-zero array, return a ConstantAggregateZero object. If
942 // all undef, return an UndefValue, if "all simple", then return a
943 // ConstantDataArray.
944 Constant *C = V[0];
945 if (isa<UndefValue>(C) && rangeOnlyContains(V.begin(), V.end(), C))
946 return UndefValue::get(Ty);
Chris Lattnerf14a67f2012-01-26 02:31:22 +0000947
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000948 if (C->isNullValue() && rangeOnlyContains(V.begin(), V.end(), C))
949 return ConstantAggregateZero::get(Ty);
950
951 // Check to see if all of the elements are ConstantFP or ConstantInt and if
952 // the element type is compatible with ConstantDataVector. If so, use it.
Justin Bogner909e1c02015-12-01 20:20:49 +0000953 if (ConstantDataSequential::isElementTypeCompatible(C->getType()))
954 return getSequenceIfElementsMatch<ConstantDataArray>(C, V);
Chris Lattnerf14a67f2012-01-26 02:31:22 +0000955
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000956 // Otherwise, we really do want to create a ConstantArray.
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +0000957 return nullptr;
Owen Andersonc2c79322009-07-28 18:32:17 +0000958}
959
Chris Lattnercc19efa2011-06-20 04:01:31 +0000960/// getTypeForElements - Return an anonymous struct type to use for a constant
961/// with the specified set of elements. The list must not be empty.
962StructType *ConstantStruct::getTypeForElements(LLVMContext &Context,
963 ArrayRef<Constant*> V,
964 bool Packed) {
Bill Wendling3ae7dd32012-02-07 01:27:51 +0000965 unsigned VecSize = V.size();
966 SmallVector<Type*, 16> EltTypes(VecSize);
967 for (unsigned i = 0; i != VecSize; ++i)
968 EltTypes[i] = V[i]->getType();
Galina Kistanovafc259902012-07-13 01:25:27 +0000969
Chris Lattnercc19efa2011-06-20 04:01:31 +0000970 return StructType::get(Context, EltTypes, Packed);
971}
972
973
974StructType *ConstantStruct::getTypeForElements(ArrayRef<Constant*> V,
975 bool Packed) {
976 assert(!V.empty() &&
977 "ConstantStruct::getTypeForElements cannot be called on empty list");
978 return getTypeForElements(V[0]->getContext(), V, Packed);
979}
980
981
Jay Foad89d9b812011-07-25 10:14:44 +0000982ConstantStruct::ConstantStruct(StructType *T, ArrayRef<Constant *> V)
Gabor Greiff6caff662008-05-10 08:32:32 +0000983 : Constant(T, ConstantStructVal,
984 OperandTraits<ConstantStruct>::op_end(this) - V.size(),
985 V.size()) {
Chris Lattnerc3e74cd2011-08-07 04:18:48 +0000986 assert(V.size() == T->getNumElements() &&
Vikram S. Adve4e537b22002-07-14 23:13:17 +0000987 "Invalid initializer vector for constant structure");
Jay Foad89d9b812011-07-25 10:14:44 +0000988 for (unsigned i = 0, e = V.size(); i != e; ++i)
989 assert((T->isOpaque() || V[i]->getType() == T->getElementType(i)) &&
Chris Lattner93c8f142003-06-02 17:42:47 +0000990 "Initializer for struct element doesn't match struct element type!");
Jay Foad89d9b812011-07-25 10:14:44 +0000991 std::copy(V.begin(), V.end(), op_begin());
Chris Lattner2f7c9632001-06-06 20:29:01 +0000992}
993
Owen Anderson45308b52009-07-27 22:29:26 +0000994// ConstantStruct accessors.
Chris Lattner229907c2011-07-18 04:54:35 +0000995Constant *ConstantStruct::get(StructType *ST, ArrayRef<Constant*> V) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000996 assert((ST->isOpaque() || ST->getNumElements() == V.size()) &&
997 "Incorrect # elements specified to ConstantStruct::get");
Chris Lattnerf14a67f2012-01-26 02:31:22 +0000998
999 // Create a ConstantAggregateZero value if all elements are zeros.
1000 bool isZero = true;
1001 bool isUndef = false;
1002
1003 if (!V.empty()) {
1004 isUndef = isa<UndefValue>(V[0]);
1005 isZero = V[0]->isNullValue();
1006 if (isUndef || isZero) {
1007 for (unsigned i = 0, e = V.size(); i != e; ++i) {
1008 if (!V[i]->isNullValue())
1009 isZero = false;
1010 if (!isa<UndefValue>(V[i]))
1011 isUndef = false;
1012 }
1013 }
Galina Kistanovafc259902012-07-13 01:25:27 +00001014 }
Chris Lattnerf14a67f2012-01-26 02:31:22 +00001015 if (isZero)
1016 return ConstantAggregateZero::get(ST);
1017 if (isUndef)
1018 return UndefValue::get(ST);
Galina Kistanovafc259902012-07-13 01:25:27 +00001019
Chris Lattnerf14a67f2012-01-26 02:31:22 +00001020 return ST->getContext().pImpl->StructConstants.getOrCreate(ST, V);
Owen Anderson45308b52009-07-27 22:29:26 +00001021}
1022
Chris Lattnerc3e74cd2011-08-07 04:18:48 +00001023Constant *ConstantStruct::get(StructType *T, ...) {
Talin3a0a30d2011-02-28 23:53:27 +00001024 va_list ap;
Chris Lattnercc19efa2011-06-20 04:01:31 +00001025 SmallVector<Constant*, 8> Values;
1026 va_start(ap, T);
1027 while (Constant *Val = va_arg(ap, llvm::Constant*))
Talin3a0a30d2011-02-28 23:53:27 +00001028 Values.push_back(Val);
Talinde422be2011-03-01 18:00:49 +00001029 va_end(ap);
Chris Lattnercc19efa2011-06-20 04:01:31 +00001030 return get(T, Values);
Talin3a0a30d2011-02-28 23:53:27 +00001031}
1032
Jay Foad89d9b812011-07-25 10:14:44 +00001033ConstantVector::ConstantVector(VectorType *T, ArrayRef<Constant *> V)
Gabor Greiff6caff662008-05-10 08:32:32 +00001034 : Constant(T, ConstantVectorVal,
1035 OperandTraits<ConstantVector>::op_end(this) - V.size(),
1036 V.size()) {
Jay Foad89d9b812011-07-25 10:14:44 +00001037 for (size_t i = 0, e = V.size(); i != e; i++)
1038 assert(V[i]->getType() == T->getElementType() &&
Dan Gohman30978072007-05-24 14:36:04 +00001039 "Initializer for vector element doesn't match vector element type!");
Jay Foad89d9b812011-07-25 10:14:44 +00001040 std::copy(V.begin(), V.end(), op_begin());
Brian Gaeke02209042004-08-20 06:00:58 +00001041}
1042
Owen Anderson4aa32952009-07-28 21:19:26 +00001043// ConstantVector accessors.
Jay Foadb8a8bed32011-06-22 09:10:19 +00001044Constant *ConstantVector::get(ArrayRef<Constant*> V) {
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00001045 if (Constant *C = getImpl(V))
1046 return C;
1047 VectorType *Ty = VectorType::get(V.front()->getType(), V.size());
1048 return Ty->getContext().pImpl->VectorConstants.getOrCreate(Ty, V);
1049}
Justin Bogner909e1c02015-12-01 20:20:49 +00001050
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00001051Constant *ConstantVector::getImpl(ArrayRef<Constant*> V) {
Jay Foad9f32cfd2011-01-27 14:44:55 +00001052 assert(!V.empty() && "Vectors can't be empty");
Chris Lattner229907c2011-07-18 04:54:35 +00001053 VectorType *T = VectorType::get(V.front()->getType(), V.size());
Jay Foad9f32cfd2011-01-27 14:44:55 +00001054
Chris Lattner69229312011-02-15 00:14:00 +00001055 // If this is an all-undef or all-zero vector, return a
Owen Anderson4aa32952009-07-28 21:19:26 +00001056 // ConstantAggregateZero or UndefValue.
1057 Constant *C = V[0];
1058 bool isZero = C->isNullValue();
1059 bool isUndef = isa<UndefValue>(C);
1060
1061 if (isZero || isUndef) {
1062 for (unsigned i = 1, e = V.size(); i != e; ++i)
1063 if (V[i] != C) {
1064 isZero = isUndef = false;
1065 break;
1066 }
1067 }
Galina Kistanovafc259902012-07-13 01:25:27 +00001068
Owen Anderson4aa32952009-07-28 21:19:26 +00001069 if (isZero)
Owen Andersonb292b8c2009-07-30 23:03:37 +00001070 return ConstantAggregateZero::get(T);
Owen Anderson4aa32952009-07-28 21:19:26 +00001071 if (isUndef)
Owen Andersonb292b8c2009-07-30 23:03:37 +00001072 return UndefValue::get(T);
Galina Kistanovafc259902012-07-13 01:25:27 +00001073
Chris Lattner978fe0c2012-01-30 06:21:21 +00001074 // Check to see if all of the elements are ConstantFP or ConstantInt and if
1075 // the element type is compatible with ConstantDataVector. If so, use it.
Justin Bogner909e1c02015-12-01 20:20:49 +00001076 if (ConstantDataSequential::isElementTypeCompatible(C->getType()))
1077 return getSequenceIfElementsMatch<ConstantDataVector>(C, V);
Galina Kistanovafc259902012-07-13 01:25:27 +00001078
Chris Lattner978fe0c2012-01-30 06:21:21 +00001079 // Otherwise, the element type isn't compatible with ConstantDataVector, or
1080 // the operand list constants a ConstantExpr or something else strange.
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00001081 return nullptr;
Owen Anderson4aa32952009-07-28 21:19:26 +00001082}
1083
Chris Lattnere9eed292012-01-25 05:19:54 +00001084Constant *ConstantVector::getSplat(unsigned NumElts, Constant *V) {
Chris Lattner978fe0c2012-01-30 06:21:21 +00001085 // If this splat is compatible with ConstantDataVector, use it instead of
1086 // ConstantVector.
1087 if ((isa<ConstantFP>(V) || isa<ConstantInt>(V)) &&
1088 ConstantDataSequential::isElementTypeCompatible(V->getType()))
1089 return ConstantDataVector::getSplat(NumElts, V);
Galina Kistanovafc259902012-07-13 01:25:27 +00001090
Chris Lattnere9eed292012-01-25 05:19:54 +00001091 SmallVector<Constant*, 32> Elts(NumElts, V);
1092 return get(Elts);
1093}
1094
David Majnemerf0f224d2015-11-11 21:57:16 +00001095ConstantTokenNone *ConstantTokenNone::get(LLVMContext &Context) {
1096 LLVMContextImpl *pImpl = Context.pImpl;
1097 if (!pImpl->TheNoneToken)
David Majnemer2dd41c52015-11-16 20:55:57 +00001098 pImpl->TheNoneToken.reset(new ConstantTokenNone(Context));
1099 return pImpl->TheNoneToken.get();
David Majnemerf0f224d2015-11-11 21:57:16 +00001100}
1101
1102/// Remove the constant from the constant table.
1103void ConstantTokenNone::destroyConstantImpl() {
1104 llvm_unreachable("You can't ConstantTokenNone->destroyConstantImpl()!");
1105}
Chris Lattnere9eed292012-01-25 05:19:54 +00001106
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001107// Utility function for determining if a ConstantExpr is a CastOp or not. This
1108// can't be inline because we don't want to #include Instruction.h into
1109// Constant.h
1110bool ConstantExpr::isCast() const {
1111 return Instruction::isCast(getOpcode());
1112}
1113
Reid Spenceree3c9912006-12-04 05:19:50 +00001114bool ConstantExpr::isCompare() const {
Nick Lewyckya21d3da2009-07-08 03:04:38 +00001115 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
Reid Spenceree3c9912006-12-04 05:19:50 +00001116}
1117
Dan Gohman7190d482009-09-10 23:37:55 +00001118bool ConstantExpr::isGEPWithNoNotionalOverIndexing() const {
1119 if (getOpcode() != Instruction::GetElementPtr) return false;
1120
1121 gep_type_iterator GEPI = gep_type_begin(this), E = gep_type_end(this);
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001122 User::const_op_iterator OI = std::next(this->op_begin());
Dan Gohman7190d482009-09-10 23:37:55 +00001123
1124 // Skip the first index, as it has no static limit.
1125 ++GEPI;
1126 ++OI;
1127
1128 // The remaining indices must be compile-time known integers within the
1129 // bounds of the corresponding notional static array types.
1130 for (; GEPI != E; ++GEPI, ++OI) {
1131 ConstantInt *CI = dyn_cast<ConstantInt>(*OI);
1132 if (!CI) return false;
Chris Lattner229907c2011-07-18 04:54:35 +00001133 if (ArrayType *ATy = dyn_cast<ArrayType>(*GEPI))
Dan Gohman7190d482009-09-10 23:37:55 +00001134 if (CI->getValue().getActiveBits() > 64 ||
1135 CI->getZExtValue() >= ATy->getNumElements())
1136 return false;
1137 }
1138
1139 // All the indices checked out.
1140 return true;
1141}
1142
Dan Gohman1ecaf452008-05-31 00:58:22 +00001143bool ConstantExpr::hasIndices() const {
1144 return getOpcode() == Instruction::ExtractValue ||
1145 getOpcode() == Instruction::InsertValue;
1146}
1147
Jay Foad0091fe82011-04-13 15:22:40 +00001148ArrayRef<unsigned> ConstantExpr::getIndices() const {
Dan Gohman1ecaf452008-05-31 00:58:22 +00001149 if (const ExtractValueConstantExpr *EVCE =
1150 dyn_cast<ExtractValueConstantExpr>(this))
1151 return EVCE->Indices;
Dan Gohmana469bdb2008-06-23 16:39:44 +00001152
1153 return cast<InsertValueConstantExpr>(this)->Indices;
Dan Gohman1ecaf452008-05-31 00:58:22 +00001154}
1155
Reid Spencer10fbf0e2006-12-03 05:48:19 +00001156unsigned ConstantExpr::getPredicate() const {
Chris Lattnerd04e32d2011-07-17 06:01:30 +00001157 assert(isCompare());
Chris Lattneref650092007-10-18 16:26:24 +00001158 return ((const CompareConstantExpr*)this)->predicate;
Reid Spencer10fbf0e2006-12-03 05:48:19 +00001159}
Chris Lattner60e0dd72001-10-03 06:12:09 +00001160
Chris Lattner7c1018a2006-07-14 19:37:40 +00001161/// getWithOperandReplaced - Return a constant expression identical to this
1162/// one, but with the specified operand set to the specified value.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001163Constant *
1164ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
Chris Lattner7c1018a2006-07-14 19:37:40 +00001165 assert(Op->getType() == getOperand(OpNo)->getType() &&
1166 "Replacing operand with value of different type!");
Chris Lattner227816342006-07-14 22:20:01 +00001167 if (getOperand(OpNo) == Op)
1168 return const_cast<ConstantExpr*>(this);
Chris Lattner37e38352012-01-26 20:37:11 +00001169
1170 SmallVector<Constant*, 8> NewOps;
1171 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1172 NewOps.push_back(i == OpNo ? Op : getOperand(i));
Galina Kistanovafc259902012-07-13 01:25:27 +00001173
Chris Lattner37e38352012-01-26 20:37:11 +00001174 return getWithOperands(NewOps);
Chris Lattner227816342006-07-14 22:20:01 +00001175}
1176
1177/// getWithOperands - This returns the current constant expression with the
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001178/// operands replaced with the specified values. The specified array must
1179/// have the same number of operands as our current one.
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001180Constant *ConstantExpr::getWithOperands(ArrayRef<Constant *> Ops, Type *Ty,
David Blaikie88208842015-08-21 20:16:51 +00001181 bool OnlyIfReduced, Type *SrcTy) const {
Jay Foad5c984e562011-04-13 13:46:01 +00001182 assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
Galina Kistanovafc259902012-07-13 01:25:27 +00001183
Benjamin Kramer8008e9f2015-03-02 11:57:04 +00001184 // If no operands changed return self.
1185 if (Ty == getType() && std::equal(Ops.begin(), Ops.end(), op_begin()))
Chris Lattner227816342006-07-14 22:20:01 +00001186 return const_cast<ConstantExpr*>(this);
1187
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001188 Type *OnlyIfReducedTy = OnlyIfReduced ? Ty : nullptr;
Chris Lattner227816342006-07-14 22:20:01 +00001189 switch (getOpcode()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001190 case Instruction::Trunc:
1191 case Instruction::ZExt:
1192 case Instruction::SExt:
1193 case Instruction::FPTrunc:
1194 case Instruction::FPExt:
1195 case Instruction::UIToFP:
1196 case Instruction::SIToFP:
1197 case Instruction::FPToUI:
1198 case Instruction::FPToSI:
1199 case Instruction::PtrToInt:
1200 case Instruction::IntToPtr:
1201 case Instruction::BitCast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00001202 case Instruction::AddrSpaceCast:
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001203 return ConstantExpr::getCast(getOpcode(), Ops[0], Ty, OnlyIfReduced);
Chris Lattner227816342006-07-14 22:20:01 +00001204 case Instruction::Select:
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001205 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2], OnlyIfReducedTy);
Chris Lattner227816342006-07-14 22:20:01 +00001206 case Instruction::InsertElement:
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001207 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2],
1208 OnlyIfReducedTy);
Chris Lattner227816342006-07-14 22:20:01 +00001209 case Instruction::ExtractElement:
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001210 return ConstantExpr::getExtractElement(Ops[0], Ops[1], OnlyIfReducedTy);
Chris Lattner37e38352012-01-26 20:37:11 +00001211 case Instruction::InsertValue:
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001212 return ConstantExpr::getInsertValue(Ops[0], Ops[1], getIndices(),
1213 OnlyIfReducedTy);
Chris Lattner37e38352012-01-26 20:37:11 +00001214 case Instruction::ExtractValue:
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001215 return ConstantExpr::getExtractValue(Ops[0], getIndices(), OnlyIfReducedTy);
Chris Lattner227816342006-07-14 22:20:01 +00001216 case Instruction::ShuffleVector:
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001217 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2],
1218 OnlyIfReducedTy);
David Blaikie88208842015-08-21 20:16:51 +00001219 case Instruction::GetElementPtr: {
1220 auto *GEPO = cast<GEPOperator>(this);
1221 assert(SrcTy || (Ops[0]->getType() == getOperand(0)->getType()));
1222 return ConstantExpr::getGetElementPtr(
1223 SrcTy ? SrcTy : GEPO->getSourceElementType(), Ops[0], Ops.slice(1),
1224 GEPO->isInBounds(), OnlyIfReducedTy);
1225 }
Reid Spencer266e42b2006-12-23 06:05:41 +00001226 case Instruction::ICmp:
1227 case Instruction::FCmp:
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001228 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1],
1229 OnlyIfReducedTy);
Chris Lattner227816342006-07-14 22:20:01 +00001230 default:
1231 assert(getNumOperands() == 2 && "Must be binary operator?");
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001232 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1], SubclassOptionalData,
1233 OnlyIfReducedTy);
Chris Lattner7c1018a2006-07-14 19:37:40 +00001234 }
1235}
1236
Chris Lattner2f7c9632001-06-06 20:29:01 +00001237
1238//===----------------------------------------------------------------------===//
Chris Lattner2f7c9632001-06-06 20:29:01 +00001239// isValueValidForType implementations
1240
Chris Lattner229907c2011-07-18 04:54:35 +00001241bool ConstantInt::isValueValidForType(Type *Ty, uint64_t Val) {
Chris Lattner8326bd82012-01-26 00:42:34 +00001242 unsigned NumBits = Ty->getIntegerBitWidth(); // assert okay
1243 if (Ty->isIntegerTy(1))
Reid Spencer7a9c62b2007-01-12 07:05:14 +00001244 return Val == 0 || Val == 1;
Reid Spencerd7a00d72007-02-05 23:47:56 +00001245 if (NumBits >= 64)
Reid Spencer7a9c62b2007-01-12 07:05:14 +00001246 return true; // always true, has to fit in largest type
1247 uint64_t Max = (1ll << NumBits) - 1;
1248 return Val <= Max;
Reid Spencere7334722006-12-19 01:28:19 +00001249}
1250
Chris Lattner229907c2011-07-18 04:54:35 +00001251bool ConstantInt::isValueValidForType(Type *Ty, int64_t Val) {
Chris Lattner8326bd82012-01-26 00:42:34 +00001252 unsigned NumBits = Ty->getIntegerBitWidth();
1253 if (Ty->isIntegerTy(1))
Reid Spencera94d3942007-01-19 21:13:56 +00001254 return Val == 0 || Val == 1 || Val == -1;
Reid Spencerd7a00d72007-02-05 23:47:56 +00001255 if (NumBits >= 64)
Reid Spencer7a9c62b2007-01-12 07:05:14 +00001256 return true; // always true, has to fit in largest type
1257 int64_t Min = -(1ll << (NumBits-1));
1258 int64_t Max = (1ll << (NumBits-1)) - 1;
1259 return (Val >= Min && Val <= Max);
Chris Lattner2f7c9632001-06-06 20:29:01 +00001260}
1261
Chris Lattner229907c2011-07-18 04:54:35 +00001262bool ConstantFP::isValueValidForType(Type *Ty, const APFloat& Val) {
Dale Johannesend246b2c2007-08-30 00:23:21 +00001263 // convert modifies in place, so make a copy.
1264 APFloat Val2 = APFloat(Val);
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001265 bool losesInfo;
Chris Lattner6b727592004-06-17 18:19:28 +00001266 switch (Ty->getTypeID()) {
Chris Lattner2f7c9632001-06-06 20:29:01 +00001267 default:
1268 return false; // These can't be represented as floating point!
1269
Dale Johannesend246b2c2007-08-30 00:23:21 +00001270 // FIXME rounding mode needs to be more flexible
Dan Gohman518cda42011-12-17 00:04:22 +00001271 case Type::HalfTyID: {
1272 if (&Val2.getSemantics() == &APFloat::IEEEhalf)
1273 return true;
1274 Val2.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven, &losesInfo);
1275 return !losesInfo;
1276 }
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001277 case Type::FloatTyID: {
1278 if (&Val2.getSemantics() == &APFloat::IEEEsingle)
1279 return true;
1280 Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &losesInfo);
1281 return !losesInfo;
1282 }
1283 case Type::DoubleTyID: {
Dan Gohman518cda42011-12-17 00:04:22 +00001284 if (&Val2.getSemantics() == &APFloat::IEEEhalf ||
1285 &Val2.getSemantics() == &APFloat::IEEEsingle ||
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001286 &Val2.getSemantics() == &APFloat::IEEEdouble)
1287 return true;
1288 Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &losesInfo);
1289 return !losesInfo;
1290 }
Dale Johannesenbdad8092007-08-09 22:51:36 +00001291 case Type::X86_FP80TyID:
Dan Gohman518cda42011-12-17 00:04:22 +00001292 return &Val2.getSemantics() == &APFloat::IEEEhalf ||
1293 &Val2.getSemantics() == &APFloat::IEEEsingle ||
Dale Johannesen028084e2007-09-12 03:30:33 +00001294 &Val2.getSemantics() == &APFloat::IEEEdouble ||
1295 &Val2.getSemantics() == &APFloat::x87DoubleExtended;
Dale Johannesenbdad8092007-08-09 22:51:36 +00001296 case Type::FP128TyID:
Dan Gohman518cda42011-12-17 00:04:22 +00001297 return &Val2.getSemantics() == &APFloat::IEEEhalf ||
1298 &Val2.getSemantics() == &APFloat::IEEEsingle ||
Dale Johannesen028084e2007-09-12 03:30:33 +00001299 &Val2.getSemantics() == &APFloat::IEEEdouble ||
1300 &Val2.getSemantics() == &APFloat::IEEEquad;
Dale Johannesen007aa372007-10-11 18:07:22 +00001301 case Type::PPC_FP128TyID:
Dan Gohman518cda42011-12-17 00:04:22 +00001302 return &Val2.getSemantics() == &APFloat::IEEEhalf ||
1303 &Val2.getSemantics() == &APFloat::IEEEsingle ||
Dale Johannesen007aa372007-10-11 18:07:22 +00001304 &Val2.getSemantics() == &APFloat::IEEEdouble ||
1305 &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
Chris Lattner2f7c9632001-06-06 20:29:01 +00001306 }
Chris Lattneraa2372562006-05-24 17:04:05 +00001307}
Chris Lattner9655e542001-07-20 19:16:02 +00001308
Chris Lattner030af792012-01-24 05:42:11 +00001309
Chris Lattner49d855c2001-09-07 16:46:31 +00001310//===----------------------------------------------------------------------===//
Chris Lattner49d855c2001-09-07 16:46:31 +00001311// Factory Function Implementation
1312
Chris Lattnerc7f9fd42012-01-23 15:20:12 +00001313ConstantAggregateZero *ConstantAggregateZero::get(Type *Ty) {
Chris Lattner13ee7952010-08-28 04:09:24 +00001314 assert((Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()) &&
Owen Andersonb292b8c2009-07-30 23:03:37 +00001315 "Cannot create an aggregate zero of non-aggregate type!");
David Blaikiecb2818f2014-11-25 02:26:22 +00001316
1317 ConstantAggregateZero *&Entry = Ty->getContext().pImpl->CAZConstants[Ty];
David Blaikie899b85a2014-11-25 02:13:54 +00001318 if (!Entry)
David Blaikiecb2818f2014-11-25 02:26:22 +00001319 Entry = new ConstantAggregateZero(Ty);
David Blaikie899b85a2014-11-25 02:13:54 +00001320
David Blaikiecb2818f2014-11-25 02:26:22 +00001321 return Entry;
Owen Andersonb292b8c2009-07-30 23:03:37 +00001322}
1323
Chris Lattner030af792012-01-24 05:42:11 +00001324/// destroyConstant - Remove the constant from the constant table.
Dan Gohman92b551b2009-03-03 02:55:14 +00001325///
Pete Cooper86dd4cf2015-06-23 21:55:11 +00001326void ConstantAggregateZero::destroyConstantImpl() {
Chris Lattnerc7f9fd42012-01-23 15:20:12 +00001327 getContext().pImpl->CAZConstants.erase(getType());
Chris Lattner9fba3da2004-02-15 05:53:04 +00001328}
1329
Dan Gohman92b551b2009-03-03 02:55:14 +00001330/// destroyConstant - Remove the constant from the constant table...
1331///
Pete Cooper86dd4cf2015-06-23 21:55:11 +00001332void ConstantArray::destroyConstantImpl() {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001333 getType()->getContext().pImpl->ArrayConstants.remove(this);
Chris Lattner98fa07b2003-05-23 20:03:32 +00001334}
1335
Chris Lattner81fabb02002-08-26 17:53:56 +00001336
Chris Lattner3462ae32001-12-03 22:26:30 +00001337//---- ConstantStruct::get() implementation...
Chris Lattner49d855c2001-09-07 16:46:31 +00001338//
Chris Lattnerb50d1352003-10-05 00:17:43 +00001339
Chris Lattnerd7a73302001-10-13 06:57:33 +00001340// destroyConstant - Remove the constant from the constant table...
Chris Lattner883ad0b2001-10-03 15:39:36 +00001341//
Pete Cooper86dd4cf2015-06-23 21:55:11 +00001342void ConstantStruct::destroyConstantImpl() {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001343 getType()->getContext().pImpl->StructConstants.remove(this);
Chris Lattnerd7a73302001-10-13 06:57:33 +00001344}
Chris Lattner883ad0b2001-10-03 15:39:36 +00001345
Brian Gaeke02209042004-08-20 06:00:58 +00001346// destroyConstant - Remove the constant from the constant table...
1347//
Pete Cooper86dd4cf2015-06-23 21:55:11 +00001348void ConstantVector::destroyConstantImpl() {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001349 getType()->getContext().pImpl->VectorConstants.remove(this);
Brian Gaeke02209042004-08-20 06:00:58 +00001350}
1351
Duncan Sandse6beec62012-11-13 12:59:33 +00001352/// getSplatValue - If this is a splat vector constant, meaning that all of
1353/// the elements have the same value, return that value. Otherwise return 0.
1354Constant *Constant::getSplatValue() const {
1355 assert(this->getType()->isVectorTy() && "Only valid for vectors!");
1356 if (isa<ConstantAggregateZero>(this))
1357 return getNullValue(this->getType()->getVectorElementType());
1358 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
1359 return CV->getSplatValue();
1360 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
1361 return CV->getSplatValue();
Craig Topperc6207612014-04-09 06:08:46 +00001362 return nullptr;
Duncan Sandse6beec62012-11-13 12:59:33 +00001363}
1364
Dan Gohman07159202007-10-17 17:51:30 +00001365/// getSplatValue - If this is a splat constant, where all of the
1366/// elements have the same value, return that value. Otherwise return null.
Duncan Sandscf0ff032011-02-01 08:39:12 +00001367Constant *ConstantVector::getSplatValue() const {
Dan Gohman07159202007-10-17 17:51:30 +00001368 // Check out first element.
1369 Constant *Elt = getOperand(0);
1370 // Then make sure all remaining elements point to the same value.
1371 for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
Chris Lattnerd04e32d2011-07-17 06:01:30 +00001372 if (getOperand(I) != Elt)
Craig Topperc6207612014-04-09 06:08:46 +00001373 return nullptr;
Dan Gohman07159202007-10-17 17:51:30 +00001374 return Elt;
1375}
1376
Duncan Sandse6beec62012-11-13 12:59:33 +00001377/// If C is a constant integer then return its value, otherwise C must be a
1378/// vector of constant integers, all equal, and the common value is returned.
1379const APInt &Constant::getUniqueInteger() const {
1380 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
1381 return CI->getValue();
1382 assert(this->getSplatValue() && "Doesn't contain a unique integer!");
1383 const Constant *C = this->getAggregateElement(0U);
1384 assert(C && isa<ConstantInt>(C) && "Not a vector of numbers!");
1385 return cast<ConstantInt>(C)->getValue();
1386}
1387
Chris Lattner31b132c2009-10-28 00:01:44 +00001388//---- ConstantPointerNull::get() implementation.
Chris Lattnerd7a73302001-10-13 06:57:33 +00001389//
Chris Lattner98fa07b2003-05-23 20:03:32 +00001390
Chris Lattner229907c2011-07-18 04:54:35 +00001391ConstantPointerNull *ConstantPointerNull::get(PointerType *Ty) {
Chris Lattnerc7f9fd42012-01-23 15:20:12 +00001392 ConstantPointerNull *&Entry = Ty->getContext().pImpl->CPNConstants[Ty];
Craig Topperc6207612014-04-09 06:08:46 +00001393 if (!Entry)
Chris Lattnerc7f9fd42012-01-23 15:20:12 +00001394 Entry = new ConstantPointerNull(Ty);
Galina Kistanovafc259902012-07-13 01:25:27 +00001395
Chris Lattnerc7f9fd42012-01-23 15:20:12 +00001396 return Entry;
Chris Lattner883ad0b2001-10-03 15:39:36 +00001397}
1398
Chris Lattner0c6e0b92002-08-18 00:40:04 +00001399// destroyConstant - Remove the constant from the constant table...
1400//
Pete Cooper86dd4cf2015-06-23 21:55:11 +00001401void ConstantPointerNull::destroyConstantImpl() {
Chris Lattnerc7f9fd42012-01-23 15:20:12 +00001402 getContext().pImpl->CPNConstants.erase(getType());
Chris Lattner0c6e0b92002-08-18 00:40:04 +00001403}
1404
1405
Chris Lattner31b132c2009-10-28 00:01:44 +00001406//---- UndefValue::get() implementation.
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001407//
1408
Chris Lattner229907c2011-07-18 04:54:35 +00001409UndefValue *UndefValue::get(Type *Ty) {
Chris Lattnerc7f9fd42012-01-23 15:20:12 +00001410 UndefValue *&Entry = Ty->getContext().pImpl->UVConstants[Ty];
Craig Topperc6207612014-04-09 06:08:46 +00001411 if (!Entry)
Chris Lattnerc7f9fd42012-01-23 15:20:12 +00001412 Entry = new UndefValue(Ty);
Galina Kistanovafc259902012-07-13 01:25:27 +00001413
Chris Lattnerc7f9fd42012-01-23 15:20:12 +00001414 return Entry;
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001415}
1416
1417// destroyConstant - Remove the constant from the constant table.
1418//
Pete Cooper86dd4cf2015-06-23 21:55:11 +00001419void UndefValue::destroyConstantImpl() {
Chris Lattnerc7f9fd42012-01-23 15:20:12 +00001420 // Free the constant and any dangling references to it.
1421 getContext().pImpl->UVConstants.erase(getType());
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001422}
1423
Chris Lattner31b132c2009-10-28 00:01:44 +00001424//---- BlockAddress::get() implementation.
1425//
1426
1427BlockAddress *BlockAddress::get(BasicBlock *BB) {
Craig Topper2617dcc2014-04-15 06:32:26 +00001428 assert(BB->getParent() && "Block must have a parent");
Chris Lattner31b132c2009-10-28 00:01:44 +00001429 return get(BB->getParent(), BB);
1430}
1431
1432BlockAddress *BlockAddress::get(Function *F, BasicBlock *BB) {
1433 BlockAddress *&BA =
1434 F->getContext().pImpl->BlockAddresses[std::make_pair(F, BB)];
Craig Topperc6207612014-04-09 06:08:46 +00001435 if (!BA)
Chris Lattner31b132c2009-10-28 00:01:44 +00001436 BA = new BlockAddress(F, BB);
Galina Kistanovafc259902012-07-13 01:25:27 +00001437
Chris Lattner31b132c2009-10-28 00:01:44 +00001438 assert(BA->getFunction() == F && "Basic block moved between functions");
1439 return BA;
1440}
1441
1442BlockAddress::BlockAddress(Function *F, BasicBlock *BB)
1443: Constant(Type::getInt8PtrTy(F->getContext()), Value::BlockAddressVal,
1444 &Op<0>(), 2) {
Chris Lattnerc559a9f2009-11-01 03:03:03 +00001445 setOperand(0, F);
1446 setOperand(1, BB);
Chris Lattneraa99c942009-11-01 01:27:45 +00001447 BB->AdjustBlockAddressRefCount(1);
Chris Lattner31b132c2009-10-28 00:01:44 +00001448}
1449
Chandler Carruth6a936922014-01-19 02:13:50 +00001450BlockAddress *BlockAddress::lookup(const BasicBlock *BB) {
1451 if (!BB->hasAddressTaken())
Craig Topperc6207612014-04-09 06:08:46 +00001452 return nullptr;
Chandler Carruth6a936922014-01-19 02:13:50 +00001453
1454 const Function *F = BB->getParent();
Craig Topper2617dcc2014-04-15 06:32:26 +00001455 assert(F && "Block must have a parent");
Chandler Carruth6a936922014-01-19 02:13:50 +00001456 BlockAddress *BA =
1457 F->getContext().pImpl->BlockAddresses.lookup(std::make_pair(F, BB));
1458 assert(BA && "Refcount and block address map disagree!");
1459 return BA;
1460}
Chris Lattner31b132c2009-10-28 00:01:44 +00001461
1462// destroyConstant - Remove the constant from the constant table.
1463//
Pete Cooper86dd4cf2015-06-23 21:55:11 +00001464void BlockAddress::destroyConstantImpl() {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001465 getFunction()->getType()->getContext().pImpl
Chris Lattner31b132c2009-10-28 00:01:44 +00001466 ->BlockAddresses.erase(std::make_pair(getFunction(), getBasicBlock()));
Chris Lattneraa99c942009-11-01 01:27:45 +00001467 getBasicBlock()->AdjustBlockAddressRefCount(-1);
Chris Lattner31b132c2009-10-28 00:01:44 +00001468}
1469
Pete Cooper5815b1f2015-06-24 18:55:24 +00001470Value *BlockAddress::handleOperandChangeImpl(Value *From, Value *To, Use *U) {
Chris Lattner31b132c2009-10-28 00:01:44 +00001471 // This could be replacing either the Basic Block or the Function. In either
1472 // case, we have to remove the map entry.
1473 Function *NewF = getFunction();
1474 BasicBlock *NewBB = getBasicBlock();
Galina Kistanovafc259902012-07-13 01:25:27 +00001475
Chris Lattner31b132c2009-10-28 00:01:44 +00001476 if (U == &Op<0>())
Derek Schuffec9dc012013-06-13 19:51:17 +00001477 NewF = cast<Function>(To->stripPointerCasts());
Chris Lattner31b132c2009-10-28 00:01:44 +00001478 else
1479 NewBB = cast<BasicBlock>(To);
Galina Kistanovafc259902012-07-13 01:25:27 +00001480
Chris Lattner31b132c2009-10-28 00:01:44 +00001481 // See if the 'new' entry already exists, if not, just update this in place
1482 // and return early.
1483 BlockAddress *&NewBA =
1484 getContext().pImpl->BlockAddresses[std::make_pair(NewF, NewBB)];
Pete Cooper5815b1f2015-06-24 18:55:24 +00001485 if (NewBA)
1486 return NewBA;
Chris Lattner31b132c2009-10-28 00:01:44 +00001487
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00001488 getBasicBlock()->AdjustBlockAddressRefCount(-1);
Galina Kistanovafc259902012-07-13 01:25:27 +00001489
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00001490 // Remove the old entry, this can't cause the map to rehash (just a
1491 // tombstone will get added).
1492 getContext().pImpl->BlockAddresses.erase(std::make_pair(getFunction(),
1493 getBasicBlock()));
1494 NewBA = this;
1495 setOperand(0, NewF);
1496 setOperand(1, NewBB);
1497 getBasicBlock()->AdjustBlockAddressRefCount(1);
Pete Cooper5815b1f2015-06-24 18:55:24 +00001498
1499 // If we just want to keep the existing value, then return null.
1500 // Callers know that this means we shouldn't delete this value.
1501 return nullptr;
Chris Lattner31b132c2009-10-28 00:01:44 +00001502}
1503
1504//---- ConstantExpr::get() implementations.
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001505//
Reid Spencer8d9336d2006-12-31 05:26:44 +00001506
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001507/// This is a utility function to handle folding of casts and lookup of the
Duncan Sands7d6c8ae2008-03-30 19:38:55 +00001508/// cast in the ExprConstants map. It is used by the various get* methods below.
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001509static Constant *getFoldedCast(Instruction::CastOps opc, Constant *C, Type *Ty,
1510 bool OnlyIfReduced = false) {
Chris Lattner815ae2b2003-10-07 22:19:19 +00001511 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001512 // Fold a few common cases
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00001513 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001514 return FC;
Chris Lattneracdbe712003-04-17 19:24:48 +00001515
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001516 if (OnlyIfReduced)
1517 return nullptr;
1518
Owen Anderson1584a292009-08-04 20:25:11 +00001519 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
1520
Nadav Rotem88330432013-03-07 01:30:40 +00001521 // Look up the constant in the table first to ensure uniqueness.
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00001522 ConstantExprKeyType Key(opc, C);
Galina Kistanovafc259902012-07-13 01:25:27 +00001523
Owen Anderson1584a292009-08-04 20:25:11 +00001524 return pImpl->ExprConstants.getOrCreate(Ty, Key);
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001525}
Galina Kistanovafc259902012-07-13 01:25:27 +00001526
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001527Constant *ConstantExpr::getCast(unsigned oc, Constant *C, Type *Ty,
1528 bool OnlyIfReduced) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001529 Instruction::CastOps opc = Instruction::CastOps(oc);
1530 assert(Instruction::isCast(opc) && "opcode out of range");
1531 assert(C && Ty && "Null arguments to getCast");
Chris Lattner37bc78a2010-01-26 21:51:43 +00001532 assert(CastInst::castIsValid(opc, C, Ty) && "Invalid constantexpr cast!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001533
1534 switch (opc) {
Chris Lattner37bc78a2010-01-26 21:51:43 +00001535 default:
1536 llvm_unreachable("Invalid cast opcode");
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001537 case Instruction::Trunc:
1538 return getTrunc(C, Ty, OnlyIfReduced);
1539 case Instruction::ZExt:
1540 return getZExt(C, Ty, OnlyIfReduced);
1541 case Instruction::SExt:
1542 return getSExt(C, Ty, OnlyIfReduced);
1543 case Instruction::FPTrunc:
1544 return getFPTrunc(C, Ty, OnlyIfReduced);
1545 case Instruction::FPExt:
1546 return getFPExtend(C, Ty, OnlyIfReduced);
1547 case Instruction::UIToFP:
1548 return getUIToFP(C, Ty, OnlyIfReduced);
1549 case Instruction::SIToFP:
1550 return getSIToFP(C, Ty, OnlyIfReduced);
1551 case Instruction::FPToUI:
1552 return getFPToUI(C, Ty, OnlyIfReduced);
1553 case Instruction::FPToSI:
1554 return getFPToSI(C, Ty, OnlyIfReduced);
1555 case Instruction::PtrToInt:
1556 return getPtrToInt(C, Ty, OnlyIfReduced);
1557 case Instruction::IntToPtr:
1558 return getIntToPtr(C, Ty, OnlyIfReduced);
1559 case Instruction::BitCast:
1560 return getBitCast(C, Ty, OnlyIfReduced);
1561 case Instruction::AddrSpaceCast:
1562 return getAddrSpaceCast(C, Ty, OnlyIfReduced);
Chris Lattner1ece6f82005-01-01 15:59:57 +00001563 }
Galina Kistanovafc259902012-07-13 01:25:27 +00001564}
Reid Spencerf37dc652006-12-05 19:14:13 +00001565
Chris Lattner229907c2011-07-18 04:54:35 +00001566Constant *ConstantExpr::getZExtOrBitCast(Constant *C, Type *Ty) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001567 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
Dan Gohman3cdcc3f2010-04-12 22:12:29 +00001568 return getBitCast(C, Ty);
1569 return getZExt(C, Ty);
Reid Spencer5c140882006-12-04 20:17:56 +00001570}
1571
Chris Lattner229907c2011-07-18 04:54:35 +00001572Constant *ConstantExpr::getSExtOrBitCast(Constant *C, Type *Ty) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001573 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
Dan Gohman3cdcc3f2010-04-12 22:12:29 +00001574 return getBitCast(C, Ty);
1575 return getSExt(C, Ty);
Reid Spencer5c140882006-12-04 20:17:56 +00001576}
1577
Chris Lattner229907c2011-07-18 04:54:35 +00001578Constant *ConstantExpr::getTruncOrBitCast(Constant *C, Type *Ty) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001579 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
Dan Gohman3cdcc3f2010-04-12 22:12:29 +00001580 return getBitCast(C, Ty);
1581 return getTrunc(C, Ty);
Reid Spencer5c140882006-12-04 20:17:56 +00001582}
1583
Chris Lattner229907c2011-07-18 04:54:35 +00001584Constant *ConstantExpr::getPointerCast(Constant *S, Type *Ty) {
Evgeniy Stepanov23382642013-01-16 14:41:46 +00001585 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
1586 assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
1587 "Invalid cast");
Reid Spencerbc245a02006-12-05 03:25:26 +00001588
Evgeniy Stepanov23382642013-01-16 14:41:46 +00001589 if (Ty->isIntOrIntVectorTy())
Dan Gohman3cdcc3f2010-04-12 22:12:29 +00001590 return getPtrToInt(S, Ty);
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00001591
1592 unsigned SrcAS = S->getType()->getPointerAddressSpace();
1593 if (Ty->isPtrOrPtrVectorTy() && SrcAS != Ty->getPointerAddressSpace())
1594 return getAddrSpaceCast(S, Ty);
1595
Dan Gohman3cdcc3f2010-04-12 22:12:29 +00001596 return getBitCast(S, Ty);
Reid Spencerbc245a02006-12-05 03:25:26 +00001597}
1598
Matt Arsenault21f38f42013-12-07 02:58:41 +00001599Constant *ConstantExpr::getPointerBitCastOrAddrSpaceCast(Constant *S,
1600 Type *Ty) {
1601 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
1602 assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast");
1603
1604 if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace())
1605 return getAddrSpaceCast(S, Ty);
1606
1607 return getBitCast(S, Ty);
1608}
1609
1610Constant *ConstantExpr::getIntegerCast(Constant *C, Type *Ty,
Reid Spencer56521c42006-12-12 00:51:07 +00001611 bool isSigned) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00001612 assert(C->getType()->isIntOrIntVectorTy() &&
1613 Ty->isIntOrIntVectorTy() && "Invalid cast");
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001614 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1615 unsigned DstBits = Ty->getScalarSizeInBits();
Reid Spencer56521c42006-12-12 00:51:07 +00001616 Instruction::CastOps opcode =
1617 (SrcBits == DstBits ? Instruction::BitCast :
1618 (SrcBits > DstBits ? Instruction::Trunc :
1619 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1620 return getCast(opcode, C, Ty);
1621}
1622
Chris Lattner229907c2011-07-18 04:54:35 +00001623Constant *ConstantExpr::getFPCast(Constant *C, Type *Ty) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00001624 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
Reid Spencer56521c42006-12-12 00:51:07 +00001625 "Invalid cast");
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001626 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1627 unsigned DstBits = Ty->getScalarSizeInBits();
Reid Spencerca104e82006-12-12 05:38:50 +00001628 if (SrcBits == DstBits)
1629 return C; // Avoid a useless cast
Reid Spencer56521c42006-12-12 00:51:07 +00001630 Instruction::CastOps opcode =
Jay Foad9f32cfd2011-01-27 14:44:55 +00001631 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
Reid Spencer56521c42006-12-12 00:51:07 +00001632 return getCast(opcode, C, Ty);
1633}
1634
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001635Constant *ConstantExpr::getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001636#ifndef NDEBUG
1637 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1638 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1639#endif
1640 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001641 assert(C->getType()->isIntOrIntVectorTy() && "Trunc operand must be integer");
1642 assert(Ty->isIntOrIntVectorTy() && "Trunc produces only integral");
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001643 assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001644 "SrcTy must be larger than DestTy for Trunc!");
1645
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001646 return getFoldedCast(Instruction::Trunc, C, Ty, OnlyIfReduced);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001647}
1648
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001649Constant *ConstantExpr::getSExt(Constant *C, Type *Ty, bool OnlyIfReduced) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001650#ifndef NDEBUG
1651 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1652 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1653#endif
1654 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001655 assert(C->getType()->isIntOrIntVectorTy() && "SExt operand must be integral");
1656 assert(Ty->isIntOrIntVectorTy() && "SExt produces only integer");
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001657 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001658 "SrcTy must be smaller than DestTy for SExt!");
1659
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001660 return getFoldedCast(Instruction::SExt, C, Ty, OnlyIfReduced);
Chris Lattnerdd284742004-04-04 23:20:30 +00001661}
1662
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001663Constant *ConstantExpr::getZExt(Constant *C, Type *Ty, bool OnlyIfReduced) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001664#ifndef NDEBUG
1665 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1666 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1667#endif
1668 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001669 assert(C->getType()->isIntOrIntVectorTy() && "ZEXt operand must be integral");
1670 assert(Ty->isIntOrIntVectorTy() && "ZExt produces only integer");
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001671 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001672 "SrcTy must be smaller than DestTy for ZExt!");
1673
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001674 return getFoldedCast(Instruction::ZExt, C, Ty, OnlyIfReduced);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001675}
1676
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001677Constant *ConstantExpr::getFPTrunc(Constant *C, Type *Ty, bool OnlyIfReduced) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001678#ifndef NDEBUG
1679 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1680 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1681#endif
1682 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001683 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001684 C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001685 "This is an illegal floating point truncation!");
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001686 return getFoldedCast(Instruction::FPTrunc, C, Ty, OnlyIfReduced);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001687}
1688
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001689Constant *ConstantExpr::getFPExtend(Constant *C, Type *Ty, bool OnlyIfReduced) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001690#ifndef NDEBUG
1691 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1692 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1693#endif
1694 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001695 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001696 C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001697 "This is an illegal floating point extension!");
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001698 return getFoldedCast(Instruction::FPExt, C, Ty, OnlyIfReduced);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001699}
1700
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001701Constant *ConstantExpr::getUIToFP(Constant *C, Type *Ty, bool OnlyIfReduced) {
Devang Pateld26344d2008-11-03 23:20:04 +00001702#ifndef NDEBUG
Nate Begemand4d45c22007-11-17 03:58:34 +00001703 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1704 bool toVec = Ty->getTypeID() == Type::VectorTyID;
Devang Pateld26344d2008-11-03 23:20:04 +00001705#endif
Nate Begemand4d45c22007-11-17 03:58:34 +00001706 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001707 assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
Nate Begemand4d45c22007-11-17 03:58:34 +00001708 "This is an illegal uint to floating point cast!");
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001709 return getFoldedCast(Instruction::UIToFP, C, Ty, OnlyIfReduced);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001710}
1711
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001712Constant *ConstantExpr::getSIToFP(Constant *C, Type *Ty, bool OnlyIfReduced) {
Devang Pateld26344d2008-11-03 23:20:04 +00001713#ifndef NDEBUG
Nate Begemand4d45c22007-11-17 03:58:34 +00001714 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1715 bool toVec = Ty->getTypeID() == Type::VectorTyID;
Devang Pateld26344d2008-11-03 23:20:04 +00001716#endif
Nate Begemand4d45c22007-11-17 03:58:34 +00001717 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001718 assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001719 "This is an illegal sint to floating point cast!");
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001720 return getFoldedCast(Instruction::SIToFP, C, Ty, OnlyIfReduced);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001721}
1722
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001723Constant *ConstantExpr::getFPToUI(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()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
Nate Begemand4d45c22007-11-17 03:58:34 +00001730 "This is an illegal floating point to uint cast!");
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001731 return getFoldedCast(Instruction::FPToUI, C, Ty, OnlyIfReduced);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001732}
1733
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001734Constant *ConstantExpr::getFPToSI(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()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
Nate Begemand4d45c22007-11-17 03:58:34 +00001741 "This is an illegal floating point to sint cast!");
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001742 return getFoldedCast(Instruction::FPToSI, C, Ty, OnlyIfReduced);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001743}
1744
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001745Constant *ConstantExpr::getPtrToInt(Constant *C, Type *DstTy,
1746 bool OnlyIfReduced) {
Nadav Rotem3924cb02011-12-05 06:29:09 +00001747 assert(C->getType()->getScalarType()->isPointerTy() &&
1748 "PtrToInt source must be pointer or pointer vector");
1749 assert(DstTy->getScalarType()->isIntegerTy() &&
1750 "PtrToInt destination must be integer or integer vector");
Chris Lattner8a3df542012-01-25 01:32:59 +00001751 assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
Nick Lewyckyff509622012-01-25 03:20:12 +00001752 if (isa<VectorType>(C->getType()))
Chris Lattner8326bd82012-01-26 00:42:34 +00001753 assert(C->getType()->getVectorNumElements()==DstTy->getVectorNumElements()&&
Chris Lattner8a3df542012-01-25 01:32:59 +00001754 "Invalid cast between a different number of vector elements");
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001755 return getFoldedCast(Instruction::PtrToInt, C, DstTy, OnlyIfReduced);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001756}
1757
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001758Constant *ConstantExpr::getIntToPtr(Constant *C, Type *DstTy,
1759 bool OnlyIfReduced) {
Nadav Rotem3924cb02011-12-05 06:29:09 +00001760 assert(C->getType()->getScalarType()->isIntegerTy() &&
1761 "IntToPtr source must be integer or integer vector");
1762 assert(DstTy->getScalarType()->isPointerTy() &&
1763 "IntToPtr destination must be a pointer or pointer vector");
Chris Lattner8a3df542012-01-25 01:32:59 +00001764 assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
Nick Lewyckyff509622012-01-25 03:20:12 +00001765 if (isa<VectorType>(C->getType()))
Chris Lattner8326bd82012-01-26 00:42:34 +00001766 assert(C->getType()->getVectorNumElements()==DstTy->getVectorNumElements()&&
Chris Lattner8a3df542012-01-25 01:32:59 +00001767 "Invalid cast between a different number of vector elements");
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001768 return getFoldedCast(Instruction::IntToPtr, C, DstTy, OnlyIfReduced);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001769}
1770
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001771Constant *ConstantExpr::getBitCast(Constant *C, Type *DstTy,
1772 bool OnlyIfReduced) {
Chris Lattner37bc78a2010-01-26 21:51:43 +00001773 assert(CastInst::castIsValid(Instruction::BitCast, C, DstTy) &&
1774 "Invalid constantexpr bitcast!");
Galina Kistanovafc259902012-07-13 01:25:27 +00001775
Chris Lattnercbeda872009-03-21 06:55:54 +00001776 // It is common to ask for a bitcast of a value to its own type, handle this
1777 // speedily.
1778 if (C->getType() == DstTy) return C;
Galina Kistanovafc259902012-07-13 01:25:27 +00001779
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001780 return getFoldedCast(Instruction::BitCast, C, DstTy, OnlyIfReduced);
Chris Lattnerdd284742004-04-04 23:20:30 +00001781}
1782
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001783Constant *ConstantExpr::getAddrSpaceCast(Constant *C, Type *DstTy,
1784 bool OnlyIfReduced) {
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00001785 assert(CastInst::castIsValid(Instruction::AddrSpaceCast, C, DstTy) &&
1786 "Invalid constantexpr addrspacecast!");
1787
Jingyue Wubaabe502014-06-15 21:40:57 +00001788 // Canonicalize addrspacecasts between different pointer types by first
1789 // bitcasting the pointer type and then converting the address space.
1790 PointerType *SrcScalarTy = cast<PointerType>(C->getType()->getScalarType());
1791 PointerType *DstScalarTy = cast<PointerType>(DstTy->getScalarType());
1792 Type *DstElemTy = DstScalarTy->getElementType();
1793 if (SrcScalarTy->getElementType() != DstElemTy) {
1794 Type *MidTy = PointerType::get(DstElemTy, SrcScalarTy->getAddressSpace());
1795 if (VectorType *VT = dyn_cast<VectorType>(DstTy)) {
1796 // Handle vectors of pointers.
1797 MidTy = VectorType::get(MidTy, VT->getNumElements());
1798 }
1799 C = getBitCast(C, MidTy);
1800 }
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001801 return getFoldedCast(Instruction::AddrSpaceCast, C, DstTy, OnlyIfReduced);
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00001802}
1803
Chris Lattner887ecac2011-07-09 18:23:52 +00001804Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2,
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001805 unsigned Flags, Type *OnlyIfReducedTy) {
Chris Lattner887ecac2011-07-09 18:23:52 +00001806 // Check the operands for consistency first.
Reid Spencer7eb55b32006-11-02 01:53:59 +00001807 assert(Opcode >= Instruction::BinaryOpsBegin &&
1808 Opcode < Instruction::BinaryOpsEnd &&
Chris Lattner38a9bcd2003-05-21 17:49:25 +00001809 "Invalid opcode in binary constant expression");
1810 assert(C1->getType() == C2->getType() &&
1811 "Operand types in binary constant expression should match");
Galina Kistanovafc259902012-07-13 01:25:27 +00001812
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001813#ifndef NDEBUG
1814 switch (Opcode) {
Dan Gohmana5b96452009-06-04 22:49:04 +00001815 case Instruction::Add:
Reid Spencer7eb55b32006-11-02 01:53:59 +00001816 case Instruction::Sub:
Dan Gohmana5b96452009-06-04 22:49:04 +00001817 case Instruction::Mul:
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001818 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001819 assert(C1->getType()->isIntOrIntVectorTy() &&
Dan Gohmana5b96452009-06-04 22:49:04 +00001820 "Tried to create an integer operation on a non-integer type!");
1821 break;
1822 case Instruction::FAdd:
1823 case Instruction::FSub:
1824 case Instruction::FMul:
1825 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001826 assert(C1->getType()->isFPOrFPVectorTy() &&
Dan Gohmana5b96452009-06-04 22:49:04 +00001827 "Tried to create a floating-point operation on a "
1828 "non-floating-point type!");
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001829 break;
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001830 case Instruction::UDiv:
1831 case Instruction::SDiv:
1832 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001833 assert(C1->getType()->isIntOrIntVectorTy() &&
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001834 "Tried to create an arithmetic operation on a non-arithmetic type!");
1835 break;
1836 case Instruction::FDiv:
1837 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001838 assert(C1->getType()->isFPOrFPVectorTy() &&
Dan Gohman7889f2b2009-06-15 22:25:12 +00001839 "Tried to create an arithmetic operation on a non-arithmetic type!");
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001840 break;
Reid Spencer7eb55b32006-11-02 01:53:59 +00001841 case Instruction::URem:
1842 case Instruction::SRem:
1843 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001844 assert(C1->getType()->isIntOrIntVectorTy() &&
Reid Spencer7eb55b32006-11-02 01:53:59 +00001845 "Tried to create an arithmetic operation on a non-arithmetic type!");
1846 break;
1847 case Instruction::FRem:
1848 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001849 assert(C1->getType()->isFPOrFPVectorTy() &&
Dan Gohman7889f2b2009-06-15 22:25:12 +00001850 "Tried to create an arithmetic operation on a non-arithmetic type!");
Reid Spencer7eb55b32006-11-02 01:53:59 +00001851 break;
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001852 case Instruction::And:
1853 case Instruction::Or:
1854 case Instruction::Xor:
1855 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001856 assert(C1->getType()->isIntOrIntVectorTy() &&
Misha Brukman3852f652005-01-27 06:46:38 +00001857 "Tried to create a logical operation on a non-integral type!");
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001858 break;
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001859 case Instruction::Shl:
Reid Spencerfdff9382006-11-08 06:47:33 +00001860 case Instruction::LShr:
1861 case Instruction::AShr:
Reid Spencer2341c222007-02-02 02:16:23 +00001862 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001863 assert(C1->getType()->isIntOrIntVectorTy() &&
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001864 "Tried to create a shift operation on a non-integer type!");
1865 break;
1866 default:
1867 break;
1868 }
1869#endif
1870
Chris Lattner887ecac2011-07-09 18:23:52 +00001871 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1872 return FC; // Fold a few common cases.
Galina Kistanovafc259902012-07-13 01:25:27 +00001873
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001874 if (OnlyIfReducedTy == C1->getType())
1875 return nullptr;
1876
Benjamin Kramer324322b2013-03-07 20:53:34 +00001877 Constant *ArgVec[] = { C1, C2 };
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00001878 ConstantExprKeyType Key(Opcode, ArgVec, 0, Flags);
Galina Kistanovafc259902012-07-13 01:25:27 +00001879
Chris Lattner887ecac2011-07-09 18:23:52 +00001880 LLVMContextImpl *pImpl = C1->getContext().pImpl;
1881 return pImpl->ExprConstants.getOrCreate(C1->getType(), Key);
Reid Spencera009d0d2006-12-04 21:35:24 +00001882}
1883
Chris Lattner229907c2011-07-18 04:54:35 +00001884Constant *ConstantExpr::getSizeOf(Type* Ty) {
Owen Anderson487375e2009-07-29 18:55:55 +00001885 // sizeof is implemented as: (i64) gep (Ty*)null, 1
1886 // Note that a non-inbounds gep is used, as null isn't within any object.
Owen Anderson55f1c092009-08-13 21:58:54 +00001887 Constant *GEPIdx = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
Owen Anderson487375e2009-07-29 18:55:55 +00001888 Constant *GEP = getGetElementPtr(
David Blaikie4a2e73b2015-04-02 18:55:32 +00001889 Ty, Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx);
Dan Gohman3cdcc3f2010-04-12 22:12:29 +00001890 return getPtrToInt(GEP,
1891 Type::getInt64Ty(Ty->getContext()));
Owen Anderson487375e2009-07-29 18:55:55 +00001892}
1893
Chris Lattner229907c2011-07-18 04:54:35 +00001894Constant *ConstantExpr::getAlignOf(Type* Ty) {
Dan Gohmancf913832010-01-28 02:15:55 +00001895 // alignof is implemented as: (i64) gep ({i1,Ty}*)null, 0, 1
Dan Gohman50c09d02009-08-11 17:57:01 +00001896 // Note that a non-inbounds gep is used, as null isn't within any object.
Chris Lattner229907c2011-07-18 04:54:35 +00001897 Type *AligningTy =
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001898 StructType::get(Type::getInt1Ty(Ty->getContext()), Ty, nullptr);
Matt Arsenaultbe558882014-04-23 20:58:57 +00001899 Constant *NullPtr = Constant::getNullValue(AligningTy->getPointerTo(0));
Dan Gohmana9be7392010-01-28 02:43:22 +00001900 Constant *Zero = ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0);
Owen Anderson55f1c092009-08-13 21:58:54 +00001901 Constant *One = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
Owen Anderson487375e2009-07-29 18:55:55 +00001902 Constant *Indices[2] = { Zero, One };
David Blaikie4a2e73b2015-04-02 18:55:32 +00001903 Constant *GEP = getGetElementPtr(AligningTy, NullPtr, Indices);
Dan Gohman3cdcc3f2010-04-12 22:12:29 +00001904 return getPtrToInt(GEP,
1905 Type::getInt64Ty(Ty->getContext()));
Owen Anderson487375e2009-07-29 18:55:55 +00001906}
1907
Chris Lattner229907c2011-07-18 04:54:35 +00001908Constant *ConstantExpr::getOffsetOf(StructType* STy, unsigned FieldNo) {
Dan Gohmanede94e62010-02-01 16:37:38 +00001909 return getOffsetOf(STy, ConstantInt::get(Type::getInt32Ty(STy->getContext()),
1910 FieldNo));
1911}
1912
Chris Lattner229907c2011-07-18 04:54:35 +00001913Constant *ConstantExpr::getOffsetOf(Type* Ty, Constant *FieldNo) {
Dan Gohmanff3af7252009-08-16 21:26:11 +00001914 // offsetof is implemented as: (i64) gep (Ty*)null, 0, FieldNo
1915 // Note that a non-inbounds gep is used, as null isn't within any object.
1916 Constant *GEPIdx[] = {
Dan Gohmanede94e62010-02-01 16:37:38 +00001917 ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0),
1918 FieldNo
Dan Gohmanff3af7252009-08-16 21:26:11 +00001919 };
1920 Constant *GEP = getGetElementPtr(
David Blaikie4a2e73b2015-04-02 18:55:32 +00001921 Ty, Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx);
Dan Gohman3cdcc3f2010-04-12 22:12:29 +00001922 return getPtrToInt(GEP,
1923 Type::getInt64Ty(Ty->getContext()));
Dan Gohmanff3af7252009-08-16 21:26:11 +00001924}
Owen Anderson487375e2009-07-29 18:55:55 +00001925
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001926Constant *ConstantExpr::getCompare(unsigned short Predicate, Constant *C1,
1927 Constant *C2, bool OnlyIfReduced) {
Reid Spencera009d0d2006-12-04 21:35:24 +00001928 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Galina Kistanovafc259902012-07-13 01:25:27 +00001929
Chris Lattner887ecac2011-07-09 18:23:52 +00001930 switch (Predicate) {
1931 default: llvm_unreachable("Invalid CmpInst predicate");
1932 case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
1933 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
1934 case CmpInst::FCMP_ONE: case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
1935 case CmpInst::FCMP_UEQ: case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
1936 case CmpInst::FCMP_ULT: case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
1937 case CmpInst::FCMP_TRUE:
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001938 return getFCmp(Predicate, C1, C2, OnlyIfReduced);
Galina Kistanovafc259902012-07-13 01:25:27 +00001939
Chris Lattner887ecac2011-07-09 18:23:52 +00001940 case CmpInst::ICMP_EQ: case CmpInst::ICMP_NE: case CmpInst::ICMP_UGT:
1941 case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
1942 case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
1943 case CmpInst::ICMP_SLE:
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001944 return getICmp(Predicate, C1, C2, OnlyIfReduced);
Chris Lattner887ecac2011-07-09 18:23:52 +00001945 }
Chris Lattner29ca2c62004-08-04 18:50:09 +00001946}
1947
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001948Constant *ConstantExpr::getSelect(Constant *C, Constant *V1, Constant *V2,
1949 Type *OnlyIfReducedTy) {
Chris Lattner41632132008-12-29 00:16:12 +00001950 assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
Chris Lattner6e415c02004-03-12 05:54:04 +00001951
Chris Lattner887ecac2011-07-09 18:23:52 +00001952 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1953 return SC; // Fold common cases
Chris Lattner6e415c02004-03-12 05:54:04 +00001954
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001955 if (OnlyIfReducedTy == V1->getType())
1956 return nullptr;
1957
Benjamin Kramer324322b2013-03-07 20:53:34 +00001958 Constant *ArgVec[] = { C, V1, V2 };
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00001959 ConstantExprKeyType Key(Instruction::Select, ArgVec);
Galina Kistanovafc259902012-07-13 01:25:27 +00001960
Chris Lattner887ecac2011-07-09 18:23:52 +00001961 LLVMContextImpl *pImpl = C->getContext().pImpl;
1962 return pImpl->ExprConstants.getOrCreate(V1->getType(), Key);
Chris Lattner6e415c02004-03-12 05:54:04 +00001963}
1964
David Blaikie4a2e73b2015-04-02 18:55:32 +00001965Constant *ConstantExpr::getGetElementPtr(Type *Ty, Constant *C,
1966 ArrayRef<Value *> Idxs, bool InBounds,
1967 Type *OnlyIfReducedTy) {
David Blaikie4a2e73b2015-04-02 18:55:32 +00001968 if (!Ty)
1969 Ty = cast<PointerType>(C->getType()->getScalarType())->getElementType();
1970 else
David Blaikied9d900c2015-05-07 17:28:58 +00001971 assert(
1972 Ty ==
1973 cast<PointerType>(C->getType()->getScalarType())->getContainedType(0u));
1974
1975 if (Constant *FC = ConstantFoldGetElementPtr(Ty, C, InBounds, Idxs))
1976 return FC; // Fold a few common cases.
1977
Chris Lattner887ecac2011-07-09 18:23:52 +00001978 // Get the result type of the getelementptr!
David Blaikie4a2e73b2015-04-02 18:55:32 +00001979 Type *DestTy = GetElementPtrInst::getIndexedType(Ty, Idxs);
1980 assert(DestTy && "GEP indices invalid!");
Chris Lattner8326bd82012-01-26 00:42:34 +00001981 unsigned AS = C->getType()->getPointerAddressSpace();
David Blaikie4a2e73b2015-04-02 18:55:32 +00001982 Type *ReqTy = DestTy->getPointerTo(AS);
Duncan Sandse6beec62012-11-13 12:59:33 +00001983 if (VectorType *VecTy = dyn_cast<VectorType>(C->getType()))
1984 ReqTy = VectorType::get(ReqTy, VecTy->getNumElements());
Galina Kistanovafc259902012-07-13 01:25:27 +00001985
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001986 if (OnlyIfReducedTy == ReqTy)
1987 return nullptr;
1988
Dan Gohman1b849082009-09-07 23:54:19 +00001989 // Look up the constant in the table first to ensure uniqueness
1990 std::vector<Constant*> ArgVec;
Jay Foaded8db7d2011-07-21 14:31:17 +00001991 ArgVec.reserve(1 + Idxs.size());
Dan Gohman1b849082009-09-07 23:54:19 +00001992 ArgVec.push_back(C);
Duncan Sandse6beec62012-11-13 12:59:33 +00001993 for (unsigned i = 0, e = Idxs.size(); i != e; ++i) {
1994 assert(Idxs[i]->getType()->isVectorTy() == ReqTy->isVectorTy() &&
1995 "getelementptr index type missmatch");
1996 assert((!Idxs[i]->getType()->isVectorTy() ||
1997 ReqTy->getVectorNumElements() ==
1998 Idxs[i]->getType()->getVectorNumElements()) &&
1999 "getelementptr index type missmatch");
Dan Gohman1b849082009-09-07 23:54:19 +00002000 ArgVec.push_back(cast<Constant>(Idxs[i]));
Duncan Sandse6beec62012-11-13 12:59:33 +00002001 }
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002002 const ConstantExprKeyType Key(Instruction::GetElementPtr, ArgVec, 0,
David Blaikie60310f22015-05-08 00:42:26 +00002003 InBounds ? GEPOperator::IsInBounds : 0, None,
2004 Ty);
Galina Kistanovafc259902012-07-13 01:25:27 +00002005
Chris Lattner887ecac2011-07-09 18:23:52 +00002006 LLVMContextImpl *pImpl = C->getContext().pImpl;
Dan Gohman1b849082009-09-07 23:54:19 +00002007 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
2008}
2009
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002010Constant *ConstantExpr::getICmp(unsigned short pred, Constant *LHS,
2011 Constant *RHS, bool OnlyIfReduced) {
Reid Spenceree3c9912006-12-04 05:19:50 +00002012 assert(LHS->getType() == RHS->getType());
2013 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
2014 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
2015
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00002016 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
Reid Spenceree3c9912006-12-04 05:19:50 +00002017 return FC; // Fold a few common cases...
2018
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002019 if (OnlyIfReduced)
2020 return nullptr;
2021
Reid Spenceree3c9912006-12-04 05:19:50 +00002022 // Look up the constant in the table first to ensure uniqueness
Benjamin Kramer324322b2013-03-07 20:53:34 +00002023 Constant *ArgVec[] = { LHS, RHS };
Reid Spencerb1537492006-12-24 18:42:29 +00002024 // Get the key type with both the opcode and predicate
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002025 const ConstantExprKeyType Key(Instruction::ICmp, ArgVec, pred);
Owen Anderson61794042009-06-17 20:10:08 +00002026
Chris Lattner229907c2011-07-18 04:54:35 +00002027 Type *ResultTy = Type::getInt1Ty(LHS->getContext());
2028 if (VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
Nick Lewycky9e26c1c2010-01-21 07:03:21 +00002029 ResultTy = VectorType::get(ResultTy, VT->getNumElements());
2030
Owen Anderson1584a292009-08-04 20:25:11 +00002031 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
Nick Lewycky9e26c1c2010-01-21 07:03:21 +00002032 return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
Reid Spenceree3c9912006-12-04 05:19:50 +00002033}
2034
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002035Constant *ConstantExpr::getFCmp(unsigned short pred, Constant *LHS,
2036 Constant *RHS, bool OnlyIfReduced) {
Reid Spenceree3c9912006-12-04 05:19:50 +00002037 assert(LHS->getType() == RHS->getType());
2038 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
2039
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00002040 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
Reid Spenceree3c9912006-12-04 05:19:50 +00002041 return FC; // Fold a few common cases...
2042
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002043 if (OnlyIfReduced)
2044 return nullptr;
2045
Reid Spenceree3c9912006-12-04 05:19:50 +00002046 // Look up the constant in the table first to ensure uniqueness
Benjamin Kramer324322b2013-03-07 20:53:34 +00002047 Constant *ArgVec[] = { LHS, RHS };
Reid Spencerb1537492006-12-24 18:42:29 +00002048 // Get the key type with both the opcode and predicate
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002049 const ConstantExprKeyType Key(Instruction::FCmp, ArgVec, pred);
Nick Lewycky9e26c1c2010-01-21 07:03:21 +00002050
Chris Lattner229907c2011-07-18 04:54:35 +00002051 Type *ResultTy = Type::getInt1Ty(LHS->getContext());
2052 if (VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
Nick Lewycky9e26c1c2010-01-21 07:03:21 +00002053 ResultTy = VectorType::get(ResultTy, VT->getNumElements());
2054
Owen Anderson1584a292009-08-04 20:25:11 +00002055 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
Nick Lewycky9e26c1c2010-01-21 07:03:21 +00002056 return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
Reid Spenceree3c9912006-12-04 05:19:50 +00002057}
2058
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002059Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx,
2060 Type *OnlyIfReducedTy) {
Duncan Sands19d0b472010-02-16 11:11:14 +00002061 assert(Val->getType()->isVectorTy() &&
Reid Spencer09575ba2007-02-15 03:39:18 +00002062 "Tried to create extractelement operation on non-vector type!");
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002063 assert(Idx->getType()->isIntegerTy() &&
2064 "Extractelement index must be an integer type!");
Galina Kistanovafc259902012-07-13 01:25:27 +00002065
Chris Lattner887ecac2011-07-09 18:23:52 +00002066 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
Chris Lattner09660c92009-12-30 20:25:09 +00002067 return FC; // Fold a few common cases.
Galina Kistanovafc259902012-07-13 01:25:27 +00002068
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002069 Type *ReqTy = Val->getType()->getVectorElementType();
2070 if (OnlyIfReducedTy == ReqTy)
2071 return nullptr;
2072
Robert Bocchinoca27f032006-01-17 20:07:22 +00002073 // Look up the constant in the table first to ensure uniqueness
Benjamin Kramer324322b2013-03-07 20:53:34 +00002074 Constant *ArgVec[] = { Val, Idx };
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002075 const ConstantExprKeyType Key(Instruction::ExtractElement, ArgVec);
Galina Kistanovafc259902012-07-13 01:25:27 +00002076
Chris Lattner887ecac2011-07-09 18:23:52 +00002077 LLVMContextImpl *pImpl = Val->getContext().pImpl;
Owen Anderson1584a292009-08-04 20:25:11 +00002078 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
Robert Bocchinoca27f032006-01-17 20:07:22 +00002079}
2080
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002081Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
2082 Constant *Idx, Type *OnlyIfReducedTy) {
Duncan Sands19d0b472010-02-16 11:11:14 +00002083 assert(Val->getType()->isVectorTy() &&
Reid Spencer09575ba2007-02-15 03:39:18 +00002084 "Tried to create insertelement operation on non-vector type!");
Chris Lattner8326bd82012-01-26 00:42:34 +00002085 assert(Elt->getType() == Val->getType()->getVectorElementType() &&
2086 "Insertelement types must match!");
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002087 assert(Idx->getType()->isIntegerTy() &&
Reid Spencer2546b762007-01-26 07:37:34 +00002088 "Insertelement index must be i32 type!");
Robert Bocchinoca27f032006-01-17 20:07:22 +00002089
Chris Lattner887ecac2011-07-09 18:23:52 +00002090 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
2091 return FC; // Fold a few common cases.
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002092
2093 if (OnlyIfReducedTy == Val->getType())
2094 return nullptr;
2095
Chris Lattnerbbe0a422006-04-08 01:18:18 +00002096 // Look up the constant in the table first to ensure uniqueness
Benjamin Kramer324322b2013-03-07 20:53:34 +00002097 Constant *ArgVec[] = { Val, Elt, Idx };
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002098 const ConstantExprKeyType Key(Instruction::InsertElement, ArgVec);
Galina Kistanovafc259902012-07-13 01:25:27 +00002099
Chris Lattner887ecac2011-07-09 18:23:52 +00002100 LLVMContextImpl *pImpl = Val->getContext().pImpl;
2101 return pImpl->ExprConstants.getOrCreate(Val->getType(), Key);
Chris Lattnerbbe0a422006-04-08 01:18:18 +00002102}
2103
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002104Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
2105 Constant *Mask, Type *OnlyIfReducedTy) {
Chris Lattnerbbe0a422006-04-08 01:18:18 +00002106 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
2107 "Invalid shuffle vector constant expr operands!");
Nate Begeman94aa38d2009-02-12 21:28:33 +00002108
Chris Lattner887ecac2011-07-09 18:23:52 +00002109 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
2110 return FC; // Fold a few common cases.
2111
Chris Lattner8326bd82012-01-26 00:42:34 +00002112 unsigned NElts = Mask->getType()->getVectorNumElements();
2113 Type *EltTy = V1->getType()->getVectorElementType();
Chris Lattner229907c2011-07-18 04:54:35 +00002114 Type *ShufTy = VectorType::get(EltTy, NElts);
Chris Lattner887ecac2011-07-09 18:23:52 +00002115
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002116 if (OnlyIfReducedTy == ShufTy)
2117 return nullptr;
2118
Chris Lattner887ecac2011-07-09 18:23:52 +00002119 // Look up the constant in the table first to ensure uniqueness
Benjamin Kramer324322b2013-03-07 20:53:34 +00002120 Constant *ArgVec[] = { V1, V2, Mask };
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002121 const ConstantExprKeyType Key(Instruction::ShuffleVector, ArgVec);
Galina Kistanovafc259902012-07-13 01:25:27 +00002122
Chris Lattner887ecac2011-07-09 18:23:52 +00002123 LLVMContextImpl *pImpl = ShufTy->getContext().pImpl;
2124 return pImpl->ExprConstants.getOrCreate(ShufTy, Key);
Chris Lattnerbbe0a422006-04-08 01:18:18 +00002125}
2126
Chris Lattner887ecac2011-07-09 18:23:52 +00002127Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002128 ArrayRef<unsigned> Idxs,
2129 Type *OnlyIfReducedTy) {
Hal Finkelb31366d2013-07-10 22:51:01 +00002130 assert(Agg->getType()->isFirstClassType() &&
2131 "Non-first-class type for constant insertvalue expression");
2132
Jay Foad57aa6362011-07-13 10:26:04 +00002133 assert(ExtractValueInst::getIndexedType(Agg->getType(),
2134 Idxs) == Val->getType() &&
Dan Gohman12fce772008-05-15 19:50:34 +00002135 "insertvalue indices invalid!");
Hal Finkelb31366d2013-07-10 22:51:01 +00002136 Type *ReqTy = Val->getType();
2137
2138 if (Constant *FC = ConstantFoldInsertValueInstruction(Agg, Val, Idxs))
2139 return FC;
2140
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002141 if (OnlyIfReducedTy == ReqTy)
2142 return nullptr;
2143
Hal Finkelb31366d2013-07-10 22:51:01 +00002144 Constant *ArgVec[] = { Agg, Val };
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002145 const ConstantExprKeyType Key(Instruction::InsertValue, ArgVec, 0, 0, Idxs);
Hal Finkelb31366d2013-07-10 22:51:01 +00002146
2147 LLVMContextImpl *pImpl = Agg->getContext().pImpl;
2148 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
Dan Gohman12fce772008-05-15 19:50:34 +00002149}
2150
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002151Constant *ConstantExpr::getExtractValue(Constant *Agg, ArrayRef<unsigned> Idxs,
2152 Type *OnlyIfReducedTy) {
Dan Gohman0752bff2008-05-23 00:36:11 +00002153 assert(Agg->getType()->isFirstClassType() &&
Chris Lattner887ecac2011-07-09 18:23:52 +00002154 "Tried to create extractelement operation on non-first-class type!");
Dan Gohman12fce772008-05-15 19:50:34 +00002155
Chris Lattner229907c2011-07-18 04:54:35 +00002156 Type *ReqTy = ExtractValueInst::getIndexedType(Agg->getType(), Idxs);
Chandler Carruth9db56b82011-07-10 09:45:35 +00002157 (void)ReqTy;
Chris Lattner887ecac2011-07-09 18:23:52 +00002158 assert(ReqTy && "extractvalue indices invalid!");
Galina Kistanovafc259902012-07-13 01:25:27 +00002159
Dan Gohman0752bff2008-05-23 00:36:11 +00002160 assert(Agg->getType()->isFirstClassType() &&
2161 "Non-first-class type for constant extractvalue expression");
Hal Finkelb31366d2013-07-10 22:51:01 +00002162 if (Constant *FC = ConstantFoldExtractValueInstruction(Agg, Idxs))
2163 return FC;
2164
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002165 if (OnlyIfReducedTy == ReqTy)
2166 return nullptr;
2167
Hal Finkelb31366d2013-07-10 22:51:01 +00002168 Constant *ArgVec[] = { Agg };
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002169 const ConstantExprKeyType Key(Instruction::ExtractValue, ArgVec, 0, 0, Idxs);
Hal Finkelb31366d2013-07-10 22:51:01 +00002170
2171 LLVMContextImpl *pImpl = Agg->getContext().pImpl;
2172 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
Dan Gohman12fce772008-05-15 19:50:34 +00002173}
2174
Chris Lattnere9b4ad72011-02-10 07:01:55 +00002175Constant *ConstantExpr::getNeg(Constant *C, bool HasNUW, bool HasNSW) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00002176 assert(C->getType()->isIntOrIntVectorTy() &&
Owen Anderson487375e2009-07-29 18:55:55 +00002177 "Cannot NEG a nonintegral value!");
Chris Lattnere9b4ad72011-02-10 07:01:55 +00002178 return getSub(ConstantFP::getZeroValueForNegation(C->getType()),
2179 C, HasNUW, HasNSW);
Owen Anderson487375e2009-07-29 18:55:55 +00002180}
2181
Chris Lattnera676c0f2011-02-07 16:40:21 +00002182Constant *ConstantExpr::getFNeg(Constant *C) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00002183 assert(C->getType()->isFPOrFPVectorTy() &&
Owen Anderson487375e2009-07-29 18:55:55 +00002184 "Cannot FNEG a non-floating-point value!");
Chris Lattnere9b4ad72011-02-10 07:01:55 +00002185 return getFSub(ConstantFP::getZeroValueForNegation(C->getType()), C);
Owen Anderson487375e2009-07-29 18:55:55 +00002186}
2187
Chris Lattnera676c0f2011-02-07 16:40:21 +00002188Constant *ConstantExpr::getNot(Constant *C) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00002189 assert(C->getType()->isIntOrIntVectorTy() &&
Owen Anderson487375e2009-07-29 18:55:55 +00002190 "Cannot NOT a nonintegral value!");
Owen Anderson5a1acd92009-07-31 20:28:14 +00002191 return get(Instruction::Xor, C, Constant::getAllOnesValue(C->getType()));
Owen Anderson487375e2009-07-29 18:55:55 +00002192}
2193
Chris Lattnere9b4ad72011-02-10 07:01:55 +00002194Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2,
2195 bool HasNUW, bool HasNSW) {
2196 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2197 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2198 return get(Instruction::Add, C1, C2, Flags);
Owen Anderson487375e2009-07-29 18:55:55 +00002199}
2200
Chris Lattnera676c0f2011-02-07 16:40:21 +00002201Constant *ConstantExpr::getFAdd(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002202 return get(Instruction::FAdd, C1, C2);
2203}
2204
Chris Lattnere9b4ad72011-02-10 07:01:55 +00002205Constant *ConstantExpr::getSub(Constant *C1, Constant *C2,
2206 bool HasNUW, bool HasNSW) {
2207 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2208 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2209 return get(Instruction::Sub, C1, C2, Flags);
Owen Anderson487375e2009-07-29 18:55:55 +00002210}
2211
Chris Lattnera676c0f2011-02-07 16:40:21 +00002212Constant *ConstantExpr::getFSub(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002213 return get(Instruction::FSub, C1, C2);
2214}
2215
Chris Lattnere9b4ad72011-02-10 07:01:55 +00002216Constant *ConstantExpr::getMul(Constant *C1, Constant *C2,
2217 bool HasNUW, bool HasNSW) {
2218 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2219 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2220 return get(Instruction::Mul, C1, C2, Flags);
Owen Anderson487375e2009-07-29 18:55:55 +00002221}
2222
Chris Lattnera676c0f2011-02-07 16:40:21 +00002223Constant *ConstantExpr::getFMul(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002224 return get(Instruction::FMul, C1, C2);
2225}
2226
Chris Lattner0d75eac2011-02-09 16:43:07 +00002227Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2, bool isExact) {
2228 return get(Instruction::UDiv, C1, C2,
2229 isExact ? PossiblyExactOperator::IsExact : 0);
Owen Anderson487375e2009-07-29 18:55:55 +00002230}
2231
Chris Lattner0d75eac2011-02-09 16:43:07 +00002232Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2, bool isExact) {
2233 return get(Instruction::SDiv, C1, C2,
2234 isExact ? PossiblyExactOperator::IsExact : 0);
Owen Anderson487375e2009-07-29 18:55:55 +00002235}
2236
Chris Lattnera676c0f2011-02-07 16:40:21 +00002237Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002238 return get(Instruction::FDiv, C1, C2);
2239}
2240
Chris Lattnera676c0f2011-02-07 16:40:21 +00002241Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002242 return get(Instruction::URem, C1, C2);
2243}
2244
Chris Lattnera676c0f2011-02-07 16:40:21 +00002245Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002246 return get(Instruction::SRem, C1, C2);
2247}
2248
Chris Lattnera676c0f2011-02-07 16:40:21 +00002249Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002250 return get(Instruction::FRem, C1, C2);
2251}
2252
Chris Lattnera676c0f2011-02-07 16:40:21 +00002253Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002254 return get(Instruction::And, C1, C2);
2255}
2256
Chris Lattnera676c0f2011-02-07 16:40:21 +00002257Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002258 return get(Instruction::Or, C1, C2);
2259}
2260
Chris Lattnera676c0f2011-02-07 16:40:21 +00002261Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002262 return get(Instruction::Xor, C1, C2);
2263}
2264
Chris Lattnere9b4ad72011-02-10 07:01:55 +00002265Constant *ConstantExpr::getShl(Constant *C1, Constant *C2,
2266 bool HasNUW, bool HasNSW) {
2267 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2268 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2269 return get(Instruction::Shl, C1, C2, Flags);
Owen Anderson487375e2009-07-29 18:55:55 +00002270}
2271
Chris Lattner0d75eac2011-02-09 16:43:07 +00002272Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2, bool isExact) {
2273 return get(Instruction::LShr, C1, C2,
2274 isExact ? PossiblyExactOperator::IsExact : 0);
Owen Anderson487375e2009-07-29 18:55:55 +00002275}
2276
Chris Lattner0d75eac2011-02-09 16:43:07 +00002277Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2, bool isExact) {
2278 return get(Instruction::AShr, C1, C2,
2279 isExact ? PossiblyExactOperator::IsExact : 0);
Owen Anderson487375e2009-07-29 18:55:55 +00002280}
2281
Duncan Sandsd7aeefe2012-06-12 14:33:56 +00002282/// getBinOpIdentity - Return the identity for the given binary operation,
2283/// 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 +00002284/// returns null if the operator doesn't have an identity.
Duncan Sandsd7aeefe2012-06-12 14:33:56 +00002285Constant *ConstantExpr::getBinOpIdentity(unsigned Opcode, Type *Ty) {
2286 switch (Opcode) {
2287 default:
Duncan Sands318a89d2012-06-13 09:42:13 +00002288 // Doesn't have an identity.
Craig Topperc6207612014-04-09 06:08:46 +00002289 return nullptr;
Duncan Sands318a89d2012-06-13 09:42:13 +00002290
Duncan Sandsd7aeefe2012-06-12 14:33:56 +00002291 case Instruction::Add:
2292 case Instruction::Or:
2293 case Instruction::Xor:
2294 return Constant::getNullValue(Ty);
2295
2296 case Instruction::Mul:
2297 return ConstantInt::get(Ty, 1);
2298
2299 case Instruction::And:
2300 return Constant::getAllOnesValue(Ty);
2301 }
2302}
2303
Duncan Sands318a89d2012-06-13 09:42:13 +00002304/// getBinOpAbsorber - Return the absorbing element for the given binary
2305/// operation, i.e. a constant C such that X op C = C and C op X = C for
2306/// every X. For example, this returns zero for integer multiplication.
2307/// It returns null if the operator doesn't have an absorbing element.
2308Constant *ConstantExpr::getBinOpAbsorber(unsigned Opcode, Type *Ty) {
2309 switch (Opcode) {
2310 default:
2311 // Doesn't have an absorber.
Craig Topperc6207612014-04-09 06:08:46 +00002312 return nullptr;
Duncan Sands318a89d2012-06-13 09:42:13 +00002313
2314 case Instruction::Or:
2315 return Constant::getAllOnesValue(Ty);
2316
2317 case Instruction::And:
2318 case Instruction::Mul:
2319 return Constant::getNullValue(Ty);
2320 }
2321}
2322
Vikram S. Adve4c485332002-07-15 18:19:33 +00002323// destroyConstant - Remove the constant from the constant table...
2324//
Pete Cooper86dd4cf2015-06-23 21:55:11 +00002325void ConstantExpr::destroyConstantImpl() {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002326 getType()->getContext().pImpl->ExprConstants.remove(this);
Vikram S. Adve4e537b22002-07-14 23:13:17 +00002327}
2328
Chris Lattner3cd8c562002-07-30 18:54:25 +00002329const char *ConstantExpr::getOpcodeName() const {
2330 return Instruction::getOpcodeName(getOpcode());
Vikram S. Adve4e537b22002-07-14 23:13:17 +00002331}
Reid Spencer1ebe1ab2004-07-17 23:48:33 +00002332
David Blaikie60310f22015-05-08 00:42:26 +00002333GetElementPtrConstantExpr::GetElementPtrConstantExpr(
2334 Type *SrcElementTy, Constant *C, ArrayRef<Constant *> IdxList, Type *DestTy)
2335 : ConstantExpr(DestTy, Instruction::GetElementPtr,
2336 OperandTraits<GetElementPtrConstantExpr>::op_end(this) -
2337 (IdxList.size() + 1),
2338 IdxList.size() + 1),
2339 SrcElementTy(SrcElementTy) {
Pete Coopereb31b682015-05-21 22:48:54 +00002340 Op<0>() = C;
Pete Cooper74510a42015-06-12 17:48:05 +00002341 Use *OperandList = getOperandList();
Chris Lattnera3b94ba2010-03-30 20:48:48 +00002342 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
2343 OperandList[i+1] = IdxList[i];
2344}
2345
David Blaikie60310f22015-05-08 00:42:26 +00002346Type *GetElementPtrConstantExpr::getSourceElementType() const {
2347 return SrcElementTy;
2348}
2349
Chris Lattner3756b912012-01-23 22:57:10 +00002350//===----------------------------------------------------------------------===//
2351// ConstantData* implementations
2352
2353void ConstantDataArray::anchor() {}
2354void ConstantDataVector::anchor() {}
2355
Chris Lattnere4f3f102012-01-24 04:43:41 +00002356/// getElementType - Return the element type of the array/vector.
2357Type *ConstantDataSequential::getElementType() const {
2358 return getType()->getElementType();
2359}
2360
Chris Lattner5d4497b2012-01-24 09:31:43 +00002361StringRef ConstantDataSequential::getRawDataValues() const {
Chris Lattner00245f42012-01-24 13:41:11 +00002362 return StringRef(DataElements, getNumElements()*getElementByteSize());
Chris Lattner5d4497b2012-01-24 09:31:43 +00002363}
2364
Chris Lattner030af792012-01-24 05:42:11 +00002365/// isElementTypeCompatible - Return true if a ConstantDataSequential can be
2366/// formed with a vector or array of the specified element type.
2367/// ConstantDataArray only works with normal float and int types that are
2368/// stored densely in memory, not with things like i42 or x86_f80.
Craig Toppere3dcce92015-08-01 22:20:21 +00002369bool ConstantDataSequential::isElementTypeCompatible(Type *Ty) {
Justin Bogner0ebc8602015-12-08 03:01:16 +00002370 if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy()) return true;
Craig Toppere3dcce92015-08-01 22:20:21 +00002371 if (auto *IT = dyn_cast<IntegerType>(Ty)) {
Chris Lattnere4f3f102012-01-24 04:43:41 +00002372 switch (IT->getBitWidth()) {
2373 case 8:
2374 case 16:
2375 case 32:
2376 case 64:
2377 return true;
2378 default: break;
2379 }
2380 }
2381 return false;
2382}
2383
Chris Lattner00245f42012-01-24 13:41:11 +00002384/// getNumElements - Return the number of elements in the array or vector.
2385unsigned ConstantDataSequential::getNumElements() const {
Chris Lattner8a3df542012-01-25 01:32:59 +00002386 if (ArrayType *AT = dyn_cast<ArrayType>(getType()))
2387 return AT->getNumElements();
Chris Lattner8326bd82012-01-26 00:42:34 +00002388 return getType()->getVectorNumElements();
Chris Lattner00245f42012-01-24 13:41:11 +00002389}
2390
2391
Chris Lattnere4f3f102012-01-24 04:43:41 +00002392/// getElementByteSize - Return the size in bytes of the elements in the data.
2393uint64_t ConstantDataSequential::getElementByteSize() const {
2394 return getElementType()->getPrimitiveSizeInBits()/8;
2395}
2396
2397/// getElementPointer - Return the start of the specified element.
2398const char *ConstantDataSequential::getElementPointer(unsigned Elt) const {
Chris Lattner00245f42012-01-24 13:41:11 +00002399 assert(Elt < getNumElements() && "Invalid Elt");
Chris Lattnere4f3f102012-01-24 04:43:41 +00002400 return DataElements+Elt*getElementByteSize();
2401}
2402
2403
Chris Lattner3756b912012-01-23 22:57:10 +00002404/// isAllZeros - return true if the array is empty or all zeros.
2405static bool isAllZeros(StringRef Arr) {
2406 for (StringRef::iterator I = Arr.begin(), E = Arr.end(); I != E; ++I)
2407 if (*I != 0)
2408 return false;
2409 return true;
2410}
Chris Lattner030af792012-01-24 05:42:11 +00002411
Chris Lattner3756b912012-01-23 22:57:10 +00002412/// getImpl - This is the underlying implementation of all of the
2413/// ConstantDataSequential::get methods. They all thunk down to here, providing
Chris Lattnerf06039b2012-01-30 18:19:30 +00002414/// the correct element type. We take the bytes in as a StringRef because
Chris Lattner3756b912012-01-23 22:57:10 +00002415/// we *want* an underlying "char*" to avoid TBAA type punning violations.
2416Constant *ConstantDataSequential::getImpl(StringRef Elements, Type *Ty) {
Chris Lattner8326bd82012-01-26 00:42:34 +00002417 assert(isElementTypeCompatible(Ty->getSequentialElementType()));
Chris Lattner139822f2012-01-24 14:17:05 +00002418 // If the elements are all zero or there are no elements, return a CAZ, which
2419 // is more dense and canonical.
Chris Lattner3756b912012-01-23 22:57:10 +00002420 if (isAllZeros(Elements))
2421 return ConstantAggregateZero::get(Ty);
2422
2423 // Do a lookup to see if we have already formed one of these.
David Blaikie5106ce72014-11-19 05:49:42 +00002424 auto &Slot =
2425 *Ty->getContext()
2426 .pImpl->CDSConstants.insert(std::make_pair(Elements, nullptr))
2427 .first;
Galina Kistanovafc259902012-07-13 01:25:27 +00002428
Chris Lattner3756b912012-01-23 22:57:10 +00002429 // The bucket can point to a linked list of different CDS's that have the same
2430 // body but different types. For example, 0,0,0,1 could be a 4 element array
2431 // of i8, or a 1-element array of i32. They'll both end up in the same
2432 /// StringMap bucket, linked up by their Next pointers. Walk the list.
David Blaikie5106ce72014-11-19 05:49:42 +00002433 ConstantDataSequential **Entry = &Slot.second;
Craig Topperc6207612014-04-09 06:08:46 +00002434 for (ConstantDataSequential *Node = *Entry; Node;
Chris Lattner3756b912012-01-23 22:57:10 +00002435 Entry = &Node->Next, Node = *Entry)
2436 if (Node->getType() == Ty)
2437 return Node;
Galina Kistanovafc259902012-07-13 01:25:27 +00002438
Chris Lattner3756b912012-01-23 22:57:10 +00002439 // Okay, we didn't get a hit. Create a node of the right class, link it in,
2440 // and return it.
2441 if (isa<ArrayType>(Ty))
David Blaikie5106ce72014-11-19 05:49:42 +00002442 return *Entry = new ConstantDataArray(Ty, Slot.first().data());
Chris Lattner3756b912012-01-23 22:57:10 +00002443
2444 assert(isa<VectorType>(Ty));
David Blaikie5106ce72014-11-19 05:49:42 +00002445 return *Entry = new ConstantDataVector(Ty, Slot.first().data());
Chris Lattner3756b912012-01-23 22:57:10 +00002446}
2447
Pete Cooper86dd4cf2015-06-23 21:55:11 +00002448void ConstantDataSequential::destroyConstantImpl() {
Chris Lattner3756b912012-01-23 22:57:10 +00002449 // Remove the constant from the StringMap.
2450 StringMap<ConstantDataSequential*> &CDSConstants =
2451 getType()->getContext().pImpl->CDSConstants;
Galina Kistanovafc259902012-07-13 01:25:27 +00002452
Chris Lattner3756b912012-01-23 22:57:10 +00002453 StringMap<ConstantDataSequential*>::iterator Slot =
Chris Lattner5d4497b2012-01-24 09:31:43 +00002454 CDSConstants.find(getRawDataValues());
Chris Lattner3756b912012-01-23 22:57:10 +00002455
2456 assert(Slot != CDSConstants.end() && "CDS not found in uniquing table");
2457
2458 ConstantDataSequential **Entry = &Slot->getValue();
2459
2460 // Remove the entry from the hash table.
Craig Topperc6207612014-04-09 06:08:46 +00002461 if (!(*Entry)->Next) {
Chris Lattner3756b912012-01-23 22:57:10 +00002462 // If there is only one value in the bucket (common case) it must be this
2463 // entry, and removing the entry should remove the bucket completely.
2464 assert((*Entry) == this && "Hash mismatch in ConstantDataSequential");
2465 getContext().pImpl->CDSConstants.erase(Slot);
2466 } else {
2467 // Otherwise, there are multiple entries linked off the bucket, unlink the
2468 // node we care about but keep the bucket around.
2469 for (ConstantDataSequential *Node = *Entry; ;
2470 Entry = &Node->Next, Node = *Entry) {
2471 assert(Node && "Didn't find entry in its uniquing hash table!");
2472 // If we found our entry, unlink it from the list and we're done.
2473 if (Node == this) {
2474 *Entry = Node->Next;
2475 break;
2476 }
2477 }
2478 }
Galina Kistanovafc259902012-07-13 01:25:27 +00002479
Chris Lattner3756b912012-01-23 22:57:10 +00002480 // If we were part of a list, make sure that we don't delete the list that is
2481 // still owned by the uniquing map.
Craig Topperc6207612014-04-09 06:08:46 +00002482 Next = nullptr;
Chris Lattner3756b912012-01-23 22:57:10 +00002483}
2484
2485/// get() constructors - Return a constant with array type with an element
2486/// count and element type matching the ArrayRef passed in. Note that this
2487/// can return a ConstantAggregateZero object.
Chris Lattner20683932012-01-24 14:04:40 +00002488Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint8_t> Elts) {
Chris Lattner3756b912012-01-23 22:57:10 +00002489 Type *Ty = ArrayType::get(Type::getInt8Ty(Context), Elts.size());
Galina Kistanovafc259902012-07-13 01:25:27 +00002490 const char *Data = reinterpret_cast<const char *>(Elts.data());
2491 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*1), Ty);
Chris Lattner3756b912012-01-23 22:57:10 +00002492}
Chris Lattner20683932012-01-24 14:04:40 +00002493Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint16_t> Elts){
Chris Lattner3756b912012-01-23 22:57:10 +00002494 Type *Ty = ArrayType::get(Type::getInt16Ty(Context), Elts.size());
Galina Kistanovafc259902012-07-13 01:25:27 +00002495 const char *Data = reinterpret_cast<const char *>(Elts.data());
2496 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*2), Ty);
Chris Lattner3756b912012-01-23 22:57:10 +00002497}
Chris Lattner20683932012-01-24 14:04:40 +00002498Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint32_t> Elts){
Chris Lattner3756b912012-01-23 22:57:10 +00002499 Type *Ty = ArrayType::get(Type::getInt32Ty(Context), Elts.size());
Galina Kistanovafc259902012-07-13 01:25:27 +00002500 const char *Data = reinterpret_cast<const char *>(Elts.data());
2501 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*4), Ty);
Chris Lattner3756b912012-01-23 22:57:10 +00002502}
Chris Lattner20683932012-01-24 14:04:40 +00002503Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint64_t> Elts){
Chris Lattner3756b912012-01-23 22:57:10 +00002504 Type *Ty = ArrayType::get(Type::getInt64Ty(Context), Elts.size());
Galina Kistanovafc259902012-07-13 01:25:27 +00002505 const char *Data = reinterpret_cast<const char *>(Elts.data());
2506 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*8), Ty);
Chris Lattner3756b912012-01-23 22:57:10 +00002507}
Chris Lattner20683932012-01-24 14:04:40 +00002508Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<float> Elts) {
Chris Lattner3756b912012-01-23 22:57:10 +00002509 Type *Ty = ArrayType::get(Type::getFloatTy(Context), Elts.size());
Galina Kistanovafc259902012-07-13 01:25:27 +00002510 const char *Data = reinterpret_cast<const char *>(Elts.data());
2511 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*4), Ty);
Chris Lattner3756b912012-01-23 22:57:10 +00002512}
Chris Lattner20683932012-01-24 14:04:40 +00002513Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<double> Elts) {
Chris Lattner3756b912012-01-23 22:57:10 +00002514 Type *Ty = ArrayType::get(Type::getDoubleTy(Context), Elts.size());
Galina Kistanovafc259902012-07-13 01:25:27 +00002515 const char *Data = reinterpret_cast<const char *>(Elts.data());
Rafael Espindola8c97e192015-02-19 16:08:20 +00002516 return getImpl(StringRef(const_cast<char *>(Data), Elts.size() * 8), Ty);
2517}
2518
2519/// getFP() constructors - Return a constant with array type with an element
2520/// count and element type of float with precision matching the number of
2521/// bits in the ArrayRef passed in. (i.e. half for 16bits, float for 32bits,
2522/// double for 64bits) Note that this can return a ConstantAggregateZero
2523/// object.
2524Constant *ConstantDataArray::getFP(LLVMContext &Context,
2525 ArrayRef<uint16_t> Elts) {
Justin Bognerb7389d6712015-12-09 21:21:07 +00002526 Type *Ty = ArrayType::get(Type::getHalfTy(Context), Elts.size());
Rafael Espindola8c97e192015-02-19 16:08:20 +00002527 const char *Data = reinterpret_cast<const char *>(Elts.data());
2528 return getImpl(StringRef(const_cast<char *>(Data), Elts.size() * 2), Ty);
2529}
2530Constant *ConstantDataArray::getFP(LLVMContext &Context,
2531 ArrayRef<uint32_t> Elts) {
2532 Type *Ty = ArrayType::get(Type::getFloatTy(Context), Elts.size());
2533 const char *Data = reinterpret_cast<const char *>(Elts.data());
2534 return getImpl(StringRef(const_cast<char *>(Data), Elts.size() * 4), Ty);
2535}
2536Constant *ConstantDataArray::getFP(LLVMContext &Context,
2537 ArrayRef<uint64_t> Elts) {
2538 Type *Ty = ArrayType::get(Type::getDoubleTy(Context), Elts.size());
2539 const char *Data = reinterpret_cast<const char *>(Elts.data());
2540 return getImpl(StringRef(const_cast<char *>(Data), Elts.size() * 8), Ty);
Chris Lattner3756b912012-01-23 22:57:10 +00002541}
2542
Chris Lattner20683932012-01-24 14:04:40 +00002543/// getString - This method constructs a CDS and initializes it with a text
2544/// string. The default behavior (AddNull==true) causes a null terminator to
2545/// be placed at the end of the array (increasing the length of the string by
2546/// one more than the StringRef would normally indicate. Pass AddNull=false
2547/// to disable this behavior.
2548Constant *ConstantDataArray::getString(LLVMContext &Context,
2549 StringRef Str, bool AddNull) {
Galina Kistanovafc259902012-07-13 01:25:27 +00002550 if (!AddNull) {
2551 const uint8_t *Data = reinterpret_cast<const uint8_t *>(Str.data());
Craig Toppere1d12942014-08-27 05:25:25 +00002552 return get(Context, makeArrayRef(const_cast<uint8_t *>(Data),
Galina Kistanovafc259902012-07-13 01:25:27 +00002553 Str.size()));
2554 }
2555
Chris Lattner20683932012-01-24 14:04:40 +00002556 SmallVector<uint8_t, 64> ElementVals;
2557 ElementVals.append(Str.begin(), Str.end());
2558 ElementVals.push_back(0);
2559 return get(Context, ElementVals);
2560}
Chris Lattner3756b912012-01-23 22:57:10 +00002561
2562/// get() constructors - Return a constant with vector type with an element
2563/// count and element type matching the ArrayRef passed in. Note that this
2564/// can return a ConstantAggregateZero object.
Chris Lattner20683932012-01-24 14:04:40 +00002565Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint8_t> Elts){
Chris Lattner3756b912012-01-23 22:57:10 +00002566 Type *Ty = VectorType::get(Type::getInt8Ty(Context), Elts.size());
Galina Kistanovafc259902012-07-13 01:25:27 +00002567 const char *Data = reinterpret_cast<const char *>(Elts.data());
2568 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*1), Ty);
Chris Lattner3756b912012-01-23 22:57:10 +00002569}
Chris Lattner20683932012-01-24 14:04:40 +00002570Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint16_t> Elts){
Chris Lattner3756b912012-01-23 22:57:10 +00002571 Type *Ty = VectorType::get(Type::getInt16Ty(Context), Elts.size());
Galina Kistanovafc259902012-07-13 01:25:27 +00002572 const char *Data = reinterpret_cast<const char *>(Elts.data());
2573 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*2), Ty);
Chris Lattner3756b912012-01-23 22:57:10 +00002574}
Chris Lattner20683932012-01-24 14:04:40 +00002575Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint32_t> Elts){
Chris Lattner3756b912012-01-23 22:57:10 +00002576 Type *Ty = VectorType::get(Type::getInt32Ty(Context), Elts.size());
Galina Kistanovafc259902012-07-13 01:25:27 +00002577 const char *Data = reinterpret_cast<const char *>(Elts.data());
2578 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*4), Ty);
Chris Lattner3756b912012-01-23 22:57:10 +00002579}
Chris Lattner20683932012-01-24 14:04:40 +00002580Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint64_t> Elts){
Chris Lattner3756b912012-01-23 22:57:10 +00002581 Type *Ty = VectorType::get(Type::getInt64Ty(Context), Elts.size());
Galina Kistanovafc259902012-07-13 01:25:27 +00002582 const char *Data = reinterpret_cast<const char *>(Elts.data());
2583 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*8), Ty);
Chris Lattner3756b912012-01-23 22:57:10 +00002584}
Chris Lattner20683932012-01-24 14:04:40 +00002585Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<float> Elts) {
Chris Lattner3756b912012-01-23 22:57:10 +00002586 Type *Ty = VectorType::get(Type::getFloatTy(Context), Elts.size());
Galina Kistanovafc259902012-07-13 01:25:27 +00002587 const char *Data = reinterpret_cast<const char *>(Elts.data());
2588 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*4), Ty);
Chris Lattner3756b912012-01-23 22:57:10 +00002589}
Chris Lattner20683932012-01-24 14:04:40 +00002590Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<double> Elts) {
Chris Lattner3756b912012-01-23 22:57:10 +00002591 Type *Ty = VectorType::get(Type::getDoubleTy(Context), Elts.size());
Galina Kistanovafc259902012-07-13 01:25:27 +00002592 const char *Data = reinterpret_cast<const char *>(Elts.data());
Rafael Espindola8c97e192015-02-19 16:08:20 +00002593 return getImpl(StringRef(const_cast<char *>(Data), Elts.size() * 8), Ty);
2594}
2595
2596/// getFP() constructors - Return a constant with vector type with an element
2597/// count and element type of float with the precision matching the number of
2598/// bits in the ArrayRef passed in. (i.e. half for 16bits, float for 32bits,
2599/// double for 64bits) Note that this can return a ConstantAggregateZero
2600/// object.
2601Constant *ConstantDataVector::getFP(LLVMContext &Context,
2602 ArrayRef<uint16_t> Elts) {
2603 Type *Ty = VectorType::get(Type::getHalfTy(Context), Elts.size());
2604 const char *Data = reinterpret_cast<const char *>(Elts.data());
2605 return getImpl(StringRef(const_cast<char *>(Data), Elts.size() * 2), Ty);
2606}
2607Constant *ConstantDataVector::getFP(LLVMContext &Context,
2608 ArrayRef<uint32_t> Elts) {
2609 Type *Ty = VectorType::get(Type::getFloatTy(Context), Elts.size());
2610 const char *Data = reinterpret_cast<const char *>(Elts.data());
2611 return getImpl(StringRef(const_cast<char *>(Data), Elts.size() * 4), Ty);
2612}
2613Constant *ConstantDataVector::getFP(LLVMContext &Context,
2614 ArrayRef<uint64_t> Elts) {
2615 Type *Ty = VectorType::get(Type::getDoubleTy(Context), Elts.size());
2616 const char *Data = reinterpret_cast<const char *>(Elts.data());
2617 return getImpl(StringRef(const_cast<char *>(Data), Elts.size() * 8), Ty);
Chris Lattner3756b912012-01-23 22:57:10 +00002618}
2619
Chris Lattnere9eed292012-01-25 05:19:54 +00002620Constant *ConstantDataVector::getSplat(unsigned NumElts, Constant *V) {
2621 assert(isElementTypeCompatible(V->getType()) &&
2622 "Element type not compatible with ConstantData");
2623 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
2624 if (CI->getType()->isIntegerTy(8)) {
2625 SmallVector<uint8_t, 16> Elts(NumElts, CI->getZExtValue());
2626 return get(V->getContext(), Elts);
2627 }
2628 if (CI->getType()->isIntegerTy(16)) {
2629 SmallVector<uint16_t, 16> Elts(NumElts, CI->getZExtValue());
2630 return get(V->getContext(), Elts);
2631 }
2632 if (CI->getType()->isIntegerTy(32)) {
2633 SmallVector<uint32_t, 16> Elts(NumElts, CI->getZExtValue());
2634 return get(V->getContext(), Elts);
2635 }
2636 assert(CI->getType()->isIntegerTy(64) && "Unsupported ConstantData type");
2637 SmallVector<uint64_t, 16> Elts(NumElts, CI->getZExtValue());
2638 return get(V->getContext(), Elts);
2639 }
2640
Chris Lattner978fe0c2012-01-30 06:21:21 +00002641 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
Justin Bogner0ebc8602015-12-08 03:01:16 +00002642 if (CFP->getType()->isHalfTy()) {
2643 SmallVector<uint16_t, 16> Elts(
2644 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
2645 return getFP(V->getContext(), Elts);
2646 }
Chris Lattner978fe0c2012-01-30 06:21:21 +00002647 if (CFP->getType()->isFloatTy()) {
Rafael Espindola8c97e192015-02-19 16:08:20 +00002648 SmallVector<uint32_t, 16> Elts(
2649 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
2650 return getFP(V->getContext(), Elts);
Chris Lattner978fe0c2012-01-30 06:21:21 +00002651 }
2652 if (CFP->getType()->isDoubleTy()) {
Rafael Espindola8c97e192015-02-19 16:08:20 +00002653 SmallVector<uint64_t, 16> Elts(
2654 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
2655 return getFP(V->getContext(), Elts);
Chris Lattner978fe0c2012-01-30 06:21:21 +00002656 }
Chris Lattnere9eed292012-01-25 05:19:54 +00002657 }
Chris Lattner978fe0c2012-01-30 06:21:21 +00002658 return ConstantVector::getSplat(NumElts, V);
Chris Lattnere9eed292012-01-25 05:19:54 +00002659}
2660
2661
Chris Lattnere4f3f102012-01-24 04:43:41 +00002662/// getElementAsInteger - If this is a sequential container of integers (of
2663/// any size), return the specified element in the low bits of a uint64_t.
2664uint64_t ConstantDataSequential::getElementAsInteger(unsigned Elt) const {
2665 assert(isa<IntegerType>(getElementType()) &&
2666 "Accessor can only be used when element is an integer");
2667 const char *EltPtr = getElementPointer(Elt);
Galina Kistanovafc259902012-07-13 01:25:27 +00002668
Chris Lattnere4f3f102012-01-24 04:43:41 +00002669 // The data is stored in host byte order, make sure to cast back to the right
2670 // type to load with the right endianness.
Chris Lattner8326bd82012-01-26 00:42:34 +00002671 switch (getElementType()->getIntegerBitWidth()) {
Craig Topperc514b542012-02-05 22:14:15 +00002672 default: llvm_unreachable("Invalid bitwidth for CDS");
Galina Kistanovafc259902012-07-13 01:25:27 +00002673 case 8:
2674 return *const_cast<uint8_t *>(reinterpret_cast<const uint8_t *>(EltPtr));
2675 case 16:
2676 return *const_cast<uint16_t *>(reinterpret_cast<const uint16_t *>(EltPtr));
2677 case 32:
2678 return *const_cast<uint32_t *>(reinterpret_cast<const uint32_t *>(EltPtr));
2679 case 64:
2680 return *const_cast<uint64_t *>(reinterpret_cast<const uint64_t *>(EltPtr));
Chris Lattnere4f3f102012-01-24 04:43:41 +00002681 }
2682}
2683
2684/// getElementAsAPFloat - If this is a sequential container of floating point
2685/// type, return the specified element as an APFloat.
2686APFloat ConstantDataSequential::getElementAsAPFloat(unsigned Elt) const {
2687 const char *EltPtr = getElementPointer(Elt);
2688
2689 switch (getElementType()->getTypeID()) {
Nick Lewyckyff509622012-01-25 03:20:12 +00002690 default:
Craig Topperc514b542012-02-05 22:14:15 +00002691 llvm_unreachable("Accessor can only be used when element is float/double!");
Justin Bogner0ebc8602015-12-08 03:01:16 +00002692 case Type::HalfTyID: {
2693 auto EltVal = *reinterpret_cast<const uint16_t *>(EltPtr);
2694 return APFloat(APFloat::IEEEhalf, APInt(16, EltVal));
2695 }
Benjamin Kramer7af984b2015-02-20 15:11:55 +00002696 case Type::FloatTyID: {
2697 auto EltVal = *reinterpret_cast<const uint32_t *>(EltPtr);
NAKAMURA Takumie86b9b72015-02-20 14:24:49 +00002698 return APFloat(APFloat::IEEEsingle, APInt(32, EltVal));
Benjamin Kramer7af984b2015-02-20 15:11:55 +00002699 }
2700 case Type::DoubleTyID: {
2701 auto EltVal = *reinterpret_cast<const uint64_t *>(EltPtr);
NAKAMURA Takumie86b9b72015-02-20 14:24:49 +00002702 return APFloat(APFloat::IEEEdouble, APInt(64, EltVal));
Chris Lattnere4f3f102012-01-24 04:43:41 +00002703 }
Benjamin Kramer7af984b2015-02-20 15:11:55 +00002704 }
Chris Lattnere4f3f102012-01-24 04:43:41 +00002705}
2706
2707/// getElementAsFloat - If this is an sequential container of floats, return
2708/// the specified element as a float.
2709float ConstantDataSequential::getElementAsFloat(unsigned Elt) const {
2710 assert(getElementType()->isFloatTy() &&
2711 "Accessor can only be used when element is a 'float'");
Galina Kistanovafc259902012-07-13 01:25:27 +00002712 const float *EltPtr = reinterpret_cast<const float *>(getElementPointer(Elt));
2713 return *const_cast<float *>(EltPtr);
Chris Lattnere4f3f102012-01-24 04:43:41 +00002714}
2715
2716/// getElementAsDouble - If this is an sequential container of doubles, return
2717/// the specified element as a float.
2718double ConstantDataSequential::getElementAsDouble(unsigned Elt) const {
2719 assert(getElementType()->isDoubleTy() &&
2720 "Accessor can only be used when element is a 'float'");
Galina Kistanovafc259902012-07-13 01:25:27 +00002721 const double *EltPtr =
2722 reinterpret_cast<const double *>(getElementPointer(Elt));
2723 return *const_cast<double *>(EltPtr);
Chris Lattnere4f3f102012-01-24 04:43:41 +00002724}
2725
2726/// getElementAsConstant - Return a Constant for a specified index's element.
2727/// Note that this has to compute a new constant to return, so it isn't as
2728/// efficient as getElementAsInteger/Float/Double.
2729Constant *ConstantDataSequential::getElementAsConstant(unsigned Elt) const {
Justin Bogner0ebc8602015-12-08 03:01:16 +00002730 if (getElementType()->isHalfTy() || getElementType()->isFloatTy() ||
2731 getElementType()->isDoubleTy())
Chris Lattnere4f3f102012-01-24 04:43:41 +00002732 return ConstantFP::get(getContext(), getElementAsAPFloat(Elt));
Galina Kistanovafc259902012-07-13 01:25:27 +00002733
Chris Lattnere4f3f102012-01-24 04:43:41 +00002734 return ConstantInt::get(getElementType(), getElementAsInteger(Elt));
2735}
2736
Chris Lattner5dd4d872012-01-24 09:01:07 +00002737/// isString - This method returns true if this is an array of i8.
2738bool ConstantDataSequential::isString() const {
2739 return isa<ArrayType>(getType()) && getElementType()->isIntegerTy(8);
2740}
Chris Lattner3756b912012-01-23 22:57:10 +00002741
Chris Lattner5dd4d872012-01-24 09:01:07 +00002742/// isCString - This method returns true if the array "isString", ends with a
2743/// nul byte, and does not contains any other nul bytes.
2744bool ConstantDataSequential::isCString() const {
2745 if (!isString())
2746 return false;
Galina Kistanovafc259902012-07-13 01:25:27 +00002747
Chris Lattner5dd4d872012-01-24 09:01:07 +00002748 StringRef Str = getAsString();
Galina Kistanovafc259902012-07-13 01:25:27 +00002749
Chris Lattner5dd4d872012-01-24 09:01:07 +00002750 // The last value must be nul.
2751 if (Str.back() != 0) return false;
Galina Kistanovafc259902012-07-13 01:25:27 +00002752
Chris Lattner5dd4d872012-01-24 09:01:07 +00002753 // Other elements must be non-nul.
2754 return Str.drop_back().find(0) == StringRef::npos;
2755}
Chris Lattner3756b912012-01-23 22:57:10 +00002756
Chris Lattnerf14a67f2012-01-26 02:31:22 +00002757/// getSplatValue - If this is a splat constant, meaning that all of the
Reid Kleckner971c3ea2014-11-13 22:55:19 +00002758/// elements have the same value, return that value. Otherwise return nullptr.
Chris Lattnerf14a67f2012-01-26 02:31:22 +00002759Constant *ConstantDataVector::getSplatValue() const {
2760 const char *Base = getRawDataValues().data();
Galina Kistanovafc259902012-07-13 01:25:27 +00002761
Chris Lattnerf14a67f2012-01-26 02:31:22 +00002762 // Compare elements 1+ to the 0'th element.
2763 unsigned EltSize = getElementByteSize();
2764 for (unsigned i = 1, e = getNumElements(); i != e; ++i)
2765 if (memcmp(Base, Base+i*EltSize, EltSize))
Craig Topperc6207612014-04-09 06:08:46 +00002766 return nullptr;
Galina Kistanovafc259902012-07-13 01:25:27 +00002767
Chris Lattnerf14a67f2012-01-26 02:31:22 +00002768 // If they're all the same, return the 0th one as a representative.
2769 return getElementAsConstant(0);
2770}
Chris Lattnera3b94ba2010-03-30 20:48:48 +00002771
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002772//===----------------------------------------------------------------------===//
Pete Cooper5815b1f2015-06-24 18:55:24 +00002773// handleOperandChange implementations
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002774
Pete Cooper5815b1f2015-06-24 18:55:24 +00002775/// Update this constant array to change uses of
Chris Lattner913849b2007-08-21 00:55:23 +00002776/// 'From' to be uses of 'To'. This must update the uniquing data structures
2777/// etc.
2778///
2779/// Note that we intentionally replace all uses of From with To here. Consider
2780/// a large array that uses 'From' 1000 times. By handling this case all here,
Pete Cooper5815b1f2015-06-24 18:55:24 +00002781/// ConstantArray::handleOperandChange is only invoked once, and that
Chris Lattner913849b2007-08-21 00:55:23 +00002782/// single invocation handles all 1000 uses. Handling them one at a time would
2783/// work, but would be really slow because it would have to unique each updated
2784/// array instance.
Chris Lattner31b132c2009-10-28 00:01:44 +00002785///
Pete Cooper5815b1f2015-06-24 18:55:24 +00002786void Constant::handleOperandChange(Value *From, Value *To, Use *U) {
2787 Value *Replacement = nullptr;
2788 switch (getValueID()) {
2789 default:
2790 llvm_unreachable("Not a constant!");
2791#define HANDLE_CONSTANT(Name) \
2792 case Value::Name##Val: \
2793 Replacement = cast<Name>(this)->handleOperandChangeImpl(From, To, U); \
2794 break;
2795#include "llvm/IR/Value.def"
2796 }
2797
2798 // If handleOperandChangeImpl returned nullptr, then it handled
2799 // replacing itself and we don't want to delete or replace anything else here.
2800 if (!Replacement)
2801 return;
2802
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002803 // I do need to replace this with an existing value.
2804 assert(Replacement != this && "I didn't contain From!");
2805
2806 // Everyone using this now uses the replacement.
2807 replaceAllUsesWith(Replacement);
2808
2809 // Delete the old constant!
2810 destroyConstant();
2811}
2812
Pete Cooper5815b1f2015-06-24 18:55:24 +00002813Value *ConstantInt::handleOperandChangeImpl(Value *From, Value *To, Use *U) {
2814 llvm_unreachable("Unsupported class for handleOperandChange()!");
2815}
2816
2817Value *ConstantFP::handleOperandChangeImpl(Value *From, Value *To, Use *U) {
2818 llvm_unreachable("Unsupported class for handleOperandChange()!");
2819}
2820
David Majnemerf0f224d2015-11-11 21:57:16 +00002821Value *ConstantTokenNone::handleOperandChangeImpl(Value *From, Value *To,
2822 Use *U) {
2823 llvm_unreachable("Unsupported class for handleOperandChange()!");
2824}
2825
Pete Cooper5815b1f2015-06-24 18:55:24 +00002826Value *UndefValue::handleOperandChangeImpl(Value *From, Value *To, Use *U) {
2827 llvm_unreachable("Unsupported class for handleOperandChange()!");
2828}
2829
2830Value *ConstantPointerNull::handleOperandChangeImpl(Value *From, Value *To,
2831 Use *U) {
2832 llvm_unreachable("Unsupported class for handleOperandChange()!");
2833}
2834
2835Value *ConstantAggregateZero::handleOperandChangeImpl(Value *From, Value *To,
2836 Use *U) {
2837 llvm_unreachable("Unsupported class for handleOperandChange()!");
2838}
2839
2840Value *ConstantDataSequential::handleOperandChangeImpl(Value *From, Value *To,
2841 Use *U) {
2842 llvm_unreachable("Unsupported class for handleOperandChange()!");
2843}
2844
2845Value *ConstantArray::handleOperandChangeImpl(Value *From, Value *To, Use *U) {
Owen Andersonc2c79322009-07-28 18:32:17 +00002846 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2847 Constant *ToC = cast<Constant>(To);
2848
Talin46e9b442012-02-05 20:54:10 +00002849 SmallVector<Constant*, 8> Values;
Owen Andersonc2c79322009-07-28 18:32:17 +00002850 Values.reserve(getNumOperands()); // Build replacement array.
2851
Galina Kistanovafc259902012-07-13 01:25:27 +00002852 // Fill values with the modified operands of the constant array. Also,
Owen Andersonc2c79322009-07-28 18:32:17 +00002853 // compute whether this turns into an all-zeros array.
Owen Andersonc2c79322009-07-28 18:32:17 +00002854 unsigned NumUpdated = 0;
Galina Kistanovafc259902012-07-13 01:25:27 +00002855
Chris Lattnerf14a67f2012-01-26 02:31:22 +00002856 // Keep track of whether all the values in the array are "ToC".
2857 bool AllSame = true;
Pete Cooper74510a42015-06-12 17:48:05 +00002858 Use *OperandList = getOperandList();
Chris Lattnerf14a67f2012-01-26 02:31:22 +00002859 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2860 Constant *Val = cast<Constant>(O->get());
2861 if (Val == From) {
2862 Val = ToC;
2863 ++NumUpdated;
Owen Andersonc2c79322009-07-28 18:32:17 +00002864 }
Chris Lattnerf14a67f2012-01-26 02:31:22 +00002865 Values.push_back(Val);
Talin46e9b442012-02-05 20:54:10 +00002866 AllSame &= Val == ToC;
Owen Andersonc2c79322009-07-28 18:32:17 +00002867 }
Galina Kistanovafc259902012-07-13 01:25:27 +00002868
Pete Cooper5815b1f2015-06-24 18:55:24 +00002869 if (AllSame && ToC->isNullValue())
2870 return ConstantAggregateZero::get(getType());
2871
2872 if (AllSame && isa<UndefValue>(ToC))
2873 return UndefValue::get(getType());
Aaron Ballmane4b91dc2014-08-19 14:59:02 +00002874
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002875 // Check for any other type of constant-folding.
Pete Cooper5815b1f2015-06-24 18:55:24 +00002876 if (Constant *C = getImpl(getType(), Values))
2877 return C;
Aaron Ballmane4b91dc2014-08-19 14:59:02 +00002878
Duncan P. N. Exon Smith909620a2014-08-19 19:13:30 +00002879 // Update to the new value.
Pete Cooper5815b1f2015-06-24 18:55:24 +00002880 return getContext().pImpl->ArrayConstants.replaceOperandsInPlace(
2881 Values, this, From, ToC, NumUpdated, U - OperandList);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002882}
2883
Pete Cooper5815b1f2015-06-24 18:55:24 +00002884Value *ConstantStruct::handleOperandChangeImpl(Value *From, Value *To, Use *U) {
Owen Anderson45308b52009-07-27 22:29:26 +00002885 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2886 Constant *ToC = cast<Constant>(To);
2887
Pete Cooper74510a42015-06-12 17:48:05 +00002888 Use *OperandList = getOperandList();
Owen Anderson45308b52009-07-27 22:29:26 +00002889 unsigned OperandToUpdate = U-OperandList;
2890 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
2891
Talin46e9b442012-02-05 20:54:10 +00002892 SmallVector<Constant*, 8> Values;
Owen Anderson45308b52009-07-27 22:29:26 +00002893 Values.reserve(getNumOperands()); // Build replacement struct.
Galina Kistanovafc259902012-07-13 01:25:27 +00002894
2895 // Fill values with the modified operands of the constant struct. Also,
Owen Anderson45308b52009-07-27 22:29:26 +00002896 // compute whether this turns into an all-zeros struct.
2897 bool isAllZeros = false;
Chris Lattnerf14a67f2012-01-26 02:31:22 +00002898 bool isAllUndef = false;
2899 if (ToC->isNullValue()) {
Owen Anderson45308b52009-07-27 22:29:26 +00002900 isAllZeros = true;
2901 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2902 Constant *Val = cast<Constant>(O->get());
2903 Values.push_back(Val);
2904 if (isAllZeros) isAllZeros = Val->isNullValue();
2905 }
Chris Lattnerf14a67f2012-01-26 02:31:22 +00002906 } else if (isa<UndefValue>(ToC)) {
2907 isAllUndef = true;
2908 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2909 Constant *Val = cast<Constant>(O->get());
2910 Values.push_back(Val);
2911 if (isAllUndef) isAllUndef = isa<UndefValue>(Val);
2912 }
2913 } else {
2914 for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O)
2915 Values.push_back(cast<Constant>(O->get()));
Owen Anderson45308b52009-07-27 22:29:26 +00002916 }
2917 Values[OperandToUpdate] = ToC;
Galina Kistanovafc259902012-07-13 01:25:27 +00002918
Pete Cooper5815b1f2015-06-24 18:55:24 +00002919 if (isAllZeros)
2920 return ConstantAggregateZero::get(getType());
2921
2922 if (isAllUndef)
2923 return UndefValue::get(getType());
Galina Kistanovafc259902012-07-13 01:25:27 +00002924
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002925 // Update to the new value.
Pete Cooper5815b1f2015-06-24 18:55:24 +00002926 return getContext().pImpl->StructConstants.replaceOperandsInPlace(
2927 Values, this, From, ToC);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002928}
2929
Pete Cooper5815b1f2015-06-24 18:55:24 +00002930Value *ConstantVector::handleOperandChangeImpl(Value *From, Value *To, Use *U) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002931 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002932 Constant *ToC = cast<Constant>(To);
Galina Kistanovafc259902012-07-13 01:25:27 +00002933
Chris Lattnera474bb22012-01-26 20:40:56 +00002934 SmallVector<Constant*, 8> Values;
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002935 Values.reserve(getNumOperands()); // Build replacement array...
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002936 unsigned NumUpdated = 0;
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002937 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2938 Constant *Val = getOperand(i);
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002939 if (Val == From) {
2940 ++NumUpdated;
2941 Val = ToC;
2942 }
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002943 Values.push_back(Val);
2944 }
Galina Kistanovafc259902012-07-13 01:25:27 +00002945
Pete Cooper5815b1f2015-06-24 18:55:24 +00002946 if (Constant *C = getImpl(Values))
2947 return C;
Duncan P. N. Exon Smith687744d2014-08-19 02:24:46 +00002948
Duncan P. N. Exon Smith909620a2014-08-19 19:13:30 +00002949 // Update to the new value.
Pete Cooper74510a42015-06-12 17:48:05 +00002950 Use *OperandList = getOperandList();
Pete Cooper5815b1f2015-06-24 18:55:24 +00002951 return getContext().pImpl->VectorConstants.replaceOperandsInPlace(
2952 Values, this, From, ToC, NumUpdated, U - OperandList);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002953}
2954
Pete Cooper5815b1f2015-06-24 18:55:24 +00002955Value *ConstantExpr::handleOperandChangeImpl(Value *From, Value *ToV, Use *U) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002956 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2957 Constant *To = cast<Constant>(ToV);
Galina Kistanovafc259902012-07-13 01:25:27 +00002958
Chris Lattner37e38352012-01-26 20:37:11 +00002959 SmallVector<Constant*, 8> NewOps;
Duncan P. N. Exon Smith33de00c2014-08-19 20:03:35 +00002960 unsigned NumUpdated = 0;
Chris Lattner37e38352012-01-26 20:37:11 +00002961 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2962 Constant *Op = getOperand(i);
Duncan P. N. Exon Smith33de00c2014-08-19 20:03:35 +00002963 if (Op == From) {
2964 ++NumUpdated;
2965 Op = To;
2966 }
2967 NewOps.push_back(Op);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002968 }
Duncan P. N. Exon Smith33de00c2014-08-19 20:03:35 +00002969 assert(NumUpdated && "I didn't contain From!");
Galina Kistanovafc259902012-07-13 01:25:27 +00002970
Pete Cooper5815b1f2015-06-24 18:55:24 +00002971 if (Constant *C = getWithOperands(NewOps, getType(), true))
2972 return C;
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002973
Duncan P. N. Exon Smith33de00c2014-08-19 20:03:35 +00002974 // Update to the new value.
Pete Cooper74510a42015-06-12 17:48:05 +00002975 Use *OperandList = getOperandList();
Pete Cooper5815b1f2015-06-24 18:55:24 +00002976 return getContext().pImpl->ExprConstants.replaceOperandsInPlace(
2977 NewOps, this, From, To, NumUpdated, U - OperandList);
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002978}
2979
James Molloyce545682012-11-17 17:56:30 +00002980Instruction *ConstantExpr::getAsInstruction() {
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +00002981 SmallVector<Value *, 4> ValueOperands(op_begin(), op_end());
James Molloyce545682012-11-17 17:56:30 +00002982 ArrayRef<Value*> Ops(ValueOperands);
2983
2984 switch (getOpcode()) {
2985 case Instruction::Trunc:
2986 case Instruction::ZExt:
2987 case Instruction::SExt:
2988 case Instruction::FPTrunc:
2989 case Instruction::FPExt:
2990 case Instruction::UIToFP:
2991 case Instruction::SIToFP:
2992 case Instruction::FPToUI:
2993 case Instruction::FPToSI:
2994 case Instruction::PtrToInt:
2995 case Instruction::IntToPtr:
2996 case Instruction::BitCast:
Eli Bendersky157a97a2014-01-18 22:54:33 +00002997 case Instruction::AddrSpaceCast:
James Molloyce545682012-11-17 17:56:30 +00002998 return CastInst::Create((Instruction::CastOps)getOpcode(),
2999 Ops[0], getType());
3000 case Instruction::Select:
3001 return SelectInst::Create(Ops[0], Ops[1], Ops[2]);
3002 case Instruction::InsertElement:
3003 return InsertElementInst::Create(Ops[0], Ops[1], Ops[2]);
3004 case Instruction::ExtractElement:
3005 return ExtractElementInst::Create(Ops[0], Ops[1]);
3006 case Instruction::InsertValue:
3007 return InsertValueInst::Create(Ops[0], Ops[1], getIndices());
3008 case Instruction::ExtractValue:
3009 return ExtractValueInst::Create(Ops[0], getIndices());
3010 case Instruction::ShuffleVector:
3011 return new ShuffleVectorInst(Ops[0], Ops[1], Ops[2]);
3012
David Blaikie741c8f82015-03-14 01:53:18 +00003013 case Instruction::GetElementPtr: {
3014 const auto *GO = cast<GEPOperator>(this);
3015 if (GO->isInBounds())
3016 return GetElementPtrInst::CreateInBounds(GO->getSourceElementType(),
3017 Ops[0], Ops.slice(1));
3018 return GetElementPtrInst::Create(GO->getSourceElementType(), Ops[0],
3019 Ops.slice(1));
3020 }
James Molloyce545682012-11-17 17:56:30 +00003021 case Instruction::ICmp:
3022 case Instruction::FCmp:
3023 return CmpInst::Create((Instruction::OtherOps)getOpcode(),
Craig Topper1c3f2832015-12-15 06:11:33 +00003024 (CmpInst::Predicate)getPredicate(), Ops[0], Ops[1]);
James Molloyce545682012-11-17 17:56:30 +00003025
3026 default:
3027 assert(getNumOperands() == 2 && "Must be binary operator?");
3028 BinaryOperator *BO =
3029 BinaryOperator::Create((Instruction::BinaryOps)getOpcode(),
3030 Ops[0], Ops[1]);
3031 if (isa<OverflowingBinaryOperator>(BO)) {
3032 BO->setHasNoUnsignedWrap(SubclassOptionalData &
3033 OverflowingBinaryOperator::NoUnsignedWrap);
3034 BO->setHasNoSignedWrap(SubclassOptionalData &
3035 OverflowingBinaryOperator::NoSignedWrap);
3036 }
3037 if (isa<PossiblyExactOperator>(BO))
3038 BO->setIsExact(SubclassOptionalData & PossiblyExactOperator::IsExact);
3039 return BO;
3040 }
3041}