blob: ad99c0a8587a824774e84c4484e03f833a1c8956 [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"
Chandler Carruthed0881b2012-12-03 16:50:05 +000017#include "llvm/ADT/STLExtras.h"
18#include "llvm/ADT/SmallVector.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000019#include "llvm/ADT/StringMap.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000020#include "llvm/IR/DerivedTypes.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000021#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000022#include "llvm/IR/GlobalValue.h"
23#include "llvm/IR/Instructions.h"
24#include "llvm/IR/Module.h"
25#include "llvm/IR/Operator.h"
Bill Wendling6a462f12006-11-17 08:03:48 +000026#include "llvm/Support/Debug.h"
Torok Edwinccb29cd2009-07-11 13:10:19 +000027#include "llvm/Support/ErrorHandling.h"
Chris Lattner69edc982006-09-28 00:35:06 +000028#include "llvm/Support/ManagedStatic.h"
Bill Wendling6a462f12006-11-17 08:03:48 +000029#include "llvm/Support/MathExtras.h"
Chris Lattner78683a72009-08-23 04:02:03 +000030#include "llvm/Support/raw_ostream.h"
Chris Lattner2f7c9632001-06-06 20:29:01 +000031#include <algorithm>
Serge Gueltone38003f2017-05-09 19:31:13 +000032
Chris Lattner189d19f2003-11-21 20:23:48 +000033using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000034
Chris Lattner2f7c9632001-06-06 20:29:01 +000035//===----------------------------------------------------------------------===//
Chris Lattner3462ae32001-12-03 22:26:30 +000036// Constant Class
Chris Lattner2f7c9632001-06-06 20:29:01 +000037//===----------------------------------------------------------------------===//
38
Chris Lattnerac5fb562011-07-15 05:58:04 +000039bool Constant::isNegativeZeroValue() const {
40 // Floating point values have an explicit -0.0 value.
41 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
42 return CFP->isZero() && CFP->isNegative();
Galina Kistanovafc259902012-07-13 01:25:27 +000043
David Tweed5493fee2013-03-18 11:54:44 +000044 // Equivalent for a vector of -0.0's.
45 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
Craig Topper0b4b4e32017-07-15 22:06:19 +000046 if (CV->getElementType()->isFloatingPointTy() && CV->isSplat())
47 if (CV->getElementAsAPFloat(0).isNegZero())
David Tweed5493fee2013-03-18 11:54:44 +000048 return true;
49
Owen Anderson8e851302015-11-20 22:34:48 +000050 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
51 if (ConstantFP *SplatCFP = dyn_cast_or_null<ConstantFP>(CV->getSplatValue()))
52 if (SplatCFP && SplatCFP->isZero() && SplatCFP->isNegative())
53 return true;
54
David Tweed298e4192013-03-19 10:16:40 +000055 // We've already handled true FP case; any other FP vectors can't represent -0.0.
56 if (getType()->isFPOrFPVectorTy())
57 return false;
David Tweed5493fee2013-03-18 11:54:44 +000058
Chris Lattnerac5fb562011-07-15 05:58:04 +000059 // Otherwise, just use +0.0.
60 return isNullValue();
61}
62
Shuxin Yang9ca562e2013-01-09 00:53:25 +000063// Return true iff this constant is positive zero (floating point), negative
64// zero (floating point), or a null value.
Shuxin Yangf0537ab2013-01-09 00:13:41 +000065bool Constant::isZeroValue() const {
66 // Floating point values have an explicit -0.0 value.
67 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
68 return CFP->isZero();
69
Owen Anderson630077e2015-11-20 08:16:13 +000070 // Equivalent for a vector of -0.0's.
71 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
Craig Topper0b4b4e32017-07-15 22:06:19 +000072 if (CV->getElementType()->isFloatingPointTy() && CV->isSplat())
73 if (CV->getElementAsAPFloat(0).isZero())
Owen Anderson630077e2015-11-20 08:16:13 +000074 return true;
75
Owen Anderson8e851302015-11-20 22:34:48 +000076 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
77 if (ConstantFP *SplatCFP = dyn_cast_or_null<ConstantFP>(CV->getSplatValue()))
78 if (SplatCFP && SplatCFP->isZero())
79 return true;
80
Shuxin Yangf0537ab2013-01-09 00:13:41 +000081 // Otherwise, just use +0.0.
82 return isNullValue();
83}
84
Chris Lattnerbe6610c2011-07-15 06:14:08 +000085bool Constant::isNullValue() const {
86 // 0 is null.
87 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
88 return CI->isZero();
Galina Kistanovafc259902012-07-13 01:25:27 +000089
Chris Lattnerbe6610c2011-07-15 06:14:08 +000090 // +0.0 is null.
91 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
92 return CFP->isZero() && !CFP->isNegative();
93
David Majnemerf0f224d2015-11-11 21:57:16 +000094 // constant zero is zero for aggregates, cpnull is null for pointers, none for
95 // tokens.
96 return isa<ConstantAggregateZero>(this) || isa<ConstantPointerNull>(this) ||
97 isa<ConstantTokenNone>(this);
Chris Lattnerbe6610c2011-07-15 06:14:08 +000098}
99
Nadav Rotem365af6f2011-08-24 20:18:38 +0000100bool Constant::isAllOnesValue() const {
101 // Check for -1 integers
102 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
103 return CI->isMinusOne();
104
105 // Check for FP which are bitcasted from -1 integers
106 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
107 return CFP->getValueAPF().bitcastToAPInt().isAllOnesValue();
108
Benjamin Kramer42d098e2011-11-14 19:12:20 +0000109 // Check for constant vectors which are splats of -1 values.
Nadav Rotem365af6f2011-08-24 20:18:38 +0000110 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
Benjamin Kramer42d098e2011-11-14 19:12:20 +0000111 if (Constant *Splat = CV->getSplatValue())
112 return Splat->isAllOnesValue();
Nadav Rotem365af6f2011-08-24 20:18:38 +0000113
Chris Lattnerf14a67f2012-01-26 02:31:22 +0000114 // Check for constant vectors which are splats of -1 values.
Craig Topper0b4b4e32017-07-15 22:06:19 +0000115 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this)) {
116 if (CV->isSplat()) {
117 if (CV->getElementType()->isFloatingPointTy())
118 return CV->getElementAsAPFloat(0).bitcastToAPInt().isAllOnesValue();
119 return CV->getElementAsAPInt(0).isAllOnesValue();
120 }
121 }
Chris Lattnerf14a67f2012-01-26 02:31:22 +0000122
Nadav Rotem365af6f2011-08-24 20:18:38 +0000123 return false;
124}
Benjamin Kramer42d098e2011-11-14 19:12:20 +0000125
David Majnemer1a0bbc82014-08-16 09:23:42 +0000126bool Constant::isOneValue() const {
127 // Check for 1 integers
128 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
129 return CI->isOne();
130
131 // Check for FP which are bitcasted from 1 integers
132 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
Craig Topper93ac6e12017-06-07 00:58:02 +0000133 return CFP->getValueAPF().bitcastToAPInt().isOneValue();
David Majnemer1a0bbc82014-08-16 09:23:42 +0000134
135 // Check for constant vectors which are splats of 1 values.
136 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
137 if (Constant *Splat = CV->getSplatValue())
138 return Splat->isOneValue();
139
140 // Check for constant vectors which are splats of 1 values.
Craig Topper0b4b4e32017-07-15 22:06:19 +0000141 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this)) {
142 if (CV->isSplat()) {
143 if (CV->getElementType()->isFloatingPointTy())
144 return CV->getElementAsAPFloat(0).bitcastToAPInt().isOneValue();
145 return CV->getElementAsAPInt(0).isOneValue();
146 }
147 }
David Majnemer1a0bbc82014-08-16 09:23:42 +0000148
149 return false;
150}
151
David Majnemerbdeef602014-07-02 06:07:09 +0000152bool Constant::isMinSignedValue() const {
153 // Check for INT_MIN integers
154 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
155 return CI->isMinValue(/*isSigned=*/true);
156
157 // Check for FP which are bitcasted from INT_MIN integers
158 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
159 return CFP->getValueAPF().bitcastToAPInt().isMinSignedValue();
160
161 // Check for constant vectors which are splats of INT_MIN values.
162 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
163 if (Constant *Splat = CV->getSplatValue())
164 return Splat->isMinSignedValue();
165
166 // Check for constant vectors which are splats of INT_MIN values.
Craig Topper0b4b4e32017-07-15 22:06:19 +0000167 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this)) {
168 if (CV->isSplat()) {
169 if (CV->getElementType()->isFloatingPointTy())
170 return CV->getElementAsAPFloat(0).bitcastToAPInt().isMinSignedValue();
171 return CV->getElementAsAPInt(0).isMinSignedValue();
172 }
173 }
David Majnemerbdeef602014-07-02 06:07:09 +0000174
175 return false;
176}
177
David Majnemer0e6c9862014-08-22 16:41:23 +0000178bool Constant::isNotMinSignedValue() const {
179 // Check for INT_MIN integers
180 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
181 return !CI->isMinValue(/*isSigned=*/true);
182
183 // Check for FP which are bitcasted from INT_MIN integers
184 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
185 return !CFP->getValueAPF().bitcastToAPInt().isMinSignedValue();
186
187 // Check for constant vectors which are splats of INT_MIN values.
188 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
189 if (Constant *Splat = CV->getSplatValue())
190 return Splat->isNotMinSignedValue();
191
192 // Check for constant vectors which are splats of INT_MIN values.
Craig Topper0b4b4e32017-07-15 22:06:19 +0000193 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this)) {
194 if (CV->isSplat()) {
195 if (CV->getElementType()->isFloatingPointTy())
196 return !CV->getElementAsAPFloat(0).bitcastToAPInt().isMinSignedValue();
197 return !CV->getElementAsAPInt(0).isMinSignedValue();
198 }
199 }
David Majnemer0e6c9862014-08-22 16:41:23 +0000200
201 // It *may* contain INT_MIN, we can't tell.
202 return false;
203}
204
Sanjay Patel08868e4942018-02-16 22:32:54 +0000205bool Constant::isFiniteNonZeroFP() const {
206 if (auto *CFP = dyn_cast<ConstantFP>(this))
207 return CFP->getValueAPF().isFiniteNonZero();
208 if (!getType()->isVectorTy())
209 return false;
210 for (unsigned i = 0, e = getType()->getVectorNumElements(); i != e; ++i) {
211 auto *CFP = dyn_cast_or_null<ConstantFP>(this->getAggregateElement(i));
212 if (!CFP || !CFP->getValueAPF().isFiniteNonZero())
213 return false;
214 }
215 return true;
216}
217
218bool Constant::isNormalFP() const {
219 if (auto *CFP = dyn_cast<ConstantFP>(this))
220 return CFP->getValueAPF().isNormal();
221 if (!getType()->isVectorTy())
222 return false;
223 for (unsigned i = 0, e = getType()->getVectorNumElements(); i != e; ++i) {
224 auto *CFP = dyn_cast_or_null<ConstantFP>(this->getAggregateElement(i));
225 if (!CFP || !CFP->getValueAPF().isNormal())
226 return false;
227 }
228 return true;
229}
230
Sanjay Patel90f4c8e2018-02-20 16:08:15 +0000231bool Constant::hasExactInverseFP() const {
232 if (auto *CFP = dyn_cast<ConstantFP>(this))
233 return CFP->getValueAPF().getExactInverse(nullptr);
234 if (!getType()->isVectorTy())
235 return false;
236 for (unsigned i = 0, e = getType()->getVectorNumElements(); i != e; ++i) {
237 auto *CFP = dyn_cast_or_null<ConstantFP>(this->getAggregateElement(i));
238 if (!CFP || !CFP->getValueAPF().getExactInverse(nullptr))
239 return false;
240 }
241 return true;
242}
243
Sanjay Patel46b083e2018-03-02 18:36:08 +0000244bool Constant::isNaN() const {
245 if (auto *CFP = dyn_cast<ConstantFP>(this))
246 return CFP->isNaN();
247 if (!getType()->isVectorTy())
248 return false;
249 for (unsigned i = 0, e = getType()->getVectorNumElements(); i != e; ++i) {
250 auto *CFP = dyn_cast_or_null<ConstantFP>(this->getAggregateElement(i));
251 if (!CFP || !CFP->isNaN())
252 return false;
253 }
254 return true;
255}
256
Sanjay Patel1d0ac7c2016-04-29 22:03:27 +0000257/// Constructor to create a '0' constant of arbitrary type.
Chris Lattner229907c2011-07-18 04:54:35 +0000258Constant *Constant::getNullValue(Type *Ty) {
Owen Anderson5a1acd92009-07-31 20:28:14 +0000259 switch (Ty->getTypeID()) {
260 case Type::IntegerTyID:
261 return ConstantInt::get(Ty, 0);
Dan Gohman518cda42011-12-17 00:04:22 +0000262 case Type::HalfTyID:
263 return ConstantFP::get(Ty->getContext(),
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000264 APFloat::getZero(APFloat::IEEEhalf()));
Owen Anderson5a1acd92009-07-31 20:28:14 +0000265 case Type::FloatTyID:
Benjamin Kramer8ceebfa2010-12-04 14:22:24 +0000266 return ConstantFP::get(Ty->getContext(),
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000267 APFloat::getZero(APFloat::IEEEsingle()));
Owen Anderson5a1acd92009-07-31 20:28:14 +0000268 case Type::DoubleTyID:
Benjamin Kramer8ceebfa2010-12-04 14:22:24 +0000269 return ConstantFP::get(Ty->getContext(),
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000270 APFloat::getZero(APFloat::IEEEdouble()));
Owen Anderson5a1acd92009-07-31 20:28:14 +0000271 case Type::X86_FP80TyID:
Benjamin Kramer8ceebfa2010-12-04 14:22:24 +0000272 return ConstantFP::get(Ty->getContext(),
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000273 APFloat::getZero(APFloat::x87DoubleExtended()));
Owen Anderson5a1acd92009-07-31 20:28:14 +0000274 case Type::FP128TyID:
275 return ConstantFP::get(Ty->getContext(),
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000276 APFloat::getZero(APFloat::IEEEquad()));
Owen Anderson5a1acd92009-07-31 20:28:14 +0000277 case Type::PPC_FP128TyID:
Benjamin Kramer8ceebfa2010-12-04 14:22:24 +0000278 return ConstantFP::get(Ty->getContext(),
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000279 APFloat(APFloat::PPCDoubleDouble(),
Tim Northover29178a32013-01-22 09:46:31 +0000280 APInt::getNullValue(128)));
Owen Anderson5a1acd92009-07-31 20:28:14 +0000281 case Type::PointerTyID:
282 return ConstantPointerNull::get(cast<PointerType>(Ty));
283 case Type::StructTyID:
284 case Type::ArrayTyID:
285 case Type::VectorTyID:
286 return ConstantAggregateZero::get(Ty);
David Majnemerf0f224d2015-11-11 21:57:16 +0000287 case Type::TokenTyID:
288 return ConstantTokenNone::get(Ty->getContext());
Owen Anderson5a1acd92009-07-31 20:28:14 +0000289 default:
290 // Function, Label, or Opaque type?
Craig Topperc514b542012-02-05 22:14:15 +0000291 llvm_unreachable("Cannot create a null constant of that type!");
Owen Anderson5a1acd92009-07-31 20:28:14 +0000292 }
293}
294
Chris Lattner229907c2011-07-18 04:54:35 +0000295Constant *Constant::getIntegerValue(Type *Ty, const APInt &V) {
296 Type *ScalarTy = Ty->getScalarType();
Dan Gohmanf011f5a2009-08-03 22:07:33 +0000297
298 // Create the base integer constant.
299 Constant *C = ConstantInt::get(Ty->getContext(), V);
300
301 // Convert an integer to a pointer, if necessary.
Chris Lattner229907c2011-07-18 04:54:35 +0000302 if (PointerType *PTy = dyn_cast<PointerType>(ScalarTy))
Dan Gohmanf011f5a2009-08-03 22:07:33 +0000303 C = ConstantExpr::getIntToPtr(C, PTy);
304
305 // Broadcast a scalar to a vector, if necessary.
Chris Lattner229907c2011-07-18 04:54:35 +0000306 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
Chris Lattnere9eed292012-01-25 05:19:54 +0000307 C = ConstantVector::getSplat(VTy->getNumElements(), C);
Dan Gohmanf011f5a2009-08-03 22:07:33 +0000308
309 return C;
310}
311
Chris Lattner229907c2011-07-18 04:54:35 +0000312Constant *Constant::getAllOnesValue(Type *Ty) {
313 if (IntegerType *ITy = dyn_cast<IntegerType>(Ty))
Owen Anderson5a1acd92009-07-31 20:28:14 +0000314 return ConstantInt::get(Ty->getContext(),
315 APInt::getAllOnesValue(ITy->getBitWidth()));
Nadav Rotem7cc6d122011-02-17 21:22:27 +0000316
317 if (Ty->isFloatingPointTy()) {
318 APFloat FL = APFloat::getAllOnesValue(Ty->getPrimitiveSizeInBits(),
319 !Ty->isPPC_FP128Ty());
320 return ConstantFP::get(Ty->getContext(), FL);
321 }
322
Chris Lattner229907c2011-07-18 04:54:35 +0000323 VectorType *VTy = cast<VectorType>(Ty);
Chris Lattnere9eed292012-01-25 05:19:54 +0000324 return ConstantVector::getSplat(VTy->getNumElements(),
325 getAllOnesValue(VTy->getElementType()));
Owen Anderson5a1acd92009-07-31 20:28:14 +0000326}
327
Chris Lattner7e683d12012-01-25 06:16:32 +0000328Constant *Constant::getAggregateElement(unsigned Elt) const {
Duncan P. N. Exon Smith1de3c7e2016-04-05 21:10:45 +0000329 if (const ConstantAggregate *CC = dyn_cast<ConstantAggregate>(this))
330 return Elt < CC->getNumOperands() ? CC->getOperand(Elt) : nullptr;
Galina Kistanovafc259902012-07-13 01:25:27 +0000331
David Majnemer9b529a72015-02-16 04:02:09 +0000332 if (const ConstantAggregateZero *CAZ = dyn_cast<ConstantAggregateZero>(this))
333 return Elt < CAZ->getNumElements() ? CAZ->getElementValue(Elt) : nullptr;
Galina Kistanovafc259902012-07-13 01:25:27 +0000334
Chris Lattner7e683d12012-01-25 06:16:32 +0000335 if (const UndefValue *UV = dyn_cast<UndefValue>(this))
David Majnemer9b529a72015-02-16 04:02:09 +0000336 return Elt < UV->getNumElements() ? UV->getElementValue(Elt) : nullptr;
Galina Kistanovafc259902012-07-13 01:25:27 +0000337
Chris Lattner8326bd82012-01-26 00:42:34 +0000338 if (const ConstantDataSequential *CDS =dyn_cast<ConstantDataSequential>(this))
Craig Topperc6207612014-04-09 06:08:46 +0000339 return Elt < CDS->getNumElements() ? CDS->getElementAsConstant(Elt)
340 : nullptr;
341 return nullptr;
Chris Lattner7e683d12012-01-25 06:16:32 +0000342}
343
344Constant *Constant::getAggregateElement(Constant *Elt) const {
345 assert(isa<IntegerType>(Elt->getType()) && "Index must be an integer");
346 if (ConstantInt *CI = dyn_cast<ConstantInt>(Elt))
347 return getAggregateElement(CI->getZExtValue());
Craig Topperc6207612014-04-09 06:08:46 +0000348 return nullptr;
Chris Lattner7e683d12012-01-25 06:16:32 +0000349}
350
Pete Cooper86dd4cf2015-06-23 21:55:11 +0000351void Constant::destroyConstant() {
352 /// First call destroyConstantImpl on the subclass. This gives the subclass
353 /// a chance to remove the constant from any maps/pools it's contained in.
354 switch (getValueID()) {
355 default:
356 llvm_unreachable("Not a constant!");
357#define HANDLE_CONSTANT(Name) \
358 case Value::Name##Val: \
359 cast<Name>(this)->destroyConstantImpl(); \
360 break;
361#include "llvm/IR/Value.def"
362 }
Chris Lattner7e683d12012-01-25 06:16:32 +0000363
Chris Lattner3462ae32001-12-03 22:26:30 +0000364 // When a Constant is destroyed, there may be lingering
Chris Lattnerd7a73302001-10-13 06:57:33 +0000365 // references to the constant by other constants in the constant pool. These
Misha Brukmanbe372b92003-08-21 22:14:26 +0000366 // constants are implicitly dependent on the module that is being deleted,
Chris Lattnerd7a73302001-10-13 06:57:33 +0000367 // but they don't know that. Because we only find out when the CPV is
368 // deleted, we must now notify all of our users (that should only be
Chris Lattner3462ae32001-12-03 22:26:30 +0000369 // Constants) that they are, in fact, invalid now and should be deleted.
Chris Lattnerd7a73302001-10-13 06:57:33 +0000370 //
371 while (!use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000372 Value *V = user_back();
Pete Cooper86dd4cf2015-06-23 21:55:11 +0000373#ifndef NDEBUG // Only in -g mode...
Chris Lattner78683a72009-08-23 04:02:03 +0000374 if (!isa<Constant>(V)) {
David Greene1e27a132010-01-05 01:29:19 +0000375 dbgs() << "While deleting: " << *this
Pete Cooper86dd4cf2015-06-23 21:55:11 +0000376 << "\n\nUse still stuck around after Def is destroyed: " << *V
377 << "\n\n";
Chris Lattner78683a72009-08-23 04:02:03 +0000378 }
Chris Lattnerd7a73302001-10-13 06:57:33 +0000379#endif
Vikram S. Adve4e537b22002-07-14 23:13:17 +0000380 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
Chris Lattner8326bd82012-01-26 00:42:34 +0000381 cast<Constant>(V)->destroyConstant();
Chris Lattnerd7a73302001-10-13 06:57:33 +0000382
383 // The constant should remove itself from our use list...
Chandler Carruthcdf47882014-03-09 03:16:01 +0000384 assert((use_empty() || user_back() != V) && "Constant not removed!");
Chris Lattnerd7a73302001-10-13 06:57:33 +0000385 }
386
387 // Value has no outstanding references it is safe to delete it now...
388 delete this;
Chris Lattner38569342001-10-01 20:11:19 +0000389}
Chris Lattner2f7c9632001-06-06 20:29:01 +0000390
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +0000391static bool canTrapImpl(const Constant *C,
Craig Topper71b7b682014-08-21 05:55:13 +0000392 SmallPtrSetImpl<const ConstantExpr *> &NonTrappingOps) {
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +0000393 assert(C->getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
Chris Lattner23dd1f62006-10-20 00:27:06 +0000394 // The only thing that could possibly trap are constant exprs.
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +0000395 const ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
396 if (!CE)
397 return false;
Galina Kistanovafc259902012-07-13 01:25:27 +0000398
399 // ConstantExpr traps if any operands can trap.
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +0000400 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) {
401 if (ConstantExpr *Op = dyn_cast<ConstantExpr>(CE->getOperand(i))) {
David Blaikie70573dc2014-11-19 07:49:26 +0000402 if (NonTrappingOps.insert(Op).second && canTrapImpl(Op, NonTrappingOps))
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +0000403 return true;
404 }
405 }
Chris Lattner23dd1f62006-10-20 00:27:06 +0000406
407 // Otherwise, only specific operations can trap.
408 switch (CE->getOpcode()) {
409 default:
410 return false;
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000411 case Instruction::UDiv:
412 case Instruction::SDiv:
Reid Spencer7eb55b32006-11-02 01:53:59 +0000413 case Instruction::URem:
414 case Instruction::SRem:
Chris Lattner23dd1f62006-10-20 00:27:06 +0000415 // Div and rem can trap if the RHS is not known to be non-zero.
Chris Lattnera91a5632009-10-28 05:14:34 +0000416 if (!isa<ConstantInt>(CE->getOperand(1)) ||CE->getOperand(1)->isNullValue())
Chris Lattner23dd1f62006-10-20 00:27:06 +0000417 return true;
418 return false;
419 }
420}
421
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +0000422bool Constant::canTrap() const {
423 SmallPtrSet<const ConstantExpr *, 4> NonTrappingOps;
424 return canTrapImpl(this, NonTrappingOps);
425}
426
Hans Wennborg4dc89512014-06-20 00:38:12 +0000427/// Check if C contains a GlobalValue for which Predicate is true.
428static bool
429ConstHasGlobalValuePredicate(const Constant *C,
430 bool (*Predicate)(const GlobalValue *)) {
431 SmallPtrSet<const Constant *, 8> Visited;
432 SmallVector<const Constant *, 8> WorkList;
433 WorkList.push_back(C);
434 Visited.insert(C);
Hans Wennborg709e0152012-11-15 11:40:00 +0000435
436 while (!WorkList.empty()) {
Hans Wennborg4dc89512014-06-20 00:38:12 +0000437 const Constant *WorkItem = WorkList.pop_back_val();
438 if (const auto *GV = dyn_cast<GlobalValue>(WorkItem))
439 if (Predicate(GV))
Hans Wennborg709e0152012-11-15 11:40:00 +0000440 return true;
Hans Wennborg4dc89512014-06-20 00:38:12 +0000441 for (const Value *Op : WorkItem->operands()) {
442 const Constant *ConstOp = dyn_cast<Constant>(Op);
443 if (!ConstOp)
Hans Wennborg18aa12402012-11-16 10:33:25 +0000444 continue;
David Blaikie70573dc2014-11-19 07:49:26 +0000445 if (Visited.insert(ConstOp).second)
Hans Wennborg4dc89512014-06-20 00:38:12 +0000446 WorkList.push_back(ConstOp);
Hans Wennborg709e0152012-11-15 11:40:00 +0000447 }
448 }
Hans Wennborg709e0152012-11-15 11:40:00 +0000449 return false;
450}
451
Hans Wennborg4dc89512014-06-20 00:38:12 +0000452bool Constant::isThreadDependent() const {
453 auto DLLImportPredicate = [](const GlobalValue *GV) {
454 return GV->isThreadLocal();
455 };
456 return ConstHasGlobalValuePredicate(this, DLLImportPredicate);
457}
458
459bool Constant::isDLLImportDependent() const {
460 auto DLLImportPredicate = [](const GlobalValue *GV) {
461 return GV->hasDLLImportStorageClass();
462 };
463 return ConstHasGlobalValuePredicate(this, DLLImportPredicate);
464}
465
Chris Lattner253bc772009-11-01 18:11:50 +0000466bool Constant::isConstantUsed() const {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000467 for (const User *U : users()) {
468 const Constant *UC = dyn_cast<Constant>(U);
Craig Topperc6207612014-04-09 06:08:46 +0000469 if (!UC || isa<GlobalValue>(UC))
Chris Lattner253bc772009-11-01 18:11:50 +0000470 return true;
Galina Kistanovafc259902012-07-13 01:25:27 +0000471
Chris Lattner253bc772009-11-01 18:11:50 +0000472 if (UC->isConstantUsed())
473 return true;
474 }
475 return false;
476}
477
Rafael Espindola65e49022015-11-17 00:51:23 +0000478bool Constant::needsRelocation() const {
479 if (isa<GlobalValue>(this))
480 return true; // Global reference.
481
Chris Lattner2cb85b42009-10-28 04:12:16 +0000482 if (const BlockAddress *BA = dyn_cast<BlockAddress>(this))
Rafael Espindola65e49022015-11-17 00:51:23 +0000483 return BA->getFunction()->needsRelocation();
484
Chris Lattnera7cfc432010-01-03 18:09:40 +0000485 // While raw uses of blockaddress need to be relocated, differences between
486 // two of them don't when they are for labels in the same function. This is a
487 // common idiom when creating a table for the indirect goto extension, so we
488 // handle it efficiently here.
489 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(this))
490 if (CE->getOpcode() == Instruction::Sub) {
491 ConstantExpr *LHS = dyn_cast<ConstantExpr>(CE->getOperand(0));
492 ConstantExpr *RHS = dyn_cast<ConstantExpr>(CE->getOperand(1));
Rafael Espindola65e49022015-11-17 00:51:23 +0000493 if (LHS && RHS && LHS->getOpcode() == Instruction::PtrToInt &&
Chris Lattnera7cfc432010-01-03 18:09:40 +0000494 RHS->getOpcode() == Instruction::PtrToInt &&
495 isa<BlockAddress>(LHS->getOperand(0)) &&
496 isa<BlockAddress>(RHS->getOperand(0)) &&
497 cast<BlockAddress>(LHS->getOperand(0))->getFunction() ==
Rafael Espindola65e49022015-11-17 00:51:23 +0000498 cast<BlockAddress>(RHS->getOperand(0))->getFunction())
499 return false;
Chris Lattnera7cfc432010-01-03 18:09:40 +0000500 }
Galina Kistanovafc259902012-07-13 01:25:27 +0000501
Rafael Espindola65e49022015-11-17 00:51:23 +0000502 bool Result = false;
Evan Chengf9e003b2007-03-08 00:59:12 +0000503 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
Rafael Espindola65e49022015-11-17 00:51:23 +0000504 Result |= cast<Constant>(getOperand(i))->needsRelocation();
Galina Kistanovafc259902012-07-13 01:25:27 +0000505
Chris Lattner4565ef52009-07-22 00:05:44 +0000506 return Result;
Evan Chengf9e003b2007-03-08 00:59:12 +0000507}
508
Sanjay Patel1d0ac7c2016-04-29 22:03:27 +0000509/// If the specified constantexpr is dead, remove it. This involves recursively
510/// eliminating any dead users of the constantexpr.
Chris Lattner84886402011-02-18 04:41:42 +0000511static bool removeDeadUsersOfConstant(const Constant *C) {
512 if (isa<GlobalValue>(C)) return false; // Cannot remove this
Galina Kistanovafc259902012-07-13 01:25:27 +0000513
Chris Lattner84886402011-02-18 04:41:42 +0000514 while (!C->use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000515 const Constant *User = dyn_cast<Constant>(C->user_back());
Chris Lattner84886402011-02-18 04:41:42 +0000516 if (!User) return false; // Non-constant usage;
517 if (!removeDeadUsersOfConstant(User))
518 return false; // Constant wasn't dead
519 }
Galina Kistanovafc259902012-07-13 01:25:27 +0000520
Chris Lattner84886402011-02-18 04:41:42 +0000521 const_cast<Constant*>(C)->destroyConstant();
522 return true;
523}
524
525
Chris Lattner84886402011-02-18 04:41:42 +0000526void Constant::removeDeadConstantUsers() const {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000527 Value::const_user_iterator I = user_begin(), E = user_end();
528 Value::const_user_iterator LastNonDeadUser = E;
Chris Lattner84886402011-02-18 04:41:42 +0000529 while (I != E) {
530 const Constant *User = dyn_cast<Constant>(*I);
Craig Topperc6207612014-04-09 06:08:46 +0000531 if (!User) {
Chris Lattner84886402011-02-18 04:41:42 +0000532 LastNonDeadUser = I;
533 ++I;
534 continue;
535 }
Galina Kistanovafc259902012-07-13 01:25:27 +0000536
Chris Lattner84886402011-02-18 04:41:42 +0000537 if (!removeDeadUsersOfConstant(User)) {
538 // If the constant wasn't dead, remember that this was the last live use
539 // and move on to the next constant.
540 LastNonDeadUser = I;
541 ++I;
542 continue;
543 }
Galina Kistanovafc259902012-07-13 01:25:27 +0000544
Chris Lattner84886402011-02-18 04:41:42 +0000545 // If the constant was dead, then the iterator is invalidated.
546 if (LastNonDeadUser == E) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000547 I = user_begin();
Chris Lattner84886402011-02-18 04:41:42 +0000548 if (I == E) break;
549 } else {
550 I = LastNonDeadUser;
551 ++I;
552 }
553 }
554}
555
556
Chris Lattner2105d662008-07-10 00:28:11 +0000557
Chris Lattner2f7c9632001-06-06 20:29:01 +0000558//===----------------------------------------------------------------------===//
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000559// ConstantInt
Chris Lattner2f7c9632001-06-06 20:29:01 +0000560//===----------------------------------------------------------------------===//
561
Duncan P. N. Exon Smithb6452792016-02-21 02:39:49 +0000562ConstantInt::ConstantInt(IntegerType *Ty, const APInt &V)
563 : ConstantData(Ty, ConstantIntVal), Val(V) {
Reid Spencerb31bffe2007-02-26 23:54:03 +0000564 assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
Chris Lattner2f7c9632001-06-06 20:29:01 +0000565}
566
Nick Lewycky92db8e82011-03-06 03:36:19 +0000567ConstantInt *ConstantInt::getTrue(LLVMContext &Context) {
Owen Anderson23a204d2009-07-31 17:39:07 +0000568 LLVMContextImpl *pImpl = Context.pImpl;
Benjamin Kramerddd1b7b2010-11-20 18:43:35 +0000569 if (!pImpl->TheTrueVal)
570 pImpl->TheTrueVal = ConstantInt::get(Type::getInt1Ty(Context), 1);
571 return pImpl->TheTrueVal;
Owen Anderson23a204d2009-07-31 17:39:07 +0000572}
573
Nick Lewycky92db8e82011-03-06 03:36:19 +0000574ConstantInt *ConstantInt::getFalse(LLVMContext &Context) {
Owen Anderson23a204d2009-07-31 17:39:07 +0000575 LLVMContextImpl *pImpl = Context.pImpl;
Benjamin Kramerddd1b7b2010-11-20 18:43:35 +0000576 if (!pImpl->TheFalseVal)
577 pImpl->TheFalseVal = ConstantInt::get(Type::getInt1Ty(Context), 0);
578 return pImpl->TheFalseVal;
Owen Anderson23a204d2009-07-31 17:39:07 +0000579}
580
Chris Lattner229907c2011-07-18 04:54:35 +0000581Constant *ConstantInt::getTrue(Type *Ty) {
Craig Topperfde47232017-07-09 07:04:03 +0000582 assert(Ty->isIntOrIntVectorTy(1) && "Type not i1 or vector of i1.");
Sanjay Patel70a575a2017-04-16 17:00:21 +0000583 ConstantInt *TrueC = ConstantInt::getTrue(Ty->getContext());
584 if (auto *VTy = dyn_cast<VectorType>(Ty))
585 return ConstantVector::getSplat(VTy->getNumElements(), TrueC);
586 return TrueC;
Nick Lewycky92db8e82011-03-06 03:36:19 +0000587}
588
Chris Lattner229907c2011-07-18 04:54:35 +0000589Constant *ConstantInt::getFalse(Type *Ty) {
Craig Topperfde47232017-07-09 07:04:03 +0000590 assert(Ty->isIntOrIntVectorTy(1) && "Type not i1 or vector of i1.");
Sanjay Patel70a575a2017-04-16 17:00:21 +0000591 ConstantInt *FalseC = ConstantInt::getFalse(Ty->getContext());
592 if (auto *VTy = dyn_cast<VectorType>(Ty))
593 return ConstantVector::getSplat(VTy->getNumElements(), FalseC);
594 return FalseC;
Nick Lewycky92db8e82011-03-06 03:36:19 +0000595}
596
Benjamin Kramer8e5dc532014-12-06 13:12:56 +0000597// Get a ConstantInt from an APInt.
Nick Lewycky92db8e82011-03-06 03:36:19 +0000598ConstantInt *ConstantInt::get(LLVMContext &Context, const APInt &V) {
Owen Andersonedb4a702009-07-24 23:12:02 +0000599 // get an existing value or the insertion position
Benjamin Kramer320682f2013-06-01 17:51:03 +0000600 LLVMContextImpl *pImpl = Context.pImpl;
Justin Lebar611c5c22016-10-10 16:26:13 +0000601 std::unique_ptr<ConstantInt> &Slot = pImpl->IntConstants[V];
Benjamin Kramer8e5dc532014-12-06 13:12:56 +0000602 if (!Slot) {
603 // Get the corresponding integer type for the bit width of the value.
604 IntegerType *ITy = IntegerType::get(Context, V.getBitWidth());
Justin Lebar611c5c22016-10-10 16:26:13 +0000605 Slot.reset(new ConstantInt(ITy, V));
Benjamin Kramer8e5dc532014-12-06 13:12:56 +0000606 }
607 assert(Slot->getType() == IntegerType::get(Context, V.getBitWidth()));
Justin Lebar611c5c22016-10-10 16:26:13 +0000608 return Slot.get();
Owen Andersonedb4a702009-07-24 23:12:02 +0000609}
610
Chris Lattner229907c2011-07-18 04:54:35 +0000611Constant *ConstantInt::get(Type *Ty, uint64_t V, bool isSigned) {
Nick Lewycky92db8e82011-03-06 03:36:19 +0000612 Constant *C = get(cast<IntegerType>(Ty->getScalarType()), V, isSigned);
Owen Andersonedb4a702009-07-24 23:12:02 +0000613
614 // For vectors, broadcast the value.
Chris Lattner229907c2011-07-18 04:54:35 +0000615 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
Chris Lattnere9eed292012-01-25 05:19:54 +0000616 return ConstantVector::getSplat(VTy->getNumElements(), C);
Owen Andersonedb4a702009-07-24 23:12:02 +0000617
618 return C;
619}
620
Sanjay Patelf3587ec2016-05-18 22:05:28 +0000621ConstantInt *ConstantInt::get(IntegerType *Ty, uint64_t V, bool isSigned) {
Owen Andersonedb4a702009-07-24 23:12:02 +0000622 return get(Ty->getContext(), APInt(Ty->getBitWidth(), V, isSigned));
623}
624
Chris Lattner0256be92012-01-27 03:08:05 +0000625ConstantInt *ConstantInt::getSigned(IntegerType *Ty, int64_t V) {
Owen Andersonedb4a702009-07-24 23:12:02 +0000626 return get(Ty, V, true);
627}
628
Chris Lattner229907c2011-07-18 04:54:35 +0000629Constant *ConstantInt::getSigned(Type *Ty, int64_t V) {
Owen Andersonedb4a702009-07-24 23:12:02 +0000630 return get(Ty, V, true);
631}
632
Chris Lattner0256be92012-01-27 03:08:05 +0000633Constant *ConstantInt::get(Type *Ty, const APInt& V) {
Owen Andersonedb4a702009-07-24 23:12:02 +0000634 ConstantInt *C = get(Ty->getContext(), V);
635 assert(C->getType() == Ty->getScalarType() &&
636 "ConstantInt type doesn't match the type implied by its value!");
637
638 // For vectors, broadcast the value.
Chris Lattner229907c2011-07-18 04:54:35 +0000639 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
Chris Lattnere9eed292012-01-25 05:19:54 +0000640 return ConstantVector::getSplat(VTy->getNumElements(), C);
Owen Andersonedb4a702009-07-24 23:12:02 +0000641
642 return C;
643}
644
Sanjay Patelf3587ec2016-05-18 22:05:28 +0000645ConstantInt *ConstantInt::get(IntegerType* Ty, StringRef Str, uint8_t radix) {
Erick Tryzelaarfc2280d2009-08-16 23:36:33 +0000646 return get(Ty->getContext(), APInt(Ty->getBitWidth(), Str, radix));
647}
648
Pete Cooper86dd4cf2015-06-23 21:55:11 +0000649/// Remove the constant from the constant table.
650void ConstantInt::destroyConstantImpl() {
651 llvm_unreachable("You can't ConstantInt->destroyConstantImpl()!");
652}
653
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000654//===----------------------------------------------------------------------===//
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000655// ConstantFP
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000656//===----------------------------------------------------------------------===//
657
Chris Lattner229907c2011-07-18 04:54:35 +0000658static const fltSemantics *TypeToFloatSemantics(Type *Ty) {
Dan Gohman518cda42011-12-17 00:04:22 +0000659 if (Ty->isHalfTy())
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000660 return &APFloat::IEEEhalf();
Chris Lattnerfdd87902009-10-05 05:54:46 +0000661 if (Ty->isFloatTy())
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000662 return &APFloat::IEEEsingle();
Chris Lattnerfdd87902009-10-05 05:54:46 +0000663 if (Ty->isDoubleTy())
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000664 return &APFloat::IEEEdouble();
Chris Lattnerfdd87902009-10-05 05:54:46 +0000665 if (Ty->isX86_FP80Ty())
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000666 return &APFloat::x87DoubleExtended();
Chris Lattnerfdd87902009-10-05 05:54:46 +0000667 else if (Ty->isFP128Ty())
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000668 return &APFloat::IEEEquad();
Galina Kistanovafc259902012-07-13 01:25:27 +0000669
Chris Lattnerfdd87902009-10-05 05:54:46 +0000670 assert(Ty->isPPC_FP128Ty() && "Unknown FP format");
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000671 return &APFloat::PPCDoubleDouble();
Rafael Espindolaf5d53d42009-07-15 17:40:42 +0000672}
673
Chris Lattner0256be92012-01-27 03:08:05 +0000674Constant *ConstantFP::get(Type *Ty, double V) {
Owen Anderson69c464d2009-07-27 20:59:43 +0000675 LLVMContext &Context = Ty->getContext();
Galina Kistanovafc259902012-07-13 01:25:27 +0000676
Owen Anderson69c464d2009-07-27 20:59:43 +0000677 APFloat FV(V);
678 bool ignored;
679 FV.convert(*TypeToFloatSemantics(Ty->getScalarType()),
680 APFloat::rmNearestTiesToEven, &ignored);
681 Constant *C = get(Context, FV);
682
683 // For vectors, broadcast the value.
Chris Lattner229907c2011-07-18 04:54:35 +0000684 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
Chris Lattnere9eed292012-01-25 05:19:54 +0000685 return ConstantVector::getSplat(VTy->getNumElements(), C);
Owen Anderson69c464d2009-07-27 20:59:43 +0000686
687 return C;
688}
689
Sanjay Patel6a0f6672018-02-15 13:55:52 +0000690Constant *ConstantFP::get(Type *Ty, const APFloat &V) {
691 ConstantFP *C = get(Ty->getContext(), V);
692 assert(C->getType() == Ty->getScalarType() &&
693 "ConstantFP type doesn't match the type implied by its value!");
694
695 // For vectors, broadcast the value.
696 if (auto *VTy = dyn_cast<VectorType>(Ty))
697 return ConstantVector::getSplat(VTy->getNumElements(), C);
698
699 return C;
700}
Erick Tryzelaarfc2280d2009-08-16 23:36:33 +0000701
Chris Lattner0256be92012-01-27 03:08:05 +0000702Constant *ConstantFP::get(Type *Ty, StringRef Str) {
Erick Tryzelaarfc2280d2009-08-16 23:36:33 +0000703 LLVMContext &Context = Ty->getContext();
704
705 APFloat FV(*TypeToFloatSemantics(Ty->getScalarType()), Str);
706 Constant *C = get(Context, FV);
707
708 // For vectors, broadcast the value.
Chris Lattner229907c2011-07-18 04:54:35 +0000709 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
Chris Lattnere9eed292012-01-25 05:19:54 +0000710 return ConstantVector::getSplat(VTy->getNumElements(), C);
Erick Tryzelaarfc2280d2009-08-16 23:36:33 +0000711
Bjorn Petterssonaa025802018-07-03 12:39:52 +0000712 return C;
Erick Tryzelaarfc2280d2009-08-16 23:36:33 +0000713}
714
Tom Stellard67246d12015-04-20 19:38:24 +0000715Constant *ConstantFP::getNaN(Type *Ty, bool Negative, unsigned Type) {
716 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
717 APFloat NaN = APFloat::getNaN(Semantics, Negative, Type);
718 Constant *C = get(Ty->getContext(), NaN);
719
720 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
721 return ConstantVector::getSplat(VTy->getNumElements(), C);
722
723 return C;
724}
725
Benjamin Kramer5d2ff222014-01-18 16:43:06 +0000726Constant *ConstantFP::getNegativeZero(Type *Ty) {
727 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
728 APFloat NegZero = APFloat::getZero(Semantics, /*Negative=*/true);
729 Constant *C = get(Ty->getContext(), NegZero);
Erick Tryzelaarfc2280d2009-08-16 23:36:33 +0000730
Benjamin Kramer5d2ff222014-01-18 16:43:06 +0000731 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
732 return ConstantVector::getSplat(VTy->getNumElements(), C);
733
734 return C;
Owen Anderson69c464d2009-07-27 20:59:43 +0000735}
736
737
Chris Lattnere9eed292012-01-25 05:19:54 +0000738Constant *ConstantFP::getZeroValueForNegation(Type *Ty) {
Benjamin Kramer5d2ff222014-01-18 16:43:06 +0000739 if (Ty->isFPOrFPVectorTy())
740 return getNegativeZero(Ty);
Owen Anderson69c464d2009-07-27 20:59:43 +0000741
Owen Anderson5a1acd92009-07-31 20:28:14 +0000742 return Constant::getNullValue(Ty);
Owen Anderson69c464d2009-07-27 20:59:43 +0000743}
744
745
746// ConstantFP accessors.
747ConstantFP* ConstantFP::get(LLVMContext &Context, const APFloat& V) {
Owen Anderson69c464d2009-07-27 20:59:43 +0000748 LLVMContextImpl* pImpl = Context.pImpl;
Galina Kistanovafc259902012-07-13 01:25:27 +0000749
Justin Lebar611c5c22016-10-10 16:26:13 +0000750 std::unique_ptr<ConstantFP> &Slot = pImpl->FPConstants[V];
Galina Kistanovafc259902012-07-13 01:25:27 +0000751
Owen Anderson69c464d2009-07-27 20:59:43 +0000752 if (!Slot) {
Chris Lattner229907c2011-07-18 04:54:35 +0000753 Type *Ty;
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000754 if (&V.getSemantics() == &APFloat::IEEEhalf())
Dan Gohman518cda42011-12-17 00:04:22 +0000755 Ty = Type::getHalfTy(Context);
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000756 else if (&V.getSemantics() == &APFloat::IEEEsingle())
Owen Anderson5dab84c2009-10-19 20:11:52 +0000757 Ty = Type::getFloatTy(Context);
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000758 else if (&V.getSemantics() == &APFloat::IEEEdouble())
Owen Anderson5dab84c2009-10-19 20:11:52 +0000759 Ty = Type::getDoubleTy(Context);
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000760 else if (&V.getSemantics() == &APFloat::x87DoubleExtended())
Owen Anderson5dab84c2009-10-19 20:11:52 +0000761 Ty = Type::getX86_FP80Ty(Context);
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000762 else if (&V.getSemantics() == &APFloat::IEEEquad())
Owen Anderson5dab84c2009-10-19 20:11:52 +0000763 Ty = Type::getFP128Ty(Context);
764 else {
Bjorn Petterssonaa025802018-07-03 12:39:52 +0000765 assert(&V.getSemantics() == &APFloat::PPCDoubleDouble() &&
Owen Anderson5dab84c2009-10-19 20:11:52 +0000766 "Unknown FP format");
767 Ty = Type::getPPC_FP128Ty(Context);
Owen Anderson69c464d2009-07-27 20:59:43 +0000768 }
Justin Lebar611c5c22016-10-10 16:26:13 +0000769 Slot.reset(new ConstantFP(Ty, V));
Owen Anderson69c464d2009-07-27 20:59:43 +0000770 }
Galina Kistanovafc259902012-07-13 01:25:27 +0000771
Justin Lebar611c5c22016-10-10 16:26:13 +0000772 return Slot.get();
Owen Anderson69c464d2009-07-27 20:59:43 +0000773}
774
Benjamin Kramer5d2ff222014-01-18 16:43:06 +0000775Constant *ConstantFP::getInfinity(Type *Ty, bool Negative) {
776 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
777 Constant *C = get(Ty->getContext(), APFloat::getInf(Semantics, Negative));
778
779 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
780 return ConstantVector::getSplat(VTy->getNumElements(), C);
781
782 return C;
Dan Gohmanfeb50212009-09-25 23:00:48 +0000783}
784
Duncan P. N. Exon Smithb6452792016-02-21 02:39:49 +0000785ConstantFP::ConstantFP(Type *Ty, const APFloat &V)
786 : ConstantData(Ty, ConstantFPVal), Val(V) {
Chris Lattner98bd9392008-04-09 06:38:30 +0000787 assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
788 "FP type Mismatch");
Chris Lattner2f7c9632001-06-06 20:29:01 +0000789}
790
Chris Lattnerbe6610c2011-07-15 06:14:08 +0000791bool ConstantFP::isExactlyValue(const APFloat &V) const {
Dale Johannesend246b2c2007-08-30 00:23:21 +0000792 return Val.bitwiseIsEqual(V);
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000793}
794
Pete Cooper86dd4cf2015-06-23 21:55:11 +0000795/// Remove the constant from the constant table.
796void ConstantFP::destroyConstantImpl() {
Craig Topperccbb8102017-06-27 19:57:51 +0000797 llvm_unreachable("You can't ConstantFP->destroyConstantImpl()!");
Pete Cooper86dd4cf2015-06-23 21:55:11 +0000798}
799
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000800//===----------------------------------------------------------------------===//
Chris Lattner030af792012-01-24 05:42:11 +0000801// ConstantAggregateZero Implementation
802//===----------------------------------------------------------------------===//
803
Chris Lattner7e683d12012-01-25 06:16:32 +0000804Constant *ConstantAggregateZero::getSequentialElement() const {
Chris Lattner8326bd82012-01-26 00:42:34 +0000805 return Constant::getNullValue(getType()->getSequentialElementType());
Chris Lattner030af792012-01-24 05:42:11 +0000806}
807
Chris Lattner7e683d12012-01-25 06:16:32 +0000808Constant *ConstantAggregateZero::getStructElement(unsigned Elt) const {
Chris Lattner8326bd82012-01-26 00:42:34 +0000809 return Constant::getNullValue(getType()->getStructElementType(Elt));
Chris Lattner030af792012-01-24 05:42:11 +0000810}
811
Chris Lattner7e683d12012-01-25 06:16:32 +0000812Constant *ConstantAggregateZero::getElementValue(Constant *C) const {
Chris Lattner030af792012-01-24 05:42:11 +0000813 if (isa<SequentialType>(getType()))
814 return getSequentialElement();
815 return getStructElement(cast<ConstantInt>(C)->getZExtValue());
816}
817
Chris Lattner7e683d12012-01-25 06:16:32 +0000818Constant *ConstantAggregateZero::getElementValue(unsigned Idx) const {
Chris Lattnerf7eb5432012-01-24 07:54:10 +0000819 if (isa<SequentialType>(getType()))
820 return getSequentialElement();
821 return getStructElement(Idx);
822}
823
David Majnemer9b529a72015-02-16 04:02:09 +0000824unsigned ConstantAggregateZero::getNumElements() const {
Craig Toppere3dcce92015-08-01 22:20:21 +0000825 Type *Ty = getType();
826 if (auto *AT = dyn_cast<ArrayType>(Ty))
David Majnemer9b529a72015-02-16 04:02:09 +0000827 return AT->getNumElements();
Craig Toppere3dcce92015-08-01 22:20:21 +0000828 if (auto *VT = dyn_cast<VectorType>(Ty))
David Majnemer9b529a72015-02-16 04:02:09 +0000829 return VT->getNumElements();
830 return Ty->getStructNumElements();
831}
Chris Lattnerf7eb5432012-01-24 07:54:10 +0000832
Chris Lattner030af792012-01-24 05:42:11 +0000833//===----------------------------------------------------------------------===//
834// UndefValue Implementation
835//===----------------------------------------------------------------------===//
836
Chris Lattner7e683d12012-01-25 06:16:32 +0000837UndefValue *UndefValue::getSequentialElement() const {
Chris Lattner8326bd82012-01-26 00:42:34 +0000838 return UndefValue::get(getType()->getSequentialElementType());
Chris Lattner030af792012-01-24 05:42:11 +0000839}
840
Chris Lattner7e683d12012-01-25 06:16:32 +0000841UndefValue *UndefValue::getStructElement(unsigned Elt) const {
Chris Lattner8326bd82012-01-26 00:42:34 +0000842 return UndefValue::get(getType()->getStructElementType(Elt));
Chris Lattner030af792012-01-24 05:42:11 +0000843}
844
Chris Lattner7e683d12012-01-25 06:16:32 +0000845UndefValue *UndefValue::getElementValue(Constant *C) const {
Chris Lattner030af792012-01-24 05:42:11 +0000846 if (isa<SequentialType>(getType()))
847 return getSequentialElement();
848 return getStructElement(cast<ConstantInt>(C)->getZExtValue());
849}
850
Chris Lattner7e683d12012-01-25 06:16:32 +0000851UndefValue *UndefValue::getElementValue(unsigned Idx) const {
Chris Lattnerf7eb5432012-01-24 07:54:10 +0000852 if (isa<SequentialType>(getType()))
853 return getSequentialElement();
854 return getStructElement(Idx);
855}
856
David Majnemer9b529a72015-02-16 04:02:09 +0000857unsigned UndefValue::getNumElements() const {
Craig Toppere3dcce92015-08-01 22:20:21 +0000858 Type *Ty = getType();
Peter Collingbournebc070522016-12-02 03:20:58 +0000859 if (auto *ST = dyn_cast<SequentialType>(Ty))
860 return ST->getNumElements();
David Majnemer9b529a72015-02-16 04:02:09 +0000861 return Ty->getStructNumElements();
862}
Chris Lattner030af792012-01-24 05:42:11 +0000863
864//===----------------------------------------------------------------------===//
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000865// ConstantXXX Classes
866//===----------------------------------------------------------------------===//
867
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000868template <typename ItTy, typename EltTy>
869static bool rangeOnlyContains(ItTy Start, ItTy End, EltTy Elt) {
870 for (; Start != End; ++Start)
871 if (*Start != Elt)
872 return false;
873 return true;
874}
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000875
Justin Bogner909e1c02015-12-01 20:20:49 +0000876template <typename SequentialTy, typename ElementTy>
877static Constant *getIntSequenceIfElementsMatch(ArrayRef<Constant *> V) {
878 assert(!V.empty() && "Cannot get empty int sequence.");
879
880 SmallVector<ElementTy, 16> Elts;
881 for (Constant *C : V)
882 if (auto *CI = dyn_cast<ConstantInt>(C))
883 Elts.push_back(CI->getZExtValue());
884 else
885 return nullptr;
886 return SequentialTy::get(V[0]->getContext(), Elts);
887}
888
889template <typename SequentialTy, typename ElementTy>
890static Constant *getFPSequenceIfElementsMatch(ArrayRef<Constant *> V) {
891 assert(!V.empty() && "Cannot get empty FP sequence.");
892
893 SmallVector<ElementTy, 16> Elts;
894 for (Constant *C : V)
895 if (auto *CFP = dyn_cast<ConstantFP>(C))
896 Elts.push_back(CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
897 else
898 return nullptr;
899 return SequentialTy::getFP(V[0]->getContext(), Elts);
900}
901
902template <typename SequenceTy>
903static Constant *getSequenceIfElementsMatch(Constant *C,
904 ArrayRef<Constant *> V) {
905 // We speculatively build the elements here even if it turns out that there is
906 // a constantexpr or something else weird, since it is so uncommon for that to
907 // happen.
908 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
909 if (CI->getType()->isIntegerTy(8))
910 return getIntSequenceIfElementsMatch<SequenceTy, uint8_t>(V);
911 else if (CI->getType()->isIntegerTy(16))
912 return getIntSequenceIfElementsMatch<SequenceTy, uint16_t>(V);
913 else if (CI->getType()->isIntegerTy(32))
914 return getIntSequenceIfElementsMatch<SequenceTy, uint32_t>(V);
915 else if (CI->getType()->isIntegerTy(64))
916 return getIntSequenceIfElementsMatch<SequenceTy, uint64_t>(V);
917 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
Justin Bogner0ebc8602015-12-08 03:01:16 +0000918 if (CFP->getType()->isHalfTy())
919 return getFPSequenceIfElementsMatch<SequenceTy, uint16_t>(V);
920 else if (CFP->getType()->isFloatTy())
Justin Bogner909e1c02015-12-01 20:20:49 +0000921 return getFPSequenceIfElementsMatch<SequenceTy, uint32_t>(V);
922 else if (CFP->getType()->isDoubleTy())
923 return getFPSequenceIfElementsMatch<SequenceTy, uint64_t>(V);
924 }
925
926 return nullptr;
927}
928
Duncan P. N. Exon Smith1de3c7e2016-04-05 21:10:45 +0000929ConstantAggregate::ConstantAggregate(CompositeType *T, ValueTy VT,
930 ArrayRef<Constant *> V)
931 : Constant(T, VT, OperandTraits<ConstantAggregate>::op_end(this) - V.size(),
932 V.size()) {
Jay Foad89d9b812011-07-25 10:14:44 +0000933 std::copy(V.begin(), V.end(), op_begin());
Duncan P. N. Exon Smith1de3c7e2016-04-05 21:10:45 +0000934
935 // Check that types match, unless this is an opaque struct.
936 if (auto *ST = dyn_cast<StructType>(T))
937 if (ST->isOpaque())
938 return;
939 for (unsigned I = 0, E = V.size(); I != E; ++I)
940 assert(V[I]->getType() == T->getTypeAtIndex(I) &&
941 "Initializer for composite element doesn't match!");
942}
943
944ConstantArray::ConstantArray(ArrayType *T, ArrayRef<Constant *> V)
945 : ConstantAggregate(T, ConstantArrayVal, V) {
946 assert(V.size() == T->getNumElements() &&
947 "Invalid initializer for constant array");
Chris Lattner2f7c9632001-06-06 20:29:01 +0000948}
949
Chris Lattner229907c2011-07-18 04:54:35 +0000950Constant *ConstantArray::get(ArrayType *Ty, ArrayRef<Constant*> V) {
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +0000951 if (Constant *C = getImpl(Ty, V))
952 return C;
953 return Ty->getContext().pImpl->ArrayConstants.getOrCreate(Ty, V);
954}
Justin Bogner909e1c02015-12-01 20:20:49 +0000955
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +0000956Constant *ConstantArray::getImpl(ArrayType *Ty, ArrayRef<Constant*> V) {
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000957 // Empty arrays are canonicalized to ConstantAggregateZero.
958 if (V.empty())
959 return ConstantAggregateZero::get(Ty);
960
Jeffrey Yasskin8ce67f82009-09-30 21:08:08 +0000961 for (unsigned i = 0, e = V.size(); i != e; ++i) {
962 assert(V[i]->getType() == Ty->getElementType() &&
963 "Wrong type in array element initializer");
964 }
Galina Kistanovafc259902012-07-13 01:25:27 +0000965
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000966 // If this is an all-zero array, return a ConstantAggregateZero object. If
967 // all undef, return an UndefValue, if "all simple", then return a
968 // ConstantDataArray.
969 Constant *C = V[0];
970 if (isa<UndefValue>(C) && rangeOnlyContains(V.begin(), V.end(), C))
971 return UndefValue::get(Ty);
Chris Lattnerf14a67f2012-01-26 02:31:22 +0000972
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000973 if (C->isNullValue() && rangeOnlyContains(V.begin(), V.end(), C))
974 return ConstantAggregateZero::get(Ty);
975
976 // Check to see if all of the elements are ConstantFP or ConstantInt and if
977 // the element type is compatible with ConstantDataVector. If so, use it.
Justin Bogner909e1c02015-12-01 20:20:49 +0000978 if (ConstantDataSequential::isElementTypeCompatible(C->getType()))
979 return getSequenceIfElementsMatch<ConstantDataArray>(C, V);
Chris Lattnerf14a67f2012-01-26 02:31:22 +0000980
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000981 // Otherwise, we really do want to create a ConstantArray.
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +0000982 return nullptr;
Owen Andersonc2c79322009-07-28 18:32:17 +0000983}
984
Chris Lattnercc19efa2011-06-20 04:01:31 +0000985StructType *ConstantStruct::getTypeForElements(LLVMContext &Context,
986 ArrayRef<Constant*> V,
987 bool Packed) {
Bill Wendling3ae7dd32012-02-07 01:27:51 +0000988 unsigned VecSize = V.size();
989 SmallVector<Type*, 16> EltTypes(VecSize);
990 for (unsigned i = 0; i != VecSize; ++i)
991 EltTypes[i] = V[i]->getType();
Galina Kistanovafc259902012-07-13 01:25:27 +0000992
Chris Lattnercc19efa2011-06-20 04:01:31 +0000993 return StructType::get(Context, EltTypes, Packed);
994}
995
996
997StructType *ConstantStruct::getTypeForElements(ArrayRef<Constant*> V,
998 bool Packed) {
999 assert(!V.empty() &&
1000 "ConstantStruct::getTypeForElements cannot be called on empty list");
1001 return getTypeForElements(V[0]->getContext(), V, Packed);
1002}
1003
Jay Foad89d9b812011-07-25 10:14:44 +00001004ConstantStruct::ConstantStruct(StructType *T, ArrayRef<Constant *> V)
Duncan P. N. Exon Smith1de3c7e2016-04-05 21:10:45 +00001005 : ConstantAggregate(T, ConstantStructVal, V) {
1006 assert((T->isOpaque() || V.size() == T->getNumElements()) &&
1007 "Invalid initializer for constant struct");
Chris Lattner2f7c9632001-06-06 20:29:01 +00001008}
1009
Owen Anderson45308b52009-07-27 22:29:26 +00001010// ConstantStruct accessors.
Chris Lattner229907c2011-07-18 04:54:35 +00001011Constant *ConstantStruct::get(StructType *ST, ArrayRef<Constant*> V) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001012 assert((ST->isOpaque() || ST->getNumElements() == V.size()) &&
1013 "Incorrect # elements specified to ConstantStruct::get");
Chris Lattnerf14a67f2012-01-26 02:31:22 +00001014
1015 // Create a ConstantAggregateZero value if all elements are zeros.
1016 bool isZero = true;
1017 bool isUndef = false;
Bjorn Petterssonaa025802018-07-03 12:39:52 +00001018
Chris Lattnerf14a67f2012-01-26 02:31:22 +00001019 if (!V.empty()) {
1020 isUndef = isa<UndefValue>(V[0]);
1021 isZero = V[0]->isNullValue();
1022 if (isUndef || isZero) {
1023 for (unsigned i = 0, e = V.size(); i != e; ++i) {
1024 if (!V[i]->isNullValue())
1025 isZero = false;
1026 if (!isa<UndefValue>(V[i]))
1027 isUndef = false;
1028 }
1029 }
Galina Kistanovafc259902012-07-13 01:25:27 +00001030 }
Chris Lattnerf14a67f2012-01-26 02:31:22 +00001031 if (isZero)
1032 return ConstantAggregateZero::get(ST);
1033 if (isUndef)
1034 return UndefValue::get(ST);
Galina Kistanovafc259902012-07-13 01:25:27 +00001035
Chris Lattnerf14a67f2012-01-26 02:31:22 +00001036 return ST->getContext().pImpl->StructConstants.getOrCreate(ST, V);
Owen Anderson45308b52009-07-27 22:29:26 +00001037}
1038
Jay Foad89d9b812011-07-25 10:14:44 +00001039ConstantVector::ConstantVector(VectorType *T, ArrayRef<Constant *> V)
Duncan P. N. Exon Smith1de3c7e2016-04-05 21:10:45 +00001040 : ConstantAggregate(T, ConstantVectorVal, V) {
Duncan P. N. Exon Smithdb63bda2016-04-05 20:53:47 +00001041 assert(V.size() == T->getNumElements() &&
Duncan P. N. Exon Smith1de3c7e2016-04-05 21:10:45 +00001042 "Invalid initializer for constant vector");
Brian Gaeke02209042004-08-20 06:00:58 +00001043}
1044
Owen Anderson4aa32952009-07-28 21:19:26 +00001045// ConstantVector accessors.
Jay Foadb8a8bed32011-06-22 09:10:19 +00001046Constant *ConstantVector::get(ArrayRef<Constant*> V) {
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00001047 if (Constant *C = getImpl(V))
1048 return C;
1049 VectorType *Ty = VectorType::get(V.front()->getType(), V.size());
1050 return Ty->getContext().pImpl->VectorConstants.getOrCreate(Ty, V);
1051}
Justin Bogner909e1c02015-12-01 20:20:49 +00001052
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00001053Constant *ConstantVector::getImpl(ArrayRef<Constant*> V) {
Jay Foad9f32cfd2011-01-27 14:44:55 +00001054 assert(!V.empty() && "Vectors can't be empty");
Chris Lattner229907c2011-07-18 04:54:35 +00001055 VectorType *T = VectorType::get(V.front()->getType(), V.size());
Jay Foad9f32cfd2011-01-27 14:44:55 +00001056
Chris Lattner69229312011-02-15 00:14:00 +00001057 // If this is an all-undef or all-zero vector, return a
Owen Anderson4aa32952009-07-28 21:19:26 +00001058 // ConstantAggregateZero or UndefValue.
1059 Constant *C = V[0];
1060 bool isZero = C->isNullValue();
1061 bool isUndef = isa<UndefValue>(C);
1062
1063 if (isZero || isUndef) {
1064 for (unsigned i = 1, e = V.size(); i != e; ++i)
1065 if (V[i] != C) {
1066 isZero = isUndef = false;
1067 break;
1068 }
1069 }
Galina Kistanovafc259902012-07-13 01:25:27 +00001070
Owen Anderson4aa32952009-07-28 21:19:26 +00001071 if (isZero)
Owen Andersonb292b8c2009-07-30 23:03:37 +00001072 return ConstantAggregateZero::get(T);
Owen Anderson4aa32952009-07-28 21:19:26 +00001073 if (isUndef)
Owen Andersonb292b8c2009-07-30 23:03:37 +00001074 return UndefValue::get(T);
Galina Kistanovafc259902012-07-13 01:25:27 +00001075
Chris Lattner978fe0c2012-01-30 06:21:21 +00001076 // Check to see if all of the elements are ConstantFP or ConstantInt and if
1077 // the element type is compatible with ConstantDataVector. If so, use it.
Justin Bogner909e1c02015-12-01 20:20:49 +00001078 if (ConstantDataSequential::isElementTypeCompatible(C->getType()))
1079 return getSequenceIfElementsMatch<ConstantDataVector>(C, V);
Galina Kistanovafc259902012-07-13 01:25:27 +00001080
Chris Lattner978fe0c2012-01-30 06:21:21 +00001081 // Otherwise, the element type isn't compatible with ConstantDataVector, or
Craig Topperdf907262017-04-11 06:41:55 +00001082 // the operand list contains a ConstantExpr or something else strange.
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00001083 return nullptr;
Owen Anderson4aa32952009-07-28 21:19:26 +00001084}
1085
Chris Lattnere9eed292012-01-25 05:19:54 +00001086Constant *ConstantVector::getSplat(unsigned NumElts, Constant *V) {
Chris Lattner978fe0c2012-01-30 06:21:21 +00001087 // If this splat is compatible with ConstantDataVector, use it instead of
1088 // ConstantVector.
1089 if ((isa<ConstantFP>(V) || isa<ConstantInt>(V)) &&
1090 ConstantDataSequential::isElementTypeCompatible(V->getType()))
1091 return ConstantDataVector::getSplat(NumElts, V);
Galina Kistanovafc259902012-07-13 01:25:27 +00001092
Chris Lattnere9eed292012-01-25 05:19:54 +00001093 SmallVector<Constant*, 32> Elts(NumElts, V);
1094 return get(Elts);
1095}
1096
David Majnemerf0f224d2015-11-11 21:57:16 +00001097ConstantTokenNone *ConstantTokenNone::get(LLVMContext &Context) {
1098 LLVMContextImpl *pImpl = Context.pImpl;
1099 if (!pImpl->TheNoneToken)
David Majnemer2dd41c52015-11-16 20:55:57 +00001100 pImpl->TheNoneToken.reset(new ConstantTokenNone(Context));
1101 return pImpl->TheNoneToken.get();
David Majnemerf0f224d2015-11-11 21:57:16 +00001102}
1103
1104/// Remove the constant from the constant table.
1105void ConstantTokenNone::destroyConstantImpl() {
1106 llvm_unreachable("You can't ConstantTokenNone->destroyConstantImpl()!");
1107}
Chris Lattnere9eed292012-01-25 05:19:54 +00001108
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001109// Utility function for determining if a ConstantExpr is a CastOp or not. This
1110// can't be inline because we don't want to #include Instruction.h into
1111// Constant.h
1112bool ConstantExpr::isCast() const {
1113 return Instruction::isCast(getOpcode());
1114}
1115
Reid Spenceree3c9912006-12-04 05:19:50 +00001116bool ConstantExpr::isCompare() const {
Nick Lewyckya21d3da2009-07-08 03:04:38 +00001117 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
Reid Spenceree3c9912006-12-04 05:19:50 +00001118}
1119
Dan Gohman7190d482009-09-10 23:37:55 +00001120bool ConstantExpr::isGEPWithNoNotionalOverIndexing() const {
1121 if (getOpcode() != Instruction::GetElementPtr) return false;
1122
1123 gep_type_iterator GEPI = gep_type_begin(this), E = gep_type_end(this);
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001124 User::const_op_iterator OI = std::next(this->op_begin());
Dan Gohman7190d482009-09-10 23:37:55 +00001125
Sanjay Patel81ed3492016-12-11 20:07:02 +00001126 // The remaining indices may be compile-time known integers within the bounds
1127 // of the corresponding notional static array types.
Dan Gohman7190d482009-09-10 23:37:55 +00001128 for (; GEPI != E; ++GEPI, ++OI) {
Sanjay Patel81ed3492016-12-11 20:07:02 +00001129 if (isa<UndefValue>(*OI))
1130 continue;
1131 auto *CI = dyn_cast<ConstantInt>(*OI);
1132 if (!CI || (GEPI.isBoundedSequential() &&
1133 (CI->getValue().getActiveBits() > 64 ||
1134 CI->getZExtValue() >= GEPI.getSequentialNumElements())))
Peter Collingbourneab85225b2016-12-02 02:24:42 +00001135 return false;
Dan Gohman7190d482009-09-10 23:37:55 +00001136 }
1137
1138 // All the indices checked out.
1139 return true;
1140}
1141
Dan Gohman1ecaf452008-05-31 00:58:22 +00001142bool ConstantExpr::hasIndices() const {
1143 return getOpcode() == Instruction::ExtractValue ||
1144 getOpcode() == Instruction::InsertValue;
1145}
1146
Jay Foad0091fe82011-04-13 15:22:40 +00001147ArrayRef<unsigned> ConstantExpr::getIndices() const {
Dan Gohman1ecaf452008-05-31 00:58:22 +00001148 if (const ExtractValueConstantExpr *EVCE =
1149 dyn_cast<ExtractValueConstantExpr>(this))
1150 return EVCE->Indices;
Dan Gohmana469bdb2008-06-23 16:39:44 +00001151
1152 return cast<InsertValueConstantExpr>(this)->Indices;
Dan Gohman1ecaf452008-05-31 00:58:22 +00001153}
1154
Reid Spencer10fbf0e2006-12-03 05:48:19 +00001155unsigned ConstantExpr::getPredicate() const {
Craig Toppercc03b492015-12-15 06:11:36 +00001156 return cast<CompareConstantExpr>(this)->predicate;
Reid Spencer10fbf0e2006-12-03 05:48:19 +00001157}
Chris Lattner60e0dd72001-10-03 06:12:09 +00001158
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001159Constant *
1160ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
Chris Lattner7c1018a2006-07-14 19:37:40 +00001161 assert(Op->getType() == getOperand(OpNo)->getType() &&
1162 "Replacing operand with value of different type!");
Chris Lattner227816342006-07-14 22:20:01 +00001163 if (getOperand(OpNo) == Op)
1164 return const_cast<ConstantExpr*>(this);
Chris Lattner37e38352012-01-26 20:37:11 +00001165
1166 SmallVector<Constant*, 8> NewOps;
1167 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1168 NewOps.push_back(i == OpNo ? Op : getOperand(i));
Galina Kistanovafc259902012-07-13 01:25:27 +00001169
Chris Lattner37e38352012-01-26 20:37:11 +00001170 return getWithOperands(NewOps);
Chris Lattner227816342006-07-14 22:20:01 +00001171}
1172
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001173Constant *ConstantExpr::getWithOperands(ArrayRef<Constant *> Ops, Type *Ty,
David Blaikie88208842015-08-21 20:16:51 +00001174 bool OnlyIfReduced, Type *SrcTy) const {
Jay Foad5c984e562011-04-13 13:46:01 +00001175 assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
Galina Kistanovafc259902012-07-13 01:25:27 +00001176
Benjamin Kramer8008e9f2015-03-02 11:57:04 +00001177 // If no operands changed return self.
1178 if (Ty == getType() && std::equal(Ops.begin(), Ops.end(), op_begin()))
Chris Lattner227816342006-07-14 22:20:01 +00001179 return const_cast<ConstantExpr*>(this);
1180
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001181 Type *OnlyIfReducedTy = OnlyIfReduced ? Ty : nullptr;
Chris Lattner227816342006-07-14 22:20:01 +00001182 switch (getOpcode()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001183 case Instruction::Trunc:
1184 case Instruction::ZExt:
1185 case Instruction::SExt:
1186 case Instruction::FPTrunc:
1187 case Instruction::FPExt:
1188 case Instruction::UIToFP:
1189 case Instruction::SIToFP:
1190 case Instruction::FPToUI:
1191 case Instruction::FPToSI:
1192 case Instruction::PtrToInt:
1193 case Instruction::IntToPtr:
1194 case Instruction::BitCast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00001195 case Instruction::AddrSpaceCast:
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001196 return ConstantExpr::getCast(getOpcode(), Ops[0], Ty, OnlyIfReduced);
Chris Lattner227816342006-07-14 22:20:01 +00001197 case Instruction::Select:
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001198 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2], OnlyIfReducedTy);
Chris Lattner227816342006-07-14 22:20:01 +00001199 case Instruction::InsertElement:
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001200 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2],
1201 OnlyIfReducedTy);
Chris Lattner227816342006-07-14 22:20:01 +00001202 case Instruction::ExtractElement:
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001203 return ConstantExpr::getExtractElement(Ops[0], Ops[1], OnlyIfReducedTy);
Chris Lattner37e38352012-01-26 20:37:11 +00001204 case Instruction::InsertValue:
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001205 return ConstantExpr::getInsertValue(Ops[0], Ops[1], getIndices(),
1206 OnlyIfReducedTy);
Chris Lattner37e38352012-01-26 20:37:11 +00001207 case Instruction::ExtractValue:
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001208 return ConstantExpr::getExtractValue(Ops[0], getIndices(), OnlyIfReducedTy);
Chris Lattner227816342006-07-14 22:20:01 +00001209 case Instruction::ShuffleVector:
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001210 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2],
1211 OnlyIfReducedTy);
David Blaikie88208842015-08-21 20:16:51 +00001212 case Instruction::GetElementPtr: {
1213 auto *GEPO = cast<GEPOperator>(this);
1214 assert(SrcTy || (Ops[0]->getType() == getOperand(0)->getType()));
1215 return ConstantExpr::getGetElementPtr(
1216 SrcTy ? SrcTy : GEPO->getSourceElementType(), Ops[0], Ops.slice(1),
Peter Collingbourned93620b2016-11-10 22:34:55 +00001217 GEPO->isInBounds(), GEPO->getInRangeIndex(), OnlyIfReducedTy);
David Blaikie88208842015-08-21 20:16:51 +00001218 }
Reid Spencer266e42b2006-12-23 06:05:41 +00001219 case Instruction::ICmp:
1220 case Instruction::FCmp:
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001221 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1],
1222 OnlyIfReducedTy);
Chris Lattner227816342006-07-14 22:20:01 +00001223 default:
1224 assert(getNumOperands() == 2 && "Must be binary operator?");
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001225 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1], SubclassOptionalData,
1226 OnlyIfReducedTy);
Chris Lattner7c1018a2006-07-14 19:37:40 +00001227 }
1228}
1229
Chris Lattner2f7c9632001-06-06 20:29:01 +00001230
1231//===----------------------------------------------------------------------===//
Chris Lattner2f7c9632001-06-06 20:29:01 +00001232// isValueValidForType implementations
1233
Chris Lattner229907c2011-07-18 04:54:35 +00001234bool ConstantInt::isValueValidForType(Type *Ty, uint64_t Val) {
Chris Lattner8326bd82012-01-26 00:42:34 +00001235 unsigned NumBits = Ty->getIntegerBitWidth(); // assert okay
1236 if (Ty->isIntegerTy(1))
Reid Spencer7a9c62b2007-01-12 07:05:14 +00001237 return Val == 0 || Val == 1;
Craig Topper50b1e512017-06-07 00:58:05 +00001238 return isUIntN(NumBits, Val);
Reid Spencere7334722006-12-19 01:28:19 +00001239}
1240
Chris Lattner229907c2011-07-18 04:54:35 +00001241bool ConstantInt::isValueValidForType(Type *Ty, int64_t Val) {
Chris Lattner8326bd82012-01-26 00:42:34 +00001242 unsigned NumBits = Ty->getIntegerBitWidth();
1243 if (Ty->isIntegerTy(1))
Reid Spencera94d3942007-01-19 21:13:56 +00001244 return Val == 0 || Val == 1 || Val == -1;
Craig Topper50b1e512017-06-07 00:58:05 +00001245 return isIntN(NumBits, Val);
Chris Lattner2f7c9632001-06-06 20:29:01 +00001246}
1247
Chris Lattner229907c2011-07-18 04:54:35 +00001248bool ConstantFP::isValueValidForType(Type *Ty, const APFloat& Val) {
Dale Johannesend246b2c2007-08-30 00:23:21 +00001249 // convert modifies in place, so make a copy.
1250 APFloat Val2 = APFloat(Val);
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001251 bool losesInfo;
Chris Lattner6b727592004-06-17 18:19:28 +00001252 switch (Ty->getTypeID()) {
Chris Lattner2f7c9632001-06-06 20:29:01 +00001253 default:
1254 return false; // These can't be represented as floating point!
1255
Dale Johannesend246b2c2007-08-30 00:23:21 +00001256 // FIXME rounding mode needs to be more flexible
Dan Gohman518cda42011-12-17 00:04:22 +00001257 case Type::HalfTyID: {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001258 if (&Val2.getSemantics() == &APFloat::IEEEhalf())
Dan Gohman518cda42011-12-17 00:04:22 +00001259 return true;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001260 Val2.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven, &losesInfo);
Dan Gohman518cda42011-12-17 00:04:22 +00001261 return !losesInfo;
1262 }
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001263 case Type::FloatTyID: {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001264 if (&Val2.getSemantics() == &APFloat::IEEEsingle())
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001265 return true;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001266 Val2.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, &losesInfo);
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001267 return !losesInfo;
1268 }
1269 case Type::DoubleTyID: {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001270 if (&Val2.getSemantics() == &APFloat::IEEEhalf() ||
1271 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
1272 &Val2.getSemantics() == &APFloat::IEEEdouble())
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001273 return true;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001274 Val2.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven, &losesInfo);
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001275 return !losesInfo;
1276 }
Dale Johannesenbdad8092007-08-09 22:51:36 +00001277 case Type::X86_FP80TyID:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001278 return &Val2.getSemantics() == &APFloat::IEEEhalf() ||
Bjorn Petterssonaa025802018-07-03 12:39:52 +00001279 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001280 &Val2.getSemantics() == &APFloat::IEEEdouble() ||
1281 &Val2.getSemantics() == &APFloat::x87DoubleExtended();
Dale Johannesenbdad8092007-08-09 22:51:36 +00001282 case Type::FP128TyID:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001283 return &Val2.getSemantics() == &APFloat::IEEEhalf() ||
Bjorn Petterssonaa025802018-07-03 12:39:52 +00001284 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001285 &Val2.getSemantics() == &APFloat::IEEEdouble() ||
1286 &Val2.getSemantics() == &APFloat::IEEEquad();
Dale Johannesen007aa372007-10-11 18:07:22 +00001287 case Type::PPC_FP128TyID:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001288 return &Val2.getSemantics() == &APFloat::IEEEhalf() ||
Bjorn Petterssonaa025802018-07-03 12:39:52 +00001289 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001290 &Val2.getSemantics() == &APFloat::IEEEdouble() ||
1291 &Val2.getSemantics() == &APFloat::PPCDoubleDouble();
Chris Lattner2f7c9632001-06-06 20:29:01 +00001292 }
Chris Lattneraa2372562006-05-24 17:04:05 +00001293}
Chris Lattner9655e542001-07-20 19:16:02 +00001294
Chris Lattner030af792012-01-24 05:42:11 +00001295
Chris Lattner49d855c2001-09-07 16:46:31 +00001296//===----------------------------------------------------------------------===//
Chris Lattner49d855c2001-09-07 16:46:31 +00001297// Factory Function Implementation
1298
Chris Lattnerc7f9fd42012-01-23 15:20:12 +00001299ConstantAggregateZero *ConstantAggregateZero::get(Type *Ty) {
Chris Lattner13ee7952010-08-28 04:09:24 +00001300 assert((Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()) &&
Owen Andersonb292b8c2009-07-30 23:03:37 +00001301 "Cannot create an aggregate zero of non-aggregate type!");
David Blaikie899b85a2014-11-25 02:13:54 +00001302
Justin Lebar611c5c22016-10-10 16:26:13 +00001303 std::unique_ptr<ConstantAggregateZero> &Entry =
1304 Ty->getContext().pImpl->CAZConstants[Ty];
1305 if (!Entry)
1306 Entry.reset(new ConstantAggregateZero(Ty));
1307
1308 return Entry.get();
Owen Andersonb292b8c2009-07-30 23:03:37 +00001309}
1310
Sanjay Patel1d0ac7c2016-04-29 22:03:27 +00001311/// Remove the constant from the constant table.
Pete Cooper86dd4cf2015-06-23 21:55:11 +00001312void ConstantAggregateZero::destroyConstantImpl() {
Chris Lattnerc7f9fd42012-01-23 15:20:12 +00001313 getContext().pImpl->CAZConstants.erase(getType());
Chris Lattner9fba3da2004-02-15 05:53:04 +00001314}
1315
Sanjay Patel1d0ac7c2016-04-29 22:03:27 +00001316/// Remove the constant from the constant table.
Pete Cooper86dd4cf2015-06-23 21:55:11 +00001317void ConstantArray::destroyConstantImpl() {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001318 getType()->getContext().pImpl->ArrayConstants.remove(this);
Chris Lattner98fa07b2003-05-23 20:03:32 +00001319}
1320
Chris Lattner81fabb02002-08-26 17:53:56 +00001321
Chris Lattner3462ae32001-12-03 22:26:30 +00001322//---- ConstantStruct::get() implementation...
Chris Lattner49d855c2001-09-07 16:46:31 +00001323//
Chris Lattnerb50d1352003-10-05 00:17:43 +00001324
Sanjay Patel1d0ac7c2016-04-29 22:03:27 +00001325/// Remove the constant from the constant table.
Pete Cooper86dd4cf2015-06-23 21:55:11 +00001326void ConstantStruct::destroyConstantImpl() {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001327 getType()->getContext().pImpl->StructConstants.remove(this);
Chris Lattnerd7a73302001-10-13 06:57:33 +00001328}
Chris Lattner883ad0b2001-10-03 15:39:36 +00001329
Sanjay Patel1d0ac7c2016-04-29 22:03:27 +00001330/// Remove the constant from the constant table.
Pete Cooper86dd4cf2015-06-23 21:55:11 +00001331void ConstantVector::destroyConstantImpl() {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001332 getType()->getContext().pImpl->VectorConstants.remove(this);
Brian Gaeke02209042004-08-20 06:00:58 +00001333}
1334
Duncan Sandse6beec62012-11-13 12:59:33 +00001335Constant *Constant::getSplatValue() const {
1336 assert(this->getType()->isVectorTy() && "Only valid for vectors!");
1337 if (isa<ConstantAggregateZero>(this))
1338 return getNullValue(this->getType()->getVectorElementType());
1339 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
1340 return CV->getSplatValue();
1341 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
1342 return CV->getSplatValue();
Craig Topperc6207612014-04-09 06:08:46 +00001343 return nullptr;
Duncan Sandse6beec62012-11-13 12:59:33 +00001344}
1345
Duncan Sandscf0ff032011-02-01 08:39:12 +00001346Constant *ConstantVector::getSplatValue() const {
Dan Gohman07159202007-10-17 17:51:30 +00001347 // Check out first element.
1348 Constant *Elt = getOperand(0);
1349 // Then make sure all remaining elements point to the same value.
1350 for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
Chris Lattnerd04e32d2011-07-17 06:01:30 +00001351 if (getOperand(I) != Elt)
Craig Topperc6207612014-04-09 06:08:46 +00001352 return nullptr;
Dan Gohman07159202007-10-17 17:51:30 +00001353 return Elt;
1354}
1355
Duncan Sandse6beec62012-11-13 12:59:33 +00001356const APInt &Constant::getUniqueInteger() const {
1357 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
1358 return CI->getValue();
1359 assert(this->getSplatValue() && "Doesn't contain a unique integer!");
1360 const Constant *C = this->getAggregateElement(0U);
1361 assert(C && isa<ConstantInt>(C) && "Not a vector of numbers!");
1362 return cast<ConstantInt>(C)->getValue();
1363}
1364
Chris Lattner31b132c2009-10-28 00:01:44 +00001365//---- ConstantPointerNull::get() implementation.
Chris Lattnerd7a73302001-10-13 06:57:33 +00001366//
Chris Lattner98fa07b2003-05-23 20:03:32 +00001367
Chris Lattner229907c2011-07-18 04:54:35 +00001368ConstantPointerNull *ConstantPointerNull::get(PointerType *Ty) {
Justin Lebar611c5c22016-10-10 16:26:13 +00001369 std::unique_ptr<ConstantPointerNull> &Entry =
1370 Ty->getContext().pImpl->CPNConstants[Ty];
Craig Topperc6207612014-04-09 06:08:46 +00001371 if (!Entry)
Justin Lebar611c5c22016-10-10 16:26:13 +00001372 Entry.reset(new ConstantPointerNull(Ty));
Galina Kistanovafc259902012-07-13 01:25:27 +00001373
Justin Lebar611c5c22016-10-10 16:26:13 +00001374 return Entry.get();
Chris Lattner883ad0b2001-10-03 15:39:36 +00001375}
1376
Sanjay Patel1d0ac7c2016-04-29 22:03:27 +00001377/// Remove the constant from the constant table.
Pete Cooper86dd4cf2015-06-23 21:55:11 +00001378void ConstantPointerNull::destroyConstantImpl() {
Chris Lattnerc7f9fd42012-01-23 15:20:12 +00001379 getContext().pImpl->CPNConstants.erase(getType());
Chris Lattner0c6e0b92002-08-18 00:40:04 +00001380}
1381
Chris Lattner229907c2011-07-18 04:54:35 +00001382UndefValue *UndefValue::get(Type *Ty) {
Justin Lebar611c5c22016-10-10 16:26:13 +00001383 std::unique_ptr<UndefValue> &Entry = Ty->getContext().pImpl->UVConstants[Ty];
Craig Topperc6207612014-04-09 06:08:46 +00001384 if (!Entry)
Justin Lebar611c5c22016-10-10 16:26:13 +00001385 Entry.reset(new UndefValue(Ty));
Galina Kistanovafc259902012-07-13 01:25:27 +00001386
Justin Lebar611c5c22016-10-10 16:26:13 +00001387 return Entry.get();
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001388}
1389
Sanjay Patel1d0ac7c2016-04-29 22:03:27 +00001390/// Remove the constant from the constant table.
Pete Cooper86dd4cf2015-06-23 21:55:11 +00001391void UndefValue::destroyConstantImpl() {
Chris Lattnerc7f9fd42012-01-23 15:20:12 +00001392 // Free the constant and any dangling references to it.
1393 getContext().pImpl->UVConstants.erase(getType());
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001394}
1395
Chris Lattner31b132c2009-10-28 00:01:44 +00001396BlockAddress *BlockAddress::get(BasicBlock *BB) {
Craig Topper2617dcc2014-04-15 06:32:26 +00001397 assert(BB->getParent() && "Block must have a parent");
Chris Lattner31b132c2009-10-28 00:01:44 +00001398 return get(BB->getParent(), BB);
1399}
1400
1401BlockAddress *BlockAddress::get(Function *F, BasicBlock *BB) {
1402 BlockAddress *&BA =
1403 F->getContext().pImpl->BlockAddresses[std::make_pair(F, BB)];
Craig Topperc6207612014-04-09 06:08:46 +00001404 if (!BA)
Chris Lattner31b132c2009-10-28 00:01:44 +00001405 BA = new BlockAddress(F, BB);
Galina Kistanovafc259902012-07-13 01:25:27 +00001406
Chris Lattner31b132c2009-10-28 00:01:44 +00001407 assert(BA->getFunction() == F && "Basic block moved between functions");
1408 return BA;
1409}
1410
1411BlockAddress::BlockAddress(Function *F, BasicBlock *BB)
1412: Constant(Type::getInt8PtrTy(F->getContext()), Value::BlockAddressVal,
1413 &Op<0>(), 2) {
Chris Lattnerc559a9f2009-11-01 03:03:03 +00001414 setOperand(0, F);
1415 setOperand(1, BB);
Chris Lattneraa99c942009-11-01 01:27:45 +00001416 BB->AdjustBlockAddressRefCount(1);
Chris Lattner31b132c2009-10-28 00:01:44 +00001417}
1418
Chandler Carruth6a936922014-01-19 02:13:50 +00001419BlockAddress *BlockAddress::lookup(const BasicBlock *BB) {
1420 if (!BB->hasAddressTaken())
Craig Topperc6207612014-04-09 06:08:46 +00001421 return nullptr;
Chandler Carruth6a936922014-01-19 02:13:50 +00001422
1423 const Function *F = BB->getParent();
Craig Topper2617dcc2014-04-15 06:32:26 +00001424 assert(F && "Block must have a parent");
Chandler Carruth6a936922014-01-19 02:13:50 +00001425 BlockAddress *BA =
1426 F->getContext().pImpl->BlockAddresses.lookup(std::make_pair(F, BB));
1427 assert(BA && "Refcount and block address map disagree!");
1428 return BA;
1429}
Chris Lattner31b132c2009-10-28 00:01:44 +00001430
Sanjay Patel1d0ac7c2016-04-29 22:03:27 +00001431/// Remove the constant from the constant table.
Pete Cooper86dd4cf2015-06-23 21:55:11 +00001432void BlockAddress::destroyConstantImpl() {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001433 getFunction()->getType()->getContext().pImpl
Chris Lattner31b132c2009-10-28 00:01:44 +00001434 ->BlockAddresses.erase(std::make_pair(getFunction(), getBasicBlock()));
Chris Lattneraa99c942009-11-01 01:27:45 +00001435 getBasicBlock()->AdjustBlockAddressRefCount(-1);
Chris Lattner31b132c2009-10-28 00:01:44 +00001436}
1437
Mehdi Amini8914d292016-02-10 22:47:15 +00001438Value *BlockAddress::handleOperandChangeImpl(Value *From, Value *To) {
Chris Lattner31b132c2009-10-28 00:01:44 +00001439 // This could be replacing either the Basic Block or the Function. In either
1440 // case, we have to remove the map entry.
1441 Function *NewF = getFunction();
1442 BasicBlock *NewBB = getBasicBlock();
Galina Kistanovafc259902012-07-13 01:25:27 +00001443
Mehdi Amini8914d292016-02-10 22:47:15 +00001444 if (From == NewF)
Derek Schuffec9dc012013-06-13 19:51:17 +00001445 NewF = cast<Function>(To->stripPointerCasts());
Mehdi Amini8914d292016-02-10 22:47:15 +00001446 else {
1447 assert(From == NewBB && "From does not match any operand");
Chris Lattner31b132c2009-10-28 00:01:44 +00001448 NewBB = cast<BasicBlock>(To);
Mehdi Amini8914d292016-02-10 22:47:15 +00001449 }
Galina Kistanovafc259902012-07-13 01:25:27 +00001450
Chris Lattner31b132c2009-10-28 00:01:44 +00001451 // See if the 'new' entry already exists, if not, just update this in place
1452 // and return early.
1453 BlockAddress *&NewBA =
1454 getContext().pImpl->BlockAddresses[std::make_pair(NewF, NewBB)];
Pete Cooper5815b1f2015-06-24 18:55:24 +00001455 if (NewBA)
1456 return NewBA;
Chris Lattner31b132c2009-10-28 00:01:44 +00001457
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00001458 getBasicBlock()->AdjustBlockAddressRefCount(-1);
Galina Kistanovafc259902012-07-13 01:25:27 +00001459
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00001460 // Remove the old entry, this can't cause the map to rehash (just a
1461 // tombstone will get added).
1462 getContext().pImpl->BlockAddresses.erase(std::make_pair(getFunction(),
1463 getBasicBlock()));
1464 NewBA = this;
1465 setOperand(0, NewF);
1466 setOperand(1, NewBB);
1467 getBasicBlock()->AdjustBlockAddressRefCount(1);
Pete Cooper5815b1f2015-06-24 18:55:24 +00001468
1469 // If we just want to keep the existing value, then return null.
1470 // Callers know that this means we shouldn't delete this value.
1471 return nullptr;
Chris Lattner31b132c2009-10-28 00:01:44 +00001472}
1473
1474//---- ConstantExpr::get() implementations.
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001475//
Reid Spencer8d9336d2006-12-31 05:26:44 +00001476
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001477/// This is a utility function to handle folding of casts and lookup of the
Duncan Sands7d6c8ae2008-03-30 19:38:55 +00001478/// cast in the ExprConstants map. It is used by the various get* methods below.
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001479static Constant *getFoldedCast(Instruction::CastOps opc, Constant *C, Type *Ty,
1480 bool OnlyIfReduced = false) {
Chris Lattner815ae2b2003-10-07 22:19:19 +00001481 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001482 // Fold a few common cases
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00001483 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001484 return FC;
Chris Lattneracdbe712003-04-17 19:24:48 +00001485
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001486 if (OnlyIfReduced)
1487 return nullptr;
1488
Owen Anderson1584a292009-08-04 20:25:11 +00001489 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
1490
Nadav Rotem88330432013-03-07 01:30:40 +00001491 // Look up the constant in the table first to ensure uniqueness.
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00001492 ConstantExprKeyType Key(opc, C);
Galina Kistanovafc259902012-07-13 01:25:27 +00001493
Owen Anderson1584a292009-08-04 20:25:11 +00001494 return pImpl->ExprConstants.getOrCreate(Ty, Key);
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001495}
Galina Kistanovafc259902012-07-13 01:25:27 +00001496
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001497Constant *ConstantExpr::getCast(unsigned oc, Constant *C, Type *Ty,
1498 bool OnlyIfReduced) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001499 Instruction::CastOps opc = Instruction::CastOps(oc);
1500 assert(Instruction::isCast(opc) && "opcode out of range");
1501 assert(C && Ty && "Null arguments to getCast");
Chris Lattner37bc78a2010-01-26 21:51:43 +00001502 assert(CastInst::castIsValid(opc, C, Ty) && "Invalid constantexpr cast!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001503
1504 switch (opc) {
Chris Lattner37bc78a2010-01-26 21:51:43 +00001505 default:
1506 llvm_unreachable("Invalid cast opcode");
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001507 case Instruction::Trunc:
1508 return getTrunc(C, Ty, OnlyIfReduced);
1509 case Instruction::ZExt:
1510 return getZExt(C, Ty, OnlyIfReduced);
1511 case Instruction::SExt:
1512 return getSExt(C, Ty, OnlyIfReduced);
1513 case Instruction::FPTrunc:
1514 return getFPTrunc(C, Ty, OnlyIfReduced);
1515 case Instruction::FPExt:
1516 return getFPExtend(C, Ty, OnlyIfReduced);
1517 case Instruction::UIToFP:
1518 return getUIToFP(C, Ty, OnlyIfReduced);
1519 case Instruction::SIToFP:
1520 return getSIToFP(C, Ty, OnlyIfReduced);
1521 case Instruction::FPToUI:
1522 return getFPToUI(C, Ty, OnlyIfReduced);
1523 case Instruction::FPToSI:
1524 return getFPToSI(C, Ty, OnlyIfReduced);
1525 case Instruction::PtrToInt:
1526 return getPtrToInt(C, Ty, OnlyIfReduced);
1527 case Instruction::IntToPtr:
1528 return getIntToPtr(C, Ty, OnlyIfReduced);
1529 case Instruction::BitCast:
1530 return getBitCast(C, Ty, OnlyIfReduced);
1531 case Instruction::AddrSpaceCast:
1532 return getAddrSpaceCast(C, Ty, OnlyIfReduced);
Chris Lattner1ece6f82005-01-01 15:59:57 +00001533 }
Galina Kistanovafc259902012-07-13 01:25:27 +00001534}
Reid Spencerf37dc652006-12-05 19:14:13 +00001535
Chris Lattner229907c2011-07-18 04:54:35 +00001536Constant *ConstantExpr::getZExtOrBitCast(Constant *C, Type *Ty) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001537 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
Dan Gohman3cdcc3f2010-04-12 22:12:29 +00001538 return getBitCast(C, Ty);
1539 return getZExt(C, Ty);
Reid Spencer5c140882006-12-04 20:17:56 +00001540}
1541
Chris Lattner229907c2011-07-18 04:54:35 +00001542Constant *ConstantExpr::getSExtOrBitCast(Constant *C, Type *Ty) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001543 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
Dan Gohman3cdcc3f2010-04-12 22:12:29 +00001544 return getBitCast(C, Ty);
1545 return getSExt(C, Ty);
Reid Spencer5c140882006-12-04 20:17:56 +00001546}
1547
Chris Lattner229907c2011-07-18 04:54:35 +00001548Constant *ConstantExpr::getTruncOrBitCast(Constant *C, Type *Ty) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001549 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
Dan Gohman3cdcc3f2010-04-12 22:12:29 +00001550 return getBitCast(C, Ty);
1551 return getTrunc(C, Ty);
Reid Spencer5c140882006-12-04 20:17:56 +00001552}
1553
Chris Lattner229907c2011-07-18 04:54:35 +00001554Constant *ConstantExpr::getPointerCast(Constant *S, Type *Ty) {
Evgeniy Stepanov23382642013-01-16 14:41:46 +00001555 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
1556 assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
1557 "Invalid cast");
Reid Spencerbc245a02006-12-05 03:25:26 +00001558
Evgeniy Stepanov23382642013-01-16 14:41:46 +00001559 if (Ty->isIntOrIntVectorTy())
Dan Gohman3cdcc3f2010-04-12 22:12:29 +00001560 return getPtrToInt(S, Ty);
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00001561
1562 unsigned SrcAS = S->getType()->getPointerAddressSpace();
1563 if (Ty->isPtrOrPtrVectorTy() && SrcAS != Ty->getPointerAddressSpace())
1564 return getAddrSpaceCast(S, Ty);
1565
Dan Gohman3cdcc3f2010-04-12 22:12:29 +00001566 return getBitCast(S, Ty);
Reid Spencerbc245a02006-12-05 03:25:26 +00001567}
1568
Matt Arsenault21f38f42013-12-07 02:58:41 +00001569Constant *ConstantExpr::getPointerBitCastOrAddrSpaceCast(Constant *S,
1570 Type *Ty) {
1571 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
1572 assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast");
1573
1574 if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace())
1575 return getAddrSpaceCast(S, Ty);
1576
1577 return getBitCast(S, Ty);
1578}
1579
Sanjay Patelf3587ec2016-05-18 22:05:28 +00001580Constant *ConstantExpr::getIntegerCast(Constant *C, Type *Ty, bool isSigned) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00001581 assert(C->getType()->isIntOrIntVectorTy() &&
1582 Ty->isIntOrIntVectorTy() && "Invalid cast");
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001583 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1584 unsigned DstBits = Ty->getScalarSizeInBits();
Reid Spencer56521c42006-12-12 00:51:07 +00001585 Instruction::CastOps opcode =
1586 (SrcBits == DstBits ? Instruction::BitCast :
1587 (SrcBits > DstBits ? Instruction::Trunc :
1588 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1589 return getCast(opcode, C, Ty);
1590}
1591
Chris Lattner229907c2011-07-18 04:54:35 +00001592Constant *ConstantExpr::getFPCast(Constant *C, Type *Ty) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00001593 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
Reid Spencer56521c42006-12-12 00:51:07 +00001594 "Invalid cast");
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001595 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1596 unsigned DstBits = Ty->getScalarSizeInBits();
Reid Spencerca104e82006-12-12 05:38:50 +00001597 if (SrcBits == DstBits)
1598 return C; // Avoid a useless cast
Reid Spencer56521c42006-12-12 00:51:07 +00001599 Instruction::CastOps opcode =
Jay Foad9f32cfd2011-01-27 14:44:55 +00001600 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
Reid Spencer56521c42006-12-12 00:51:07 +00001601 return getCast(opcode, C, Ty);
1602}
1603
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001604Constant *ConstantExpr::getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001605#ifndef NDEBUG
1606 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1607 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1608#endif
1609 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001610 assert(C->getType()->isIntOrIntVectorTy() && "Trunc operand must be integer");
1611 assert(Ty->isIntOrIntVectorTy() && "Trunc produces only integral");
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001612 assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001613 "SrcTy must be larger than DestTy for Trunc!");
1614
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001615 return getFoldedCast(Instruction::Trunc, C, Ty, OnlyIfReduced);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001616}
1617
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001618Constant *ConstantExpr::getSExt(Constant *C, Type *Ty, bool OnlyIfReduced) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001619#ifndef NDEBUG
1620 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1621 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1622#endif
1623 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001624 assert(C->getType()->isIntOrIntVectorTy() && "SExt operand must be integral");
1625 assert(Ty->isIntOrIntVectorTy() && "SExt produces only integer");
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001626 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001627 "SrcTy must be smaller than DestTy for SExt!");
1628
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001629 return getFoldedCast(Instruction::SExt, C, Ty, OnlyIfReduced);
Chris Lattnerdd284742004-04-04 23:20:30 +00001630}
1631
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001632Constant *ConstantExpr::getZExt(Constant *C, Type *Ty, bool OnlyIfReduced) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001633#ifndef NDEBUG
1634 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1635 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1636#endif
1637 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001638 assert(C->getType()->isIntOrIntVectorTy() && "ZEXt operand must be integral");
1639 assert(Ty->isIntOrIntVectorTy() && "ZExt produces only integer");
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001640 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001641 "SrcTy must be smaller than DestTy for ZExt!");
1642
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001643 return getFoldedCast(Instruction::ZExt, C, Ty, OnlyIfReduced);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001644}
1645
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001646Constant *ConstantExpr::getFPTrunc(Constant *C, Type *Ty, bool OnlyIfReduced) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001647#ifndef NDEBUG
1648 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1649 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1650#endif
1651 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001652 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001653 C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001654 "This is an illegal floating point truncation!");
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001655 return getFoldedCast(Instruction::FPTrunc, C, Ty, OnlyIfReduced);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001656}
1657
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001658Constant *ConstantExpr::getFPExtend(Constant *C, Type *Ty, bool OnlyIfReduced) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001659#ifndef NDEBUG
1660 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1661 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1662#endif
1663 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001664 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001665 C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001666 "This is an illegal floating point extension!");
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001667 return getFoldedCast(Instruction::FPExt, C, Ty, OnlyIfReduced);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001668}
1669
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001670Constant *ConstantExpr::getUIToFP(Constant *C, Type *Ty, bool OnlyIfReduced) {
Devang Pateld26344d2008-11-03 23:20:04 +00001671#ifndef NDEBUG
Nate Begemand4d45c22007-11-17 03:58:34 +00001672 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1673 bool toVec = Ty->getTypeID() == Type::VectorTyID;
Devang Pateld26344d2008-11-03 23:20:04 +00001674#endif
Nate Begemand4d45c22007-11-17 03:58:34 +00001675 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001676 assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
Nate Begemand4d45c22007-11-17 03:58:34 +00001677 "This is an illegal uint to floating point cast!");
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001678 return getFoldedCast(Instruction::UIToFP, C, Ty, OnlyIfReduced);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001679}
1680
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001681Constant *ConstantExpr::getSIToFP(Constant *C, Type *Ty, bool OnlyIfReduced) {
Devang Pateld26344d2008-11-03 23:20:04 +00001682#ifndef NDEBUG
Nate Begemand4d45c22007-11-17 03:58:34 +00001683 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1684 bool toVec = Ty->getTypeID() == Type::VectorTyID;
Devang Pateld26344d2008-11-03 23:20:04 +00001685#endif
Nate Begemand4d45c22007-11-17 03:58:34 +00001686 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001687 assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001688 "This is an illegal sint to floating point cast!");
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001689 return getFoldedCast(Instruction::SIToFP, C, Ty, OnlyIfReduced);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001690}
1691
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001692Constant *ConstantExpr::getFPToUI(Constant *C, Type *Ty, bool OnlyIfReduced) {
Devang Pateld26344d2008-11-03 23:20:04 +00001693#ifndef NDEBUG
Nate Begemand4d45c22007-11-17 03:58:34 +00001694 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1695 bool toVec = Ty->getTypeID() == Type::VectorTyID;
Devang Pateld26344d2008-11-03 23:20:04 +00001696#endif
Nate Begemand4d45c22007-11-17 03:58:34 +00001697 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001698 assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
Nate Begemand4d45c22007-11-17 03:58:34 +00001699 "This is an illegal floating point to uint cast!");
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001700 return getFoldedCast(Instruction::FPToUI, C, Ty, OnlyIfReduced);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001701}
1702
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001703Constant *ConstantExpr::getFPToSI(Constant *C, Type *Ty, bool OnlyIfReduced) {
Devang Pateld26344d2008-11-03 23:20:04 +00001704#ifndef NDEBUG
Nate Begemand4d45c22007-11-17 03:58:34 +00001705 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1706 bool toVec = Ty->getTypeID() == Type::VectorTyID;
Devang Pateld26344d2008-11-03 23:20:04 +00001707#endif
Nate Begemand4d45c22007-11-17 03:58:34 +00001708 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001709 assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
Nate Begemand4d45c22007-11-17 03:58:34 +00001710 "This is an illegal floating point to sint cast!");
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001711 return getFoldedCast(Instruction::FPToSI, C, Ty, OnlyIfReduced);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001712}
1713
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001714Constant *ConstantExpr::getPtrToInt(Constant *C, Type *DstTy,
1715 bool OnlyIfReduced) {
Craig Topper95d23472017-07-09 07:04:00 +00001716 assert(C->getType()->isPtrOrPtrVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00001717 "PtrToInt source must be pointer or pointer vector");
Craig Topper95d23472017-07-09 07:04:00 +00001718 assert(DstTy->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00001719 "PtrToInt destination must be integer or integer vector");
Chris Lattner8a3df542012-01-25 01:32:59 +00001720 assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
Nick Lewyckyff509622012-01-25 03:20:12 +00001721 if (isa<VectorType>(C->getType()))
Chris Lattner8326bd82012-01-26 00:42:34 +00001722 assert(C->getType()->getVectorNumElements()==DstTy->getVectorNumElements()&&
Chris Lattner8a3df542012-01-25 01:32:59 +00001723 "Invalid cast between a different number of vector elements");
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001724 return getFoldedCast(Instruction::PtrToInt, C, DstTy, OnlyIfReduced);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001725}
1726
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001727Constant *ConstantExpr::getIntToPtr(Constant *C, Type *DstTy,
1728 bool OnlyIfReduced) {
Craig Topper95d23472017-07-09 07:04:00 +00001729 assert(C->getType()->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00001730 "IntToPtr source must be integer or integer vector");
Craig Topper95d23472017-07-09 07:04:00 +00001731 assert(DstTy->isPtrOrPtrVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00001732 "IntToPtr destination must be a pointer or pointer vector");
Chris Lattner8a3df542012-01-25 01:32:59 +00001733 assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
Nick Lewyckyff509622012-01-25 03:20:12 +00001734 if (isa<VectorType>(C->getType()))
Chris Lattner8326bd82012-01-26 00:42:34 +00001735 assert(C->getType()->getVectorNumElements()==DstTy->getVectorNumElements()&&
Chris Lattner8a3df542012-01-25 01:32:59 +00001736 "Invalid cast between a different number of vector elements");
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001737 return getFoldedCast(Instruction::IntToPtr, C, DstTy, OnlyIfReduced);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001738}
1739
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001740Constant *ConstantExpr::getBitCast(Constant *C, Type *DstTy,
1741 bool OnlyIfReduced) {
Chris Lattner37bc78a2010-01-26 21:51:43 +00001742 assert(CastInst::castIsValid(Instruction::BitCast, C, DstTy) &&
1743 "Invalid constantexpr bitcast!");
Galina Kistanovafc259902012-07-13 01:25:27 +00001744
Chris Lattnercbeda872009-03-21 06:55:54 +00001745 // It is common to ask for a bitcast of a value to its own type, handle this
1746 // speedily.
1747 if (C->getType() == DstTy) return C;
Galina Kistanovafc259902012-07-13 01:25:27 +00001748
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001749 return getFoldedCast(Instruction::BitCast, C, DstTy, OnlyIfReduced);
Chris Lattnerdd284742004-04-04 23:20:30 +00001750}
1751
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001752Constant *ConstantExpr::getAddrSpaceCast(Constant *C, Type *DstTy,
1753 bool OnlyIfReduced) {
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00001754 assert(CastInst::castIsValid(Instruction::AddrSpaceCast, C, DstTy) &&
1755 "Invalid constantexpr addrspacecast!");
1756
Jingyue Wubaabe502014-06-15 21:40:57 +00001757 // Canonicalize addrspacecasts between different pointer types by first
1758 // bitcasting the pointer type and then converting the address space.
1759 PointerType *SrcScalarTy = cast<PointerType>(C->getType()->getScalarType());
1760 PointerType *DstScalarTy = cast<PointerType>(DstTy->getScalarType());
1761 Type *DstElemTy = DstScalarTy->getElementType();
1762 if (SrcScalarTy->getElementType() != DstElemTy) {
1763 Type *MidTy = PointerType::get(DstElemTy, SrcScalarTy->getAddressSpace());
1764 if (VectorType *VT = dyn_cast<VectorType>(DstTy)) {
1765 // Handle vectors of pointers.
1766 MidTy = VectorType::get(MidTy, VT->getNumElements());
1767 }
1768 C = getBitCast(C, MidTy);
1769 }
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001770 return getFoldedCast(Instruction::AddrSpaceCast, C, DstTy, OnlyIfReduced);
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00001771}
1772
Chris Lattner887ecac2011-07-09 18:23:52 +00001773Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2,
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001774 unsigned Flags, Type *OnlyIfReducedTy) {
Chris Lattner887ecac2011-07-09 18:23:52 +00001775 // Check the operands for consistency first.
Simon Pilgrime0a6eb12018-06-22 10:48:02 +00001776 assert(Instruction::isBinaryOp(Opcode) &&
Chris Lattner38a9bcd2003-05-21 17:49:25 +00001777 "Invalid opcode in binary constant expression");
1778 assert(C1->getType() == C2->getType() &&
1779 "Operand types in binary constant expression should match");
Galina Kistanovafc259902012-07-13 01:25:27 +00001780
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001781#ifndef NDEBUG
1782 switch (Opcode) {
Dan Gohmana5b96452009-06-04 22:49:04 +00001783 case Instruction::Add:
Reid Spencer7eb55b32006-11-02 01:53:59 +00001784 case Instruction::Sub:
Dan Gohmana5b96452009-06-04 22:49:04 +00001785 case Instruction::Mul:
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001786 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001787 assert(C1->getType()->isIntOrIntVectorTy() &&
Dan Gohmana5b96452009-06-04 22:49:04 +00001788 "Tried to create an integer operation on a non-integer type!");
1789 break;
1790 case Instruction::FAdd:
1791 case Instruction::FSub:
1792 case Instruction::FMul:
1793 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001794 assert(C1->getType()->isFPOrFPVectorTy() &&
Dan Gohmana5b96452009-06-04 22:49:04 +00001795 "Tried to create a floating-point operation on a "
1796 "non-floating-point type!");
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001797 break;
Bjorn Petterssonaa025802018-07-03 12:39:52 +00001798 case Instruction::UDiv:
1799 case Instruction::SDiv:
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001800 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001801 assert(C1->getType()->isIntOrIntVectorTy() &&
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001802 "Tried to create an arithmetic operation on a non-arithmetic type!");
1803 break;
1804 case Instruction::FDiv:
1805 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001806 assert(C1->getType()->isFPOrFPVectorTy() &&
Dan Gohman7889f2b2009-06-15 22:25:12 +00001807 "Tried to create an arithmetic operation on a non-arithmetic type!");
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001808 break;
Bjorn Petterssonaa025802018-07-03 12:39:52 +00001809 case Instruction::URem:
1810 case Instruction::SRem:
Reid Spencer7eb55b32006-11-02 01:53:59 +00001811 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001812 assert(C1->getType()->isIntOrIntVectorTy() &&
Reid Spencer7eb55b32006-11-02 01:53:59 +00001813 "Tried to create an arithmetic operation on a non-arithmetic type!");
1814 break;
1815 case Instruction::FRem:
1816 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001817 assert(C1->getType()->isFPOrFPVectorTy() &&
Dan Gohman7889f2b2009-06-15 22:25:12 +00001818 "Tried to create an arithmetic operation on a non-arithmetic type!");
Reid Spencer7eb55b32006-11-02 01:53:59 +00001819 break;
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001820 case Instruction::And:
1821 case Instruction::Or:
1822 case Instruction::Xor:
1823 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001824 assert(C1->getType()->isIntOrIntVectorTy() &&
Misha Brukman3852f652005-01-27 06:46:38 +00001825 "Tried to create a logical operation on a non-integral type!");
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001826 break;
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001827 case Instruction::Shl:
Reid Spencerfdff9382006-11-08 06:47:33 +00001828 case Instruction::LShr:
1829 case Instruction::AShr:
Reid Spencer2341c222007-02-02 02:16:23 +00001830 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001831 assert(C1->getType()->isIntOrIntVectorTy() &&
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001832 "Tried to create a shift operation on a non-integer type!");
1833 break;
1834 default:
1835 break;
1836 }
1837#endif
1838
Chris Lattner887ecac2011-07-09 18:23:52 +00001839 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1840 return FC; // Fold a few common cases.
Galina Kistanovafc259902012-07-13 01:25:27 +00001841
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001842 if (OnlyIfReducedTy == C1->getType())
1843 return nullptr;
1844
Benjamin Kramer324322b2013-03-07 20:53:34 +00001845 Constant *ArgVec[] = { C1, C2 };
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00001846 ConstantExprKeyType Key(Opcode, ArgVec, 0, Flags);
Galina Kistanovafc259902012-07-13 01:25:27 +00001847
Chris Lattner887ecac2011-07-09 18:23:52 +00001848 LLVMContextImpl *pImpl = C1->getContext().pImpl;
1849 return pImpl->ExprConstants.getOrCreate(C1->getType(), Key);
Reid Spencera009d0d2006-12-04 21:35:24 +00001850}
1851
Chris Lattner229907c2011-07-18 04:54:35 +00001852Constant *ConstantExpr::getSizeOf(Type* Ty) {
Owen Anderson487375e2009-07-29 18:55:55 +00001853 // sizeof is implemented as: (i64) gep (Ty*)null, 1
1854 // Note that a non-inbounds gep is used, as null isn't within any object.
Owen Anderson55f1c092009-08-13 21:58:54 +00001855 Constant *GEPIdx = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
Owen Anderson487375e2009-07-29 18:55:55 +00001856 Constant *GEP = getGetElementPtr(
David Blaikie4a2e73b2015-04-02 18:55:32 +00001857 Ty, Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx);
Bjorn Petterssonaa025802018-07-03 12:39:52 +00001858 return getPtrToInt(GEP,
Dan Gohman3cdcc3f2010-04-12 22:12:29 +00001859 Type::getInt64Ty(Ty->getContext()));
Owen Anderson487375e2009-07-29 18:55:55 +00001860}
1861
Chris Lattner229907c2011-07-18 04:54:35 +00001862Constant *ConstantExpr::getAlignOf(Type* Ty) {
Dan Gohmancf913832010-01-28 02:15:55 +00001863 // alignof is implemented as: (i64) gep ({i1,Ty}*)null, 0, 1
Dan Gohman50c09d02009-08-11 17:57:01 +00001864 // Note that a non-inbounds gep is used, as null isn't within any object.
Serge Gueltone38003f2017-05-09 19:31:13 +00001865 Type *AligningTy = StructType::get(Type::getInt1Ty(Ty->getContext()), Ty);
Matt Arsenaultbe558882014-04-23 20:58:57 +00001866 Constant *NullPtr = Constant::getNullValue(AligningTy->getPointerTo(0));
Dan Gohmana9be7392010-01-28 02:43:22 +00001867 Constant *Zero = ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0);
Owen Anderson55f1c092009-08-13 21:58:54 +00001868 Constant *One = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
Owen Anderson487375e2009-07-29 18:55:55 +00001869 Constant *Indices[2] = { Zero, One };
David Blaikie4a2e73b2015-04-02 18:55:32 +00001870 Constant *GEP = getGetElementPtr(AligningTy, NullPtr, Indices);
Dan Gohman3cdcc3f2010-04-12 22:12:29 +00001871 return getPtrToInt(GEP,
1872 Type::getInt64Ty(Ty->getContext()));
Owen Anderson487375e2009-07-29 18:55:55 +00001873}
1874
Chris Lattner229907c2011-07-18 04:54:35 +00001875Constant *ConstantExpr::getOffsetOf(StructType* STy, unsigned FieldNo) {
Dan Gohmanede94e62010-02-01 16:37:38 +00001876 return getOffsetOf(STy, ConstantInt::get(Type::getInt32Ty(STy->getContext()),
1877 FieldNo));
1878}
1879
Chris Lattner229907c2011-07-18 04:54:35 +00001880Constant *ConstantExpr::getOffsetOf(Type* Ty, Constant *FieldNo) {
Dan Gohmanff3af7252009-08-16 21:26:11 +00001881 // offsetof is implemented as: (i64) gep (Ty*)null, 0, FieldNo
1882 // Note that a non-inbounds gep is used, as null isn't within any object.
1883 Constant *GEPIdx[] = {
Dan Gohmanede94e62010-02-01 16:37:38 +00001884 ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0),
1885 FieldNo
Dan Gohmanff3af7252009-08-16 21:26:11 +00001886 };
1887 Constant *GEP = getGetElementPtr(
David Blaikie4a2e73b2015-04-02 18:55:32 +00001888 Ty, Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx);
Dan Gohman3cdcc3f2010-04-12 22:12:29 +00001889 return getPtrToInt(GEP,
1890 Type::getInt64Ty(Ty->getContext()));
Dan Gohmanff3af7252009-08-16 21:26:11 +00001891}
Owen Anderson487375e2009-07-29 18:55:55 +00001892
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001893Constant *ConstantExpr::getCompare(unsigned short Predicate, Constant *C1,
1894 Constant *C2, bool OnlyIfReduced) {
Reid Spencera009d0d2006-12-04 21:35:24 +00001895 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Galina Kistanovafc259902012-07-13 01:25:27 +00001896
Chris Lattner887ecac2011-07-09 18:23:52 +00001897 switch (Predicate) {
1898 default: llvm_unreachable("Invalid CmpInst predicate");
1899 case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
1900 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
1901 case CmpInst::FCMP_ONE: case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
1902 case CmpInst::FCMP_UEQ: case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
1903 case CmpInst::FCMP_ULT: case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
1904 case CmpInst::FCMP_TRUE:
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001905 return getFCmp(Predicate, C1, C2, OnlyIfReduced);
Galina Kistanovafc259902012-07-13 01:25:27 +00001906
Chris Lattner887ecac2011-07-09 18:23:52 +00001907 case CmpInst::ICMP_EQ: case CmpInst::ICMP_NE: case CmpInst::ICMP_UGT:
1908 case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
1909 case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
1910 case CmpInst::ICMP_SLE:
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001911 return getICmp(Predicate, C1, C2, OnlyIfReduced);
Chris Lattner887ecac2011-07-09 18:23:52 +00001912 }
Chris Lattner29ca2c62004-08-04 18:50:09 +00001913}
1914
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001915Constant *ConstantExpr::getSelect(Constant *C, Constant *V1, Constant *V2,
1916 Type *OnlyIfReducedTy) {
Chris Lattner41632132008-12-29 00:16:12 +00001917 assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
Chris Lattner6e415c02004-03-12 05:54:04 +00001918
Chris Lattner887ecac2011-07-09 18:23:52 +00001919 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1920 return SC; // Fold common cases
Chris Lattner6e415c02004-03-12 05:54:04 +00001921
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001922 if (OnlyIfReducedTy == V1->getType())
1923 return nullptr;
1924
Benjamin Kramer324322b2013-03-07 20:53:34 +00001925 Constant *ArgVec[] = { C, V1, V2 };
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00001926 ConstantExprKeyType Key(Instruction::Select, ArgVec);
Galina Kistanovafc259902012-07-13 01:25:27 +00001927
Chris Lattner887ecac2011-07-09 18:23:52 +00001928 LLVMContextImpl *pImpl = C->getContext().pImpl;
1929 return pImpl->ExprConstants.getOrCreate(V1->getType(), Key);
Chris Lattner6e415c02004-03-12 05:54:04 +00001930}
1931
David Blaikie4a2e73b2015-04-02 18:55:32 +00001932Constant *ConstantExpr::getGetElementPtr(Type *Ty, Constant *C,
1933 ArrayRef<Value *> Idxs, bool InBounds,
Peter Collingbourned93620b2016-11-10 22:34:55 +00001934 Optional<unsigned> InRangeIndex,
David Blaikie4a2e73b2015-04-02 18:55:32 +00001935 Type *OnlyIfReducedTy) {
David Blaikie4a2e73b2015-04-02 18:55:32 +00001936 if (!Ty)
1937 Ty = cast<PointerType>(C->getType()->getScalarType())->getElementType();
1938 else
David Blaikied9d900c2015-05-07 17:28:58 +00001939 assert(
1940 Ty ==
1941 cast<PointerType>(C->getType()->getScalarType())->getContainedType(0u));
1942
Peter Collingbourned93620b2016-11-10 22:34:55 +00001943 if (Constant *FC =
1944 ConstantFoldGetElementPtr(Ty, C, InBounds, InRangeIndex, Idxs))
David Blaikied9d900c2015-05-07 17:28:58 +00001945 return FC; // Fold a few common cases.
1946
Chris Lattner887ecac2011-07-09 18:23:52 +00001947 // Get the result type of the getelementptr!
David Blaikie4a2e73b2015-04-02 18:55:32 +00001948 Type *DestTy = GetElementPtrInst::getIndexedType(Ty, Idxs);
1949 assert(DestTy && "GEP indices invalid!");
Chris Lattner8326bd82012-01-26 00:42:34 +00001950 unsigned AS = C->getType()->getPointerAddressSpace();
David Blaikie4a2e73b2015-04-02 18:55:32 +00001951 Type *ReqTy = DestTy->getPointerTo(AS);
Elena Demikhovskyee004bc2016-05-15 12:30:25 +00001952
1953 unsigned NumVecElts = 0;
1954 if (C->getType()->isVectorTy())
1955 NumVecElts = C->getType()->getVectorNumElements();
1956 else for (auto Idx : Idxs)
1957 if (Idx->getType()->isVectorTy())
1958 NumVecElts = Idx->getType()->getVectorNumElements();
1959
1960 if (NumVecElts)
1961 ReqTy = VectorType::get(ReqTy, NumVecElts);
Galina Kistanovafc259902012-07-13 01:25:27 +00001962
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001963 if (OnlyIfReducedTy == ReqTy)
1964 return nullptr;
1965
Dan Gohman1b849082009-09-07 23:54:19 +00001966 // Look up the constant in the table first to ensure uniqueness
1967 std::vector<Constant*> ArgVec;
Jay Foaded8db7d2011-07-21 14:31:17 +00001968 ArgVec.reserve(1 + Idxs.size());
Dan Gohman1b849082009-09-07 23:54:19 +00001969 ArgVec.push_back(C);
Duncan Sandse6beec62012-11-13 12:59:33 +00001970 for (unsigned i = 0, e = Idxs.size(); i != e; ++i) {
Duncan Sandse6beec62012-11-13 12:59:33 +00001971 assert((!Idxs[i]->getType()->isVectorTy() ||
Elena Demikhovskyee004bc2016-05-15 12:30:25 +00001972 Idxs[i]->getType()->getVectorNumElements() == NumVecElts) &&
Duncan Sandse6beec62012-11-13 12:59:33 +00001973 "getelementptr index type missmatch");
Elena Demikhovskyee004bc2016-05-15 12:30:25 +00001974
1975 Constant *Idx = cast<Constant>(Idxs[i]);
1976 if (NumVecElts && !Idxs[i]->getType()->isVectorTy())
1977 Idx = ConstantVector::getSplat(NumVecElts, Idx);
1978 ArgVec.push_back(Idx);
Duncan Sandse6beec62012-11-13 12:59:33 +00001979 }
Peter Collingbourned93620b2016-11-10 22:34:55 +00001980
1981 unsigned SubClassOptionalData = InBounds ? GEPOperator::IsInBounds : 0;
1982 if (InRangeIndex && *InRangeIndex < 63)
1983 SubClassOptionalData |= (*InRangeIndex + 1) << 1;
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00001984 const ConstantExprKeyType Key(Instruction::GetElementPtr, ArgVec, 0,
Peter Collingbourned93620b2016-11-10 22:34:55 +00001985 SubClassOptionalData, None, Ty);
Galina Kistanovafc259902012-07-13 01:25:27 +00001986
Chris Lattner887ecac2011-07-09 18:23:52 +00001987 LLVMContextImpl *pImpl = C->getContext().pImpl;
Dan Gohman1b849082009-09-07 23:54:19 +00001988 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1989}
1990
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001991Constant *ConstantExpr::getICmp(unsigned short pred, Constant *LHS,
1992 Constant *RHS, bool OnlyIfReduced) {
Reid Spenceree3c9912006-12-04 05:19:50 +00001993 assert(LHS->getType() == RHS->getType());
Craig Topper45844762017-07-05 23:35:46 +00001994 assert(CmpInst::isIntPredicate((CmpInst::Predicate)pred) &&
1995 "Invalid ICmp Predicate");
Reid Spenceree3c9912006-12-04 05:19:50 +00001996
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00001997 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
Reid Spenceree3c9912006-12-04 05:19:50 +00001998 return FC; // Fold a few common cases...
1999
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002000 if (OnlyIfReduced)
2001 return nullptr;
2002
Reid Spenceree3c9912006-12-04 05:19:50 +00002003 // Look up the constant in the table first to ensure uniqueness
Benjamin Kramer324322b2013-03-07 20:53:34 +00002004 Constant *ArgVec[] = { LHS, RHS };
Reid Spencerb1537492006-12-24 18:42:29 +00002005 // Get the key type with both the opcode and predicate
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002006 const ConstantExprKeyType Key(Instruction::ICmp, ArgVec, pred);
Owen Anderson61794042009-06-17 20:10:08 +00002007
Chris Lattner229907c2011-07-18 04:54:35 +00002008 Type *ResultTy = Type::getInt1Ty(LHS->getContext());
2009 if (VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
Nick Lewycky9e26c1c2010-01-21 07:03:21 +00002010 ResultTy = VectorType::get(ResultTy, VT->getNumElements());
2011
Owen Anderson1584a292009-08-04 20:25:11 +00002012 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
Nick Lewycky9e26c1c2010-01-21 07:03:21 +00002013 return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
Reid Spenceree3c9912006-12-04 05:19:50 +00002014}
2015
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002016Constant *ConstantExpr::getFCmp(unsigned short pred, Constant *LHS,
2017 Constant *RHS, bool OnlyIfReduced) {
Reid Spenceree3c9912006-12-04 05:19:50 +00002018 assert(LHS->getType() == RHS->getType());
Craig Topper45844762017-07-05 23:35:46 +00002019 assert(CmpInst::isFPPredicate((CmpInst::Predicate)pred) &&
2020 "Invalid FCmp Predicate");
Reid Spenceree3c9912006-12-04 05:19:50 +00002021
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00002022 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
Reid Spenceree3c9912006-12-04 05:19:50 +00002023 return FC; // Fold a few common cases...
2024
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002025 if (OnlyIfReduced)
2026 return nullptr;
2027
Reid Spenceree3c9912006-12-04 05:19:50 +00002028 // Look up the constant in the table first to ensure uniqueness
Benjamin Kramer324322b2013-03-07 20:53:34 +00002029 Constant *ArgVec[] = { LHS, RHS };
Reid Spencerb1537492006-12-24 18:42:29 +00002030 // Get the key type with both the opcode and predicate
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002031 const ConstantExprKeyType Key(Instruction::FCmp, ArgVec, pred);
Nick Lewycky9e26c1c2010-01-21 07:03:21 +00002032
Chris Lattner229907c2011-07-18 04:54:35 +00002033 Type *ResultTy = Type::getInt1Ty(LHS->getContext());
2034 if (VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
Nick Lewycky9e26c1c2010-01-21 07:03:21 +00002035 ResultTy = VectorType::get(ResultTy, VT->getNumElements());
2036
Owen Anderson1584a292009-08-04 20:25:11 +00002037 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
Nick Lewycky9e26c1c2010-01-21 07:03:21 +00002038 return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
Reid Spenceree3c9912006-12-04 05:19:50 +00002039}
2040
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002041Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx,
2042 Type *OnlyIfReducedTy) {
Duncan Sands19d0b472010-02-16 11:11:14 +00002043 assert(Val->getType()->isVectorTy() &&
Reid Spencer09575ba2007-02-15 03:39:18 +00002044 "Tried to create extractelement operation on non-vector type!");
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002045 assert(Idx->getType()->isIntegerTy() &&
2046 "Extractelement index must be an integer type!");
Galina Kistanovafc259902012-07-13 01:25:27 +00002047
Chris Lattner887ecac2011-07-09 18:23:52 +00002048 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
Chris Lattner09660c92009-12-30 20:25:09 +00002049 return FC; // Fold a few common cases.
Galina Kistanovafc259902012-07-13 01:25:27 +00002050
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002051 Type *ReqTy = Val->getType()->getVectorElementType();
2052 if (OnlyIfReducedTy == ReqTy)
2053 return nullptr;
2054
Robert Bocchinoca27f032006-01-17 20:07:22 +00002055 // Look up the constant in the table first to ensure uniqueness
Benjamin Kramer324322b2013-03-07 20:53:34 +00002056 Constant *ArgVec[] = { Val, Idx };
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002057 const ConstantExprKeyType Key(Instruction::ExtractElement, ArgVec);
Galina Kistanovafc259902012-07-13 01:25:27 +00002058
Chris Lattner887ecac2011-07-09 18:23:52 +00002059 LLVMContextImpl *pImpl = Val->getContext().pImpl;
Owen Anderson1584a292009-08-04 20:25:11 +00002060 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
Robert Bocchinoca27f032006-01-17 20:07:22 +00002061}
2062
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002063Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
2064 Constant *Idx, Type *OnlyIfReducedTy) {
Duncan Sands19d0b472010-02-16 11:11:14 +00002065 assert(Val->getType()->isVectorTy() &&
Reid Spencer09575ba2007-02-15 03:39:18 +00002066 "Tried to create insertelement operation on non-vector type!");
Chris Lattner8326bd82012-01-26 00:42:34 +00002067 assert(Elt->getType() == Val->getType()->getVectorElementType() &&
2068 "Insertelement types must match!");
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002069 assert(Idx->getType()->isIntegerTy() &&
Reid Spencer2546b762007-01-26 07:37:34 +00002070 "Insertelement index must be i32 type!");
Robert Bocchinoca27f032006-01-17 20:07:22 +00002071
Chris Lattner887ecac2011-07-09 18:23:52 +00002072 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
2073 return FC; // Fold a few common cases.
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002074
2075 if (OnlyIfReducedTy == Val->getType())
2076 return nullptr;
2077
Chris Lattnerbbe0a422006-04-08 01:18:18 +00002078 // Look up the constant in the table first to ensure uniqueness
Benjamin Kramer324322b2013-03-07 20:53:34 +00002079 Constant *ArgVec[] = { Val, Elt, Idx };
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002080 const ConstantExprKeyType Key(Instruction::InsertElement, ArgVec);
Galina Kistanovafc259902012-07-13 01:25:27 +00002081
Chris Lattner887ecac2011-07-09 18:23:52 +00002082 LLVMContextImpl *pImpl = Val->getContext().pImpl;
2083 return pImpl->ExprConstants.getOrCreate(Val->getType(), Key);
Chris Lattnerbbe0a422006-04-08 01:18:18 +00002084}
2085
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002086Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
2087 Constant *Mask, Type *OnlyIfReducedTy) {
Chris Lattnerbbe0a422006-04-08 01:18:18 +00002088 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
2089 "Invalid shuffle vector constant expr operands!");
Nate Begeman94aa38d2009-02-12 21:28:33 +00002090
Chris Lattner887ecac2011-07-09 18:23:52 +00002091 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
2092 return FC; // Fold a few common cases.
2093
Chris Lattner8326bd82012-01-26 00:42:34 +00002094 unsigned NElts = Mask->getType()->getVectorNumElements();
2095 Type *EltTy = V1->getType()->getVectorElementType();
Chris Lattner229907c2011-07-18 04:54:35 +00002096 Type *ShufTy = VectorType::get(EltTy, NElts);
Chris Lattner887ecac2011-07-09 18:23:52 +00002097
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002098 if (OnlyIfReducedTy == ShufTy)
2099 return nullptr;
2100
Chris Lattner887ecac2011-07-09 18:23:52 +00002101 // Look up the constant in the table first to ensure uniqueness
Benjamin Kramer324322b2013-03-07 20:53:34 +00002102 Constant *ArgVec[] = { V1, V2, Mask };
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002103 const ConstantExprKeyType Key(Instruction::ShuffleVector, ArgVec);
Galina Kistanovafc259902012-07-13 01:25:27 +00002104
Chris Lattner887ecac2011-07-09 18:23:52 +00002105 LLVMContextImpl *pImpl = ShufTy->getContext().pImpl;
2106 return pImpl->ExprConstants.getOrCreate(ShufTy, Key);
Chris Lattnerbbe0a422006-04-08 01:18:18 +00002107}
2108
Chris Lattner887ecac2011-07-09 18:23:52 +00002109Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002110 ArrayRef<unsigned> Idxs,
2111 Type *OnlyIfReducedTy) {
Hal Finkelb31366d2013-07-10 22:51:01 +00002112 assert(Agg->getType()->isFirstClassType() &&
2113 "Non-first-class type for constant insertvalue expression");
2114
Jay Foad57aa6362011-07-13 10:26:04 +00002115 assert(ExtractValueInst::getIndexedType(Agg->getType(),
2116 Idxs) == Val->getType() &&
Dan Gohman12fce772008-05-15 19:50:34 +00002117 "insertvalue indices invalid!");
Hal Finkelb31366d2013-07-10 22:51:01 +00002118 Type *ReqTy = Val->getType();
2119
2120 if (Constant *FC = ConstantFoldInsertValueInstruction(Agg, Val, Idxs))
2121 return FC;
2122
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002123 if (OnlyIfReducedTy == ReqTy)
2124 return nullptr;
2125
Hal Finkelb31366d2013-07-10 22:51:01 +00002126 Constant *ArgVec[] = { Agg, Val };
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002127 const ConstantExprKeyType Key(Instruction::InsertValue, ArgVec, 0, 0, Idxs);
Hal Finkelb31366d2013-07-10 22:51:01 +00002128
2129 LLVMContextImpl *pImpl = Agg->getContext().pImpl;
2130 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
Dan Gohman12fce772008-05-15 19:50:34 +00002131}
2132
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002133Constant *ConstantExpr::getExtractValue(Constant *Agg, ArrayRef<unsigned> Idxs,
2134 Type *OnlyIfReducedTy) {
Dan Gohman0752bff2008-05-23 00:36:11 +00002135 assert(Agg->getType()->isFirstClassType() &&
Chris Lattner887ecac2011-07-09 18:23:52 +00002136 "Tried to create extractelement operation on non-first-class type!");
Dan Gohman12fce772008-05-15 19:50:34 +00002137
Chris Lattner229907c2011-07-18 04:54:35 +00002138 Type *ReqTy = ExtractValueInst::getIndexedType(Agg->getType(), Idxs);
Chandler Carruth9db56b82011-07-10 09:45:35 +00002139 (void)ReqTy;
Chris Lattner887ecac2011-07-09 18:23:52 +00002140 assert(ReqTy && "extractvalue indices invalid!");
Galina Kistanovafc259902012-07-13 01:25:27 +00002141
Dan Gohman0752bff2008-05-23 00:36:11 +00002142 assert(Agg->getType()->isFirstClassType() &&
2143 "Non-first-class type for constant extractvalue expression");
Hal Finkelb31366d2013-07-10 22:51:01 +00002144 if (Constant *FC = ConstantFoldExtractValueInstruction(Agg, Idxs))
2145 return FC;
2146
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002147 if (OnlyIfReducedTy == ReqTy)
2148 return nullptr;
2149
Hal Finkelb31366d2013-07-10 22:51:01 +00002150 Constant *ArgVec[] = { Agg };
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002151 const ConstantExprKeyType Key(Instruction::ExtractValue, ArgVec, 0, 0, Idxs);
Hal Finkelb31366d2013-07-10 22:51:01 +00002152
2153 LLVMContextImpl *pImpl = Agg->getContext().pImpl;
2154 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
Dan Gohman12fce772008-05-15 19:50:34 +00002155}
2156
Chris Lattnere9b4ad72011-02-10 07:01:55 +00002157Constant *ConstantExpr::getNeg(Constant *C, bool HasNUW, bool HasNSW) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00002158 assert(C->getType()->isIntOrIntVectorTy() &&
Owen Anderson487375e2009-07-29 18:55:55 +00002159 "Cannot NEG a nonintegral value!");
Chris Lattnere9b4ad72011-02-10 07:01:55 +00002160 return getSub(ConstantFP::getZeroValueForNegation(C->getType()),
2161 C, HasNUW, HasNSW);
Owen Anderson487375e2009-07-29 18:55:55 +00002162}
2163
Chris Lattnera676c0f2011-02-07 16:40:21 +00002164Constant *ConstantExpr::getFNeg(Constant *C) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00002165 assert(C->getType()->isFPOrFPVectorTy() &&
Owen Anderson487375e2009-07-29 18:55:55 +00002166 "Cannot FNEG a non-floating-point value!");
Chris Lattnere9b4ad72011-02-10 07:01:55 +00002167 return getFSub(ConstantFP::getZeroValueForNegation(C->getType()), C);
Owen Anderson487375e2009-07-29 18:55:55 +00002168}
2169
Chris Lattnera676c0f2011-02-07 16:40:21 +00002170Constant *ConstantExpr::getNot(Constant *C) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00002171 assert(C->getType()->isIntOrIntVectorTy() &&
Owen Anderson487375e2009-07-29 18:55:55 +00002172 "Cannot NOT a nonintegral value!");
Owen Anderson5a1acd92009-07-31 20:28:14 +00002173 return get(Instruction::Xor, C, Constant::getAllOnesValue(C->getType()));
Owen Anderson487375e2009-07-29 18:55:55 +00002174}
2175
Chris Lattnere9b4ad72011-02-10 07:01:55 +00002176Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2,
2177 bool HasNUW, bool HasNSW) {
2178 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2179 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2180 return get(Instruction::Add, C1, C2, Flags);
Owen Anderson487375e2009-07-29 18:55:55 +00002181}
2182
Chris Lattnera676c0f2011-02-07 16:40:21 +00002183Constant *ConstantExpr::getFAdd(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002184 return get(Instruction::FAdd, C1, C2);
2185}
2186
Chris Lattnere9b4ad72011-02-10 07:01:55 +00002187Constant *ConstantExpr::getSub(Constant *C1, Constant *C2,
2188 bool HasNUW, bool HasNSW) {
2189 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2190 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2191 return get(Instruction::Sub, C1, C2, Flags);
Owen Anderson487375e2009-07-29 18:55:55 +00002192}
2193
Chris Lattnera676c0f2011-02-07 16:40:21 +00002194Constant *ConstantExpr::getFSub(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002195 return get(Instruction::FSub, C1, C2);
2196}
2197
Chris Lattnere9b4ad72011-02-10 07:01:55 +00002198Constant *ConstantExpr::getMul(Constant *C1, Constant *C2,
2199 bool HasNUW, bool HasNSW) {
2200 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2201 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2202 return get(Instruction::Mul, C1, C2, Flags);
Owen Anderson487375e2009-07-29 18:55:55 +00002203}
2204
Chris Lattnera676c0f2011-02-07 16:40:21 +00002205Constant *ConstantExpr::getFMul(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002206 return get(Instruction::FMul, C1, C2);
2207}
2208
Chris Lattner0d75eac2011-02-09 16:43:07 +00002209Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2, bool isExact) {
2210 return get(Instruction::UDiv, C1, C2,
2211 isExact ? PossiblyExactOperator::IsExact : 0);
Owen Anderson487375e2009-07-29 18:55:55 +00002212}
2213
Chris Lattner0d75eac2011-02-09 16:43:07 +00002214Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2, bool isExact) {
2215 return get(Instruction::SDiv, C1, C2,
2216 isExact ? PossiblyExactOperator::IsExact : 0);
Owen Anderson487375e2009-07-29 18:55:55 +00002217}
2218
Chris Lattnera676c0f2011-02-07 16:40:21 +00002219Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002220 return get(Instruction::FDiv, C1, C2);
2221}
2222
Chris Lattnera676c0f2011-02-07 16:40:21 +00002223Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002224 return get(Instruction::URem, C1, C2);
2225}
2226
Chris Lattnera676c0f2011-02-07 16:40:21 +00002227Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002228 return get(Instruction::SRem, C1, C2);
2229}
2230
Chris Lattnera676c0f2011-02-07 16:40:21 +00002231Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002232 return get(Instruction::FRem, C1, C2);
2233}
2234
Chris Lattnera676c0f2011-02-07 16:40:21 +00002235Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002236 return get(Instruction::And, C1, C2);
2237}
2238
Chris Lattnera676c0f2011-02-07 16:40:21 +00002239Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002240 return get(Instruction::Or, C1, C2);
2241}
2242
Chris Lattnera676c0f2011-02-07 16:40:21 +00002243Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002244 return get(Instruction::Xor, C1, C2);
2245}
2246
Chris Lattnere9b4ad72011-02-10 07:01:55 +00002247Constant *ConstantExpr::getShl(Constant *C1, Constant *C2,
2248 bool HasNUW, bool HasNSW) {
2249 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2250 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2251 return get(Instruction::Shl, C1, C2, Flags);
Owen Anderson487375e2009-07-29 18:55:55 +00002252}
2253
Chris Lattner0d75eac2011-02-09 16:43:07 +00002254Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2, bool isExact) {
2255 return get(Instruction::LShr, C1, C2,
2256 isExact ? PossiblyExactOperator::IsExact : 0);
Owen Anderson487375e2009-07-29 18:55:55 +00002257}
2258
Chris Lattner0d75eac2011-02-09 16:43:07 +00002259Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2, bool isExact) {
2260 return get(Instruction::AShr, C1, C2,
2261 isExact ? PossiblyExactOperator::IsExact : 0);
Owen Anderson487375e2009-07-29 18:55:55 +00002262}
2263
Duncan Sandsd7aeefe2012-06-12 14:33:56 +00002264Constant *ConstantExpr::getBinOpIdentity(unsigned Opcode, Type *Ty) {
2265 switch (Opcode) {
2266 default:
Duncan Sands318a89d2012-06-13 09:42:13 +00002267 // Doesn't have an identity.
Craig Topperc6207612014-04-09 06:08:46 +00002268 return nullptr;
Duncan Sands318a89d2012-06-13 09:42:13 +00002269
Duncan Sandsd7aeefe2012-06-12 14:33:56 +00002270 case Instruction::Add:
2271 case Instruction::Or:
2272 case Instruction::Xor:
2273 return Constant::getNullValue(Ty);
2274
2275 case Instruction::Mul:
2276 return ConstantInt::get(Ty, 1);
2277
2278 case Instruction::And:
2279 return Constant::getAllOnesValue(Ty);
2280 }
2281}
2282
Duncan Sands318a89d2012-06-13 09:42:13 +00002283Constant *ConstantExpr::getBinOpAbsorber(unsigned Opcode, Type *Ty) {
2284 switch (Opcode) {
2285 default:
2286 // Doesn't have an absorber.
Craig Topperc6207612014-04-09 06:08:46 +00002287 return nullptr;
Duncan Sands318a89d2012-06-13 09:42:13 +00002288
2289 case Instruction::Or:
2290 return Constant::getAllOnesValue(Ty);
2291
2292 case Instruction::And:
2293 case Instruction::Mul:
2294 return Constant::getNullValue(Ty);
2295 }
2296}
2297
Sanjay Patel1d0ac7c2016-04-29 22:03:27 +00002298/// Remove the constant from the constant table.
Pete Cooper86dd4cf2015-06-23 21:55:11 +00002299void ConstantExpr::destroyConstantImpl() {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002300 getType()->getContext().pImpl->ExprConstants.remove(this);
Vikram S. Adve4e537b22002-07-14 23:13:17 +00002301}
2302
Chris Lattner3cd8c562002-07-30 18:54:25 +00002303const char *ConstantExpr::getOpcodeName() const {
2304 return Instruction::getOpcodeName(getOpcode());
Vikram S. Adve4e537b22002-07-14 23:13:17 +00002305}
Reid Spencer1ebe1ab2004-07-17 23:48:33 +00002306
David Blaikie60310f22015-05-08 00:42:26 +00002307GetElementPtrConstantExpr::GetElementPtrConstantExpr(
2308 Type *SrcElementTy, Constant *C, ArrayRef<Constant *> IdxList, Type *DestTy)
2309 : ConstantExpr(DestTy, Instruction::GetElementPtr,
2310 OperandTraits<GetElementPtrConstantExpr>::op_end(this) -
2311 (IdxList.size() + 1),
2312 IdxList.size() + 1),
Eduard Burtescu19eb0312016-01-19 17:28:00 +00002313 SrcElementTy(SrcElementTy),
2314 ResElementTy(GetElementPtrInst::getIndexedType(SrcElementTy, IdxList)) {
Pete Coopereb31b682015-05-21 22:48:54 +00002315 Op<0>() = C;
Pete Cooper74510a42015-06-12 17:48:05 +00002316 Use *OperandList = getOperandList();
Chris Lattnera3b94ba2010-03-30 20:48:48 +00002317 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
2318 OperandList[i+1] = IdxList[i];
2319}
2320
David Blaikie60310f22015-05-08 00:42:26 +00002321Type *GetElementPtrConstantExpr::getSourceElementType() const {
2322 return SrcElementTy;
2323}
2324
Eduard Burtescu19eb0312016-01-19 17:28:00 +00002325Type *GetElementPtrConstantExpr::getResultElementType() const {
2326 return ResElementTy;
2327}
2328
Chris Lattner3756b912012-01-23 22:57:10 +00002329//===----------------------------------------------------------------------===//
2330// ConstantData* implementations
2331
Chris Lattnere4f3f102012-01-24 04:43:41 +00002332Type *ConstantDataSequential::getElementType() const {
2333 return getType()->getElementType();
2334}
2335
Chris Lattner5d4497b2012-01-24 09:31:43 +00002336StringRef ConstantDataSequential::getRawDataValues() const {
Chris Lattner00245f42012-01-24 13:41:11 +00002337 return StringRef(DataElements, getNumElements()*getElementByteSize());
Chris Lattner5d4497b2012-01-24 09:31:43 +00002338}
2339
Craig Toppere3dcce92015-08-01 22:20:21 +00002340bool ConstantDataSequential::isElementTypeCompatible(Type *Ty) {
Justin Bogner0ebc8602015-12-08 03:01:16 +00002341 if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy()) return true;
Craig Toppere3dcce92015-08-01 22:20:21 +00002342 if (auto *IT = dyn_cast<IntegerType>(Ty)) {
Chris Lattnere4f3f102012-01-24 04:43:41 +00002343 switch (IT->getBitWidth()) {
2344 case 8:
2345 case 16:
2346 case 32:
2347 case 64:
2348 return true;
2349 default: break;
2350 }
2351 }
2352 return false;
2353}
2354
Chris Lattner00245f42012-01-24 13:41:11 +00002355unsigned ConstantDataSequential::getNumElements() const {
Chris Lattner8a3df542012-01-25 01:32:59 +00002356 if (ArrayType *AT = dyn_cast<ArrayType>(getType()))
2357 return AT->getNumElements();
Chris Lattner8326bd82012-01-26 00:42:34 +00002358 return getType()->getVectorNumElements();
Chris Lattner00245f42012-01-24 13:41:11 +00002359}
2360
2361
Chris Lattnere4f3f102012-01-24 04:43:41 +00002362uint64_t ConstantDataSequential::getElementByteSize() const {
2363 return getElementType()->getPrimitiveSizeInBits()/8;
2364}
2365
Sanjay Patel1d0ac7c2016-04-29 22:03:27 +00002366/// Return the start of the specified element.
Chris Lattnere4f3f102012-01-24 04:43:41 +00002367const char *ConstantDataSequential::getElementPointer(unsigned Elt) const {
Chris Lattner00245f42012-01-24 13:41:11 +00002368 assert(Elt < getNumElements() && "Invalid Elt");
Chris Lattnere4f3f102012-01-24 04:43:41 +00002369 return DataElements+Elt*getElementByteSize();
2370}
2371
2372
Sanjay Patel1d0ac7c2016-04-29 22:03:27 +00002373/// Return true if the array is empty or all zeros.
Chris Lattner3756b912012-01-23 22:57:10 +00002374static bool isAllZeros(StringRef Arr) {
Benjamin Krameraf28e7d2016-06-26 14:10:56 +00002375 for (char I : Arr)
2376 if (I != 0)
Chris Lattner3756b912012-01-23 22:57:10 +00002377 return false;
2378 return true;
2379}
Chris Lattner030af792012-01-24 05:42:11 +00002380
Sanjay Patel1d0ac7c2016-04-29 22:03:27 +00002381/// This is the underlying implementation of all of the
Chris Lattner3756b912012-01-23 22:57:10 +00002382/// ConstantDataSequential::get methods. They all thunk down to here, providing
Chris Lattnerf06039b2012-01-30 18:19:30 +00002383/// the correct element type. We take the bytes in as a StringRef because
Chris Lattner3756b912012-01-23 22:57:10 +00002384/// we *want* an underlying "char*" to avoid TBAA type punning violations.
2385Constant *ConstantDataSequential::getImpl(StringRef Elements, Type *Ty) {
Chris Lattner8326bd82012-01-26 00:42:34 +00002386 assert(isElementTypeCompatible(Ty->getSequentialElementType()));
Chris Lattner139822f2012-01-24 14:17:05 +00002387 // If the elements are all zero or there are no elements, return a CAZ, which
2388 // is more dense and canonical.
Chris Lattner3756b912012-01-23 22:57:10 +00002389 if (isAllZeros(Elements))
2390 return ConstantAggregateZero::get(Ty);
2391
2392 // Do a lookup to see if we have already formed one of these.
David Blaikie5106ce72014-11-19 05:49:42 +00002393 auto &Slot =
2394 *Ty->getContext()
2395 .pImpl->CDSConstants.insert(std::make_pair(Elements, nullptr))
2396 .first;
Galina Kistanovafc259902012-07-13 01:25:27 +00002397
Chris Lattner3756b912012-01-23 22:57:10 +00002398 // The bucket can point to a linked list of different CDS's that have the same
2399 // body but different types. For example, 0,0,0,1 could be a 4 element array
2400 // of i8, or a 1-element array of i32. They'll both end up in the same
2401 /// StringMap bucket, linked up by their Next pointers. Walk the list.
David Blaikie5106ce72014-11-19 05:49:42 +00002402 ConstantDataSequential **Entry = &Slot.second;
Craig Topperc6207612014-04-09 06:08:46 +00002403 for (ConstantDataSequential *Node = *Entry; Node;
Chris Lattner3756b912012-01-23 22:57:10 +00002404 Entry = &Node->Next, Node = *Entry)
2405 if (Node->getType() == Ty)
2406 return Node;
Galina Kistanovafc259902012-07-13 01:25:27 +00002407
Chris Lattner3756b912012-01-23 22:57:10 +00002408 // Okay, we didn't get a hit. Create a node of the right class, link it in,
2409 // and return it.
2410 if (isa<ArrayType>(Ty))
David Blaikie5106ce72014-11-19 05:49:42 +00002411 return *Entry = new ConstantDataArray(Ty, Slot.first().data());
Chris Lattner3756b912012-01-23 22:57:10 +00002412
2413 assert(isa<VectorType>(Ty));
David Blaikie5106ce72014-11-19 05:49:42 +00002414 return *Entry = new ConstantDataVector(Ty, Slot.first().data());
Chris Lattner3756b912012-01-23 22:57:10 +00002415}
2416
Pete Cooper86dd4cf2015-06-23 21:55:11 +00002417void ConstantDataSequential::destroyConstantImpl() {
Chris Lattner3756b912012-01-23 22:57:10 +00002418 // Remove the constant from the StringMap.
Bjorn Petterssonaa025802018-07-03 12:39:52 +00002419 StringMap<ConstantDataSequential*> &CDSConstants =
Chris Lattner3756b912012-01-23 22:57:10 +00002420 getType()->getContext().pImpl->CDSConstants;
Galina Kistanovafc259902012-07-13 01:25:27 +00002421
Chris Lattner3756b912012-01-23 22:57:10 +00002422 StringMap<ConstantDataSequential*>::iterator Slot =
Chris Lattner5d4497b2012-01-24 09:31:43 +00002423 CDSConstants.find(getRawDataValues());
Chris Lattner3756b912012-01-23 22:57:10 +00002424
2425 assert(Slot != CDSConstants.end() && "CDS not found in uniquing table");
2426
2427 ConstantDataSequential **Entry = &Slot->getValue();
2428
2429 // Remove the entry from the hash table.
Craig Topperc6207612014-04-09 06:08:46 +00002430 if (!(*Entry)->Next) {
Chris Lattner3756b912012-01-23 22:57:10 +00002431 // If there is only one value in the bucket (common case) it must be this
2432 // entry, and removing the entry should remove the bucket completely.
2433 assert((*Entry) == this && "Hash mismatch in ConstantDataSequential");
2434 getContext().pImpl->CDSConstants.erase(Slot);
2435 } else {
Bjorn Petterssonaa025802018-07-03 12:39:52 +00002436 // Otherwise, there are multiple entries linked off the bucket, unlink the
Chris Lattner3756b912012-01-23 22:57:10 +00002437 // node we care about but keep the bucket around.
2438 for (ConstantDataSequential *Node = *Entry; ;
2439 Entry = &Node->Next, Node = *Entry) {
2440 assert(Node && "Didn't find entry in its uniquing hash table!");
2441 // If we found our entry, unlink it from the list and we're done.
2442 if (Node == this) {
2443 *Entry = Node->Next;
2444 break;
2445 }
2446 }
2447 }
Galina Kistanovafc259902012-07-13 01:25:27 +00002448
Chris Lattner3756b912012-01-23 22:57:10 +00002449 // If we were part of a list, make sure that we don't delete the list that is
2450 // still owned by the uniquing map.
Craig Topperc6207612014-04-09 06:08:46 +00002451 Next = nullptr;
Chris Lattner3756b912012-01-23 22:57:10 +00002452}
2453
Rafael Espindola8c97e192015-02-19 16:08:20 +00002454/// getFP() constructors - Return a constant with array type with an element
2455/// count and element type of float with precision matching the number of
2456/// bits in the ArrayRef passed in. (i.e. half for 16bits, float for 32bits,
2457/// double for 64bits) Note that this can return a ConstantAggregateZero
2458/// object.
2459Constant *ConstantDataArray::getFP(LLVMContext &Context,
2460 ArrayRef<uint16_t> Elts) {
Justin Bognerb7389d6712015-12-09 21:21:07 +00002461 Type *Ty = ArrayType::get(Type::getHalfTy(Context), Elts.size());
Rafael Espindola8c97e192015-02-19 16:08:20 +00002462 const char *Data = reinterpret_cast<const char *>(Elts.data());
Craig Topper393ce692017-07-11 15:52:21 +00002463 return getImpl(StringRef(Data, Elts.size() * 2), Ty);
Rafael Espindola8c97e192015-02-19 16:08:20 +00002464}
2465Constant *ConstantDataArray::getFP(LLVMContext &Context,
2466 ArrayRef<uint32_t> Elts) {
2467 Type *Ty = ArrayType::get(Type::getFloatTy(Context), Elts.size());
2468 const char *Data = reinterpret_cast<const char *>(Elts.data());
Craig Topper393ce692017-07-11 15:52:21 +00002469 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
Rafael Espindola8c97e192015-02-19 16:08:20 +00002470}
2471Constant *ConstantDataArray::getFP(LLVMContext &Context,
2472 ArrayRef<uint64_t> Elts) {
2473 Type *Ty = ArrayType::get(Type::getDoubleTy(Context), Elts.size());
2474 const char *Data = reinterpret_cast<const char *>(Elts.data());
Craig Topper393ce692017-07-11 15:52:21 +00002475 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
Chris Lattner3756b912012-01-23 22:57:10 +00002476}
2477
Chris Lattner20683932012-01-24 14:04:40 +00002478Constant *ConstantDataArray::getString(LLVMContext &Context,
2479 StringRef Str, bool AddNull) {
Galina Kistanovafc259902012-07-13 01:25:27 +00002480 if (!AddNull) {
2481 const uint8_t *Data = reinterpret_cast<const uint8_t *>(Str.data());
Craig Topper393ce692017-07-11 15:52:21 +00002482 return get(Context, makeArrayRef(Data, Str.size()));
Galina Kistanovafc259902012-07-13 01:25:27 +00002483 }
2484
Chris Lattner20683932012-01-24 14:04:40 +00002485 SmallVector<uint8_t, 64> ElementVals;
2486 ElementVals.append(Str.begin(), Str.end());
2487 ElementVals.push_back(0);
2488 return get(Context, ElementVals);
2489}
Chris Lattner3756b912012-01-23 22:57:10 +00002490
2491/// get() constructors - Return a constant with vector type with an element
2492/// count and element type matching the ArrayRef passed in. Note that this
2493/// can return a ConstantAggregateZero object.
Chris Lattner20683932012-01-24 14:04:40 +00002494Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint8_t> Elts){
Chris Lattner3756b912012-01-23 22:57:10 +00002495 Type *Ty = VectorType::get(Type::getInt8Ty(Context), Elts.size());
Galina Kistanovafc259902012-07-13 01:25:27 +00002496 const char *Data = reinterpret_cast<const char *>(Elts.data());
Craig Topper393ce692017-07-11 15:52:21 +00002497 return getImpl(StringRef(Data, Elts.size() * 1), Ty);
Chris Lattner3756b912012-01-23 22:57:10 +00002498}
Chris Lattner20683932012-01-24 14:04:40 +00002499Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint16_t> Elts){
Chris Lattner3756b912012-01-23 22:57:10 +00002500 Type *Ty = VectorType::get(Type::getInt16Ty(Context), Elts.size());
Galina Kistanovafc259902012-07-13 01:25:27 +00002501 const char *Data = reinterpret_cast<const char *>(Elts.data());
Craig Topper393ce692017-07-11 15:52:21 +00002502 return getImpl(StringRef(Data, Elts.size() * 2), Ty);
Chris Lattner3756b912012-01-23 22:57:10 +00002503}
Chris Lattner20683932012-01-24 14:04:40 +00002504Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint32_t> Elts){
Chris Lattner3756b912012-01-23 22:57:10 +00002505 Type *Ty = VectorType::get(Type::getInt32Ty(Context), Elts.size());
Galina Kistanovafc259902012-07-13 01:25:27 +00002506 const char *Data = reinterpret_cast<const char *>(Elts.data());
Craig Topper393ce692017-07-11 15:52:21 +00002507 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
Chris Lattner3756b912012-01-23 22:57:10 +00002508}
Chris Lattner20683932012-01-24 14:04:40 +00002509Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint64_t> Elts){
Chris Lattner3756b912012-01-23 22:57:10 +00002510 Type *Ty = VectorType::get(Type::getInt64Ty(Context), Elts.size());
Galina Kistanovafc259902012-07-13 01:25:27 +00002511 const char *Data = reinterpret_cast<const char *>(Elts.data());
Craig Topper393ce692017-07-11 15:52:21 +00002512 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
Chris Lattner3756b912012-01-23 22:57:10 +00002513}
Chris Lattner20683932012-01-24 14:04:40 +00002514Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<float> Elts) {
Chris Lattner3756b912012-01-23 22:57:10 +00002515 Type *Ty = VectorType::get(Type::getFloatTy(Context), Elts.size());
Galina Kistanovafc259902012-07-13 01:25:27 +00002516 const char *Data = reinterpret_cast<const char *>(Elts.data());
Craig Topper393ce692017-07-11 15:52:21 +00002517 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
Chris Lattner3756b912012-01-23 22:57:10 +00002518}
Chris Lattner20683932012-01-24 14:04:40 +00002519Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<double> Elts) {
Chris Lattner3756b912012-01-23 22:57:10 +00002520 Type *Ty = VectorType::get(Type::getDoubleTy(Context), Elts.size());
Galina Kistanovafc259902012-07-13 01:25:27 +00002521 const char *Data = reinterpret_cast<const char *>(Elts.data());
Craig Topper393ce692017-07-11 15:52:21 +00002522 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
Rafael Espindola8c97e192015-02-19 16:08:20 +00002523}
2524
2525/// getFP() constructors - Return a constant with vector type with an element
2526/// count and element type of float with the precision matching the number of
2527/// bits in the ArrayRef passed in. (i.e. half for 16bits, float for 32bits,
2528/// double for 64bits) Note that this can return a ConstantAggregateZero
2529/// object.
2530Constant *ConstantDataVector::getFP(LLVMContext &Context,
2531 ArrayRef<uint16_t> Elts) {
2532 Type *Ty = VectorType::get(Type::getHalfTy(Context), Elts.size());
2533 const char *Data = reinterpret_cast<const char *>(Elts.data());
Craig Topper393ce692017-07-11 15:52:21 +00002534 return getImpl(StringRef(Data, Elts.size() * 2), Ty);
Rafael Espindola8c97e192015-02-19 16:08:20 +00002535}
2536Constant *ConstantDataVector::getFP(LLVMContext &Context,
2537 ArrayRef<uint32_t> Elts) {
2538 Type *Ty = VectorType::get(Type::getFloatTy(Context), Elts.size());
2539 const char *Data = reinterpret_cast<const char *>(Elts.data());
Craig Topper393ce692017-07-11 15:52:21 +00002540 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
Rafael Espindola8c97e192015-02-19 16:08:20 +00002541}
2542Constant *ConstantDataVector::getFP(LLVMContext &Context,
2543 ArrayRef<uint64_t> Elts) {
2544 Type *Ty = VectorType::get(Type::getDoubleTy(Context), Elts.size());
2545 const char *Data = reinterpret_cast<const char *>(Elts.data());
Craig Topper393ce692017-07-11 15:52:21 +00002546 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
Chris Lattner3756b912012-01-23 22:57:10 +00002547}
2548
Chris Lattnere9eed292012-01-25 05:19:54 +00002549Constant *ConstantDataVector::getSplat(unsigned NumElts, Constant *V) {
2550 assert(isElementTypeCompatible(V->getType()) &&
2551 "Element type not compatible with ConstantData");
2552 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
2553 if (CI->getType()->isIntegerTy(8)) {
2554 SmallVector<uint8_t, 16> Elts(NumElts, CI->getZExtValue());
2555 return get(V->getContext(), Elts);
2556 }
2557 if (CI->getType()->isIntegerTy(16)) {
2558 SmallVector<uint16_t, 16> Elts(NumElts, CI->getZExtValue());
2559 return get(V->getContext(), Elts);
2560 }
2561 if (CI->getType()->isIntegerTy(32)) {
2562 SmallVector<uint32_t, 16> Elts(NumElts, CI->getZExtValue());
2563 return get(V->getContext(), Elts);
2564 }
2565 assert(CI->getType()->isIntegerTy(64) && "Unsupported ConstantData type");
2566 SmallVector<uint64_t, 16> Elts(NumElts, CI->getZExtValue());
2567 return get(V->getContext(), Elts);
2568 }
2569
Chris Lattner978fe0c2012-01-30 06:21:21 +00002570 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
Justin Bogner0ebc8602015-12-08 03:01:16 +00002571 if (CFP->getType()->isHalfTy()) {
2572 SmallVector<uint16_t, 16> Elts(
2573 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
2574 return getFP(V->getContext(), Elts);
2575 }
Chris Lattner978fe0c2012-01-30 06:21:21 +00002576 if (CFP->getType()->isFloatTy()) {
Rafael Espindola8c97e192015-02-19 16:08:20 +00002577 SmallVector<uint32_t, 16> Elts(
2578 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
2579 return getFP(V->getContext(), Elts);
Chris Lattner978fe0c2012-01-30 06:21:21 +00002580 }
2581 if (CFP->getType()->isDoubleTy()) {
Rafael Espindola8c97e192015-02-19 16:08:20 +00002582 SmallVector<uint64_t, 16> Elts(
2583 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
2584 return getFP(V->getContext(), Elts);
Chris Lattner978fe0c2012-01-30 06:21:21 +00002585 }
Chris Lattnere9eed292012-01-25 05:19:54 +00002586 }
Chris Lattner978fe0c2012-01-30 06:21:21 +00002587 return ConstantVector::getSplat(NumElts, V);
Chris Lattnere9eed292012-01-25 05:19:54 +00002588}
2589
2590
Chris Lattnere4f3f102012-01-24 04:43:41 +00002591uint64_t ConstantDataSequential::getElementAsInteger(unsigned Elt) const {
2592 assert(isa<IntegerType>(getElementType()) &&
2593 "Accessor can only be used when element is an integer");
2594 const char *EltPtr = getElementPointer(Elt);
Galina Kistanovafc259902012-07-13 01:25:27 +00002595
Chris Lattnere4f3f102012-01-24 04:43:41 +00002596 // The data is stored in host byte order, make sure to cast back to the right
2597 // type to load with the right endianness.
Chris Lattner8326bd82012-01-26 00:42:34 +00002598 switch (getElementType()->getIntegerBitWidth()) {
Craig Topperc514b542012-02-05 22:14:15 +00002599 default: llvm_unreachable("Invalid bitwidth for CDS");
Galina Kistanovafc259902012-07-13 01:25:27 +00002600 case 8:
Craig Topper393ce692017-07-11 15:52:21 +00002601 return *reinterpret_cast<const uint8_t *>(EltPtr);
Galina Kistanovafc259902012-07-13 01:25:27 +00002602 case 16:
Craig Topper393ce692017-07-11 15:52:21 +00002603 return *reinterpret_cast<const uint16_t *>(EltPtr);
Galina Kistanovafc259902012-07-13 01:25:27 +00002604 case 32:
Craig Topper393ce692017-07-11 15:52:21 +00002605 return *reinterpret_cast<const uint32_t *>(EltPtr);
Galina Kistanovafc259902012-07-13 01:25:27 +00002606 case 64:
Craig Topper393ce692017-07-11 15:52:21 +00002607 return *reinterpret_cast<const uint64_t *>(EltPtr);
Chris Lattnere4f3f102012-01-24 04:43:41 +00002608 }
2609}
2610
Craig Topper0b4b4e32017-07-15 22:06:19 +00002611APInt ConstantDataSequential::getElementAsAPInt(unsigned Elt) const {
2612 assert(isa<IntegerType>(getElementType()) &&
2613 "Accessor can only be used when element is an integer");
2614 const char *EltPtr = getElementPointer(Elt);
2615
2616 // The data is stored in host byte order, make sure to cast back to the right
2617 // type to load with the right endianness.
2618 switch (getElementType()->getIntegerBitWidth()) {
2619 default: llvm_unreachable("Invalid bitwidth for CDS");
2620 case 8: {
2621 auto EltVal = *reinterpret_cast<const uint8_t *>(EltPtr);
2622 return APInt(8, EltVal);
2623 }
2624 case 16: {
2625 auto EltVal = *reinterpret_cast<const uint16_t *>(EltPtr);
2626 return APInt(16, EltVal);
2627 }
2628 case 32: {
2629 auto EltVal = *reinterpret_cast<const uint32_t *>(EltPtr);
2630 return APInt(32, EltVal);
2631 }
2632 case 64: {
2633 auto EltVal = *reinterpret_cast<const uint64_t *>(EltPtr);
2634 return APInt(64, EltVal);
2635 }
2636 }
2637}
2638
Chris Lattnere4f3f102012-01-24 04:43:41 +00002639APFloat ConstantDataSequential::getElementAsAPFloat(unsigned Elt) const {
2640 const char *EltPtr = getElementPointer(Elt);
2641
2642 switch (getElementType()->getTypeID()) {
Nick Lewyckyff509622012-01-25 03:20:12 +00002643 default:
Craig Topperc514b542012-02-05 22:14:15 +00002644 llvm_unreachable("Accessor can only be used when element is float/double!");
Justin Bogner0ebc8602015-12-08 03:01:16 +00002645 case Type::HalfTyID: {
2646 auto EltVal = *reinterpret_cast<const uint16_t *>(EltPtr);
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002647 return APFloat(APFloat::IEEEhalf(), APInt(16, EltVal));
Justin Bogner0ebc8602015-12-08 03:01:16 +00002648 }
Benjamin Kramer7af984b2015-02-20 15:11:55 +00002649 case Type::FloatTyID: {
2650 auto EltVal = *reinterpret_cast<const uint32_t *>(EltPtr);
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002651 return APFloat(APFloat::IEEEsingle(), APInt(32, EltVal));
Benjamin Kramer7af984b2015-02-20 15:11:55 +00002652 }
2653 case Type::DoubleTyID: {
2654 auto EltVal = *reinterpret_cast<const uint64_t *>(EltPtr);
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002655 return APFloat(APFloat::IEEEdouble(), APInt(64, EltVal));
Chris Lattnere4f3f102012-01-24 04:43:41 +00002656 }
Benjamin Kramer7af984b2015-02-20 15:11:55 +00002657 }
Chris Lattnere4f3f102012-01-24 04:43:41 +00002658}
2659
Chris Lattnere4f3f102012-01-24 04:43:41 +00002660float ConstantDataSequential::getElementAsFloat(unsigned Elt) const {
2661 assert(getElementType()->isFloatTy() &&
2662 "Accessor can only be used when element is a 'float'");
Craig Topper393ce692017-07-11 15:52:21 +00002663 return *reinterpret_cast<const float *>(getElementPointer(Elt));
Chris Lattnere4f3f102012-01-24 04:43:41 +00002664}
2665
Chris Lattnere4f3f102012-01-24 04:43:41 +00002666double ConstantDataSequential::getElementAsDouble(unsigned Elt) const {
2667 assert(getElementType()->isDoubleTy() &&
2668 "Accessor can only be used when element is a 'float'");
Craig Topper393ce692017-07-11 15:52:21 +00002669 return *reinterpret_cast<const double *>(getElementPointer(Elt));
Chris Lattnere4f3f102012-01-24 04:43:41 +00002670}
2671
Chris Lattnere4f3f102012-01-24 04:43:41 +00002672Constant *ConstantDataSequential::getElementAsConstant(unsigned Elt) const {
Justin Bogner0ebc8602015-12-08 03:01:16 +00002673 if (getElementType()->isHalfTy() || getElementType()->isFloatTy() ||
2674 getElementType()->isDoubleTy())
Chris Lattnere4f3f102012-01-24 04:43:41 +00002675 return ConstantFP::get(getContext(), getElementAsAPFloat(Elt));
Galina Kistanovafc259902012-07-13 01:25:27 +00002676
Chris Lattnere4f3f102012-01-24 04:43:41 +00002677 return ConstantInt::get(getElementType(), getElementAsInteger(Elt));
2678}
2679
Matthias Braun50ec0b52017-05-19 22:37:09 +00002680bool ConstantDataSequential::isString(unsigned CharSize) const {
2681 return isa<ArrayType>(getType()) && getElementType()->isIntegerTy(CharSize);
Chris Lattner5dd4d872012-01-24 09:01:07 +00002682}
Chris Lattner3756b912012-01-23 22:57:10 +00002683
Chris Lattner5dd4d872012-01-24 09:01:07 +00002684bool ConstantDataSequential::isCString() const {
2685 if (!isString())
2686 return false;
Galina Kistanovafc259902012-07-13 01:25:27 +00002687
Chris Lattner5dd4d872012-01-24 09:01:07 +00002688 StringRef Str = getAsString();
Galina Kistanovafc259902012-07-13 01:25:27 +00002689
Chris Lattner5dd4d872012-01-24 09:01:07 +00002690 // The last value must be nul.
2691 if (Str.back() != 0) return false;
Galina Kistanovafc259902012-07-13 01:25:27 +00002692
Chris Lattner5dd4d872012-01-24 09:01:07 +00002693 // Other elements must be non-nul.
2694 return Str.drop_back().find(0) == StringRef::npos;
2695}
Chris Lattner3756b912012-01-23 22:57:10 +00002696
Craig Topper0b4b4e32017-07-15 22:06:19 +00002697bool ConstantDataVector::isSplat() const {
Chris Lattnerf14a67f2012-01-26 02:31:22 +00002698 const char *Base = getRawDataValues().data();
Galina Kistanovafc259902012-07-13 01:25:27 +00002699
Chris Lattnerf14a67f2012-01-26 02:31:22 +00002700 // Compare elements 1+ to the 0'th element.
2701 unsigned EltSize = getElementByteSize();
2702 for (unsigned i = 1, e = getNumElements(); i != e; ++i)
2703 if (memcmp(Base, Base+i*EltSize, EltSize))
Craig Topper0b4b4e32017-07-15 22:06:19 +00002704 return false;
Galina Kistanovafc259902012-07-13 01:25:27 +00002705
Craig Topper0b4b4e32017-07-15 22:06:19 +00002706 return true;
2707}
2708
2709Constant *ConstantDataVector::getSplatValue() const {
Chris Lattnerf14a67f2012-01-26 02:31:22 +00002710 // If they're all the same, return the 0th one as a representative.
Craig Topper0b4b4e32017-07-15 22:06:19 +00002711 return isSplat() ? getElementAsConstant(0) : nullptr;
Chris Lattnerf14a67f2012-01-26 02:31:22 +00002712}
Chris Lattnera3b94ba2010-03-30 20:48:48 +00002713
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002714//===----------------------------------------------------------------------===//
Pete Cooper5815b1f2015-06-24 18:55:24 +00002715// handleOperandChange implementations
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002716
Pete Cooper5815b1f2015-06-24 18:55:24 +00002717/// Update this constant array to change uses of
Chris Lattner913849b2007-08-21 00:55:23 +00002718/// 'From' to be uses of 'To'. This must update the uniquing data structures
2719/// etc.
2720///
2721/// Note that we intentionally replace all uses of From with To here. Consider
2722/// a large array that uses 'From' 1000 times. By handling this case all here,
Pete Cooper5815b1f2015-06-24 18:55:24 +00002723/// ConstantArray::handleOperandChange is only invoked once, and that
Chris Lattner913849b2007-08-21 00:55:23 +00002724/// single invocation handles all 1000 uses. Handling them one at a time would
2725/// work, but would be really slow because it would have to unique each updated
2726/// array instance.
Chris Lattner31b132c2009-10-28 00:01:44 +00002727///
Mehdi Amini8914d292016-02-10 22:47:15 +00002728void Constant::handleOperandChange(Value *From, Value *To) {
Pete Cooper5815b1f2015-06-24 18:55:24 +00002729 Value *Replacement = nullptr;
2730 switch (getValueID()) {
2731 default:
2732 llvm_unreachable("Not a constant!");
2733#define HANDLE_CONSTANT(Name) \
2734 case Value::Name##Val: \
Mehdi Amini8914d292016-02-10 22:47:15 +00002735 Replacement = cast<Name>(this)->handleOperandChangeImpl(From, To); \
Pete Cooper5815b1f2015-06-24 18:55:24 +00002736 break;
2737#include "llvm/IR/Value.def"
2738 }
2739
2740 // If handleOperandChangeImpl returned nullptr, then it handled
2741 // replacing itself and we don't want to delete or replace anything else here.
2742 if (!Replacement)
2743 return;
2744
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002745 // I do need to replace this with an existing value.
2746 assert(Replacement != this && "I didn't contain From!");
2747
2748 // Everyone using this now uses the replacement.
2749 replaceAllUsesWith(Replacement);
2750
2751 // Delete the old constant!
2752 destroyConstant();
2753}
2754
Mehdi Amini8914d292016-02-10 22:47:15 +00002755Value *ConstantArray::handleOperandChangeImpl(Value *From, Value *To) {
Owen Andersonc2c79322009-07-28 18:32:17 +00002756 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2757 Constant *ToC = cast<Constant>(To);
2758
Talin46e9b442012-02-05 20:54:10 +00002759 SmallVector<Constant*, 8> Values;
Owen Andersonc2c79322009-07-28 18:32:17 +00002760 Values.reserve(getNumOperands()); // Build replacement array.
2761
Galina Kistanovafc259902012-07-13 01:25:27 +00002762 // Fill values with the modified operands of the constant array. Also,
Owen Andersonc2c79322009-07-28 18:32:17 +00002763 // compute whether this turns into an all-zeros array.
Owen Andersonc2c79322009-07-28 18:32:17 +00002764 unsigned NumUpdated = 0;
Galina Kistanovafc259902012-07-13 01:25:27 +00002765
Chris Lattnerf14a67f2012-01-26 02:31:22 +00002766 // Keep track of whether all the values in the array are "ToC".
2767 bool AllSame = true;
Pete Cooper74510a42015-06-12 17:48:05 +00002768 Use *OperandList = getOperandList();
Mehdi Amini8914d292016-02-10 22:47:15 +00002769 unsigned OperandNo = 0;
Chris Lattnerf14a67f2012-01-26 02:31:22 +00002770 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2771 Constant *Val = cast<Constant>(O->get());
2772 if (Val == From) {
Mehdi Amini8914d292016-02-10 22:47:15 +00002773 OperandNo = (O - OperandList);
Chris Lattnerf14a67f2012-01-26 02:31:22 +00002774 Val = ToC;
2775 ++NumUpdated;
Owen Andersonc2c79322009-07-28 18:32:17 +00002776 }
Chris Lattnerf14a67f2012-01-26 02:31:22 +00002777 Values.push_back(Val);
Talin46e9b442012-02-05 20:54:10 +00002778 AllSame &= Val == ToC;
Owen Andersonc2c79322009-07-28 18:32:17 +00002779 }
Galina Kistanovafc259902012-07-13 01:25:27 +00002780
Pete Cooper5815b1f2015-06-24 18:55:24 +00002781 if (AllSame && ToC->isNullValue())
2782 return ConstantAggregateZero::get(getType());
2783
2784 if (AllSame && isa<UndefValue>(ToC))
2785 return UndefValue::get(getType());
Aaron Ballmane4b91dc2014-08-19 14:59:02 +00002786
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002787 // Check for any other type of constant-folding.
Pete Cooper5815b1f2015-06-24 18:55:24 +00002788 if (Constant *C = getImpl(getType(), Values))
2789 return C;
Aaron Ballmane4b91dc2014-08-19 14:59:02 +00002790
Duncan P. N. Exon Smith909620a2014-08-19 19:13:30 +00002791 // Update to the new value.
Pete Cooper5815b1f2015-06-24 18:55:24 +00002792 return getContext().pImpl->ArrayConstants.replaceOperandsInPlace(
Mehdi Amini8914d292016-02-10 22:47:15 +00002793 Values, this, From, ToC, NumUpdated, OperandNo);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002794}
2795
Mehdi Amini8914d292016-02-10 22:47:15 +00002796Value *ConstantStruct::handleOperandChangeImpl(Value *From, Value *To) {
Owen Anderson45308b52009-07-27 22:29:26 +00002797 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2798 Constant *ToC = cast<Constant>(To);
2799
Pete Cooper74510a42015-06-12 17:48:05 +00002800 Use *OperandList = getOperandList();
Owen Anderson45308b52009-07-27 22:29:26 +00002801
Talin46e9b442012-02-05 20:54:10 +00002802 SmallVector<Constant*, 8> Values;
Owen Anderson45308b52009-07-27 22:29:26 +00002803 Values.reserve(getNumOperands()); // Build replacement struct.
Galina Kistanovafc259902012-07-13 01:25:27 +00002804
2805 // Fill values with the modified operands of the constant struct. Also,
Owen Anderson45308b52009-07-27 22:29:26 +00002806 // compute whether this turns into an all-zeros struct.
Mehdi Amini8914d292016-02-10 22:47:15 +00002807 unsigned NumUpdated = 0;
2808 bool AllSame = true;
2809 unsigned OperandNo = 0;
2810 for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O) {
2811 Constant *Val = cast<Constant>(O->get());
2812 if (Val == From) {
2813 OperandNo = (O - OperandList);
2814 Val = ToC;
2815 ++NumUpdated;
Owen Anderson45308b52009-07-27 22:29:26 +00002816 }
Mehdi Amini8914d292016-02-10 22:47:15 +00002817 Values.push_back(Val);
2818 AllSame &= Val == ToC;
Owen Anderson45308b52009-07-27 22:29:26 +00002819 }
Galina Kistanovafc259902012-07-13 01:25:27 +00002820
Mehdi Amini8914d292016-02-10 22:47:15 +00002821 if (AllSame && ToC->isNullValue())
Pete Cooper5815b1f2015-06-24 18:55:24 +00002822 return ConstantAggregateZero::get(getType());
2823
Mehdi Amini8914d292016-02-10 22:47:15 +00002824 if (AllSame && isa<UndefValue>(ToC))
Pete Cooper5815b1f2015-06-24 18:55:24 +00002825 return UndefValue::get(getType());
Galina Kistanovafc259902012-07-13 01:25:27 +00002826
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002827 // Update to the new value.
Pete Cooper5815b1f2015-06-24 18:55:24 +00002828 return getContext().pImpl->StructConstants.replaceOperandsInPlace(
Mehdi Amini8914d292016-02-10 22:47:15 +00002829 Values, this, From, ToC, NumUpdated, OperandNo);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002830}
2831
Mehdi Amini8914d292016-02-10 22:47:15 +00002832Value *ConstantVector::handleOperandChangeImpl(Value *From, Value *To) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002833 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002834 Constant *ToC = cast<Constant>(To);
Galina Kistanovafc259902012-07-13 01:25:27 +00002835
Chris Lattnera474bb22012-01-26 20:40:56 +00002836 SmallVector<Constant*, 8> Values;
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002837 Values.reserve(getNumOperands()); // Build replacement array...
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002838 unsigned NumUpdated = 0;
Mehdi Amini8914d292016-02-10 22:47:15 +00002839 unsigned OperandNo = 0;
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002840 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2841 Constant *Val = getOperand(i);
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002842 if (Val == From) {
Mehdi Amini8914d292016-02-10 22:47:15 +00002843 OperandNo = i;
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002844 ++NumUpdated;
2845 Val = ToC;
2846 }
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002847 Values.push_back(Val);
2848 }
Galina Kistanovafc259902012-07-13 01:25:27 +00002849
Pete Cooper5815b1f2015-06-24 18:55:24 +00002850 if (Constant *C = getImpl(Values))
2851 return C;
Duncan P. N. Exon Smith687744d2014-08-19 02:24:46 +00002852
Duncan P. N. Exon Smith909620a2014-08-19 19:13:30 +00002853 // Update to the new value.
Pete Cooper5815b1f2015-06-24 18:55:24 +00002854 return getContext().pImpl->VectorConstants.replaceOperandsInPlace(
Mehdi Amini8914d292016-02-10 22:47:15 +00002855 Values, this, From, ToC, NumUpdated, OperandNo);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002856}
2857
Mehdi Amini8914d292016-02-10 22:47:15 +00002858Value *ConstantExpr::handleOperandChangeImpl(Value *From, Value *ToV) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002859 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2860 Constant *To = cast<Constant>(ToV);
Galina Kistanovafc259902012-07-13 01:25:27 +00002861
Chris Lattner37e38352012-01-26 20:37:11 +00002862 SmallVector<Constant*, 8> NewOps;
Duncan P. N. Exon Smith33de00c2014-08-19 20:03:35 +00002863 unsigned NumUpdated = 0;
Mehdi Amini8914d292016-02-10 22:47:15 +00002864 unsigned OperandNo = 0;
Chris Lattner37e38352012-01-26 20:37:11 +00002865 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2866 Constant *Op = getOperand(i);
Duncan P. N. Exon Smith33de00c2014-08-19 20:03:35 +00002867 if (Op == From) {
Mehdi Amini8914d292016-02-10 22:47:15 +00002868 OperandNo = i;
Duncan P. N. Exon Smith33de00c2014-08-19 20:03:35 +00002869 ++NumUpdated;
2870 Op = To;
2871 }
2872 NewOps.push_back(Op);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002873 }
Duncan P. N. Exon Smith33de00c2014-08-19 20:03:35 +00002874 assert(NumUpdated && "I didn't contain From!");
Galina Kistanovafc259902012-07-13 01:25:27 +00002875
Pete Cooper5815b1f2015-06-24 18:55:24 +00002876 if (Constant *C = getWithOperands(NewOps, getType(), true))
2877 return C;
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002878
Duncan P. N. Exon Smith33de00c2014-08-19 20:03:35 +00002879 // Update to the new value.
Pete Cooper5815b1f2015-06-24 18:55:24 +00002880 return getContext().pImpl->ExprConstants.replaceOperandsInPlace(
Mehdi Amini8914d292016-02-10 22:47:15 +00002881 NewOps, this, From, To, NumUpdated, OperandNo);
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002882}
2883
James Molloyce545682012-11-17 17:56:30 +00002884Instruction *ConstantExpr::getAsInstruction() {
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +00002885 SmallVector<Value *, 4> ValueOperands(op_begin(), op_end());
James Molloyce545682012-11-17 17:56:30 +00002886 ArrayRef<Value*> Ops(ValueOperands);
2887
2888 switch (getOpcode()) {
2889 case Instruction::Trunc:
2890 case Instruction::ZExt:
2891 case Instruction::SExt:
2892 case Instruction::FPTrunc:
2893 case Instruction::FPExt:
2894 case Instruction::UIToFP:
2895 case Instruction::SIToFP:
2896 case Instruction::FPToUI:
2897 case Instruction::FPToSI:
2898 case Instruction::PtrToInt:
2899 case Instruction::IntToPtr:
2900 case Instruction::BitCast:
Eli Bendersky157a97a2014-01-18 22:54:33 +00002901 case Instruction::AddrSpaceCast:
James Molloyce545682012-11-17 17:56:30 +00002902 return CastInst::Create((Instruction::CastOps)getOpcode(),
2903 Ops[0], getType());
2904 case Instruction::Select:
2905 return SelectInst::Create(Ops[0], Ops[1], Ops[2]);
2906 case Instruction::InsertElement:
2907 return InsertElementInst::Create(Ops[0], Ops[1], Ops[2]);
2908 case Instruction::ExtractElement:
2909 return ExtractElementInst::Create(Ops[0], Ops[1]);
2910 case Instruction::InsertValue:
2911 return InsertValueInst::Create(Ops[0], Ops[1], getIndices());
2912 case Instruction::ExtractValue:
2913 return ExtractValueInst::Create(Ops[0], getIndices());
2914 case Instruction::ShuffleVector:
2915 return new ShuffleVectorInst(Ops[0], Ops[1], Ops[2]);
2916
David Blaikie741c8f82015-03-14 01:53:18 +00002917 case Instruction::GetElementPtr: {
2918 const auto *GO = cast<GEPOperator>(this);
2919 if (GO->isInBounds())
2920 return GetElementPtrInst::CreateInBounds(GO->getSourceElementType(),
2921 Ops[0], Ops.slice(1));
2922 return GetElementPtrInst::Create(GO->getSourceElementType(), Ops[0],
2923 Ops.slice(1));
2924 }
James Molloyce545682012-11-17 17:56:30 +00002925 case Instruction::ICmp:
2926 case Instruction::FCmp:
2927 return CmpInst::Create((Instruction::OtherOps)getOpcode(),
Craig Topper1c3f2832015-12-15 06:11:33 +00002928 (CmpInst::Predicate)getPredicate(), Ops[0], Ops[1]);
James Molloyce545682012-11-17 17:56:30 +00002929
2930 default:
2931 assert(getNumOperands() == 2 && "Must be binary operator?");
2932 BinaryOperator *BO =
2933 BinaryOperator::Create((Instruction::BinaryOps)getOpcode(),
2934 Ops[0], Ops[1]);
2935 if (isa<OverflowingBinaryOperator>(BO)) {
2936 BO->setHasNoUnsignedWrap(SubclassOptionalData &
2937 OverflowingBinaryOperator::NoUnsignedWrap);
2938 BO->setHasNoSignedWrap(SubclassOptionalData &
2939 OverflowingBinaryOperator::NoSignedWrap);
2940 }
2941 if (isa<PossiblyExactOperator>(BO))
2942 BO->setIsExact(SubclassOptionalData & PossiblyExactOperator::IsExact);
2943 return BO;
2944 }
2945}