blob: df09d13d3ebaa8d6f2c5e205a42864e3f3ade446 [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
Nikita Popov0c5d6cc2018-12-01 10:58:34 +0000187 // Check that vectors don't contain INT_MIN
188 if (this->getType()->isVectorTy()) {
189 unsigned NumElts = this->getType()->getVectorNumElements();
190 for (unsigned i = 0; i != NumElts; ++i) {
191 Constant *Elt = this->getAggregateElement(i);
192 if (!Elt || !Elt->isNotMinSignedValue())
193 return false;
Craig Topper0b4b4e32017-07-15 22:06:19 +0000194 }
Nikita Popov0c5d6cc2018-12-01 10:58:34 +0000195 return true;
Craig Topper0b4b4e32017-07-15 22:06:19 +0000196 }
David Majnemer0e6c9862014-08-22 16:41:23 +0000197
198 // It *may* contain INT_MIN, we can't tell.
199 return false;
200}
201
Sanjay Patel08868e4942018-02-16 22:32:54 +0000202bool Constant::isFiniteNonZeroFP() const {
203 if (auto *CFP = dyn_cast<ConstantFP>(this))
204 return CFP->getValueAPF().isFiniteNonZero();
205 if (!getType()->isVectorTy())
206 return false;
207 for (unsigned i = 0, e = getType()->getVectorNumElements(); i != e; ++i) {
208 auto *CFP = dyn_cast_or_null<ConstantFP>(this->getAggregateElement(i));
209 if (!CFP || !CFP->getValueAPF().isFiniteNonZero())
210 return false;
211 }
212 return true;
213}
214
215bool Constant::isNormalFP() const {
216 if (auto *CFP = dyn_cast<ConstantFP>(this))
217 return CFP->getValueAPF().isNormal();
218 if (!getType()->isVectorTy())
219 return false;
220 for (unsigned i = 0, e = getType()->getVectorNumElements(); i != e; ++i) {
221 auto *CFP = dyn_cast_or_null<ConstantFP>(this->getAggregateElement(i));
222 if (!CFP || !CFP->getValueAPF().isNormal())
223 return false;
224 }
225 return true;
226}
227
Sanjay Patel90f4c8e2018-02-20 16:08:15 +0000228bool Constant::hasExactInverseFP() const {
229 if (auto *CFP = dyn_cast<ConstantFP>(this))
230 return CFP->getValueAPF().getExactInverse(nullptr);
231 if (!getType()->isVectorTy())
232 return false;
233 for (unsigned i = 0, e = getType()->getVectorNumElements(); i != e; ++i) {
234 auto *CFP = dyn_cast_or_null<ConstantFP>(this->getAggregateElement(i));
235 if (!CFP || !CFP->getValueAPF().getExactInverse(nullptr))
236 return false;
237 }
238 return true;
239}
240
Sanjay Patel46b083e2018-03-02 18:36:08 +0000241bool Constant::isNaN() const {
242 if (auto *CFP = dyn_cast<ConstantFP>(this))
243 return CFP->isNaN();
244 if (!getType()->isVectorTy())
245 return false;
246 for (unsigned i = 0, e = getType()->getVectorNumElements(); i != e; ++i) {
247 auto *CFP = dyn_cast_or_null<ConstantFP>(this->getAggregateElement(i));
248 if (!CFP || !CFP->isNaN())
249 return false;
250 }
251 return true;
252}
253
Sanjay Patele6dda2f2018-07-06 14:52:36 +0000254bool Constant::containsUndefElement() const {
255 if (!getType()->isVectorTy())
256 return false;
257 for (unsigned i = 0, e = getType()->getVectorNumElements(); i != e; ++i)
258 if (isa<UndefValue>(getAggregateElement(i)))
259 return true;
260
261 return false;
262}
263
Sanjay Patel1d0ac7c2016-04-29 22:03:27 +0000264/// Constructor to create a '0' constant of arbitrary type.
Chris Lattner229907c2011-07-18 04:54:35 +0000265Constant *Constant::getNullValue(Type *Ty) {
Owen Anderson5a1acd92009-07-31 20:28:14 +0000266 switch (Ty->getTypeID()) {
267 case Type::IntegerTyID:
268 return ConstantInt::get(Ty, 0);
Dan Gohman518cda42011-12-17 00:04:22 +0000269 case Type::HalfTyID:
270 return ConstantFP::get(Ty->getContext(),
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000271 APFloat::getZero(APFloat::IEEEhalf()));
Owen Anderson5a1acd92009-07-31 20:28:14 +0000272 case Type::FloatTyID:
Benjamin Kramer8ceebfa2010-12-04 14:22:24 +0000273 return ConstantFP::get(Ty->getContext(),
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000274 APFloat::getZero(APFloat::IEEEsingle()));
Owen Anderson5a1acd92009-07-31 20:28:14 +0000275 case Type::DoubleTyID:
Benjamin Kramer8ceebfa2010-12-04 14:22:24 +0000276 return ConstantFP::get(Ty->getContext(),
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000277 APFloat::getZero(APFloat::IEEEdouble()));
Owen Anderson5a1acd92009-07-31 20:28:14 +0000278 case Type::X86_FP80TyID:
Benjamin Kramer8ceebfa2010-12-04 14:22:24 +0000279 return ConstantFP::get(Ty->getContext(),
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000280 APFloat::getZero(APFloat::x87DoubleExtended()));
Owen Anderson5a1acd92009-07-31 20:28:14 +0000281 case Type::FP128TyID:
282 return ConstantFP::get(Ty->getContext(),
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000283 APFloat::getZero(APFloat::IEEEquad()));
Owen Anderson5a1acd92009-07-31 20:28:14 +0000284 case Type::PPC_FP128TyID:
Benjamin Kramer8ceebfa2010-12-04 14:22:24 +0000285 return ConstantFP::get(Ty->getContext(),
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000286 APFloat(APFloat::PPCDoubleDouble(),
Tim Northover29178a32013-01-22 09:46:31 +0000287 APInt::getNullValue(128)));
Owen Anderson5a1acd92009-07-31 20:28:14 +0000288 case Type::PointerTyID:
289 return ConstantPointerNull::get(cast<PointerType>(Ty));
290 case Type::StructTyID:
291 case Type::ArrayTyID:
292 case Type::VectorTyID:
293 return ConstantAggregateZero::get(Ty);
David Majnemerf0f224d2015-11-11 21:57:16 +0000294 case Type::TokenTyID:
295 return ConstantTokenNone::get(Ty->getContext());
Owen Anderson5a1acd92009-07-31 20:28:14 +0000296 default:
297 // Function, Label, or Opaque type?
Craig Topperc514b542012-02-05 22:14:15 +0000298 llvm_unreachable("Cannot create a null constant of that type!");
Owen Anderson5a1acd92009-07-31 20:28:14 +0000299 }
300}
301
Chris Lattner229907c2011-07-18 04:54:35 +0000302Constant *Constant::getIntegerValue(Type *Ty, const APInt &V) {
303 Type *ScalarTy = Ty->getScalarType();
Dan Gohmanf011f5a2009-08-03 22:07:33 +0000304
305 // Create the base integer constant.
306 Constant *C = ConstantInt::get(Ty->getContext(), V);
307
308 // Convert an integer to a pointer, if necessary.
Chris Lattner229907c2011-07-18 04:54:35 +0000309 if (PointerType *PTy = dyn_cast<PointerType>(ScalarTy))
Dan Gohmanf011f5a2009-08-03 22:07:33 +0000310 C = ConstantExpr::getIntToPtr(C, PTy);
311
312 // Broadcast a scalar to a vector, if necessary.
Chris Lattner229907c2011-07-18 04:54:35 +0000313 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
Chris Lattnere9eed292012-01-25 05:19:54 +0000314 C = ConstantVector::getSplat(VTy->getNumElements(), C);
Dan Gohmanf011f5a2009-08-03 22:07:33 +0000315
316 return C;
317}
318
Chris Lattner229907c2011-07-18 04:54:35 +0000319Constant *Constant::getAllOnesValue(Type *Ty) {
320 if (IntegerType *ITy = dyn_cast<IntegerType>(Ty))
Owen Anderson5a1acd92009-07-31 20:28:14 +0000321 return ConstantInt::get(Ty->getContext(),
322 APInt::getAllOnesValue(ITy->getBitWidth()));
Nadav Rotem7cc6d122011-02-17 21:22:27 +0000323
324 if (Ty->isFloatingPointTy()) {
325 APFloat FL = APFloat::getAllOnesValue(Ty->getPrimitiveSizeInBits(),
326 !Ty->isPPC_FP128Ty());
327 return ConstantFP::get(Ty->getContext(), FL);
328 }
329
Chris Lattner229907c2011-07-18 04:54:35 +0000330 VectorType *VTy = cast<VectorType>(Ty);
Chris Lattnere9eed292012-01-25 05:19:54 +0000331 return ConstantVector::getSplat(VTy->getNumElements(),
332 getAllOnesValue(VTy->getElementType()));
Owen Anderson5a1acd92009-07-31 20:28:14 +0000333}
334
Chris Lattner7e683d12012-01-25 06:16:32 +0000335Constant *Constant::getAggregateElement(unsigned Elt) const {
Duncan P. N. Exon Smith1de3c7e2016-04-05 21:10:45 +0000336 if (const ConstantAggregate *CC = dyn_cast<ConstantAggregate>(this))
337 return Elt < CC->getNumOperands() ? CC->getOperand(Elt) : nullptr;
Galina Kistanovafc259902012-07-13 01:25:27 +0000338
David Majnemer9b529a72015-02-16 04:02:09 +0000339 if (const ConstantAggregateZero *CAZ = dyn_cast<ConstantAggregateZero>(this))
340 return Elt < CAZ->getNumElements() ? CAZ->getElementValue(Elt) : nullptr;
Galina Kistanovafc259902012-07-13 01:25:27 +0000341
Chris Lattner7e683d12012-01-25 06:16:32 +0000342 if (const UndefValue *UV = dyn_cast<UndefValue>(this))
David Majnemer9b529a72015-02-16 04:02:09 +0000343 return Elt < UV->getNumElements() ? UV->getElementValue(Elt) : nullptr;
Galina Kistanovafc259902012-07-13 01:25:27 +0000344
Chris Lattner8326bd82012-01-26 00:42:34 +0000345 if (const ConstantDataSequential *CDS =dyn_cast<ConstantDataSequential>(this))
Craig Topperc6207612014-04-09 06:08:46 +0000346 return Elt < CDS->getNumElements() ? CDS->getElementAsConstant(Elt)
347 : nullptr;
348 return nullptr;
Chris Lattner7e683d12012-01-25 06:16:32 +0000349}
350
351Constant *Constant::getAggregateElement(Constant *Elt) const {
352 assert(isa<IntegerType>(Elt->getType()) && "Index must be an integer");
Florian Hahncc419ad2018-12-12 02:22:12 +0000353 if (ConstantInt *CI = dyn_cast<ConstantInt>(Elt)) {
354 // Check if the constant fits into an uint64_t.
355 if (CI->getValue().getActiveBits() > 64)
356 return nullptr;
Chris Lattner7e683d12012-01-25 06:16:32 +0000357 return getAggregateElement(CI->getZExtValue());
Florian Hahncc419ad2018-12-12 02:22:12 +0000358 }
Craig Topperc6207612014-04-09 06:08:46 +0000359 return nullptr;
Chris Lattner7e683d12012-01-25 06:16:32 +0000360}
361
Pete Cooper86dd4cf2015-06-23 21:55:11 +0000362void Constant::destroyConstant() {
363 /// First call destroyConstantImpl on the subclass. This gives the subclass
364 /// a chance to remove the constant from any maps/pools it's contained in.
365 switch (getValueID()) {
366 default:
367 llvm_unreachable("Not a constant!");
368#define HANDLE_CONSTANT(Name) \
369 case Value::Name##Val: \
370 cast<Name>(this)->destroyConstantImpl(); \
371 break;
372#include "llvm/IR/Value.def"
373 }
Chris Lattner7e683d12012-01-25 06:16:32 +0000374
Chris Lattner3462ae32001-12-03 22:26:30 +0000375 // When a Constant is destroyed, there may be lingering
Chris Lattnerd7a73302001-10-13 06:57:33 +0000376 // references to the constant by other constants in the constant pool. These
Misha Brukmanbe372b92003-08-21 22:14:26 +0000377 // constants are implicitly dependent on the module that is being deleted,
Chris Lattnerd7a73302001-10-13 06:57:33 +0000378 // but they don't know that. Because we only find out when the CPV is
379 // deleted, we must now notify all of our users (that should only be
Chris Lattner3462ae32001-12-03 22:26:30 +0000380 // Constants) that they are, in fact, invalid now and should be deleted.
Chris Lattnerd7a73302001-10-13 06:57:33 +0000381 //
382 while (!use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000383 Value *V = user_back();
Pete Cooper86dd4cf2015-06-23 21:55:11 +0000384#ifndef NDEBUG // Only in -g mode...
Chris Lattner78683a72009-08-23 04:02:03 +0000385 if (!isa<Constant>(V)) {
David Greene1e27a132010-01-05 01:29:19 +0000386 dbgs() << "While deleting: " << *this
Pete Cooper86dd4cf2015-06-23 21:55:11 +0000387 << "\n\nUse still stuck around after Def is destroyed: " << *V
388 << "\n\n";
Chris Lattner78683a72009-08-23 04:02:03 +0000389 }
Chris Lattnerd7a73302001-10-13 06:57:33 +0000390#endif
Vikram S. Adve4e537b22002-07-14 23:13:17 +0000391 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
Chris Lattner8326bd82012-01-26 00:42:34 +0000392 cast<Constant>(V)->destroyConstant();
Chris Lattnerd7a73302001-10-13 06:57:33 +0000393
394 // The constant should remove itself from our use list...
Chandler Carruthcdf47882014-03-09 03:16:01 +0000395 assert((use_empty() || user_back() != V) && "Constant not removed!");
Chris Lattnerd7a73302001-10-13 06:57:33 +0000396 }
397
398 // Value has no outstanding references it is safe to delete it now...
399 delete this;
Chris Lattner38569342001-10-01 20:11:19 +0000400}
Chris Lattner2f7c9632001-06-06 20:29:01 +0000401
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +0000402static bool canTrapImpl(const Constant *C,
Craig Topper71b7b682014-08-21 05:55:13 +0000403 SmallPtrSetImpl<const ConstantExpr *> &NonTrappingOps) {
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +0000404 assert(C->getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
Chris Lattner23dd1f62006-10-20 00:27:06 +0000405 // The only thing that could possibly trap are constant exprs.
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +0000406 const ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
407 if (!CE)
408 return false;
Galina Kistanovafc259902012-07-13 01:25:27 +0000409
410 // ConstantExpr traps if any operands can trap.
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +0000411 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) {
412 if (ConstantExpr *Op = dyn_cast<ConstantExpr>(CE->getOperand(i))) {
David Blaikie70573dc2014-11-19 07:49:26 +0000413 if (NonTrappingOps.insert(Op).second && canTrapImpl(Op, NonTrappingOps))
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +0000414 return true;
415 }
416 }
Chris Lattner23dd1f62006-10-20 00:27:06 +0000417
418 // Otherwise, only specific operations can trap.
419 switch (CE->getOpcode()) {
420 default:
421 return false;
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000422 case Instruction::UDiv:
423 case Instruction::SDiv:
Reid Spencer7eb55b32006-11-02 01:53:59 +0000424 case Instruction::URem:
425 case Instruction::SRem:
Chris Lattner23dd1f62006-10-20 00:27:06 +0000426 // Div and rem can trap if the RHS is not known to be non-zero.
Chris Lattnera91a5632009-10-28 05:14:34 +0000427 if (!isa<ConstantInt>(CE->getOperand(1)) ||CE->getOperand(1)->isNullValue())
Chris Lattner23dd1f62006-10-20 00:27:06 +0000428 return true;
429 return false;
430 }
431}
432
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +0000433bool Constant::canTrap() const {
434 SmallPtrSet<const ConstantExpr *, 4> NonTrappingOps;
435 return canTrapImpl(this, NonTrappingOps);
436}
437
Hans Wennborg4dc89512014-06-20 00:38:12 +0000438/// Check if C contains a GlobalValue for which Predicate is true.
439static bool
440ConstHasGlobalValuePredicate(const Constant *C,
441 bool (*Predicate)(const GlobalValue *)) {
442 SmallPtrSet<const Constant *, 8> Visited;
443 SmallVector<const Constant *, 8> WorkList;
444 WorkList.push_back(C);
445 Visited.insert(C);
Hans Wennborg709e0152012-11-15 11:40:00 +0000446
447 while (!WorkList.empty()) {
Hans Wennborg4dc89512014-06-20 00:38:12 +0000448 const Constant *WorkItem = WorkList.pop_back_val();
449 if (const auto *GV = dyn_cast<GlobalValue>(WorkItem))
450 if (Predicate(GV))
Hans Wennborg709e0152012-11-15 11:40:00 +0000451 return true;
Hans Wennborg4dc89512014-06-20 00:38:12 +0000452 for (const Value *Op : WorkItem->operands()) {
453 const Constant *ConstOp = dyn_cast<Constant>(Op);
454 if (!ConstOp)
Hans Wennborg18aa12402012-11-16 10:33:25 +0000455 continue;
David Blaikie70573dc2014-11-19 07:49:26 +0000456 if (Visited.insert(ConstOp).second)
Hans Wennborg4dc89512014-06-20 00:38:12 +0000457 WorkList.push_back(ConstOp);
Hans Wennborg709e0152012-11-15 11:40:00 +0000458 }
459 }
Hans Wennborg709e0152012-11-15 11:40:00 +0000460 return false;
461}
462
Hans Wennborg4dc89512014-06-20 00:38:12 +0000463bool Constant::isThreadDependent() const {
464 auto DLLImportPredicate = [](const GlobalValue *GV) {
465 return GV->isThreadLocal();
466 };
467 return ConstHasGlobalValuePredicate(this, DLLImportPredicate);
468}
469
470bool Constant::isDLLImportDependent() const {
471 auto DLLImportPredicate = [](const GlobalValue *GV) {
472 return GV->hasDLLImportStorageClass();
473 };
474 return ConstHasGlobalValuePredicate(this, DLLImportPredicate);
475}
476
Chris Lattner253bc772009-11-01 18:11:50 +0000477bool Constant::isConstantUsed() const {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000478 for (const User *U : users()) {
479 const Constant *UC = dyn_cast<Constant>(U);
Craig Topperc6207612014-04-09 06:08:46 +0000480 if (!UC || isa<GlobalValue>(UC))
Chris Lattner253bc772009-11-01 18:11:50 +0000481 return true;
Galina Kistanovafc259902012-07-13 01:25:27 +0000482
Chris Lattner253bc772009-11-01 18:11:50 +0000483 if (UC->isConstantUsed())
484 return true;
485 }
486 return false;
487}
488
Rafael Espindola65e49022015-11-17 00:51:23 +0000489bool Constant::needsRelocation() const {
490 if (isa<GlobalValue>(this))
491 return true; // Global reference.
492
Chris Lattner2cb85b42009-10-28 04:12:16 +0000493 if (const BlockAddress *BA = dyn_cast<BlockAddress>(this))
Rafael Espindola65e49022015-11-17 00:51:23 +0000494 return BA->getFunction()->needsRelocation();
495
Chris Lattnera7cfc432010-01-03 18:09:40 +0000496 // While raw uses of blockaddress need to be relocated, differences between
497 // two of them don't when they are for labels in the same function. This is a
498 // common idiom when creating a table for the indirect goto extension, so we
499 // handle it efficiently here.
500 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(this))
501 if (CE->getOpcode() == Instruction::Sub) {
502 ConstantExpr *LHS = dyn_cast<ConstantExpr>(CE->getOperand(0));
503 ConstantExpr *RHS = dyn_cast<ConstantExpr>(CE->getOperand(1));
Rafael Espindola65e49022015-11-17 00:51:23 +0000504 if (LHS && RHS && LHS->getOpcode() == Instruction::PtrToInt &&
Chris Lattnera7cfc432010-01-03 18:09:40 +0000505 RHS->getOpcode() == Instruction::PtrToInt &&
506 isa<BlockAddress>(LHS->getOperand(0)) &&
507 isa<BlockAddress>(RHS->getOperand(0)) &&
508 cast<BlockAddress>(LHS->getOperand(0))->getFunction() ==
Rafael Espindola65e49022015-11-17 00:51:23 +0000509 cast<BlockAddress>(RHS->getOperand(0))->getFunction())
510 return false;
Chris Lattnera7cfc432010-01-03 18:09:40 +0000511 }
Galina Kistanovafc259902012-07-13 01:25:27 +0000512
Rafael Espindola65e49022015-11-17 00:51:23 +0000513 bool Result = false;
Evan Chengf9e003b2007-03-08 00:59:12 +0000514 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
Rafael Espindola65e49022015-11-17 00:51:23 +0000515 Result |= cast<Constant>(getOperand(i))->needsRelocation();
Galina Kistanovafc259902012-07-13 01:25:27 +0000516
Chris Lattner4565ef52009-07-22 00:05:44 +0000517 return Result;
Evan Chengf9e003b2007-03-08 00:59:12 +0000518}
519
Sanjay Patel1d0ac7c2016-04-29 22:03:27 +0000520/// If the specified constantexpr is dead, remove it. This involves recursively
521/// eliminating any dead users of the constantexpr.
Chris Lattner84886402011-02-18 04:41:42 +0000522static bool removeDeadUsersOfConstant(const Constant *C) {
523 if (isa<GlobalValue>(C)) return false; // Cannot remove this
Galina Kistanovafc259902012-07-13 01:25:27 +0000524
Chris Lattner84886402011-02-18 04:41:42 +0000525 while (!C->use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000526 const Constant *User = dyn_cast<Constant>(C->user_back());
Chris Lattner84886402011-02-18 04:41:42 +0000527 if (!User) return false; // Non-constant usage;
528 if (!removeDeadUsersOfConstant(User))
529 return false; // Constant wasn't dead
530 }
Galina Kistanovafc259902012-07-13 01:25:27 +0000531
Chris Lattner84886402011-02-18 04:41:42 +0000532 const_cast<Constant*>(C)->destroyConstant();
533 return true;
534}
535
536
Chris Lattner84886402011-02-18 04:41:42 +0000537void Constant::removeDeadConstantUsers() const {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000538 Value::const_user_iterator I = user_begin(), E = user_end();
539 Value::const_user_iterator LastNonDeadUser = E;
Chris Lattner84886402011-02-18 04:41:42 +0000540 while (I != E) {
541 const Constant *User = dyn_cast<Constant>(*I);
Craig Topperc6207612014-04-09 06:08:46 +0000542 if (!User) {
Chris Lattner84886402011-02-18 04:41:42 +0000543 LastNonDeadUser = I;
544 ++I;
545 continue;
546 }
Galina Kistanovafc259902012-07-13 01:25:27 +0000547
Chris Lattner84886402011-02-18 04:41:42 +0000548 if (!removeDeadUsersOfConstant(User)) {
549 // If the constant wasn't dead, remember that this was the last live use
550 // and move on to the next constant.
551 LastNonDeadUser = I;
552 ++I;
553 continue;
554 }
Galina Kistanovafc259902012-07-13 01:25:27 +0000555
Chris Lattner84886402011-02-18 04:41:42 +0000556 // If the constant was dead, then the iterator is invalidated.
557 if (LastNonDeadUser == E) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000558 I = user_begin();
Chris Lattner84886402011-02-18 04:41:42 +0000559 if (I == E) break;
560 } else {
561 I = LastNonDeadUser;
562 ++I;
563 }
564 }
565}
566
567
Chris Lattner2105d662008-07-10 00:28:11 +0000568
Chris Lattner2f7c9632001-06-06 20:29:01 +0000569//===----------------------------------------------------------------------===//
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000570// ConstantInt
Chris Lattner2f7c9632001-06-06 20:29:01 +0000571//===----------------------------------------------------------------------===//
572
Duncan P. N. Exon Smithb6452792016-02-21 02:39:49 +0000573ConstantInt::ConstantInt(IntegerType *Ty, const APInt &V)
574 : ConstantData(Ty, ConstantIntVal), Val(V) {
Reid Spencerb31bffe2007-02-26 23:54:03 +0000575 assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
Chris Lattner2f7c9632001-06-06 20:29:01 +0000576}
577
Nick Lewycky92db8e82011-03-06 03:36:19 +0000578ConstantInt *ConstantInt::getTrue(LLVMContext &Context) {
Owen Anderson23a204d2009-07-31 17:39:07 +0000579 LLVMContextImpl *pImpl = Context.pImpl;
Benjamin Kramerddd1b7b2010-11-20 18:43:35 +0000580 if (!pImpl->TheTrueVal)
581 pImpl->TheTrueVal = ConstantInt::get(Type::getInt1Ty(Context), 1);
582 return pImpl->TheTrueVal;
Owen Anderson23a204d2009-07-31 17:39:07 +0000583}
584
Nick Lewycky92db8e82011-03-06 03:36:19 +0000585ConstantInt *ConstantInt::getFalse(LLVMContext &Context) {
Owen Anderson23a204d2009-07-31 17:39:07 +0000586 LLVMContextImpl *pImpl = Context.pImpl;
Benjamin Kramerddd1b7b2010-11-20 18:43:35 +0000587 if (!pImpl->TheFalseVal)
588 pImpl->TheFalseVal = ConstantInt::get(Type::getInt1Ty(Context), 0);
589 return pImpl->TheFalseVal;
Owen Anderson23a204d2009-07-31 17:39:07 +0000590}
591
Chris Lattner229907c2011-07-18 04:54:35 +0000592Constant *ConstantInt::getTrue(Type *Ty) {
Craig Topperfde47232017-07-09 07:04:03 +0000593 assert(Ty->isIntOrIntVectorTy(1) && "Type not i1 or vector of i1.");
Sanjay Patel70a575a2017-04-16 17:00:21 +0000594 ConstantInt *TrueC = ConstantInt::getTrue(Ty->getContext());
595 if (auto *VTy = dyn_cast<VectorType>(Ty))
596 return ConstantVector::getSplat(VTy->getNumElements(), TrueC);
597 return TrueC;
Nick Lewycky92db8e82011-03-06 03:36:19 +0000598}
599
Chris Lattner229907c2011-07-18 04:54:35 +0000600Constant *ConstantInt::getFalse(Type *Ty) {
Craig Topperfde47232017-07-09 07:04:03 +0000601 assert(Ty->isIntOrIntVectorTy(1) && "Type not i1 or vector of i1.");
Sanjay Patel70a575a2017-04-16 17:00:21 +0000602 ConstantInt *FalseC = ConstantInt::getFalse(Ty->getContext());
603 if (auto *VTy = dyn_cast<VectorType>(Ty))
604 return ConstantVector::getSplat(VTy->getNumElements(), FalseC);
605 return FalseC;
Nick Lewycky92db8e82011-03-06 03:36:19 +0000606}
607
Benjamin Kramer8e5dc532014-12-06 13:12:56 +0000608// Get a ConstantInt from an APInt.
Nick Lewycky92db8e82011-03-06 03:36:19 +0000609ConstantInt *ConstantInt::get(LLVMContext &Context, const APInt &V) {
Owen Andersonedb4a702009-07-24 23:12:02 +0000610 // get an existing value or the insertion position
Benjamin Kramer320682f2013-06-01 17:51:03 +0000611 LLVMContextImpl *pImpl = Context.pImpl;
Justin Lebar611c5c22016-10-10 16:26:13 +0000612 std::unique_ptr<ConstantInt> &Slot = pImpl->IntConstants[V];
Benjamin Kramer8e5dc532014-12-06 13:12:56 +0000613 if (!Slot) {
614 // Get the corresponding integer type for the bit width of the value.
615 IntegerType *ITy = IntegerType::get(Context, V.getBitWidth());
Justin Lebar611c5c22016-10-10 16:26:13 +0000616 Slot.reset(new ConstantInt(ITy, V));
Benjamin Kramer8e5dc532014-12-06 13:12:56 +0000617 }
618 assert(Slot->getType() == IntegerType::get(Context, V.getBitWidth()));
Justin Lebar611c5c22016-10-10 16:26:13 +0000619 return Slot.get();
Owen Andersonedb4a702009-07-24 23:12:02 +0000620}
621
Chris Lattner229907c2011-07-18 04:54:35 +0000622Constant *ConstantInt::get(Type *Ty, uint64_t V, bool isSigned) {
Nick Lewycky92db8e82011-03-06 03:36:19 +0000623 Constant *C = get(cast<IntegerType>(Ty->getScalarType()), V, isSigned);
Owen Andersonedb4a702009-07-24 23:12:02 +0000624
625 // For vectors, broadcast the value.
Chris Lattner229907c2011-07-18 04:54:35 +0000626 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
Chris Lattnere9eed292012-01-25 05:19:54 +0000627 return ConstantVector::getSplat(VTy->getNumElements(), C);
Owen Andersonedb4a702009-07-24 23:12:02 +0000628
629 return C;
630}
631
Sanjay Patelf3587ec2016-05-18 22:05:28 +0000632ConstantInt *ConstantInt::get(IntegerType *Ty, uint64_t V, bool isSigned) {
Owen Andersonedb4a702009-07-24 23:12:02 +0000633 return get(Ty->getContext(), APInt(Ty->getBitWidth(), V, isSigned));
634}
635
Chris Lattner0256be92012-01-27 03:08:05 +0000636ConstantInt *ConstantInt::getSigned(IntegerType *Ty, int64_t V) {
Owen Andersonedb4a702009-07-24 23:12:02 +0000637 return get(Ty, V, true);
638}
639
Chris Lattner229907c2011-07-18 04:54:35 +0000640Constant *ConstantInt::getSigned(Type *Ty, int64_t V) {
Owen Andersonedb4a702009-07-24 23:12:02 +0000641 return get(Ty, V, true);
642}
643
Chris Lattner0256be92012-01-27 03:08:05 +0000644Constant *ConstantInt::get(Type *Ty, const APInt& V) {
Owen Andersonedb4a702009-07-24 23:12:02 +0000645 ConstantInt *C = get(Ty->getContext(), V);
646 assert(C->getType() == Ty->getScalarType() &&
647 "ConstantInt type doesn't match the type implied by its value!");
648
649 // For vectors, broadcast the value.
Chris Lattner229907c2011-07-18 04:54:35 +0000650 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
Chris Lattnere9eed292012-01-25 05:19:54 +0000651 return ConstantVector::getSplat(VTy->getNumElements(), C);
Owen Andersonedb4a702009-07-24 23:12:02 +0000652
653 return C;
654}
655
Sanjay Patelf3587ec2016-05-18 22:05:28 +0000656ConstantInt *ConstantInt::get(IntegerType* Ty, StringRef Str, uint8_t radix) {
Erick Tryzelaarfc2280d2009-08-16 23:36:33 +0000657 return get(Ty->getContext(), APInt(Ty->getBitWidth(), Str, radix));
658}
659
Pete Cooper86dd4cf2015-06-23 21:55:11 +0000660/// Remove the constant from the constant table.
661void ConstantInt::destroyConstantImpl() {
662 llvm_unreachable("You can't ConstantInt->destroyConstantImpl()!");
663}
664
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000665//===----------------------------------------------------------------------===//
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000666// ConstantFP
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000667//===----------------------------------------------------------------------===//
668
Chris Lattner229907c2011-07-18 04:54:35 +0000669static const fltSemantics *TypeToFloatSemantics(Type *Ty) {
Dan Gohman518cda42011-12-17 00:04:22 +0000670 if (Ty->isHalfTy())
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000671 return &APFloat::IEEEhalf();
Chris Lattnerfdd87902009-10-05 05:54:46 +0000672 if (Ty->isFloatTy())
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000673 return &APFloat::IEEEsingle();
Chris Lattnerfdd87902009-10-05 05:54:46 +0000674 if (Ty->isDoubleTy())
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000675 return &APFloat::IEEEdouble();
Chris Lattnerfdd87902009-10-05 05:54:46 +0000676 if (Ty->isX86_FP80Ty())
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000677 return &APFloat::x87DoubleExtended();
Chris Lattnerfdd87902009-10-05 05:54:46 +0000678 else if (Ty->isFP128Ty())
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000679 return &APFloat::IEEEquad();
Galina Kistanovafc259902012-07-13 01:25:27 +0000680
Chris Lattnerfdd87902009-10-05 05:54:46 +0000681 assert(Ty->isPPC_FP128Ty() && "Unknown FP format");
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000682 return &APFloat::PPCDoubleDouble();
Rafael Espindolaf5d53d42009-07-15 17:40:42 +0000683}
684
Chris Lattner0256be92012-01-27 03:08:05 +0000685Constant *ConstantFP::get(Type *Ty, double V) {
Owen Anderson69c464d2009-07-27 20:59:43 +0000686 LLVMContext &Context = Ty->getContext();
Galina Kistanovafc259902012-07-13 01:25:27 +0000687
Owen Anderson69c464d2009-07-27 20:59:43 +0000688 APFloat FV(V);
689 bool ignored;
690 FV.convert(*TypeToFloatSemantics(Ty->getScalarType()),
691 APFloat::rmNearestTiesToEven, &ignored);
692 Constant *C = get(Context, FV);
693
694 // For vectors, broadcast the value.
Chris Lattner229907c2011-07-18 04:54:35 +0000695 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
Chris Lattnere9eed292012-01-25 05:19:54 +0000696 return ConstantVector::getSplat(VTy->getNumElements(), C);
Owen Anderson69c464d2009-07-27 20:59:43 +0000697
698 return C;
699}
700
Sanjay Patel6a0f6672018-02-15 13:55:52 +0000701Constant *ConstantFP::get(Type *Ty, const APFloat &V) {
702 ConstantFP *C = get(Ty->getContext(), V);
703 assert(C->getType() == Ty->getScalarType() &&
704 "ConstantFP type doesn't match the type implied by its value!");
705
706 // For vectors, broadcast the value.
707 if (auto *VTy = dyn_cast<VectorType>(Ty))
708 return ConstantVector::getSplat(VTy->getNumElements(), C);
709
710 return C;
711}
Erick Tryzelaarfc2280d2009-08-16 23:36:33 +0000712
Chris Lattner0256be92012-01-27 03:08:05 +0000713Constant *ConstantFP::get(Type *Ty, StringRef Str) {
Erick Tryzelaarfc2280d2009-08-16 23:36:33 +0000714 LLVMContext &Context = Ty->getContext();
715
716 APFloat FV(*TypeToFloatSemantics(Ty->getScalarType()), Str);
717 Constant *C = get(Context, FV);
718
719 // For vectors, broadcast the value.
Chris Lattner229907c2011-07-18 04:54:35 +0000720 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
Chris Lattnere9eed292012-01-25 05:19:54 +0000721 return ConstantVector::getSplat(VTy->getNumElements(), C);
Erick Tryzelaarfc2280d2009-08-16 23:36:33 +0000722
Bjorn Petterssonaa025802018-07-03 12:39:52 +0000723 return C;
Erick Tryzelaarfc2280d2009-08-16 23:36:33 +0000724}
725
JF Bastien69f60982018-12-10 19:27:38 +0000726Constant *ConstantFP::getNaN(Type *Ty, bool Negative, uint64_t Payload) {
Tom Stellard67246d12015-04-20 19:38:24 +0000727 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
JF Bastien69f60982018-12-10 19:27:38 +0000728 APFloat NaN = APFloat::getNaN(Semantics, Negative, Payload);
Tom Stellard67246d12015-04-20 19:38:24 +0000729 Constant *C = get(Ty->getContext(), NaN);
730
731 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
732 return ConstantVector::getSplat(VTy->getNumElements(), C);
733
734 return C;
735}
736
JF Bastien69f60982018-12-10 19:27:38 +0000737Constant *ConstantFP::getQNaN(Type *Ty, bool Negative, APInt *Payload) {
738 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
739 APFloat NaN = APFloat::getQNaN(Semantics, Negative, Payload);
740 Constant *C = get(Ty->getContext(), NaN);
741
742 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
743 return ConstantVector::getSplat(VTy->getNumElements(), C);
744
745 return C;
746}
747
748Constant *ConstantFP::getSNaN(Type *Ty, bool Negative, APInt *Payload) {
749 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
750 APFloat NaN = APFloat::getSNaN(Semantics, Negative, Payload);
751 Constant *C = get(Ty->getContext(), NaN);
752
753 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
754 return ConstantVector::getSplat(VTy->getNumElements(), C);
755
756 return C;
757}
758
Benjamin Kramer5d2ff222014-01-18 16:43:06 +0000759Constant *ConstantFP::getNegativeZero(Type *Ty) {
760 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
761 APFloat NegZero = APFloat::getZero(Semantics, /*Negative=*/true);
762 Constant *C = get(Ty->getContext(), NegZero);
Erick Tryzelaarfc2280d2009-08-16 23:36:33 +0000763
Benjamin Kramer5d2ff222014-01-18 16:43:06 +0000764 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
765 return ConstantVector::getSplat(VTy->getNumElements(), C);
766
767 return C;
Owen Anderson69c464d2009-07-27 20:59:43 +0000768}
769
770
Chris Lattnere9eed292012-01-25 05:19:54 +0000771Constant *ConstantFP::getZeroValueForNegation(Type *Ty) {
Benjamin Kramer5d2ff222014-01-18 16:43:06 +0000772 if (Ty->isFPOrFPVectorTy())
773 return getNegativeZero(Ty);
Owen Anderson69c464d2009-07-27 20:59:43 +0000774
Owen Anderson5a1acd92009-07-31 20:28:14 +0000775 return Constant::getNullValue(Ty);
Owen Anderson69c464d2009-07-27 20:59:43 +0000776}
777
778
779// ConstantFP accessors.
780ConstantFP* ConstantFP::get(LLVMContext &Context, const APFloat& V) {
Owen Anderson69c464d2009-07-27 20:59:43 +0000781 LLVMContextImpl* pImpl = Context.pImpl;
Galina Kistanovafc259902012-07-13 01:25:27 +0000782
Justin Lebar611c5c22016-10-10 16:26:13 +0000783 std::unique_ptr<ConstantFP> &Slot = pImpl->FPConstants[V];
Galina Kistanovafc259902012-07-13 01:25:27 +0000784
Owen Anderson69c464d2009-07-27 20:59:43 +0000785 if (!Slot) {
Chris Lattner229907c2011-07-18 04:54:35 +0000786 Type *Ty;
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000787 if (&V.getSemantics() == &APFloat::IEEEhalf())
Dan Gohman518cda42011-12-17 00:04:22 +0000788 Ty = Type::getHalfTy(Context);
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000789 else if (&V.getSemantics() == &APFloat::IEEEsingle())
Owen Anderson5dab84c2009-10-19 20:11:52 +0000790 Ty = Type::getFloatTy(Context);
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000791 else if (&V.getSemantics() == &APFloat::IEEEdouble())
Owen Anderson5dab84c2009-10-19 20:11:52 +0000792 Ty = Type::getDoubleTy(Context);
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000793 else if (&V.getSemantics() == &APFloat::x87DoubleExtended())
Owen Anderson5dab84c2009-10-19 20:11:52 +0000794 Ty = Type::getX86_FP80Ty(Context);
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000795 else if (&V.getSemantics() == &APFloat::IEEEquad())
Owen Anderson5dab84c2009-10-19 20:11:52 +0000796 Ty = Type::getFP128Ty(Context);
797 else {
Bjorn Petterssonaa025802018-07-03 12:39:52 +0000798 assert(&V.getSemantics() == &APFloat::PPCDoubleDouble() &&
Owen Anderson5dab84c2009-10-19 20:11:52 +0000799 "Unknown FP format");
800 Ty = Type::getPPC_FP128Ty(Context);
Owen Anderson69c464d2009-07-27 20:59:43 +0000801 }
Justin Lebar611c5c22016-10-10 16:26:13 +0000802 Slot.reset(new ConstantFP(Ty, V));
Owen Anderson69c464d2009-07-27 20:59:43 +0000803 }
Galina Kistanovafc259902012-07-13 01:25:27 +0000804
Justin Lebar611c5c22016-10-10 16:26:13 +0000805 return Slot.get();
Owen Anderson69c464d2009-07-27 20:59:43 +0000806}
807
Benjamin Kramer5d2ff222014-01-18 16:43:06 +0000808Constant *ConstantFP::getInfinity(Type *Ty, bool Negative) {
809 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
810 Constant *C = get(Ty->getContext(), APFloat::getInf(Semantics, Negative));
811
812 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
813 return ConstantVector::getSplat(VTy->getNumElements(), C);
814
815 return C;
Dan Gohmanfeb50212009-09-25 23:00:48 +0000816}
817
Duncan P. N. Exon Smithb6452792016-02-21 02:39:49 +0000818ConstantFP::ConstantFP(Type *Ty, const APFloat &V)
819 : ConstantData(Ty, ConstantFPVal), Val(V) {
Chris Lattner98bd9392008-04-09 06:38:30 +0000820 assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
821 "FP type Mismatch");
Chris Lattner2f7c9632001-06-06 20:29:01 +0000822}
823
Chris Lattnerbe6610c2011-07-15 06:14:08 +0000824bool ConstantFP::isExactlyValue(const APFloat &V) const {
Dale Johannesend246b2c2007-08-30 00:23:21 +0000825 return Val.bitwiseIsEqual(V);
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000826}
827
Pete Cooper86dd4cf2015-06-23 21:55:11 +0000828/// Remove the constant from the constant table.
829void ConstantFP::destroyConstantImpl() {
Craig Topperccbb8102017-06-27 19:57:51 +0000830 llvm_unreachable("You can't ConstantFP->destroyConstantImpl()!");
Pete Cooper86dd4cf2015-06-23 21:55:11 +0000831}
832
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000833//===----------------------------------------------------------------------===//
Chris Lattner030af792012-01-24 05:42:11 +0000834// ConstantAggregateZero Implementation
835//===----------------------------------------------------------------------===//
836
Chris Lattner7e683d12012-01-25 06:16:32 +0000837Constant *ConstantAggregateZero::getSequentialElement() const {
Chris Lattner8326bd82012-01-26 00:42:34 +0000838 return Constant::getNullValue(getType()->getSequentialElementType());
Chris Lattner030af792012-01-24 05:42:11 +0000839}
840
Chris Lattner7e683d12012-01-25 06:16:32 +0000841Constant *ConstantAggregateZero::getStructElement(unsigned Elt) const {
Chris Lattner8326bd82012-01-26 00:42:34 +0000842 return Constant::getNullValue(getType()->getStructElementType(Elt));
Chris Lattner030af792012-01-24 05:42:11 +0000843}
844
Chris Lattner7e683d12012-01-25 06:16:32 +0000845Constant *ConstantAggregateZero::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 +0000851Constant *ConstantAggregateZero::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 ConstantAggregateZero::getNumElements() const {
Craig Toppere3dcce92015-08-01 22:20:21 +0000858 Type *Ty = getType();
859 if (auto *AT = dyn_cast<ArrayType>(Ty))
David Majnemer9b529a72015-02-16 04:02:09 +0000860 return AT->getNumElements();
Craig Toppere3dcce92015-08-01 22:20:21 +0000861 if (auto *VT = dyn_cast<VectorType>(Ty))
David Majnemer9b529a72015-02-16 04:02:09 +0000862 return VT->getNumElements();
863 return Ty->getStructNumElements();
864}
Chris Lattnerf7eb5432012-01-24 07:54:10 +0000865
Chris Lattner030af792012-01-24 05:42:11 +0000866//===----------------------------------------------------------------------===//
867// UndefValue Implementation
868//===----------------------------------------------------------------------===//
869
Chris Lattner7e683d12012-01-25 06:16:32 +0000870UndefValue *UndefValue::getSequentialElement() const {
Chris Lattner8326bd82012-01-26 00:42:34 +0000871 return UndefValue::get(getType()->getSequentialElementType());
Chris Lattner030af792012-01-24 05:42:11 +0000872}
873
Chris Lattner7e683d12012-01-25 06:16:32 +0000874UndefValue *UndefValue::getStructElement(unsigned Elt) const {
Chris Lattner8326bd82012-01-26 00:42:34 +0000875 return UndefValue::get(getType()->getStructElementType(Elt));
Chris Lattner030af792012-01-24 05:42:11 +0000876}
877
Chris Lattner7e683d12012-01-25 06:16:32 +0000878UndefValue *UndefValue::getElementValue(Constant *C) const {
Chris Lattner030af792012-01-24 05:42:11 +0000879 if (isa<SequentialType>(getType()))
880 return getSequentialElement();
881 return getStructElement(cast<ConstantInt>(C)->getZExtValue());
882}
883
Chris Lattner7e683d12012-01-25 06:16:32 +0000884UndefValue *UndefValue::getElementValue(unsigned Idx) const {
Chris Lattnerf7eb5432012-01-24 07:54:10 +0000885 if (isa<SequentialType>(getType()))
886 return getSequentialElement();
887 return getStructElement(Idx);
888}
889
David Majnemer9b529a72015-02-16 04:02:09 +0000890unsigned UndefValue::getNumElements() const {
Craig Toppere3dcce92015-08-01 22:20:21 +0000891 Type *Ty = getType();
Peter Collingbournebc070522016-12-02 03:20:58 +0000892 if (auto *ST = dyn_cast<SequentialType>(Ty))
893 return ST->getNumElements();
David Majnemer9b529a72015-02-16 04:02:09 +0000894 return Ty->getStructNumElements();
895}
Chris Lattner030af792012-01-24 05:42:11 +0000896
897//===----------------------------------------------------------------------===//
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000898// ConstantXXX Classes
899//===----------------------------------------------------------------------===//
900
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000901template <typename ItTy, typename EltTy>
902static bool rangeOnlyContains(ItTy Start, ItTy End, EltTy Elt) {
903 for (; Start != End; ++Start)
904 if (*Start != Elt)
905 return false;
906 return true;
907}
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000908
Justin Bogner909e1c02015-12-01 20:20:49 +0000909template <typename SequentialTy, typename ElementTy>
910static Constant *getIntSequenceIfElementsMatch(ArrayRef<Constant *> V) {
911 assert(!V.empty() && "Cannot get empty int sequence.");
912
913 SmallVector<ElementTy, 16> Elts;
914 for (Constant *C : V)
915 if (auto *CI = dyn_cast<ConstantInt>(C))
916 Elts.push_back(CI->getZExtValue());
917 else
918 return nullptr;
919 return SequentialTy::get(V[0]->getContext(), Elts);
920}
921
922template <typename SequentialTy, typename ElementTy>
923static Constant *getFPSequenceIfElementsMatch(ArrayRef<Constant *> V) {
924 assert(!V.empty() && "Cannot get empty FP sequence.");
925
926 SmallVector<ElementTy, 16> Elts;
927 for (Constant *C : V)
928 if (auto *CFP = dyn_cast<ConstantFP>(C))
929 Elts.push_back(CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
930 else
931 return nullptr;
932 return SequentialTy::getFP(V[0]->getContext(), Elts);
933}
934
935template <typename SequenceTy>
936static Constant *getSequenceIfElementsMatch(Constant *C,
937 ArrayRef<Constant *> V) {
938 // We speculatively build the elements here even if it turns out that there is
939 // a constantexpr or something else weird, since it is so uncommon for that to
940 // happen.
941 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
942 if (CI->getType()->isIntegerTy(8))
943 return getIntSequenceIfElementsMatch<SequenceTy, uint8_t>(V);
944 else if (CI->getType()->isIntegerTy(16))
945 return getIntSequenceIfElementsMatch<SequenceTy, uint16_t>(V);
946 else if (CI->getType()->isIntegerTy(32))
947 return getIntSequenceIfElementsMatch<SequenceTy, uint32_t>(V);
948 else if (CI->getType()->isIntegerTy(64))
949 return getIntSequenceIfElementsMatch<SequenceTy, uint64_t>(V);
950 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
Justin Bogner0ebc8602015-12-08 03:01:16 +0000951 if (CFP->getType()->isHalfTy())
952 return getFPSequenceIfElementsMatch<SequenceTy, uint16_t>(V);
953 else if (CFP->getType()->isFloatTy())
Justin Bogner909e1c02015-12-01 20:20:49 +0000954 return getFPSequenceIfElementsMatch<SequenceTy, uint32_t>(V);
955 else if (CFP->getType()->isDoubleTy())
956 return getFPSequenceIfElementsMatch<SequenceTy, uint64_t>(V);
957 }
958
959 return nullptr;
960}
961
Duncan P. N. Exon Smith1de3c7e2016-04-05 21:10:45 +0000962ConstantAggregate::ConstantAggregate(CompositeType *T, ValueTy VT,
963 ArrayRef<Constant *> V)
964 : Constant(T, VT, OperandTraits<ConstantAggregate>::op_end(this) - V.size(),
965 V.size()) {
Fangrui Song75709322018-11-17 01:44:25 +0000966 llvm::copy(V, op_begin());
Duncan P. N. Exon Smith1de3c7e2016-04-05 21:10:45 +0000967
968 // Check that types match, unless this is an opaque struct.
969 if (auto *ST = dyn_cast<StructType>(T))
970 if (ST->isOpaque())
971 return;
972 for (unsigned I = 0, E = V.size(); I != E; ++I)
973 assert(V[I]->getType() == T->getTypeAtIndex(I) &&
974 "Initializer for composite element doesn't match!");
975}
976
977ConstantArray::ConstantArray(ArrayType *T, ArrayRef<Constant *> V)
978 : ConstantAggregate(T, ConstantArrayVal, V) {
979 assert(V.size() == T->getNumElements() &&
980 "Invalid initializer for constant array");
Chris Lattner2f7c9632001-06-06 20:29:01 +0000981}
982
Chris Lattner229907c2011-07-18 04:54:35 +0000983Constant *ConstantArray::get(ArrayType *Ty, ArrayRef<Constant*> V) {
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +0000984 if (Constant *C = getImpl(Ty, V))
985 return C;
986 return Ty->getContext().pImpl->ArrayConstants.getOrCreate(Ty, V);
987}
Justin Bogner909e1c02015-12-01 20:20:49 +0000988
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +0000989Constant *ConstantArray::getImpl(ArrayType *Ty, ArrayRef<Constant*> V) {
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000990 // Empty arrays are canonicalized to ConstantAggregateZero.
991 if (V.empty())
992 return ConstantAggregateZero::get(Ty);
993
Jeffrey Yasskin8ce67f82009-09-30 21:08:08 +0000994 for (unsigned i = 0, e = V.size(); i != e; ++i) {
995 assert(V[i]->getType() == Ty->getElementType() &&
996 "Wrong type in array element initializer");
997 }
Galina Kistanovafc259902012-07-13 01:25:27 +0000998
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000999 // If this is an all-zero array, return a ConstantAggregateZero object. If
1000 // all undef, return an UndefValue, if "all simple", then return a
1001 // ConstantDataArray.
1002 Constant *C = V[0];
1003 if (isa<UndefValue>(C) && rangeOnlyContains(V.begin(), V.end(), C))
1004 return UndefValue::get(Ty);
Chris Lattnerf14a67f2012-01-26 02:31:22 +00001005
Chris Lattnercf9e8f62012-02-05 02:29:43 +00001006 if (C->isNullValue() && rangeOnlyContains(V.begin(), V.end(), C))
1007 return ConstantAggregateZero::get(Ty);
1008
1009 // Check to see if all of the elements are ConstantFP or ConstantInt and if
1010 // the element type is compatible with ConstantDataVector. If so, use it.
Justin Bogner909e1c02015-12-01 20:20:49 +00001011 if (ConstantDataSequential::isElementTypeCompatible(C->getType()))
1012 return getSequenceIfElementsMatch<ConstantDataArray>(C, V);
Chris Lattnerf14a67f2012-01-26 02:31:22 +00001013
Chris Lattnercf9e8f62012-02-05 02:29:43 +00001014 // Otherwise, we really do want to create a ConstantArray.
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00001015 return nullptr;
Owen Andersonc2c79322009-07-28 18:32:17 +00001016}
1017
Chris Lattnercc19efa2011-06-20 04:01:31 +00001018StructType *ConstantStruct::getTypeForElements(LLVMContext &Context,
1019 ArrayRef<Constant*> V,
1020 bool Packed) {
Bill Wendling3ae7dd32012-02-07 01:27:51 +00001021 unsigned VecSize = V.size();
1022 SmallVector<Type*, 16> EltTypes(VecSize);
1023 for (unsigned i = 0; i != VecSize; ++i)
1024 EltTypes[i] = V[i]->getType();
Galina Kistanovafc259902012-07-13 01:25:27 +00001025
Chris Lattnercc19efa2011-06-20 04:01:31 +00001026 return StructType::get(Context, EltTypes, Packed);
1027}
1028
1029
1030StructType *ConstantStruct::getTypeForElements(ArrayRef<Constant*> V,
1031 bool Packed) {
1032 assert(!V.empty() &&
1033 "ConstantStruct::getTypeForElements cannot be called on empty list");
1034 return getTypeForElements(V[0]->getContext(), V, Packed);
1035}
1036
Jay Foad89d9b812011-07-25 10:14:44 +00001037ConstantStruct::ConstantStruct(StructType *T, ArrayRef<Constant *> V)
Duncan P. N. Exon Smith1de3c7e2016-04-05 21:10:45 +00001038 : ConstantAggregate(T, ConstantStructVal, V) {
1039 assert((T->isOpaque() || V.size() == T->getNumElements()) &&
1040 "Invalid initializer for constant struct");
Chris Lattner2f7c9632001-06-06 20:29:01 +00001041}
1042
Owen Anderson45308b52009-07-27 22:29:26 +00001043// ConstantStruct accessors.
Chris Lattner229907c2011-07-18 04:54:35 +00001044Constant *ConstantStruct::get(StructType *ST, ArrayRef<Constant*> V) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001045 assert((ST->isOpaque() || ST->getNumElements() == V.size()) &&
1046 "Incorrect # elements specified to ConstantStruct::get");
Chris Lattnerf14a67f2012-01-26 02:31:22 +00001047
1048 // Create a ConstantAggregateZero value if all elements are zeros.
1049 bool isZero = true;
1050 bool isUndef = false;
Bjorn Petterssonaa025802018-07-03 12:39:52 +00001051
Chris Lattnerf14a67f2012-01-26 02:31:22 +00001052 if (!V.empty()) {
1053 isUndef = isa<UndefValue>(V[0]);
1054 isZero = V[0]->isNullValue();
1055 if (isUndef || isZero) {
1056 for (unsigned i = 0, e = V.size(); i != e; ++i) {
1057 if (!V[i]->isNullValue())
1058 isZero = false;
1059 if (!isa<UndefValue>(V[i]))
1060 isUndef = false;
1061 }
1062 }
Galina Kistanovafc259902012-07-13 01:25:27 +00001063 }
Chris Lattnerf14a67f2012-01-26 02:31:22 +00001064 if (isZero)
1065 return ConstantAggregateZero::get(ST);
1066 if (isUndef)
1067 return UndefValue::get(ST);
Galina Kistanovafc259902012-07-13 01:25:27 +00001068
Chris Lattnerf14a67f2012-01-26 02:31:22 +00001069 return ST->getContext().pImpl->StructConstants.getOrCreate(ST, V);
Owen Anderson45308b52009-07-27 22:29:26 +00001070}
1071
Jay Foad89d9b812011-07-25 10:14:44 +00001072ConstantVector::ConstantVector(VectorType *T, ArrayRef<Constant *> V)
Duncan P. N. Exon Smith1de3c7e2016-04-05 21:10:45 +00001073 : ConstantAggregate(T, ConstantVectorVal, V) {
Duncan P. N. Exon Smithdb63bda2016-04-05 20:53:47 +00001074 assert(V.size() == T->getNumElements() &&
Duncan P. N. Exon Smith1de3c7e2016-04-05 21:10:45 +00001075 "Invalid initializer for constant vector");
Brian Gaeke02209042004-08-20 06:00:58 +00001076}
1077
Owen Anderson4aa32952009-07-28 21:19:26 +00001078// ConstantVector accessors.
Jay Foadb8a8bed32011-06-22 09:10:19 +00001079Constant *ConstantVector::get(ArrayRef<Constant*> V) {
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00001080 if (Constant *C = getImpl(V))
1081 return C;
1082 VectorType *Ty = VectorType::get(V.front()->getType(), V.size());
1083 return Ty->getContext().pImpl->VectorConstants.getOrCreate(Ty, V);
1084}
Justin Bogner909e1c02015-12-01 20:20:49 +00001085
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00001086Constant *ConstantVector::getImpl(ArrayRef<Constant*> V) {
Jay Foad9f32cfd2011-01-27 14:44:55 +00001087 assert(!V.empty() && "Vectors can't be empty");
Chris Lattner229907c2011-07-18 04:54:35 +00001088 VectorType *T = VectorType::get(V.front()->getType(), V.size());
Jay Foad9f32cfd2011-01-27 14:44:55 +00001089
Chris Lattner69229312011-02-15 00:14:00 +00001090 // If this is an all-undef or all-zero vector, return a
Owen Anderson4aa32952009-07-28 21:19:26 +00001091 // ConstantAggregateZero or UndefValue.
1092 Constant *C = V[0];
1093 bool isZero = C->isNullValue();
1094 bool isUndef = isa<UndefValue>(C);
1095
1096 if (isZero || isUndef) {
1097 for (unsigned i = 1, e = V.size(); i != e; ++i)
1098 if (V[i] != C) {
1099 isZero = isUndef = false;
1100 break;
1101 }
1102 }
Galina Kistanovafc259902012-07-13 01:25:27 +00001103
Owen Anderson4aa32952009-07-28 21:19:26 +00001104 if (isZero)
Owen Andersonb292b8c2009-07-30 23:03:37 +00001105 return ConstantAggregateZero::get(T);
Owen Anderson4aa32952009-07-28 21:19:26 +00001106 if (isUndef)
Owen Andersonb292b8c2009-07-30 23:03:37 +00001107 return UndefValue::get(T);
Galina Kistanovafc259902012-07-13 01:25:27 +00001108
Chris Lattner978fe0c2012-01-30 06:21:21 +00001109 // Check to see if all of the elements are ConstantFP or ConstantInt and if
1110 // the element type is compatible with ConstantDataVector. If so, use it.
Justin Bogner909e1c02015-12-01 20:20:49 +00001111 if (ConstantDataSequential::isElementTypeCompatible(C->getType()))
1112 return getSequenceIfElementsMatch<ConstantDataVector>(C, V);
Galina Kistanovafc259902012-07-13 01:25:27 +00001113
Chris Lattner978fe0c2012-01-30 06:21:21 +00001114 // Otherwise, the element type isn't compatible with ConstantDataVector, or
Craig Topperdf907262017-04-11 06:41:55 +00001115 // the operand list contains a ConstantExpr or something else strange.
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00001116 return nullptr;
Owen Anderson4aa32952009-07-28 21:19:26 +00001117}
1118
Chris Lattnere9eed292012-01-25 05:19:54 +00001119Constant *ConstantVector::getSplat(unsigned NumElts, Constant *V) {
Chris Lattner978fe0c2012-01-30 06:21:21 +00001120 // If this splat is compatible with ConstantDataVector, use it instead of
1121 // ConstantVector.
1122 if ((isa<ConstantFP>(V) || isa<ConstantInt>(V)) &&
1123 ConstantDataSequential::isElementTypeCompatible(V->getType()))
1124 return ConstantDataVector::getSplat(NumElts, V);
Galina Kistanovafc259902012-07-13 01:25:27 +00001125
Chris Lattnere9eed292012-01-25 05:19:54 +00001126 SmallVector<Constant*, 32> Elts(NumElts, V);
1127 return get(Elts);
1128}
1129
David Majnemerf0f224d2015-11-11 21:57:16 +00001130ConstantTokenNone *ConstantTokenNone::get(LLVMContext &Context) {
1131 LLVMContextImpl *pImpl = Context.pImpl;
1132 if (!pImpl->TheNoneToken)
David Majnemer2dd41c52015-11-16 20:55:57 +00001133 pImpl->TheNoneToken.reset(new ConstantTokenNone(Context));
1134 return pImpl->TheNoneToken.get();
David Majnemerf0f224d2015-11-11 21:57:16 +00001135}
1136
1137/// Remove the constant from the constant table.
1138void ConstantTokenNone::destroyConstantImpl() {
1139 llvm_unreachable("You can't ConstantTokenNone->destroyConstantImpl()!");
1140}
Chris Lattnere9eed292012-01-25 05:19:54 +00001141
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001142// Utility function for determining if a ConstantExpr is a CastOp or not. This
1143// can't be inline because we don't want to #include Instruction.h into
1144// Constant.h
1145bool ConstantExpr::isCast() const {
1146 return Instruction::isCast(getOpcode());
1147}
1148
Reid Spenceree3c9912006-12-04 05:19:50 +00001149bool ConstantExpr::isCompare() const {
Nick Lewyckya21d3da2009-07-08 03:04:38 +00001150 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
Reid Spenceree3c9912006-12-04 05:19:50 +00001151}
1152
Dan Gohman7190d482009-09-10 23:37:55 +00001153bool ConstantExpr::isGEPWithNoNotionalOverIndexing() const {
1154 if (getOpcode() != Instruction::GetElementPtr) return false;
1155
1156 gep_type_iterator GEPI = gep_type_begin(this), E = gep_type_end(this);
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001157 User::const_op_iterator OI = std::next(this->op_begin());
Dan Gohman7190d482009-09-10 23:37:55 +00001158
Sanjay Patel81ed3492016-12-11 20:07:02 +00001159 // The remaining indices may be compile-time known integers within the bounds
1160 // of the corresponding notional static array types.
Dan Gohman7190d482009-09-10 23:37:55 +00001161 for (; GEPI != E; ++GEPI, ++OI) {
Sanjay Patel81ed3492016-12-11 20:07:02 +00001162 if (isa<UndefValue>(*OI))
1163 continue;
1164 auto *CI = dyn_cast<ConstantInt>(*OI);
1165 if (!CI || (GEPI.isBoundedSequential() &&
1166 (CI->getValue().getActiveBits() > 64 ||
1167 CI->getZExtValue() >= GEPI.getSequentialNumElements())))
Peter Collingbourneab85225b2016-12-02 02:24:42 +00001168 return false;
Dan Gohman7190d482009-09-10 23:37:55 +00001169 }
1170
1171 // All the indices checked out.
1172 return true;
1173}
1174
Dan Gohman1ecaf452008-05-31 00:58:22 +00001175bool ConstantExpr::hasIndices() const {
1176 return getOpcode() == Instruction::ExtractValue ||
1177 getOpcode() == Instruction::InsertValue;
1178}
1179
Jay Foad0091fe82011-04-13 15:22:40 +00001180ArrayRef<unsigned> ConstantExpr::getIndices() const {
Dan Gohman1ecaf452008-05-31 00:58:22 +00001181 if (const ExtractValueConstantExpr *EVCE =
1182 dyn_cast<ExtractValueConstantExpr>(this))
1183 return EVCE->Indices;
Dan Gohmana469bdb2008-06-23 16:39:44 +00001184
1185 return cast<InsertValueConstantExpr>(this)->Indices;
Dan Gohman1ecaf452008-05-31 00:58:22 +00001186}
1187
Reid Spencer10fbf0e2006-12-03 05:48:19 +00001188unsigned ConstantExpr::getPredicate() const {
Craig Toppercc03b492015-12-15 06:11:36 +00001189 return cast<CompareConstantExpr>(this)->predicate;
Reid Spencer10fbf0e2006-12-03 05:48:19 +00001190}
Chris Lattner60e0dd72001-10-03 06:12:09 +00001191
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001192Constant *
1193ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
Chris Lattner7c1018a2006-07-14 19:37:40 +00001194 assert(Op->getType() == getOperand(OpNo)->getType() &&
1195 "Replacing operand with value of different type!");
Chris Lattner227816342006-07-14 22:20:01 +00001196 if (getOperand(OpNo) == Op)
1197 return const_cast<ConstantExpr*>(this);
Chris Lattner37e38352012-01-26 20:37:11 +00001198
1199 SmallVector<Constant*, 8> NewOps;
1200 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1201 NewOps.push_back(i == OpNo ? Op : getOperand(i));
Galina Kistanovafc259902012-07-13 01:25:27 +00001202
Chris Lattner37e38352012-01-26 20:37:11 +00001203 return getWithOperands(NewOps);
Chris Lattner227816342006-07-14 22:20:01 +00001204}
1205
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001206Constant *ConstantExpr::getWithOperands(ArrayRef<Constant *> Ops, Type *Ty,
David Blaikie88208842015-08-21 20:16:51 +00001207 bool OnlyIfReduced, Type *SrcTy) const {
Jay Foad5c984e562011-04-13 13:46:01 +00001208 assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
Galina Kistanovafc259902012-07-13 01:25:27 +00001209
Benjamin Kramer8008e9f2015-03-02 11:57:04 +00001210 // If no operands changed return self.
1211 if (Ty == getType() && std::equal(Ops.begin(), Ops.end(), op_begin()))
Chris Lattner227816342006-07-14 22:20:01 +00001212 return const_cast<ConstantExpr*>(this);
1213
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001214 Type *OnlyIfReducedTy = OnlyIfReduced ? Ty : nullptr;
Chris Lattner227816342006-07-14 22:20:01 +00001215 switch (getOpcode()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001216 case Instruction::Trunc:
1217 case Instruction::ZExt:
1218 case Instruction::SExt:
1219 case Instruction::FPTrunc:
1220 case Instruction::FPExt:
1221 case Instruction::UIToFP:
1222 case Instruction::SIToFP:
1223 case Instruction::FPToUI:
1224 case Instruction::FPToSI:
1225 case Instruction::PtrToInt:
1226 case Instruction::IntToPtr:
1227 case Instruction::BitCast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00001228 case Instruction::AddrSpaceCast:
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001229 return ConstantExpr::getCast(getOpcode(), Ops[0], Ty, OnlyIfReduced);
Chris Lattner227816342006-07-14 22:20:01 +00001230 case Instruction::Select:
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001231 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2], OnlyIfReducedTy);
Chris Lattner227816342006-07-14 22:20:01 +00001232 case Instruction::InsertElement:
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001233 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2],
1234 OnlyIfReducedTy);
Chris Lattner227816342006-07-14 22:20:01 +00001235 case Instruction::ExtractElement:
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001236 return ConstantExpr::getExtractElement(Ops[0], Ops[1], OnlyIfReducedTy);
Chris Lattner37e38352012-01-26 20:37:11 +00001237 case Instruction::InsertValue:
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001238 return ConstantExpr::getInsertValue(Ops[0], Ops[1], getIndices(),
1239 OnlyIfReducedTy);
Chris Lattner37e38352012-01-26 20:37:11 +00001240 case Instruction::ExtractValue:
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001241 return ConstantExpr::getExtractValue(Ops[0], getIndices(), OnlyIfReducedTy);
Chris Lattner227816342006-07-14 22:20:01 +00001242 case Instruction::ShuffleVector:
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001243 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2],
1244 OnlyIfReducedTy);
David Blaikie88208842015-08-21 20:16:51 +00001245 case Instruction::GetElementPtr: {
1246 auto *GEPO = cast<GEPOperator>(this);
1247 assert(SrcTy || (Ops[0]->getType() == getOperand(0)->getType()));
1248 return ConstantExpr::getGetElementPtr(
1249 SrcTy ? SrcTy : GEPO->getSourceElementType(), Ops[0], Ops.slice(1),
Peter Collingbourned93620b2016-11-10 22:34:55 +00001250 GEPO->isInBounds(), GEPO->getInRangeIndex(), OnlyIfReducedTy);
David Blaikie88208842015-08-21 20:16:51 +00001251 }
Reid Spencer266e42b2006-12-23 06:05:41 +00001252 case Instruction::ICmp:
1253 case Instruction::FCmp:
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001254 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1],
1255 OnlyIfReducedTy);
Chris Lattner227816342006-07-14 22:20:01 +00001256 default:
1257 assert(getNumOperands() == 2 && "Must be binary operator?");
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001258 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1], SubclassOptionalData,
1259 OnlyIfReducedTy);
Chris Lattner7c1018a2006-07-14 19:37:40 +00001260 }
1261}
1262
Chris Lattner2f7c9632001-06-06 20:29:01 +00001263
1264//===----------------------------------------------------------------------===//
Chris Lattner2f7c9632001-06-06 20:29:01 +00001265// isValueValidForType implementations
1266
Chris Lattner229907c2011-07-18 04:54:35 +00001267bool ConstantInt::isValueValidForType(Type *Ty, uint64_t Val) {
Chris Lattner8326bd82012-01-26 00:42:34 +00001268 unsigned NumBits = Ty->getIntegerBitWidth(); // assert okay
1269 if (Ty->isIntegerTy(1))
Reid Spencer7a9c62b2007-01-12 07:05:14 +00001270 return Val == 0 || Val == 1;
Craig Topper50b1e512017-06-07 00:58:05 +00001271 return isUIntN(NumBits, Val);
Reid Spencere7334722006-12-19 01:28:19 +00001272}
1273
Chris Lattner229907c2011-07-18 04:54:35 +00001274bool ConstantInt::isValueValidForType(Type *Ty, int64_t Val) {
Chris Lattner8326bd82012-01-26 00:42:34 +00001275 unsigned NumBits = Ty->getIntegerBitWidth();
1276 if (Ty->isIntegerTy(1))
Reid Spencera94d3942007-01-19 21:13:56 +00001277 return Val == 0 || Val == 1 || Val == -1;
Craig Topper50b1e512017-06-07 00:58:05 +00001278 return isIntN(NumBits, Val);
Chris Lattner2f7c9632001-06-06 20:29:01 +00001279}
1280
Chris Lattner229907c2011-07-18 04:54:35 +00001281bool ConstantFP::isValueValidForType(Type *Ty, const APFloat& Val) {
Dale Johannesend246b2c2007-08-30 00:23:21 +00001282 // convert modifies in place, so make a copy.
1283 APFloat Val2 = APFloat(Val);
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001284 bool losesInfo;
Chris Lattner6b727592004-06-17 18:19:28 +00001285 switch (Ty->getTypeID()) {
Chris Lattner2f7c9632001-06-06 20:29:01 +00001286 default:
1287 return false; // These can't be represented as floating point!
1288
Dale Johannesend246b2c2007-08-30 00:23:21 +00001289 // FIXME rounding mode needs to be more flexible
Dan Gohman518cda42011-12-17 00:04:22 +00001290 case Type::HalfTyID: {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001291 if (&Val2.getSemantics() == &APFloat::IEEEhalf())
Dan Gohman518cda42011-12-17 00:04:22 +00001292 return true;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001293 Val2.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven, &losesInfo);
Dan Gohman518cda42011-12-17 00:04:22 +00001294 return !losesInfo;
1295 }
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001296 case Type::FloatTyID: {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001297 if (&Val2.getSemantics() == &APFloat::IEEEsingle())
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001298 return true;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001299 Val2.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, &losesInfo);
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001300 return !losesInfo;
1301 }
1302 case Type::DoubleTyID: {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001303 if (&Val2.getSemantics() == &APFloat::IEEEhalf() ||
1304 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
1305 &Val2.getSemantics() == &APFloat::IEEEdouble())
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001306 return true;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001307 Val2.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven, &losesInfo);
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001308 return !losesInfo;
1309 }
Dale Johannesenbdad8092007-08-09 22:51:36 +00001310 case Type::X86_FP80TyID:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001311 return &Val2.getSemantics() == &APFloat::IEEEhalf() ||
Bjorn Petterssonaa025802018-07-03 12:39:52 +00001312 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001313 &Val2.getSemantics() == &APFloat::IEEEdouble() ||
1314 &Val2.getSemantics() == &APFloat::x87DoubleExtended();
Dale Johannesenbdad8092007-08-09 22:51:36 +00001315 case Type::FP128TyID:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001316 return &Val2.getSemantics() == &APFloat::IEEEhalf() ||
Bjorn Petterssonaa025802018-07-03 12:39:52 +00001317 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001318 &Val2.getSemantics() == &APFloat::IEEEdouble() ||
1319 &Val2.getSemantics() == &APFloat::IEEEquad();
Dale Johannesen007aa372007-10-11 18:07:22 +00001320 case Type::PPC_FP128TyID:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001321 return &Val2.getSemantics() == &APFloat::IEEEhalf() ||
Bjorn Petterssonaa025802018-07-03 12:39:52 +00001322 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001323 &Val2.getSemantics() == &APFloat::IEEEdouble() ||
1324 &Val2.getSemantics() == &APFloat::PPCDoubleDouble();
Chris Lattner2f7c9632001-06-06 20:29:01 +00001325 }
Chris Lattneraa2372562006-05-24 17:04:05 +00001326}
Chris Lattner9655e542001-07-20 19:16:02 +00001327
Chris Lattner030af792012-01-24 05:42:11 +00001328
Chris Lattner49d855c2001-09-07 16:46:31 +00001329//===----------------------------------------------------------------------===//
Chris Lattner49d855c2001-09-07 16:46:31 +00001330// Factory Function Implementation
1331
Chris Lattnerc7f9fd42012-01-23 15:20:12 +00001332ConstantAggregateZero *ConstantAggregateZero::get(Type *Ty) {
Chris Lattner13ee7952010-08-28 04:09:24 +00001333 assert((Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()) &&
Owen Andersonb292b8c2009-07-30 23:03:37 +00001334 "Cannot create an aggregate zero of non-aggregate type!");
David Blaikie899b85a2014-11-25 02:13:54 +00001335
Justin Lebar611c5c22016-10-10 16:26:13 +00001336 std::unique_ptr<ConstantAggregateZero> &Entry =
1337 Ty->getContext().pImpl->CAZConstants[Ty];
1338 if (!Entry)
1339 Entry.reset(new ConstantAggregateZero(Ty));
1340
1341 return Entry.get();
Owen Andersonb292b8c2009-07-30 23:03:37 +00001342}
1343
Sanjay Patel1d0ac7c2016-04-29 22:03:27 +00001344/// Remove the constant from the constant table.
Pete Cooper86dd4cf2015-06-23 21:55:11 +00001345void ConstantAggregateZero::destroyConstantImpl() {
Chris Lattnerc7f9fd42012-01-23 15:20:12 +00001346 getContext().pImpl->CAZConstants.erase(getType());
Chris Lattner9fba3da2004-02-15 05:53:04 +00001347}
1348
Sanjay Patel1d0ac7c2016-04-29 22:03:27 +00001349/// Remove the constant from the constant table.
Pete Cooper86dd4cf2015-06-23 21:55:11 +00001350void ConstantArray::destroyConstantImpl() {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001351 getType()->getContext().pImpl->ArrayConstants.remove(this);
Chris Lattner98fa07b2003-05-23 20:03:32 +00001352}
1353
Chris Lattner81fabb02002-08-26 17:53:56 +00001354
Chris Lattner3462ae32001-12-03 22:26:30 +00001355//---- ConstantStruct::get() implementation...
Chris Lattner49d855c2001-09-07 16:46:31 +00001356//
Chris Lattnerb50d1352003-10-05 00:17:43 +00001357
Sanjay Patel1d0ac7c2016-04-29 22:03:27 +00001358/// Remove the constant from the constant table.
Pete Cooper86dd4cf2015-06-23 21:55:11 +00001359void ConstantStruct::destroyConstantImpl() {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001360 getType()->getContext().pImpl->StructConstants.remove(this);
Chris Lattnerd7a73302001-10-13 06:57:33 +00001361}
Chris Lattner883ad0b2001-10-03 15:39:36 +00001362
Sanjay Patel1d0ac7c2016-04-29 22:03:27 +00001363/// Remove the constant from the constant table.
Pete Cooper86dd4cf2015-06-23 21:55:11 +00001364void ConstantVector::destroyConstantImpl() {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001365 getType()->getContext().pImpl->VectorConstants.remove(this);
Brian Gaeke02209042004-08-20 06:00:58 +00001366}
1367
Duncan Sandse6beec62012-11-13 12:59:33 +00001368Constant *Constant::getSplatValue() const {
1369 assert(this->getType()->isVectorTy() && "Only valid for vectors!");
1370 if (isa<ConstantAggregateZero>(this))
1371 return getNullValue(this->getType()->getVectorElementType());
1372 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
1373 return CV->getSplatValue();
1374 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
1375 return CV->getSplatValue();
Craig Topperc6207612014-04-09 06:08:46 +00001376 return nullptr;
Duncan Sandse6beec62012-11-13 12:59:33 +00001377}
1378
Duncan Sandscf0ff032011-02-01 08:39:12 +00001379Constant *ConstantVector::getSplatValue() const {
Dan Gohman07159202007-10-17 17:51:30 +00001380 // Check out first element.
1381 Constant *Elt = getOperand(0);
1382 // Then make sure all remaining elements point to the same value.
1383 for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
Chris Lattnerd04e32d2011-07-17 06:01:30 +00001384 if (getOperand(I) != Elt)
Craig Topperc6207612014-04-09 06:08:46 +00001385 return nullptr;
Dan Gohman07159202007-10-17 17:51:30 +00001386 return Elt;
1387}
1388
Duncan Sandse6beec62012-11-13 12:59:33 +00001389const APInt &Constant::getUniqueInteger() const {
1390 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
1391 return CI->getValue();
1392 assert(this->getSplatValue() && "Doesn't contain a unique integer!");
1393 const Constant *C = this->getAggregateElement(0U);
1394 assert(C && isa<ConstantInt>(C) && "Not a vector of numbers!");
1395 return cast<ConstantInt>(C)->getValue();
1396}
1397
Chris Lattner31b132c2009-10-28 00:01:44 +00001398//---- ConstantPointerNull::get() implementation.
Chris Lattnerd7a73302001-10-13 06:57:33 +00001399//
Chris Lattner98fa07b2003-05-23 20:03:32 +00001400
Chris Lattner229907c2011-07-18 04:54:35 +00001401ConstantPointerNull *ConstantPointerNull::get(PointerType *Ty) {
Justin Lebar611c5c22016-10-10 16:26:13 +00001402 std::unique_ptr<ConstantPointerNull> &Entry =
1403 Ty->getContext().pImpl->CPNConstants[Ty];
Craig Topperc6207612014-04-09 06:08:46 +00001404 if (!Entry)
Justin Lebar611c5c22016-10-10 16:26:13 +00001405 Entry.reset(new ConstantPointerNull(Ty));
Galina Kistanovafc259902012-07-13 01:25:27 +00001406
Justin Lebar611c5c22016-10-10 16:26:13 +00001407 return Entry.get();
Chris Lattner883ad0b2001-10-03 15:39:36 +00001408}
1409
Sanjay Patel1d0ac7c2016-04-29 22:03:27 +00001410/// Remove the constant from the constant table.
Pete Cooper86dd4cf2015-06-23 21:55:11 +00001411void ConstantPointerNull::destroyConstantImpl() {
Chris Lattnerc7f9fd42012-01-23 15:20:12 +00001412 getContext().pImpl->CPNConstants.erase(getType());
Chris Lattner0c6e0b92002-08-18 00:40:04 +00001413}
1414
Chris Lattner229907c2011-07-18 04:54:35 +00001415UndefValue *UndefValue::get(Type *Ty) {
Justin Lebar611c5c22016-10-10 16:26:13 +00001416 std::unique_ptr<UndefValue> &Entry = Ty->getContext().pImpl->UVConstants[Ty];
Craig Topperc6207612014-04-09 06:08:46 +00001417 if (!Entry)
Justin Lebar611c5c22016-10-10 16:26:13 +00001418 Entry.reset(new UndefValue(Ty));
Galina Kistanovafc259902012-07-13 01:25:27 +00001419
Justin Lebar611c5c22016-10-10 16:26:13 +00001420 return Entry.get();
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001421}
1422
Sanjay Patel1d0ac7c2016-04-29 22:03:27 +00001423/// Remove the constant from the constant table.
Pete Cooper86dd4cf2015-06-23 21:55:11 +00001424void UndefValue::destroyConstantImpl() {
Chris Lattnerc7f9fd42012-01-23 15:20:12 +00001425 // Free the constant and any dangling references to it.
1426 getContext().pImpl->UVConstants.erase(getType());
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001427}
1428
Chris Lattner31b132c2009-10-28 00:01:44 +00001429BlockAddress *BlockAddress::get(BasicBlock *BB) {
Craig Topper2617dcc2014-04-15 06:32:26 +00001430 assert(BB->getParent() && "Block must have a parent");
Chris Lattner31b132c2009-10-28 00:01:44 +00001431 return get(BB->getParent(), BB);
1432}
1433
1434BlockAddress *BlockAddress::get(Function *F, BasicBlock *BB) {
1435 BlockAddress *&BA =
1436 F->getContext().pImpl->BlockAddresses[std::make_pair(F, BB)];
Craig Topperc6207612014-04-09 06:08:46 +00001437 if (!BA)
Chris Lattner31b132c2009-10-28 00:01:44 +00001438 BA = new BlockAddress(F, BB);
Galina Kistanovafc259902012-07-13 01:25:27 +00001439
Chris Lattner31b132c2009-10-28 00:01:44 +00001440 assert(BA->getFunction() == F && "Basic block moved between functions");
1441 return BA;
1442}
1443
1444BlockAddress::BlockAddress(Function *F, BasicBlock *BB)
1445: Constant(Type::getInt8PtrTy(F->getContext()), Value::BlockAddressVal,
1446 &Op<0>(), 2) {
Chris Lattnerc559a9f2009-11-01 03:03:03 +00001447 setOperand(0, F);
1448 setOperand(1, BB);
Chris Lattneraa99c942009-11-01 01:27:45 +00001449 BB->AdjustBlockAddressRefCount(1);
Chris Lattner31b132c2009-10-28 00:01:44 +00001450}
1451
Chandler Carruth6a936922014-01-19 02:13:50 +00001452BlockAddress *BlockAddress::lookup(const BasicBlock *BB) {
1453 if (!BB->hasAddressTaken())
Craig Topperc6207612014-04-09 06:08:46 +00001454 return nullptr;
Chandler Carruth6a936922014-01-19 02:13:50 +00001455
1456 const Function *F = BB->getParent();
Craig Topper2617dcc2014-04-15 06:32:26 +00001457 assert(F && "Block must have a parent");
Chandler Carruth6a936922014-01-19 02:13:50 +00001458 BlockAddress *BA =
1459 F->getContext().pImpl->BlockAddresses.lookup(std::make_pair(F, BB));
1460 assert(BA && "Refcount and block address map disagree!");
1461 return BA;
1462}
Chris Lattner31b132c2009-10-28 00:01:44 +00001463
Sanjay Patel1d0ac7c2016-04-29 22:03:27 +00001464/// Remove the constant from the constant table.
Pete Cooper86dd4cf2015-06-23 21:55:11 +00001465void BlockAddress::destroyConstantImpl() {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001466 getFunction()->getType()->getContext().pImpl
Chris Lattner31b132c2009-10-28 00:01:44 +00001467 ->BlockAddresses.erase(std::make_pair(getFunction(), getBasicBlock()));
Chris Lattneraa99c942009-11-01 01:27:45 +00001468 getBasicBlock()->AdjustBlockAddressRefCount(-1);
Chris Lattner31b132c2009-10-28 00:01:44 +00001469}
1470
Mehdi Amini8914d292016-02-10 22:47:15 +00001471Value *BlockAddress::handleOperandChangeImpl(Value *From, Value *To) {
Chris Lattner31b132c2009-10-28 00:01:44 +00001472 // This could be replacing either the Basic Block or the Function. In either
1473 // case, we have to remove the map entry.
1474 Function *NewF = getFunction();
1475 BasicBlock *NewBB = getBasicBlock();
Galina Kistanovafc259902012-07-13 01:25:27 +00001476
Mehdi Amini8914d292016-02-10 22:47:15 +00001477 if (From == NewF)
Derek Schuffec9dc012013-06-13 19:51:17 +00001478 NewF = cast<Function>(To->stripPointerCasts());
Mehdi Amini8914d292016-02-10 22:47:15 +00001479 else {
1480 assert(From == NewBB && "From does not match any operand");
Chris Lattner31b132c2009-10-28 00:01:44 +00001481 NewBB = cast<BasicBlock>(To);
Mehdi Amini8914d292016-02-10 22:47:15 +00001482 }
Galina Kistanovafc259902012-07-13 01:25:27 +00001483
Chris Lattner31b132c2009-10-28 00:01:44 +00001484 // See if the 'new' entry already exists, if not, just update this in place
1485 // and return early.
1486 BlockAddress *&NewBA =
1487 getContext().pImpl->BlockAddresses[std::make_pair(NewF, NewBB)];
Pete Cooper5815b1f2015-06-24 18:55:24 +00001488 if (NewBA)
1489 return NewBA;
Chris Lattner31b132c2009-10-28 00:01:44 +00001490
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00001491 getBasicBlock()->AdjustBlockAddressRefCount(-1);
Galina Kistanovafc259902012-07-13 01:25:27 +00001492
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00001493 // Remove the old entry, this can't cause the map to rehash (just a
1494 // tombstone will get added).
1495 getContext().pImpl->BlockAddresses.erase(std::make_pair(getFunction(),
1496 getBasicBlock()));
1497 NewBA = this;
1498 setOperand(0, NewF);
1499 setOperand(1, NewBB);
1500 getBasicBlock()->AdjustBlockAddressRefCount(1);
Pete Cooper5815b1f2015-06-24 18:55:24 +00001501
1502 // If we just want to keep the existing value, then return null.
1503 // Callers know that this means we shouldn't delete this value.
1504 return nullptr;
Chris Lattner31b132c2009-10-28 00:01:44 +00001505}
1506
1507//---- ConstantExpr::get() implementations.
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001508//
Reid Spencer8d9336d2006-12-31 05:26:44 +00001509
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001510/// This is a utility function to handle folding of casts and lookup of the
Duncan Sands7d6c8ae2008-03-30 19:38:55 +00001511/// cast in the ExprConstants map. It is used by the various get* methods below.
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001512static Constant *getFoldedCast(Instruction::CastOps opc, Constant *C, Type *Ty,
1513 bool OnlyIfReduced = false) {
Chris Lattner815ae2b2003-10-07 22:19:19 +00001514 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001515 // Fold a few common cases
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00001516 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001517 return FC;
Chris Lattneracdbe712003-04-17 19:24:48 +00001518
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001519 if (OnlyIfReduced)
1520 return nullptr;
1521
Owen Anderson1584a292009-08-04 20:25:11 +00001522 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
1523
Nadav Rotem88330432013-03-07 01:30:40 +00001524 // Look up the constant in the table first to ensure uniqueness.
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00001525 ConstantExprKeyType Key(opc, C);
Galina Kistanovafc259902012-07-13 01:25:27 +00001526
Owen Anderson1584a292009-08-04 20:25:11 +00001527 return pImpl->ExprConstants.getOrCreate(Ty, Key);
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001528}
Galina Kistanovafc259902012-07-13 01:25:27 +00001529
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001530Constant *ConstantExpr::getCast(unsigned oc, Constant *C, Type *Ty,
1531 bool OnlyIfReduced) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001532 Instruction::CastOps opc = Instruction::CastOps(oc);
1533 assert(Instruction::isCast(opc) && "opcode out of range");
1534 assert(C && Ty && "Null arguments to getCast");
Chris Lattner37bc78a2010-01-26 21:51:43 +00001535 assert(CastInst::castIsValid(opc, C, Ty) && "Invalid constantexpr cast!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001536
1537 switch (opc) {
Chris Lattner37bc78a2010-01-26 21:51:43 +00001538 default:
1539 llvm_unreachable("Invalid cast opcode");
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001540 case Instruction::Trunc:
1541 return getTrunc(C, Ty, OnlyIfReduced);
1542 case Instruction::ZExt:
1543 return getZExt(C, Ty, OnlyIfReduced);
1544 case Instruction::SExt:
1545 return getSExt(C, Ty, OnlyIfReduced);
1546 case Instruction::FPTrunc:
1547 return getFPTrunc(C, Ty, OnlyIfReduced);
1548 case Instruction::FPExt:
1549 return getFPExtend(C, Ty, OnlyIfReduced);
1550 case Instruction::UIToFP:
1551 return getUIToFP(C, Ty, OnlyIfReduced);
1552 case Instruction::SIToFP:
1553 return getSIToFP(C, Ty, OnlyIfReduced);
1554 case Instruction::FPToUI:
1555 return getFPToUI(C, Ty, OnlyIfReduced);
1556 case Instruction::FPToSI:
1557 return getFPToSI(C, Ty, OnlyIfReduced);
1558 case Instruction::PtrToInt:
1559 return getPtrToInt(C, Ty, OnlyIfReduced);
1560 case Instruction::IntToPtr:
1561 return getIntToPtr(C, Ty, OnlyIfReduced);
1562 case Instruction::BitCast:
1563 return getBitCast(C, Ty, OnlyIfReduced);
1564 case Instruction::AddrSpaceCast:
1565 return getAddrSpaceCast(C, Ty, OnlyIfReduced);
Chris Lattner1ece6f82005-01-01 15:59:57 +00001566 }
Galina Kistanovafc259902012-07-13 01:25:27 +00001567}
Reid Spencerf37dc652006-12-05 19:14:13 +00001568
Chris Lattner229907c2011-07-18 04:54:35 +00001569Constant *ConstantExpr::getZExtOrBitCast(Constant *C, Type *Ty) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001570 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
Dan Gohman3cdcc3f2010-04-12 22:12:29 +00001571 return getBitCast(C, Ty);
1572 return getZExt(C, Ty);
Reid Spencer5c140882006-12-04 20:17:56 +00001573}
1574
Chris Lattner229907c2011-07-18 04:54:35 +00001575Constant *ConstantExpr::getSExtOrBitCast(Constant *C, Type *Ty) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001576 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
Dan Gohman3cdcc3f2010-04-12 22:12:29 +00001577 return getBitCast(C, Ty);
1578 return getSExt(C, Ty);
Reid Spencer5c140882006-12-04 20:17:56 +00001579}
1580
Chris Lattner229907c2011-07-18 04:54:35 +00001581Constant *ConstantExpr::getTruncOrBitCast(Constant *C, Type *Ty) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001582 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
Dan Gohman3cdcc3f2010-04-12 22:12:29 +00001583 return getBitCast(C, Ty);
1584 return getTrunc(C, Ty);
Reid Spencer5c140882006-12-04 20:17:56 +00001585}
1586
Chris Lattner229907c2011-07-18 04:54:35 +00001587Constant *ConstantExpr::getPointerCast(Constant *S, Type *Ty) {
Evgeniy Stepanov23382642013-01-16 14:41:46 +00001588 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
1589 assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
1590 "Invalid cast");
Reid Spencerbc245a02006-12-05 03:25:26 +00001591
Evgeniy Stepanov23382642013-01-16 14:41:46 +00001592 if (Ty->isIntOrIntVectorTy())
Dan Gohman3cdcc3f2010-04-12 22:12:29 +00001593 return getPtrToInt(S, Ty);
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00001594
1595 unsigned SrcAS = S->getType()->getPointerAddressSpace();
1596 if (Ty->isPtrOrPtrVectorTy() && SrcAS != Ty->getPointerAddressSpace())
1597 return getAddrSpaceCast(S, Ty);
1598
Dan Gohman3cdcc3f2010-04-12 22:12:29 +00001599 return getBitCast(S, Ty);
Reid Spencerbc245a02006-12-05 03:25:26 +00001600}
1601
Matt Arsenault21f38f42013-12-07 02:58:41 +00001602Constant *ConstantExpr::getPointerBitCastOrAddrSpaceCast(Constant *S,
1603 Type *Ty) {
1604 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
1605 assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast");
1606
1607 if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace())
1608 return getAddrSpaceCast(S, Ty);
1609
1610 return getBitCast(S, Ty);
1611}
1612
Sanjay Patelf3587ec2016-05-18 22:05:28 +00001613Constant *ConstantExpr::getIntegerCast(Constant *C, Type *Ty, bool isSigned) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00001614 assert(C->getType()->isIntOrIntVectorTy() &&
1615 Ty->isIntOrIntVectorTy() && "Invalid cast");
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001616 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1617 unsigned DstBits = Ty->getScalarSizeInBits();
Reid Spencer56521c42006-12-12 00:51:07 +00001618 Instruction::CastOps opcode =
1619 (SrcBits == DstBits ? Instruction::BitCast :
1620 (SrcBits > DstBits ? Instruction::Trunc :
1621 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1622 return getCast(opcode, C, Ty);
1623}
1624
Chris Lattner229907c2011-07-18 04:54:35 +00001625Constant *ConstantExpr::getFPCast(Constant *C, Type *Ty) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00001626 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
Reid Spencer56521c42006-12-12 00:51:07 +00001627 "Invalid cast");
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001628 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1629 unsigned DstBits = Ty->getScalarSizeInBits();
Reid Spencerca104e82006-12-12 05:38:50 +00001630 if (SrcBits == DstBits)
1631 return C; // Avoid a useless cast
Reid Spencer56521c42006-12-12 00:51:07 +00001632 Instruction::CastOps opcode =
Jay Foad9f32cfd2011-01-27 14:44:55 +00001633 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
Reid Spencer56521c42006-12-12 00:51:07 +00001634 return getCast(opcode, C, Ty);
1635}
1636
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001637Constant *ConstantExpr::getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001638#ifndef NDEBUG
1639 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1640 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1641#endif
1642 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001643 assert(C->getType()->isIntOrIntVectorTy() && "Trunc operand must be integer");
1644 assert(Ty->isIntOrIntVectorTy() && "Trunc produces only integral");
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001645 assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001646 "SrcTy must be larger than DestTy for Trunc!");
1647
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001648 return getFoldedCast(Instruction::Trunc, C, Ty, OnlyIfReduced);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001649}
1650
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001651Constant *ConstantExpr::getSExt(Constant *C, Type *Ty, bool OnlyIfReduced) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001652#ifndef NDEBUG
1653 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1654 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1655#endif
1656 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001657 assert(C->getType()->isIntOrIntVectorTy() && "SExt operand must be integral");
1658 assert(Ty->isIntOrIntVectorTy() && "SExt produces only integer");
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001659 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001660 "SrcTy must be smaller than DestTy for SExt!");
1661
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001662 return getFoldedCast(Instruction::SExt, C, Ty, OnlyIfReduced);
Chris Lattnerdd284742004-04-04 23:20:30 +00001663}
1664
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001665Constant *ConstantExpr::getZExt(Constant *C, Type *Ty, bool OnlyIfReduced) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001666#ifndef NDEBUG
1667 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1668 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1669#endif
1670 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001671 assert(C->getType()->isIntOrIntVectorTy() && "ZEXt operand must be integral");
1672 assert(Ty->isIntOrIntVectorTy() && "ZExt produces only integer");
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001673 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001674 "SrcTy must be smaller than DestTy for ZExt!");
1675
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001676 return getFoldedCast(Instruction::ZExt, C, Ty, OnlyIfReduced);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001677}
1678
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001679Constant *ConstantExpr::getFPTrunc(Constant *C, Type *Ty, bool OnlyIfReduced) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001680#ifndef NDEBUG
1681 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1682 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1683#endif
1684 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001685 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001686 C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001687 "This is an illegal floating point truncation!");
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001688 return getFoldedCast(Instruction::FPTrunc, C, Ty, OnlyIfReduced);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001689}
1690
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001691Constant *ConstantExpr::getFPExtend(Constant *C, Type *Ty, bool OnlyIfReduced) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001692#ifndef NDEBUG
1693 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1694 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1695#endif
1696 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001697 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001698 C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001699 "This is an illegal floating point extension!");
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001700 return getFoldedCast(Instruction::FPExt, C, Ty, OnlyIfReduced);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001701}
1702
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001703Constant *ConstantExpr::getUIToFP(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()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
Nate Begemand4d45c22007-11-17 03:58:34 +00001710 "This is an illegal uint to floating point cast!");
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001711 return getFoldedCast(Instruction::UIToFP, C, Ty, OnlyIfReduced);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001712}
1713
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001714Constant *ConstantExpr::getSIToFP(Constant *C, Type *Ty, bool OnlyIfReduced) {
Devang Pateld26344d2008-11-03 23:20:04 +00001715#ifndef NDEBUG
Nate Begemand4d45c22007-11-17 03:58:34 +00001716 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1717 bool toVec = Ty->getTypeID() == Type::VectorTyID;
Devang Pateld26344d2008-11-03 23:20:04 +00001718#endif
Nate Begemand4d45c22007-11-17 03:58:34 +00001719 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001720 assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001721 "This is an illegal sint to floating point cast!");
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001722 return getFoldedCast(Instruction::SIToFP, C, Ty, OnlyIfReduced);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001723}
1724
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001725Constant *ConstantExpr::getFPToUI(Constant *C, Type *Ty, bool OnlyIfReduced) {
Devang Pateld26344d2008-11-03 23:20:04 +00001726#ifndef NDEBUG
Nate Begemand4d45c22007-11-17 03:58:34 +00001727 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1728 bool toVec = Ty->getTypeID() == Type::VectorTyID;
Devang Pateld26344d2008-11-03 23:20:04 +00001729#endif
Nate Begemand4d45c22007-11-17 03:58:34 +00001730 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001731 assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
Nate Begemand4d45c22007-11-17 03:58:34 +00001732 "This is an illegal floating point to uint cast!");
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001733 return getFoldedCast(Instruction::FPToUI, C, Ty, OnlyIfReduced);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001734}
1735
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001736Constant *ConstantExpr::getFPToSI(Constant *C, Type *Ty, bool OnlyIfReduced) {
Devang Pateld26344d2008-11-03 23:20:04 +00001737#ifndef NDEBUG
Nate Begemand4d45c22007-11-17 03:58:34 +00001738 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1739 bool toVec = Ty->getTypeID() == Type::VectorTyID;
Devang Pateld26344d2008-11-03 23:20:04 +00001740#endif
Nate Begemand4d45c22007-11-17 03:58:34 +00001741 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001742 assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
Nate Begemand4d45c22007-11-17 03:58:34 +00001743 "This is an illegal floating point to sint cast!");
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001744 return getFoldedCast(Instruction::FPToSI, C, Ty, OnlyIfReduced);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001745}
1746
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001747Constant *ConstantExpr::getPtrToInt(Constant *C, Type *DstTy,
1748 bool OnlyIfReduced) {
Craig Topper95d23472017-07-09 07:04:00 +00001749 assert(C->getType()->isPtrOrPtrVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00001750 "PtrToInt source must be pointer or pointer vector");
Craig Topper95d23472017-07-09 07:04:00 +00001751 assert(DstTy->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00001752 "PtrToInt destination must be integer or integer vector");
Chris Lattner8a3df542012-01-25 01:32:59 +00001753 assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
Nick Lewyckyff509622012-01-25 03:20:12 +00001754 if (isa<VectorType>(C->getType()))
Chris Lattner8326bd82012-01-26 00:42:34 +00001755 assert(C->getType()->getVectorNumElements()==DstTy->getVectorNumElements()&&
Chris Lattner8a3df542012-01-25 01:32:59 +00001756 "Invalid cast between a different number of vector elements");
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001757 return getFoldedCast(Instruction::PtrToInt, C, DstTy, OnlyIfReduced);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001758}
1759
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001760Constant *ConstantExpr::getIntToPtr(Constant *C, Type *DstTy,
1761 bool OnlyIfReduced) {
Craig Topper95d23472017-07-09 07:04:00 +00001762 assert(C->getType()->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00001763 "IntToPtr source must be integer or integer vector");
Craig Topper95d23472017-07-09 07:04:00 +00001764 assert(DstTy->isPtrOrPtrVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00001765 "IntToPtr destination must be a pointer or pointer vector");
Chris Lattner8a3df542012-01-25 01:32:59 +00001766 assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
Nick Lewyckyff509622012-01-25 03:20:12 +00001767 if (isa<VectorType>(C->getType()))
Chris Lattner8326bd82012-01-26 00:42:34 +00001768 assert(C->getType()->getVectorNumElements()==DstTy->getVectorNumElements()&&
Chris Lattner8a3df542012-01-25 01:32:59 +00001769 "Invalid cast between a different number of vector elements");
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001770 return getFoldedCast(Instruction::IntToPtr, C, DstTy, OnlyIfReduced);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001771}
1772
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001773Constant *ConstantExpr::getBitCast(Constant *C, Type *DstTy,
1774 bool OnlyIfReduced) {
Chris Lattner37bc78a2010-01-26 21:51:43 +00001775 assert(CastInst::castIsValid(Instruction::BitCast, C, DstTy) &&
1776 "Invalid constantexpr bitcast!");
Galina Kistanovafc259902012-07-13 01:25:27 +00001777
Chris Lattnercbeda872009-03-21 06:55:54 +00001778 // It is common to ask for a bitcast of a value to its own type, handle this
1779 // speedily.
1780 if (C->getType() == DstTy) return C;
Galina Kistanovafc259902012-07-13 01:25:27 +00001781
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001782 return getFoldedCast(Instruction::BitCast, C, DstTy, OnlyIfReduced);
Chris Lattnerdd284742004-04-04 23:20:30 +00001783}
1784
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001785Constant *ConstantExpr::getAddrSpaceCast(Constant *C, Type *DstTy,
1786 bool OnlyIfReduced) {
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00001787 assert(CastInst::castIsValid(Instruction::AddrSpaceCast, C, DstTy) &&
1788 "Invalid constantexpr addrspacecast!");
1789
Jingyue Wubaabe502014-06-15 21:40:57 +00001790 // Canonicalize addrspacecasts between different pointer types by first
1791 // bitcasting the pointer type and then converting the address space.
1792 PointerType *SrcScalarTy = cast<PointerType>(C->getType()->getScalarType());
1793 PointerType *DstScalarTy = cast<PointerType>(DstTy->getScalarType());
1794 Type *DstElemTy = DstScalarTy->getElementType();
1795 if (SrcScalarTy->getElementType() != DstElemTy) {
1796 Type *MidTy = PointerType::get(DstElemTy, SrcScalarTy->getAddressSpace());
1797 if (VectorType *VT = dyn_cast<VectorType>(DstTy)) {
1798 // Handle vectors of pointers.
1799 MidTy = VectorType::get(MidTy, VT->getNumElements());
1800 }
1801 C = getBitCast(C, MidTy);
1802 }
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001803 return getFoldedCast(Instruction::AddrSpaceCast, C, DstTy, OnlyIfReduced);
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00001804}
1805
Cameron McInallycbde0d92018-11-13 18:15:47 +00001806Constant *ConstantExpr::get(unsigned Opcode, Constant *C, unsigned Flags,
1807 Type *OnlyIfReducedTy) {
1808 // Check the operands for consistency first.
1809 assert(Instruction::isUnaryOp(Opcode) &&
1810 "Invalid opcode in unary constant expression");
1811
1812#ifndef NDEBUG
1813 switch (Opcode) {
1814 case Instruction::FNeg:
1815 assert(C->getType()->isFPOrFPVectorTy() &&
1816 "Tried to create a floating-point operation on a "
1817 "non-floating-point type!");
1818 break;
1819 default:
1820 break;
1821 }
1822#endif
1823
1824 // TODO: Try to constant fold operation.
1825
1826 if (OnlyIfReducedTy == C->getType())
1827 return nullptr;
1828
1829 Constant *ArgVec[] = { C };
1830 ConstantExprKeyType Key(Opcode, ArgVec, 0, Flags);
1831
1832 LLVMContextImpl *pImpl = C->getContext().pImpl;
1833 return pImpl->ExprConstants.getOrCreate(C->getType(), Key);
1834}
1835
Chris Lattner887ecac2011-07-09 18:23:52 +00001836Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2,
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001837 unsigned Flags, Type *OnlyIfReducedTy) {
Chris Lattner887ecac2011-07-09 18:23:52 +00001838 // Check the operands for consistency first.
Simon Pilgrime0a6eb12018-06-22 10:48:02 +00001839 assert(Instruction::isBinaryOp(Opcode) &&
Chris Lattner38a9bcd2003-05-21 17:49:25 +00001840 "Invalid opcode in binary constant expression");
1841 assert(C1->getType() == C2->getType() &&
1842 "Operand types in binary constant expression should match");
Galina Kistanovafc259902012-07-13 01:25:27 +00001843
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001844#ifndef NDEBUG
1845 switch (Opcode) {
Dan Gohmana5b96452009-06-04 22:49:04 +00001846 case Instruction::Add:
Reid Spencer7eb55b32006-11-02 01:53:59 +00001847 case Instruction::Sub:
Dan Gohmana5b96452009-06-04 22:49:04 +00001848 case Instruction::Mul:
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001849 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001850 assert(C1->getType()->isIntOrIntVectorTy() &&
Dan Gohmana5b96452009-06-04 22:49:04 +00001851 "Tried to create an integer operation on a non-integer type!");
1852 break;
1853 case Instruction::FAdd:
1854 case Instruction::FSub:
1855 case Instruction::FMul:
1856 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001857 assert(C1->getType()->isFPOrFPVectorTy() &&
Dan Gohmana5b96452009-06-04 22:49:04 +00001858 "Tried to create a floating-point operation on a "
1859 "non-floating-point type!");
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001860 break;
Bjorn Petterssonaa025802018-07-03 12:39:52 +00001861 case Instruction::UDiv:
1862 case Instruction::SDiv:
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001863 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001864 assert(C1->getType()->isIntOrIntVectorTy() &&
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001865 "Tried to create an arithmetic operation on a non-arithmetic type!");
1866 break;
1867 case Instruction::FDiv:
1868 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001869 assert(C1->getType()->isFPOrFPVectorTy() &&
Dan Gohman7889f2b2009-06-15 22:25:12 +00001870 "Tried to create an arithmetic operation on a non-arithmetic type!");
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001871 break;
Bjorn Petterssonaa025802018-07-03 12:39:52 +00001872 case Instruction::URem:
1873 case Instruction::SRem:
Reid Spencer7eb55b32006-11-02 01:53:59 +00001874 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001875 assert(C1->getType()->isIntOrIntVectorTy() &&
Reid Spencer7eb55b32006-11-02 01:53:59 +00001876 "Tried to create an arithmetic operation on a non-arithmetic type!");
1877 break;
1878 case Instruction::FRem:
1879 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001880 assert(C1->getType()->isFPOrFPVectorTy() &&
Dan Gohman7889f2b2009-06-15 22:25:12 +00001881 "Tried to create an arithmetic operation on a non-arithmetic type!");
Reid Spencer7eb55b32006-11-02 01:53:59 +00001882 break;
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001883 case Instruction::And:
1884 case Instruction::Or:
1885 case Instruction::Xor:
1886 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001887 assert(C1->getType()->isIntOrIntVectorTy() &&
Misha Brukman3852f652005-01-27 06:46:38 +00001888 "Tried to create a logical operation on a non-integral type!");
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001889 break;
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001890 case Instruction::Shl:
Reid Spencerfdff9382006-11-08 06:47:33 +00001891 case Instruction::LShr:
1892 case Instruction::AShr:
Reid Spencer2341c222007-02-02 02:16:23 +00001893 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001894 assert(C1->getType()->isIntOrIntVectorTy() &&
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001895 "Tried to create a shift operation on a non-integer type!");
1896 break;
1897 default:
1898 break;
1899 }
1900#endif
1901
Chris Lattner887ecac2011-07-09 18:23:52 +00001902 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1903 return FC; // Fold a few common cases.
Galina Kistanovafc259902012-07-13 01:25:27 +00001904
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001905 if (OnlyIfReducedTy == C1->getType())
1906 return nullptr;
1907
Benjamin Kramer324322b2013-03-07 20:53:34 +00001908 Constant *ArgVec[] = { C1, C2 };
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00001909 ConstantExprKeyType Key(Opcode, ArgVec, 0, Flags);
Galina Kistanovafc259902012-07-13 01:25:27 +00001910
Chris Lattner887ecac2011-07-09 18:23:52 +00001911 LLVMContextImpl *pImpl = C1->getContext().pImpl;
1912 return pImpl->ExprConstants.getOrCreate(C1->getType(), Key);
Reid Spencera009d0d2006-12-04 21:35:24 +00001913}
1914
Chris Lattner229907c2011-07-18 04:54:35 +00001915Constant *ConstantExpr::getSizeOf(Type* Ty) {
Owen Anderson487375e2009-07-29 18:55:55 +00001916 // sizeof is implemented as: (i64) gep (Ty*)null, 1
1917 // Note that a non-inbounds gep is used, as null isn't within any object.
Owen Anderson55f1c092009-08-13 21:58:54 +00001918 Constant *GEPIdx = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
Owen Anderson487375e2009-07-29 18:55:55 +00001919 Constant *GEP = getGetElementPtr(
David Blaikie4a2e73b2015-04-02 18:55:32 +00001920 Ty, Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx);
Bjorn Petterssonaa025802018-07-03 12:39:52 +00001921 return getPtrToInt(GEP,
Dan Gohman3cdcc3f2010-04-12 22:12:29 +00001922 Type::getInt64Ty(Ty->getContext()));
Owen Anderson487375e2009-07-29 18:55:55 +00001923}
1924
Chris Lattner229907c2011-07-18 04:54:35 +00001925Constant *ConstantExpr::getAlignOf(Type* Ty) {
Dan Gohmancf913832010-01-28 02:15:55 +00001926 // alignof is implemented as: (i64) gep ({i1,Ty}*)null, 0, 1
Dan Gohman50c09d02009-08-11 17:57:01 +00001927 // Note that a non-inbounds gep is used, as null isn't within any object.
Serge Gueltone38003f2017-05-09 19:31:13 +00001928 Type *AligningTy = StructType::get(Type::getInt1Ty(Ty->getContext()), Ty);
Matt Arsenaultbe558882014-04-23 20:58:57 +00001929 Constant *NullPtr = Constant::getNullValue(AligningTy->getPointerTo(0));
Dan Gohmana9be7392010-01-28 02:43:22 +00001930 Constant *Zero = ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0);
Owen Anderson55f1c092009-08-13 21:58:54 +00001931 Constant *One = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
Owen Anderson487375e2009-07-29 18:55:55 +00001932 Constant *Indices[2] = { Zero, One };
David Blaikie4a2e73b2015-04-02 18:55:32 +00001933 Constant *GEP = getGetElementPtr(AligningTy, NullPtr, Indices);
Dan Gohman3cdcc3f2010-04-12 22:12:29 +00001934 return getPtrToInt(GEP,
1935 Type::getInt64Ty(Ty->getContext()));
Owen Anderson487375e2009-07-29 18:55:55 +00001936}
1937
Chris Lattner229907c2011-07-18 04:54:35 +00001938Constant *ConstantExpr::getOffsetOf(StructType* STy, unsigned FieldNo) {
Dan Gohmanede94e62010-02-01 16:37:38 +00001939 return getOffsetOf(STy, ConstantInt::get(Type::getInt32Ty(STy->getContext()),
1940 FieldNo));
1941}
1942
Chris Lattner229907c2011-07-18 04:54:35 +00001943Constant *ConstantExpr::getOffsetOf(Type* Ty, Constant *FieldNo) {
Dan Gohmanff3af7252009-08-16 21:26:11 +00001944 // offsetof is implemented as: (i64) gep (Ty*)null, 0, FieldNo
1945 // Note that a non-inbounds gep is used, as null isn't within any object.
1946 Constant *GEPIdx[] = {
Dan Gohmanede94e62010-02-01 16:37:38 +00001947 ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0),
1948 FieldNo
Dan Gohmanff3af7252009-08-16 21:26:11 +00001949 };
1950 Constant *GEP = getGetElementPtr(
David Blaikie4a2e73b2015-04-02 18:55:32 +00001951 Ty, Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx);
Dan Gohman3cdcc3f2010-04-12 22:12:29 +00001952 return getPtrToInt(GEP,
1953 Type::getInt64Ty(Ty->getContext()));
Dan Gohmanff3af7252009-08-16 21:26:11 +00001954}
Owen Anderson487375e2009-07-29 18:55:55 +00001955
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001956Constant *ConstantExpr::getCompare(unsigned short Predicate, Constant *C1,
1957 Constant *C2, bool OnlyIfReduced) {
Reid Spencera009d0d2006-12-04 21:35:24 +00001958 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Galina Kistanovafc259902012-07-13 01:25:27 +00001959
Chris Lattner887ecac2011-07-09 18:23:52 +00001960 switch (Predicate) {
1961 default: llvm_unreachable("Invalid CmpInst predicate");
1962 case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
1963 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
1964 case CmpInst::FCMP_ONE: case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
1965 case CmpInst::FCMP_UEQ: case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
1966 case CmpInst::FCMP_ULT: case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
1967 case CmpInst::FCMP_TRUE:
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001968 return getFCmp(Predicate, C1, C2, OnlyIfReduced);
Galina Kistanovafc259902012-07-13 01:25:27 +00001969
Chris Lattner887ecac2011-07-09 18:23:52 +00001970 case CmpInst::ICMP_EQ: case CmpInst::ICMP_NE: case CmpInst::ICMP_UGT:
1971 case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
1972 case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
1973 case CmpInst::ICMP_SLE:
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001974 return getICmp(Predicate, C1, C2, OnlyIfReduced);
Chris Lattner887ecac2011-07-09 18:23:52 +00001975 }
Chris Lattner29ca2c62004-08-04 18:50:09 +00001976}
1977
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001978Constant *ConstantExpr::getSelect(Constant *C, Constant *V1, Constant *V2,
1979 Type *OnlyIfReducedTy) {
Chris Lattner41632132008-12-29 00:16:12 +00001980 assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
Chris Lattner6e415c02004-03-12 05:54:04 +00001981
Chris Lattner887ecac2011-07-09 18:23:52 +00001982 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1983 return SC; // Fold common cases
Chris Lattner6e415c02004-03-12 05:54:04 +00001984
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001985 if (OnlyIfReducedTy == V1->getType())
1986 return nullptr;
1987
Benjamin Kramer324322b2013-03-07 20:53:34 +00001988 Constant *ArgVec[] = { C, V1, V2 };
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00001989 ConstantExprKeyType Key(Instruction::Select, ArgVec);
Galina Kistanovafc259902012-07-13 01:25:27 +00001990
Chris Lattner887ecac2011-07-09 18:23:52 +00001991 LLVMContextImpl *pImpl = C->getContext().pImpl;
1992 return pImpl->ExprConstants.getOrCreate(V1->getType(), Key);
Chris Lattner6e415c02004-03-12 05:54:04 +00001993}
1994
David Blaikie4a2e73b2015-04-02 18:55:32 +00001995Constant *ConstantExpr::getGetElementPtr(Type *Ty, Constant *C,
1996 ArrayRef<Value *> Idxs, bool InBounds,
Peter Collingbourned93620b2016-11-10 22:34:55 +00001997 Optional<unsigned> InRangeIndex,
David Blaikie4a2e73b2015-04-02 18:55:32 +00001998 Type *OnlyIfReducedTy) {
David Blaikie4a2e73b2015-04-02 18:55:32 +00001999 if (!Ty)
2000 Ty = cast<PointerType>(C->getType()->getScalarType())->getElementType();
2001 else
David Blaikied9d900c2015-05-07 17:28:58 +00002002 assert(
2003 Ty ==
2004 cast<PointerType>(C->getType()->getScalarType())->getContainedType(0u));
2005
Peter Collingbourned93620b2016-11-10 22:34:55 +00002006 if (Constant *FC =
2007 ConstantFoldGetElementPtr(Ty, C, InBounds, InRangeIndex, Idxs))
David Blaikied9d900c2015-05-07 17:28:58 +00002008 return FC; // Fold a few common cases.
2009
Chris Lattner887ecac2011-07-09 18:23:52 +00002010 // Get the result type of the getelementptr!
David Blaikie4a2e73b2015-04-02 18:55:32 +00002011 Type *DestTy = GetElementPtrInst::getIndexedType(Ty, Idxs);
2012 assert(DestTy && "GEP indices invalid!");
Chris Lattner8326bd82012-01-26 00:42:34 +00002013 unsigned AS = C->getType()->getPointerAddressSpace();
David Blaikie4a2e73b2015-04-02 18:55:32 +00002014 Type *ReqTy = DestTy->getPointerTo(AS);
Elena Demikhovskyee004bc2016-05-15 12:30:25 +00002015
2016 unsigned NumVecElts = 0;
2017 if (C->getType()->isVectorTy())
2018 NumVecElts = C->getType()->getVectorNumElements();
2019 else for (auto Idx : Idxs)
2020 if (Idx->getType()->isVectorTy())
2021 NumVecElts = Idx->getType()->getVectorNumElements();
2022
2023 if (NumVecElts)
2024 ReqTy = VectorType::get(ReqTy, NumVecElts);
Galina Kistanovafc259902012-07-13 01:25:27 +00002025
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002026 if (OnlyIfReducedTy == ReqTy)
2027 return nullptr;
2028
Dan Gohman1b849082009-09-07 23:54:19 +00002029 // Look up the constant in the table first to ensure uniqueness
2030 std::vector<Constant*> ArgVec;
Jay Foaded8db7d2011-07-21 14:31:17 +00002031 ArgVec.reserve(1 + Idxs.size());
Dan Gohman1b849082009-09-07 23:54:19 +00002032 ArgVec.push_back(C);
Duncan Sandse6beec62012-11-13 12:59:33 +00002033 for (unsigned i = 0, e = Idxs.size(); i != e; ++i) {
Duncan Sandse6beec62012-11-13 12:59:33 +00002034 assert((!Idxs[i]->getType()->isVectorTy() ||
Elena Demikhovskyee004bc2016-05-15 12:30:25 +00002035 Idxs[i]->getType()->getVectorNumElements() == NumVecElts) &&
Duncan Sandse6beec62012-11-13 12:59:33 +00002036 "getelementptr index type missmatch");
Elena Demikhovskyee004bc2016-05-15 12:30:25 +00002037
2038 Constant *Idx = cast<Constant>(Idxs[i]);
2039 if (NumVecElts && !Idxs[i]->getType()->isVectorTy())
2040 Idx = ConstantVector::getSplat(NumVecElts, Idx);
2041 ArgVec.push_back(Idx);
Duncan Sandse6beec62012-11-13 12:59:33 +00002042 }
Peter Collingbourned93620b2016-11-10 22:34:55 +00002043
2044 unsigned SubClassOptionalData = InBounds ? GEPOperator::IsInBounds : 0;
2045 if (InRangeIndex && *InRangeIndex < 63)
2046 SubClassOptionalData |= (*InRangeIndex + 1) << 1;
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002047 const ConstantExprKeyType Key(Instruction::GetElementPtr, ArgVec, 0,
Peter Collingbourned93620b2016-11-10 22:34:55 +00002048 SubClassOptionalData, None, Ty);
Galina Kistanovafc259902012-07-13 01:25:27 +00002049
Chris Lattner887ecac2011-07-09 18:23:52 +00002050 LLVMContextImpl *pImpl = C->getContext().pImpl;
Dan Gohman1b849082009-09-07 23:54:19 +00002051 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
2052}
2053
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002054Constant *ConstantExpr::getICmp(unsigned short pred, Constant *LHS,
2055 Constant *RHS, bool OnlyIfReduced) {
Reid Spenceree3c9912006-12-04 05:19:50 +00002056 assert(LHS->getType() == RHS->getType());
Craig Topper45844762017-07-05 23:35:46 +00002057 assert(CmpInst::isIntPredicate((CmpInst::Predicate)pred) &&
2058 "Invalid ICmp Predicate");
Reid Spenceree3c9912006-12-04 05:19:50 +00002059
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00002060 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
Reid Spenceree3c9912006-12-04 05:19:50 +00002061 return FC; // Fold a few common cases...
2062
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002063 if (OnlyIfReduced)
2064 return nullptr;
2065
Reid Spenceree3c9912006-12-04 05:19:50 +00002066 // Look up the constant in the table first to ensure uniqueness
Benjamin Kramer324322b2013-03-07 20:53:34 +00002067 Constant *ArgVec[] = { LHS, RHS };
Reid Spencerb1537492006-12-24 18:42:29 +00002068 // Get the key type with both the opcode and predicate
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002069 const ConstantExprKeyType Key(Instruction::ICmp, ArgVec, pred);
Owen Anderson61794042009-06-17 20:10:08 +00002070
Chris Lattner229907c2011-07-18 04:54:35 +00002071 Type *ResultTy = Type::getInt1Ty(LHS->getContext());
2072 if (VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
Nick Lewycky9e26c1c2010-01-21 07:03:21 +00002073 ResultTy = VectorType::get(ResultTy, VT->getNumElements());
2074
Owen Anderson1584a292009-08-04 20:25:11 +00002075 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
Nick Lewycky9e26c1c2010-01-21 07:03:21 +00002076 return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
Reid Spenceree3c9912006-12-04 05:19:50 +00002077}
2078
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002079Constant *ConstantExpr::getFCmp(unsigned short pred, Constant *LHS,
2080 Constant *RHS, bool OnlyIfReduced) {
Reid Spenceree3c9912006-12-04 05:19:50 +00002081 assert(LHS->getType() == RHS->getType());
Craig Topper45844762017-07-05 23:35:46 +00002082 assert(CmpInst::isFPPredicate((CmpInst::Predicate)pred) &&
2083 "Invalid FCmp Predicate");
Reid Spenceree3c9912006-12-04 05:19:50 +00002084
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00002085 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
Reid Spenceree3c9912006-12-04 05:19:50 +00002086 return FC; // Fold a few common cases...
2087
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002088 if (OnlyIfReduced)
2089 return nullptr;
2090
Reid Spenceree3c9912006-12-04 05:19:50 +00002091 // Look up the constant in the table first to ensure uniqueness
Benjamin Kramer324322b2013-03-07 20:53:34 +00002092 Constant *ArgVec[] = { LHS, RHS };
Reid Spencerb1537492006-12-24 18:42:29 +00002093 // Get the key type with both the opcode and predicate
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002094 const ConstantExprKeyType Key(Instruction::FCmp, ArgVec, pred);
Nick Lewycky9e26c1c2010-01-21 07:03:21 +00002095
Chris Lattner229907c2011-07-18 04:54:35 +00002096 Type *ResultTy = Type::getInt1Ty(LHS->getContext());
2097 if (VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
Nick Lewycky9e26c1c2010-01-21 07:03:21 +00002098 ResultTy = VectorType::get(ResultTy, VT->getNumElements());
2099
Owen Anderson1584a292009-08-04 20:25:11 +00002100 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
Nick Lewycky9e26c1c2010-01-21 07:03:21 +00002101 return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
Reid Spenceree3c9912006-12-04 05:19:50 +00002102}
2103
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002104Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx,
2105 Type *OnlyIfReducedTy) {
Duncan Sands19d0b472010-02-16 11:11:14 +00002106 assert(Val->getType()->isVectorTy() &&
Reid Spencer09575ba2007-02-15 03:39:18 +00002107 "Tried to create extractelement operation on non-vector type!");
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002108 assert(Idx->getType()->isIntegerTy() &&
2109 "Extractelement index must be an integer type!");
Galina Kistanovafc259902012-07-13 01:25:27 +00002110
Chris Lattner887ecac2011-07-09 18:23:52 +00002111 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
Chris Lattner09660c92009-12-30 20:25:09 +00002112 return FC; // Fold a few common cases.
Galina Kistanovafc259902012-07-13 01:25:27 +00002113
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002114 Type *ReqTy = Val->getType()->getVectorElementType();
2115 if (OnlyIfReducedTy == ReqTy)
2116 return nullptr;
2117
Robert Bocchinoca27f032006-01-17 20:07:22 +00002118 // Look up the constant in the table first to ensure uniqueness
Benjamin Kramer324322b2013-03-07 20:53:34 +00002119 Constant *ArgVec[] = { Val, Idx };
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002120 const ConstantExprKeyType Key(Instruction::ExtractElement, ArgVec);
Galina Kistanovafc259902012-07-13 01:25:27 +00002121
Chris Lattner887ecac2011-07-09 18:23:52 +00002122 LLVMContextImpl *pImpl = Val->getContext().pImpl;
Owen Anderson1584a292009-08-04 20:25:11 +00002123 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
Robert Bocchinoca27f032006-01-17 20:07:22 +00002124}
2125
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002126Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
2127 Constant *Idx, Type *OnlyIfReducedTy) {
Duncan Sands19d0b472010-02-16 11:11:14 +00002128 assert(Val->getType()->isVectorTy() &&
Reid Spencer09575ba2007-02-15 03:39:18 +00002129 "Tried to create insertelement operation on non-vector type!");
Chris Lattner8326bd82012-01-26 00:42:34 +00002130 assert(Elt->getType() == Val->getType()->getVectorElementType() &&
2131 "Insertelement types must match!");
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002132 assert(Idx->getType()->isIntegerTy() &&
Reid Spencer2546b762007-01-26 07:37:34 +00002133 "Insertelement index must be i32 type!");
Robert Bocchinoca27f032006-01-17 20:07:22 +00002134
Chris Lattner887ecac2011-07-09 18:23:52 +00002135 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
2136 return FC; // Fold a few common cases.
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002137
2138 if (OnlyIfReducedTy == Val->getType())
2139 return nullptr;
2140
Chris Lattnerbbe0a422006-04-08 01:18:18 +00002141 // Look up the constant in the table first to ensure uniqueness
Benjamin Kramer324322b2013-03-07 20:53:34 +00002142 Constant *ArgVec[] = { Val, Elt, Idx };
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002143 const ConstantExprKeyType Key(Instruction::InsertElement, ArgVec);
Galina Kistanovafc259902012-07-13 01:25:27 +00002144
Chris Lattner887ecac2011-07-09 18:23:52 +00002145 LLVMContextImpl *pImpl = Val->getContext().pImpl;
2146 return pImpl->ExprConstants.getOrCreate(Val->getType(), Key);
Chris Lattnerbbe0a422006-04-08 01:18:18 +00002147}
2148
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002149Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
2150 Constant *Mask, Type *OnlyIfReducedTy) {
Chris Lattnerbbe0a422006-04-08 01:18:18 +00002151 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
2152 "Invalid shuffle vector constant expr operands!");
Nate Begeman94aa38d2009-02-12 21:28:33 +00002153
Chris Lattner887ecac2011-07-09 18:23:52 +00002154 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
2155 return FC; // Fold a few common cases.
2156
Chris Lattner8326bd82012-01-26 00:42:34 +00002157 unsigned NElts = Mask->getType()->getVectorNumElements();
2158 Type *EltTy = V1->getType()->getVectorElementType();
Chris Lattner229907c2011-07-18 04:54:35 +00002159 Type *ShufTy = VectorType::get(EltTy, NElts);
Chris Lattner887ecac2011-07-09 18:23:52 +00002160
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002161 if (OnlyIfReducedTy == ShufTy)
2162 return nullptr;
2163
Chris Lattner887ecac2011-07-09 18:23:52 +00002164 // Look up the constant in the table first to ensure uniqueness
Benjamin Kramer324322b2013-03-07 20:53:34 +00002165 Constant *ArgVec[] = { V1, V2, Mask };
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002166 const ConstantExprKeyType Key(Instruction::ShuffleVector, ArgVec);
Galina Kistanovafc259902012-07-13 01:25:27 +00002167
Chris Lattner887ecac2011-07-09 18:23:52 +00002168 LLVMContextImpl *pImpl = ShufTy->getContext().pImpl;
2169 return pImpl->ExprConstants.getOrCreate(ShufTy, Key);
Chris Lattnerbbe0a422006-04-08 01:18:18 +00002170}
2171
Chris Lattner887ecac2011-07-09 18:23:52 +00002172Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002173 ArrayRef<unsigned> Idxs,
2174 Type *OnlyIfReducedTy) {
Hal Finkelb31366d2013-07-10 22:51:01 +00002175 assert(Agg->getType()->isFirstClassType() &&
2176 "Non-first-class type for constant insertvalue expression");
2177
Jay Foad57aa6362011-07-13 10:26:04 +00002178 assert(ExtractValueInst::getIndexedType(Agg->getType(),
2179 Idxs) == Val->getType() &&
Dan Gohman12fce772008-05-15 19:50:34 +00002180 "insertvalue indices invalid!");
Hal Finkelb31366d2013-07-10 22:51:01 +00002181 Type *ReqTy = Val->getType();
2182
2183 if (Constant *FC = ConstantFoldInsertValueInstruction(Agg, Val, Idxs))
2184 return FC;
2185
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002186 if (OnlyIfReducedTy == ReqTy)
2187 return nullptr;
2188
Hal Finkelb31366d2013-07-10 22:51:01 +00002189 Constant *ArgVec[] = { Agg, Val };
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002190 const ConstantExprKeyType Key(Instruction::InsertValue, ArgVec, 0, 0, Idxs);
Hal Finkelb31366d2013-07-10 22:51:01 +00002191
2192 LLVMContextImpl *pImpl = Agg->getContext().pImpl;
2193 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
Dan Gohman12fce772008-05-15 19:50:34 +00002194}
2195
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002196Constant *ConstantExpr::getExtractValue(Constant *Agg, ArrayRef<unsigned> Idxs,
2197 Type *OnlyIfReducedTy) {
Dan Gohman0752bff2008-05-23 00:36:11 +00002198 assert(Agg->getType()->isFirstClassType() &&
Chris Lattner887ecac2011-07-09 18:23:52 +00002199 "Tried to create extractelement operation on non-first-class type!");
Dan Gohman12fce772008-05-15 19:50:34 +00002200
Chris Lattner229907c2011-07-18 04:54:35 +00002201 Type *ReqTy = ExtractValueInst::getIndexedType(Agg->getType(), Idxs);
Chandler Carruth9db56b82011-07-10 09:45:35 +00002202 (void)ReqTy;
Chris Lattner887ecac2011-07-09 18:23:52 +00002203 assert(ReqTy && "extractvalue indices invalid!");
Galina Kistanovafc259902012-07-13 01:25:27 +00002204
Dan Gohman0752bff2008-05-23 00:36:11 +00002205 assert(Agg->getType()->isFirstClassType() &&
2206 "Non-first-class type for constant extractvalue expression");
Hal Finkelb31366d2013-07-10 22:51:01 +00002207 if (Constant *FC = ConstantFoldExtractValueInstruction(Agg, Idxs))
2208 return FC;
2209
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002210 if (OnlyIfReducedTy == ReqTy)
2211 return nullptr;
2212
Hal Finkelb31366d2013-07-10 22:51:01 +00002213 Constant *ArgVec[] = { Agg };
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002214 const ConstantExprKeyType Key(Instruction::ExtractValue, ArgVec, 0, 0, Idxs);
Hal Finkelb31366d2013-07-10 22:51:01 +00002215
2216 LLVMContextImpl *pImpl = Agg->getContext().pImpl;
2217 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
Dan Gohman12fce772008-05-15 19:50:34 +00002218}
2219
Chris Lattnere9b4ad72011-02-10 07:01:55 +00002220Constant *ConstantExpr::getNeg(Constant *C, bool HasNUW, bool HasNSW) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00002221 assert(C->getType()->isIntOrIntVectorTy() &&
Owen Anderson487375e2009-07-29 18:55:55 +00002222 "Cannot NEG a nonintegral value!");
Chris Lattnere9b4ad72011-02-10 07:01:55 +00002223 return getSub(ConstantFP::getZeroValueForNegation(C->getType()),
2224 C, HasNUW, HasNSW);
Owen Anderson487375e2009-07-29 18:55:55 +00002225}
2226
Chris Lattnera676c0f2011-02-07 16:40:21 +00002227Constant *ConstantExpr::getFNeg(Constant *C) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00002228 assert(C->getType()->isFPOrFPVectorTy() &&
Owen Anderson487375e2009-07-29 18:55:55 +00002229 "Cannot FNEG a non-floating-point value!");
Chris Lattnere9b4ad72011-02-10 07:01:55 +00002230 return getFSub(ConstantFP::getZeroValueForNegation(C->getType()), C);
Owen Anderson487375e2009-07-29 18:55:55 +00002231}
2232
Chris Lattnera676c0f2011-02-07 16:40:21 +00002233Constant *ConstantExpr::getNot(Constant *C) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00002234 assert(C->getType()->isIntOrIntVectorTy() &&
Owen Anderson487375e2009-07-29 18:55:55 +00002235 "Cannot NOT a nonintegral value!");
Owen Anderson5a1acd92009-07-31 20:28:14 +00002236 return get(Instruction::Xor, C, Constant::getAllOnesValue(C->getType()));
Owen Anderson487375e2009-07-29 18:55:55 +00002237}
2238
Chris Lattnere9b4ad72011-02-10 07:01:55 +00002239Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2,
2240 bool HasNUW, bool HasNSW) {
2241 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2242 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2243 return get(Instruction::Add, C1, C2, Flags);
Owen Anderson487375e2009-07-29 18:55:55 +00002244}
2245
Chris Lattnera676c0f2011-02-07 16:40:21 +00002246Constant *ConstantExpr::getFAdd(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002247 return get(Instruction::FAdd, C1, C2);
2248}
2249
Chris Lattnere9b4ad72011-02-10 07:01:55 +00002250Constant *ConstantExpr::getSub(Constant *C1, Constant *C2,
2251 bool HasNUW, bool HasNSW) {
2252 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2253 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2254 return get(Instruction::Sub, C1, C2, Flags);
Owen Anderson487375e2009-07-29 18:55:55 +00002255}
2256
Chris Lattnera676c0f2011-02-07 16:40:21 +00002257Constant *ConstantExpr::getFSub(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002258 return get(Instruction::FSub, C1, C2);
2259}
2260
Chris Lattnere9b4ad72011-02-10 07:01:55 +00002261Constant *ConstantExpr::getMul(Constant *C1, Constant *C2,
2262 bool HasNUW, bool HasNSW) {
2263 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2264 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2265 return get(Instruction::Mul, C1, C2, Flags);
Owen Anderson487375e2009-07-29 18:55:55 +00002266}
2267
Chris Lattnera676c0f2011-02-07 16:40:21 +00002268Constant *ConstantExpr::getFMul(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002269 return get(Instruction::FMul, C1, C2);
2270}
2271
Chris Lattner0d75eac2011-02-09 16:43:07 +00002272Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2, bool isExact) {
2273 return get(Instruction::UDiv, C1, C2,
2274 isExact ? PossiblyExactOperator::IsExact : 0);
Owen Anderson487375e2009-07-29 18:55:55 +00002275}
2276
Chris Lattner0d75eac2011-02-09 16:43:07 +00002277Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2, bool isExact) {
2278 return get(Instruction::SDiv, C1, C2,
2279 isExact ? PossiblyExactOperator::IsExact : 0);
Owen Anderson487375e2009-07-29 18:55:55 +00002280}
2281
Chris Lattnera676c0f2011-02-07 16:40:21 +00002282Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002283 return get(Instruction::FDiv, C1, C2);
2284}
2285
Chris Lattnera676c0f2011-02-07 16:40:21 +00002286Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002287 return get(Instruction::URem, C1, C2);
2288}
2289
Chris Lattnera676c0f2011-02-07 16:40:21 +00002290Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002291 return get(Instruction::SRem, C1, C2);
2292}
2293
Chris Lattnera676c0f2011-02-07 16:40:21 +00002294Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002295 return get(Instruction::FRem, C1, C2);
2296}
2297
Chris Lattnera676c0f2011-02-07 16:40:21 +00002298Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002299 return get(Instruction::And, C1, C2);
2300}
2301
Chris Lattnera676c0f2011-02-07 16:40:21 +00002302Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002303 return get(Instruction::Or, C1, C2);
2304}
2305
Chris Lattnera676c0f2011-02-07 16:40:21 +00002306Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002307 return get(Instruction::Xor, C1, C2);
2308}
2309
Chris Lattnere9b4ad72011-02-10 07:01:55 +00002310Constant *ConstantExpr::getShl(Constant *C1, Constant *C2,
2311 bool HasNUW, bool HasNSW) {
2312 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2313 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2314 return get(Instruction::Shl, C1, C2, Flags);
Owen Anderson487375e2009-07-29 18:55:55 +00002315}
2316
Chris Lattner0d75eac2011-02-09 16:43:07 +00002317Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2, bool isExact) {
2318 return get(Instruction::LShr, C1, C2,
2319 isExact ? PossiblyExactOperator::IsExact : 0);
Owen Anderson487375e2009-07-29 18:55:55 +00002320}
2321
Chris Lattner0d75eac2011-02-09 16:43:07 +00002322Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2, bool isExact) {
2323 return get(Instruction::AShr, C1, C2,
2324 isExact ? PossiblyExactOperator::IsExact : 0);
Owen Anderson487375e2009-07-29 18:55:55 +00002325}
2326
Sanjay Patele85a3002018-07-06 15:18:58 +00002327Constant *ConstantExpr::getBinOpIdentity(unsigned Opcode, Type *Ty,
2328 bool AllowRHSConstant) {
2329 assert(Instruction::isBinaryOp(Opcode) && "Only binops allowed");
2330
2331 // Commutative opcodes: it does not matter if AllowRHSConstant is set.
2332 if (Instruction::isCommutative(Opcode)) {
2333 switch (Opcode) {
2334 case Instruction::Add: // X + 0 = X
2335 case Instruction::Or: // X | 0 = X
2336 case Instruction::Xor: // X ^ 0 = X
2337 return Constant::getNullValue(Ty);
2338 case Instruction::Mul: // X * 1 = X
2339 return ConstantInt::get(Ty, 1);
2340 case Instruction::And: // X & -1 = X
2341 return Constant::getAllOnesValue(Ty);
2342 case Instruction::FAdd: // X + -0.0 = X
2343 // TODO: If the fadd has 'nsz', should we return +0.0?
2344 return ConstantFP::getNegativeZero(Ty);
2345 case Instruction::FMul: // X * 1.0 = X
2346 return ConstantFP::get(Ty, 1.0);
2347 default:
2348 llvm_unreachable("Every commutative binop has an identity constant");
2349 }
2350 }
2351
2352 // Non-commutative opcodes: AllowRHSConstant must be set.
2353 if (!AllowRHSConstant)
Craig Topperc6207612014-04-09 06:08:46 +00002354 return nullptr;
Duncan Sands318a89d2012-06-13 09:42:13 +00002355
Sanjay Patele85a3002018-07-06 15:18:58 +00002356 switch (Opcode) {
2357 case Instruction::Sub: // X - 0 = X
2358 case Instruction::Shl: // X << 0 = X
2359 case Instruction::LShr: // X >>u 0 = X
2360 case Instruction::AShr: // X >> 0 = X
2361 case Instruction::FSub: // X - 0.0 = X
2362 return Constant::getNullValue(Ty);
2363 case Instruction::SDiv: // X / 1 = X
2364 case Instruction::UDiv: // X /u 1 = X
2365 return ConstantInt::get(Ty, 1);
2366 case Instruction::FDiv: // X / 1.0 = X
2367 return ConstantFP::get(Ty, 1.0);
2368 default:
2369 return nullptr;
Duncan Sandsd7aeefe2012-06-12 14:33:56 +00002370 }
2371}
2372
Duncan Sands318a89d2012-06-13 09:42:13 +00002373Constant *ConstantExpr::getBinOpAbsorber(unsigned Opcode, Type *Ty) {
2374 switch (Opcode) {
2375 default:
2376 // Doesn't have an absorber.
Craig Topperc6207612014-04-09 06:08:46 +00002377 return nullptr;
Duncan Sands318a89d2012-06-13 09:42:13 +00002378
2379 case Instruction::Or:
2380 return Constant::getAllOnesValue(Ty);
2381
2382 case Instruction::And:
2383 case Instruction::Mul:
2384 return Constant::getNullValue(Ty);
2385 }
2386}
2387
Sanjay Patel1d0ac7c2016-04-29 22:03:27 +00002388/// Remove the constant from the constant table.
Pete Cooper86dd4cf2015-06-23 21:55:11 +00002389void ConstantExpr::destroyConstantImpl() {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002390 getType()->getContext().pImpl->ExprConstants.remove(this);
Vikram S. Adve4e537b22002-07-14 23:13:17 +00002391}
2392
Chris Lattner3cd8c562002-07-30 18:54:25 +00002393const char *ConstantExpr::getOpcodeName() const {
2394 return Instruction::getOpcodeName(getOpcode());
Vikram S. Adve4e537b22002-07-14 23:13:17 +00002395}
Reid Spencer1ebe1ab2004-07-17 23:48:33 +00002396
David Blaikie60310f22015-05-08 00:42:26 +00002397GetElementPtrConstantExpr::GetElementPtrConstantExpr(
2398 Type *SrcElementTy, Constant *C, ArrayRef<Constant *> IdxList, Type *DestTy)
2399 : ConstantExpr(DestTy, Instruction::GetElementPtr,
2400 OperandTraits<GetElementPtrConstantExpr>::op_end(this) -
2401 (IdxList.size() + 1),
2402 IdxList.size() + 1),
Eduard Burtescu19eb0312016-01-19 17:28:00 +00002403 SrcElementTy(SrcElementTy),
2404 ResElementTy(GetElementPtrInst::getIndexedType(SrcElementTy, IdxList)) {
Pete Coopereb31b682015-05-21 22:48:54 +00002405 Op<0>() = C;
Pete Cooper74510a42015-06-12 17:48:05 +00002406 Use *OperandList = getOperandList();
Chris Lattnera3b94ba2010-03-30 20:48:48 +00002407 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
2408 OperandList[i+1] = IdxList[i];
2409}
2410
David Blaikie60310f22015-05-08 00:42:26 +00002411Type *GetElementPtrConstantExpr::getSourceElementType() const {
2412 return SrcElementTy;
2413}
2414
Eduard Burtescu19eb0312016-01-19 17:28:00 +00002415Type *GetElementPtrConstantExpr::getResultElementType() const {
2416 return ResElementTy;
2417}
2418
Chris Lattner3756b912012-01-23 22:57:10 +00002419//===----------------------------------------------------------------------===//
2420// ConstantData* implementations
2421
Chris Lattnere4f3f102012-01-24 04:43:41 +00002422Type *ConstantDataSequential::getElementType() const {
2423 return getType()->getElementType();
2424}
2425
Chris Lattner5d4497b2012-01-24 09:31:43 +00002426StringRef ConstantDataSequential::getRawDataValues() const {
Chris Lattner00245f42012-01-24 13:41:11 +00002427 return StringRef(DataElements, getNumElements()*getElementByteSize());
Chris Lattner5d4497b2012-01-24 09:31:43 +00002428}
2429
Craig Toppere3dcce92015-08-01 22:20:21 +00002430bool ConstantDataSequential::isElementTypeCompatible(Type *Ty) {
Justin Bogner0ebc8602015-12-08 03:01:16 +00002431 if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy()) return true;
Craig Toppere3dcce92015-08-01 22:20:21 +00002432 if (auto *IT = dyn_cast<IntegerType>(Ty)) {
Chris Lattnere4f3f102012-01-24 04:43:41 +00002433 switch (IT->getBitWidth()) {
2434 case 8:
2435 case 16:
2436 case 32:
2437 case 64:
2438 return true;
2439 default: break;
2440 }
2441 }
2442 return false;
2443}
2444
Chris Lattner00245f42012-01-24 13:41:11 +00002445unsigned ConstantDataSequential::getNumElements() const {
Chris Lattner8a3df542012-01-25 01:32:59 +00002446 if (ArrayType *AT = dyn_cast<ArrayType>(getType()))
2447 return AT->getNumElements();
Chris Lattner8326bd82012-01-26 00:42:34 +00002448 return getType()->getVectorNumElements();
Chris Lattner00245f42012-01-24 13:41:11 +00002449}
2450
2451
Chris Lattnere4f3f102012-01-24 04:43:41 +00002452uint64_t ConstantDataSequential::getElementByteSize() const {
2453 return getElementType()->getPrimitiveSizeInBits()/8;
2454}
2455
Sanjay Patel1d0ac7c2016-04-29 22:03:27 +00002456/// Return the start of the specified element.
Chris Lattnere4f3f102012-01-24 04:43:41 +00002457const char *ConstantDataSequential::getElementPointer(unsigned Elt) const {
Chris Lattner00245f42012-01-24 13:41:11 +00002458 assert(Elt < getNumElements() && "Invalid Elt");
Chris Lattnere4f3f102012-01-24 04:43:41 +00002459 return DataElements+Elt*getElementByteSize();
2460}
2461
2462
Sanjay Patel1d0ac7c2016-04-29 22:03:27 +00002463/// Return true if the array is empty or all zeros.
Chris Lattner3756b912012-01-23 22:57:10 +00002464static bool isAllZeros(StringRef Arr) {
Benjamin Krameraf28e7d2016-06-26 14:10:56 +00002465 for (char I : Arr)
2466 if (I != 0)
Chris Lattner3756b912012-01-23 22:57:10 +00002467 return false;
2468 return true;
2469}
Chris Lattner030af792012-01-24 05:42:11 +00002470
Sanjay Patel1d0ac7c2016-04-29 22:03:27 +00002471/// This is the underlying implementation of all of the
Chris Lattner3756b912012-01-23 22:57:10 +00002472/// ConstantDataSequential::get methods. They all thunk down to here, providing
Chris Lattnerf06039b2012-01-30 18:19:30 +00002473/// the correct element type. We take the bytes in as a StringRef because
Chris Lattner3756b912012-01-23 22:57:10 +00002474/// we *want* an underlying "char*" to avoid TBAA type punning violations.
2475Constant *ConstantDataSequential::getImpl(StringRef Elements, Type *Ty) {
Chris Lattner8326bd82012-01-26 00:42:34 +00002476 assert(isElementTypeCompatible(Ty->getSequentialElementType()));
Chris Lattner139822f2012-01-24 14:17:05 +00002477 // If the elements are all zero or there are no elements, return a CAZ, which
2478 // is more dense and canonical.
Chris Lattner3756b912012-01-23 22:57:10 +00002479 if (isAllZeros(Elements))
2480 return ConstantAggregateZero::get(Ty);
2481
2482 // Do a lookup to see if we have already formed one of these.
David Blaikie5106ce72014-11-19 05:49:42 +00002483 auto &Slot =
2484 *Ty->getContext()
2485 .pImpl->CDSConstants.insert(std::make_pair(Elements, nullptr))
2486 .first;
Galina Kistanovafc259902012-07-13 01:25:27 +00002487
Chris Lattner3756b912012-01-23 22:57:10 +00002488 // The bucket can point to a linked list of different CDS's that have the same
2489 // body but different types. For example, 0,0,0,1 could be a 4 element array
2490 // of i8, or a 1-element array of i32. They'll both end up in the same
2491 /// StringMap bucket, linked up by their Next pointers. Walk the list.
David Blaikie5106ce72014-11-19 05:49:42 +00002492 ConstantDataSequential **Entry = &Slot.second;
Craig Topperc6207612014-04-09 06:08:46 +00002493 for (ConstantDataSequential *Node = *Entry; Node;
Chris Lattner3756b912012-01-23 22:57:10 +00002494 Entry = &Node->Next, Node = *Entry)
2495 if (Node->getType() == Ty)
2496 return Node;
Galina Kistanovafc259902012-07-13 01:25:27 +00002497
Chris Lattner3756b912012-01-23 22:57:10 +00002498 // Okay, we didn't get a hit. Create a node of the right class, link it in,
2499 // and return it.
2500 if (isa<ArrayType>(Ty))
David Blaikie5106ce72014-11-19 05:49:42 +00002501 return *Entry = new ConstantDataArray(Ty, Slot.first().data());
Chris Lattner3756b912012-01-23 22:57:10 +00002502
2503 assert(isa<VectorType>(Ty));
David Blaikie5106ce72014-11-19 05:49:42 +00002504 return *Entry = new ConstantDataVector(Ty, Slot.first().data());
Chris Lattner3756b912012-01-23 22:57:10 +00002505}
2506
Pete Cooper86dd4cf2015-06-23 21:55:11 +00002507void ConstantDataSequential::destroyConstantImpl() {
Chris Lattner3756b912012-01-23 22:57:10 +00002508 // Remove the constant from the StringMap.
Bjorn Petterssonaa025802018-07-03 12:39:52 +00002509 StringMap<ConstantDataSequential*> &CDSConstants =
Chris Lattner3756b912012-01-23 22:57:10 +00002510 getType()->getContext().pImpl->CDSConstants;
Galina Kistanovafc259902012-07-13 01:25:27 +00002511
Chris Lattner3756b912012-01-23 22:57:10 +00002512 StringMap<ConstantDataSequential*>::iterator Slot =
Chris Lattner5d4497b2012-01-24 09:31:43 +00002513 CDSConstants.find(getRawDataValues());
Chris Lattner3756b912012-01-23 22:57:10 +00002514
2515 assert(Slot != CDSConstants.end() && "CDS not found in uniquing table");
2516
2517 ConstantDataSequential **Entry = &Slot->getValue();
2518
2519 // Remove the entry from the hash table.
Craig Topperc6207612014-04-09 06:08:46 +00002520 if (!(*Entry)->Next) {
Chris Lattner3756b912012-01-23 22:57:10 +00002521 // If there is only one value in the bucket (common case) it must be this
2522 // entry, and removing the entry should remove the bucket completely.
2523 assert((*Entry) == this && "Hash mismatch in ConstantDataSequential");
2524 getContext().pImpl->CDSConstants.erase(Slot);
2525 } else {
Bjorn Petterssonaa025802018-07-03 12:39:52 +00002526 // Otherwise, there are multiple entries linked off the bucket, unlink the
Chris Lattner3756b912012-01-23 22:57:10 +00002527 // node we care about but keep the bucket around.
2528 for (ConstantDataSequential *Node = *Entry; ;
2529 Entry = &Node->Next, Node = *Entry) {
2530 assert(Node && "Didn't find entry in its uniquing hash table!");
2531 // If we found our entry, unlink it from the list and we're done.
2532 if (Node == this) {
2533 *Entry = Node->Next;
2534 break;
2535 }
2536 }
2537 }
Galina Kistanovafc259902012-07-13 01:25:27 +00002538
Chris Lattner3756b912012-01-23 22:57:10 +00002539 // If we were part of a list, make sure that we don't delete the list that is
2540 // still owned by the uniquing map.
Craig Topperc6207612014-04-09 06:08:46 +00002541 Next = nullptr;
Chris Lattner3756b912012-01-23 22:57:10 +00002542}
2543
Rafael Espindola8c97e192015-02-19 16:08:20 +00002544/// getFP() constructors - Return a constant with array type with an element
2545/// count and element type of float with precision matching the number of
2546/// bits in the ArrayRef passed in. (i.e. half for 16bits, float for 32bits,
2547/// double for 64bits) Note that this can return a ConstantAggregateZero
2548/// object.
2549Constant *ConstantDataArray::getFP(LLVMContext &Context,
2550 ArrayRef<uint16_t> Elts) {
Justin Bognerb7389d6712015-12-09 21:21:07 +00002551 Type *Ty = ArrayType::get(Type::getHalfTy(Context), Elts.size());
Rafael Espindola8c97e192015-02-19 16:08:20 +00002552 const char *Data = reinterpret_cast<const char *>(Elts.data());
Craig Topper393ce692017-07-11 15:52:21 +00002553 return getImpl(StringRef(Data, Elts.size() * 2), Ty);
Rafael Espindola8c97e192015-02-19 16:08:20 +00002554}
2555Constant *ConstantDataArray::getFP(LLVMContext &Context,
2556 ArrayRef<uint32_t> Elts) {
2557 Type *Ty = ArrayType::get(Type::getFloatTy(Context), Elts.size());
2558 const char *Data = reinterpret_cast<const char *>(Elts.data());
Craig Topper393ce692017-07-11 15:52:21 +00002559 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
Rafael Espindola8c97e192015-02-19 16:08:20 +00002560}
2561Constant *ConstantDataArray::getFP(LLVMContext &Context,
2562 ArrayRef<uint64_t> Elts) {
2563 Type *Ty = ArrayType::get(Type::getDoubleTy(Context), Elts.size());
2564 const char *Data = reinterpret_cast<const char *>(Elts.data());
Craig Topper393ce692017-07-11 15:52:21 +00002565 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
Chris Lattner3756b912012-01-23 22:57:10 +00002566}
2567
Chris Lattner20683932012-01-24 14:04:40 +00002568Constant *ConstantDataArray::getString(LLVMContext &Context,
2569 StringRef Str, bool AddNull) {
Galina Kistanovafc259902012-07-13 01:25:27 +00002570 if (!AddNull) {
2571 const uint8_t *Data = reinterpret_cast<const uint8_t *>(Str.data());
Craig Topper393ce692017-07-11 15:52:21 +00002572 return get(Context, makeArrayRef(Data, Str.size()));
Galina Kistanovafc259902012-07-13 01:25:27 +00002573 }
2574
Chris Lattner20683932012-01-24 14:04:40 +00002575 SmallVector<uint8_t, 64> ElementVals;
2576 ElementVals.append(Str.begin(), Str.end());
2577 ElementVals.push_back(0);
2578 return get(Context, ElementVals);
2579}
Chris Lattner3756b912012-01-23 22:57:10 +00002580
2581/// get() constructors - Return a constant with vector type with an element
2582/// count and element type matching the ArrayRef passed in. Note that this
2583/// can return a ConstantAggregateZero object.
Chris Lattner20683932012-01-24 14:04:40 +00002584Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint8_t> Elts){
Chris Lattner3756b912012-01-23 22:57:10 +00002585 Type *Ty = VectorType::get(Type::getInt8Ty(Context), Elts.size());
Galina Kistanovafc259902012-07-13 01:25:27 +00002586 const char *Data = reinterpret_cast<const char *>(Elts.data());
Craig Topper393ce692017-07-11 15:52:21 +00002587 return getImpl(StringRef(Data, Elts.size() * 1), Ty);
Chris Lattner3756b912012-01-23 22:57:10 +00002588}
Chris Lattner20683932012-01-24 14:04:40 +00002589Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint16_t> Elts){
Chris Lattner3756b912012-01-23 22:57:10 +00002590 Type *Ty = VectorType::get(Type::getInt16Ty(Context), Elts.size());
Galina Kistanovafc259902012-07-13 01:25:27 +00002591 const char *Data = reinterpret_cast<const char *>(Elts.data());
Craig Topper393ce692017-07-11 15:52:21 +00002592 return getImpl(StringRef(Data, Elts.size() * 2), Ty);
Chris Lattner3756b912012-01-23 22:57:10 +00002593}
Chris Lattner20683932012-01-24 14:04:40 +00002594Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint32_t> Elts){
Chris Lattner3756b912012-01-23 22:57:10 +00002595 Type *Ty = VectorType::get(Type::getInt32Ty(Context), Elts.size());
Galina Kistanovafc259902012-07-13 01:25:27 +00002596 const char *Data = reinterpret_cast<const char *>(Elts.data());
Craig Topper393ce692017-07-11 15:52:21 +00002597 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
Chris Lattner3756b912012-01-23 22:57:10 +00002598}
Chris Lattner20683932012-01-24 14:04:40 +00002599Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint64_t> Elts){
Chris Lattner3756b912012-01-23 22:57:10 +00002600 Type *Ty = VectorType::get(Type::getInt64Ty(Context), Elts.size());
Galina Kistanovafc259902012-07-13 01:25:27 +00002601 const char *Data = reinterpret_cast<const char *>(Elts.data());
Craig Topper393ce692017-07-11 15:52:21 +00002602 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
Chris Lattner3756b912012-01-23 22:57:10 +00002603}
Chris Lattner20683932012-01-24 14:04:40 +00002604Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<float> Elts) {
Chris Lattner3756b912012-01-23 22:57:10 +00002605 Type *Ty = VectorType::get(Type::getFloatTy(Context), Elts.size());
Galina Kistanovafc259902012-07-13 01:25:27 +00002606 const char *Data = reinterpret_cast<const char *>(Elts.data());
Craig Topper393ce692017-07-11 15:52:21 +00002607 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
Chris Lattner3756b912012-01-23 22:57:10 +00002608}
Chris Lattner20683932012-01-24 14:04:40 +00002609Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<double> Elts) {
Chris Lattner3756b912012-01-23 22:57:10 +00002610 Type *Ty = VectorType::get(Type::getDoubleTy(Context), Elts.size());
Galina Kistanovafc259902012-07-13 01:25:27 +00002611 const char *Data = reinterpret_cast<const char *>(Elts.data());
Craig Topper393ce692017-07-11 15:52:21 +00002612 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
Rafael Espindola8c97e192015-02-19 16:08:20 +00002613}
2614
2615/// getFP() constructors - Return a constant with vector type with an element
2616/// count and element type of float with the precision matching the number of
2617/// bits in the ArrayRef passed in. (i.e. half for 16bits, float for 32bits,
2618/// double for 64bits) Note that this can return a ConstantAggregateZero
2619/// object.
2620Constant *ConstantDataVector::getFP(LLVMContext &Context,
2621 ArrayRef<uint16_t> Elts) {
2622 Type *Ty = VectorType::get(Type::getHalfTy(Context), Elts.size());
2623 const char *Data = reinterpret_cast<const char *>(Elts.data());
Craig Topper393ce692017-07-11 15:52:21 +00002624 return getImpl(StringRef(Data, Elts.size() * 2), Ty);
Rafael Espindola8c97e192015-02-19 16:08:20 +00002625}
2626Constant *ConstantDataVector::getFP(LLVMContext &Context,
2627 ArrayRef<uint32_t> Elts) {
2628 Type *Ty = VectorType::get(Type::getFloatTy(Context), Elts.size());
2629 const char *Data = reinterpret_cast<const char *>(Elts.data());
Craig Topper393ce692017-07-11 15:52:21 +00002630 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
Rafael Espindola8c97e192015-02-19 16:08:20 +00002631}
2632Constant *ConstantDataVector::getFP(LLVMContext &Context,
2633 ArrayRef<uint64_t> Elts) {
2634 Type *Ty = VectorType::get(Type::getDoubleTy(Context), Elts.size());
2635 const char *Data = reinterpret_cast<const char *>(Elts.data());
Craig Topper393ce692017-07-11 15:52:21 +00002636 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
Chris Lattner3756b912012-01-23 22:57:10 +00002637}
2638
Chris Lattnere9eed292012-01-25 05:19:54 +00002639Constant *ConstantDataVector::getSplat(unsigned NumElts, Constant *V) {
2640 assert(isElementTypeCompatible(V->getType()) &&
2641 "Element type not compatible with ConstantData");
2642 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
2643 if (CI->getType()->isIntegerTy(8)) {
2644 SmallVector<uint8_t, 16> Elts(NumElts, CI->getZExtValue());
2645 return get(V->getContext(), Elts);
2646 }
2647 if (CI->getType()->isIntegerTy(16)) {
2648 SmallVector<uint16_t, 16> Elts(NumElts, CI->getZExtValue());
2649 return get(V->getContext(), Elts);
2650 }
2651 if (CI->getType()->isIntegerTy(32)) {
2652 SmallVector<uint32_t, 16> Elts(NumElts, CI->getZExtValue());
2653 return get(V->getContext(), Elts);
2654 }
2655 assert(CI->getType()->isIntegerTy(64) && "Unsupported ConstantData type");
2656 SmallVector<uint64_t, 16> Elts(NumElts, CI->getZExtValue());
2657 return get(V->getContext(), Elts);
2658 }
2659
Chris Lattner978fe0c2012-01-30 06:21:21 +00002660 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
Justin Bogner0ebc8602015-12-08 03:01:16 +00002661 if (CFP->getType()->isHalfTy()) {
2662 SmallVector<uint16_t, 16> Elts(
2663 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
2664 return getFP(V->getContext(), Elts);
2665 }
Chris Lattner978fe0c2012-01-30 06:21:21 +00002666 if (CFP->getType()->isFloatTy()) {
Rafael Espindola8c97e192015-02-19 16:08:20 +00002667 SmallVector<uint32_t, 16> Elts(
2668 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
2669 return getFP(V->getContext(), Elts);
Chris Lattner978fe0c2012-01-30 06:21:21 +00002670 }
2671 if (CFP->getType()->isDoubleTy()) {
Rafael Espindola8c97e192015-02-19 16:08:20 +00002672 SmallVector<uint64_t, 16> Elts(
2673 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
2674 return getFP(V->getContext(), Elts);
Chris Lattner978fe0c2012-01-30 06:21:21 +00002675 }
Chris Lattnere9eed292012-01-25 05:19:54 +00002676 }
Chris Lattner978fe0c2012-01-30 06:21:21 +00002677 return ConstantVector::getSplat(NumElts, V);
Chris Lattnere9eed292012-01-25 05:19:54 +00002678}
2679
2680
Chris Lattnere4f3f102012-01-24 04:43:41 +00002681uint64_t ConstantDataSequential::getElementAsInteger(unsigned Elt) const {
2682 assert(isa<IntegerType>(getElementType()) &&
2683 "Accessor can only be used when element is an integer");
2684 const char *EltPtr = getElementPointer(Elt);
Galina Kistanovafc259902012-07-13 01:25:27 +00002685
Chris Lattnere4f3f102012-01-24 04:43:41 +00002686 // The data is stored in host byte order, make sure to cast back to the right
2687 // type to load with the right endianness.
Chris Lattner8326bd82012-01-26 00:42:34 +00002688 switch (getElementType()->getIntegerBitWidth()) {
Craig Topperc514b542012-02-05 22:14:15 +00002689 default: llvm_unreachable("Invalid bitwidth for CDS");
Galina Kistanovafc259902012-07-13 01:25:27 +00002690 case 8:
Craig Topper393ce692017-07-11 15:52:21 +00002691 return *reinterpret_cast<const uint8_t *>(EltPtr);
Galina Kistanovafc259902012-07-13 01:25:27 +00002692 case 16:
Craig Topper393ce692017-07-11 15:52:21 +00002693 return *reinterpret_cast<const uint16_t *>(EltPtr);
Galina Kistanovafc259902012-07-13 01:25:27 +00002694 case 32:
Craig Topper393ce692017-07-11 15:52:21 +00002695 return *reinterpret_cast<const uint32_t *>(EltPtr);
Galina Kistanovafc259902012-07-13 01:25:27 +00002696 case 64:
Craig Topper393ce692017-07-11 15:52:21 +00002697 return *reinterpret_cast<const uint64_t *>(EltPtr);
Chris Lattnere4f3f102012-01-24 04:43:41 +00002698 }
2699}
2700
Craig Topper0b4b4e32017-07-15 22:06:19 +00002701APInt ConstantDataSequential::getElementAsAPInt(unsigned Elt) const {
2702 assert(isa<IntegerType>(getElementType()) &&
2703 "Accessor can only be used when element is an integer");
2704 const char *EltPtr = getElementPointer(Elt);
2705
2706 // The data is stored in host byte order, make sure to cast back to the right
2707 // type to load with the right endianness.
2708 switch (getElementType()->getIntegerBitWidth()) {
2709 default: llvm_unreachable("Invalid bitwidth for CDS");
2710 case 8: {
2711 auto EltVal = *reinterpret_cast<const uint8_t *>(EltPtr);
2712 return APInt(8, EltVal);
2713 }
2714 case 16: {
2715 auto EltVal = *reinterpret_cast<const uint16_t *>(EltPtr);
2716 return APInt(16, EltVal);
2717 }
2718 case 32: {
2719 auto EltVal = *reinterpret_cast<const uint32_t *>(EltPtr);
2720 return APInt(32, EltVal);
2721 }
2722 case 64: {
2723 auto EltVal = *reinterpret_cast<const uint64_t *>(EltPtr);
2724 return APInt(64, EltVal);
2725 }
2726 }
2727}
2728
Chris Lattnere4f3f102012-01-24 04:43:41 +00002729APFloat ConstantDataSequential::getElementAsAPFloat(unsigned Elt) const {
2730 const char *EltPtr = getElementPointer(Elt);
2731
2732 switch (getElementType()->getTypeID()) {
Nick Lewyckyff509622012-01-25 03:20:12 +00002733 default:
Craig Topperc514b542012-02-05 22:14:15 +00002734 llvm_unreachable("Accessor can only be used when element is float/double!");
Justin Bogner0ebc8602015-12-08 03:01:16 +00002735 case Type::HalfTyID: {
2736 auto EltVal = *reinterpret_cast<const uint16_t *>(EltPtr);
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002737 return APFloat(APFloat::IEEEhalf(), APInt(16, EltVal));
Justin Bogner0ebc8602015-12-08 03:01:16 +00002738 }
Benjamin Kramer7af984b2015-02-20 15:11:55 +00002739 case Type::FloatTyID: {
2740 auto EltVal = *reinterpret_cast<const uint32_t *>(EltPtr);
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002741 return APFloat(APFloat::IEEEsingle(), APInt(32, EltVal));
Benjamin Kramer7af984b2015-02-20 15:11:55 +00002742 }
2743 case Type::DoubleTyID: {
2744 auto EltVal = *reinterpret_cast<const uint64_t *>(EltPtr);
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002745 return APFloat(APFloat::IEEEdouble(), APInt(64, EltVal));
Chris Lattnere4f3f102012-01-24 04:43:41 +00002746 }
Benjamin Kramer7af984b2015-02-20 15:11:55 +00002747 }
Chris Lattnere4f3f102012-01-24 04:43:41 +00002748}
2749
Chris Lattnere4f3f102012-01-24 04:43:41 +00002750float ConstantDataSequential::getElementAsFloat(unsigned Elt) const {
2751 assert(getElementType()->isFloatTy() &&
2752 "Accessor can only be used when element is a 'float'");
Craig Topper393ce692017-07-11 15:52:21 +00002753 return *reinterpret_cast<const float *>(getElementPointer(Elt));
Chris Lattnere4f3f102012-01-24 04:43:41 +00002754}
2755
Chris Lattnere4f3f102012-01-24 04:43:41 +00002756double ConstantDataSequential::getElementAsDouble(unsigned Elt) const {
2757 assert(getElementType()->isDoubleTy() &&
2758 "Accessor can only be used when element is a 'float'");
Craig Topper393ce692017-07-11 15:52:21 +00002759 return *reinterpret_cast<const double *>(getElementPointer(Elt));
Chris Lattnere4f3f102012-01-24 04:43:41 +00002760}
2761
Chris Lattnere4f3f102012-01-24 04:43:41 +00002762Constant *ConstantDataSequential::getElementAsConstant(unsigned Elt) const {
Justin Bogner0ebc8602015-12-08 03:01:16 +00002763 if (getElementType()->isHalfTy() || getElementType()->isFloatTy() ||
2764 getElementType()->isDoubleTy())
Chris Lattnere4f3f102012-01-24 04:43:41 +00002765 return ConstantFP::get(getContext(), getElementAsAPFloat(Elt));
Galina Kistanovafc259902012-07-13 01:25:27 +00002766
Chris Lattnere4f3f102012-01-24 04:43:41 +00002767 return ConstantInt::get(getElementType(), getElementAsInteger(Elt));
2768}
2769
Matthias Braun50ec0b52017-05-19 22:37:09 +00002770bool ConstantDataSequential::isString(unsigned CharSize) const {
2771 return isa<ArrayType>(getType()) && getElementType()->isIntegerTy(CharSize);
Chris Lattner5dd4d872012-01-24 09:01:07 +00002772}
Chris Lattner3756b912012-01-23 22:57:10 +00002773
Chris Lattner5dd4d872012-01-24 09:01:07 +00002774bool ConstantDataSequential::isCString() const {
2775 if (!isString())
2776 return false;
Galina Kistanovafc259902012-07-13 01:25:27 +00002777
Chris Lattner5dd4d872012-01-24 09:01:07 +00002778 StringRef Str = getAsString();
Galina Kistanovafc259902012-07-13 01:25:27 +00002779
Chris Lattner5dd4d872012-01-24 09:01:07 +00002780 // The last value must be nul.
2781 if (Str.back() != 0) return false;
Galina Kistanovafc259902012-07-13 01:25:27 +00002782
Chris Lattner5dd4d872012-01-24 09:01:07 +00002783 // Other elements must be non-nul.
2784 return Str.drop_back().find(0) == StringRef::npos;
2785}
Chris Lattner3756b912012-01-23 22:57:10 +00002786
Craig Topper0b4b4e32017-07-15 22:06:19 +00002787bool ConstantDataVector::isSplat() const {
Chris Lattnerf14a67f2012-01-26 02:31:22 +00002788 const char *Base = getRawDataValues().data();
Galina Kistanovafc259902012-07-13 01:25:27 +00002789
Chris Lattnerf14a67f2012-01-26 02:31:22 +00002790 // Compare elements 1+ to the 0'th element.
2791 unsigned EltSize = getElementByteSize();
2792 for (unsigned i = 1, e = getNumElements(); i != e; ++i)
2793 if (memcmp(Base, Base+i*EltSize, EltSize))
Craig Topper0b4b4e32017-07-15 22:06:19 +00002794 return false;
Galina Kistanovafc259902012-07-13 01:25:27 +00002795
Craig Topper0b4b4e32017-07-15 22:06:19 +00002796 return true;
2797}
2798
2799Constant *ConstantDataVector::getSplatValue() const {
Chris Lattnerf14a67f2012-01-26 02:31:22 +00002800 // If they're all the same, return the 0th one as a representative.
Craig Topper0b4b4e32017-07-15 22:06:19 +00002801 return isSplat() ? getElementAsConstant(0) : nullptr;
Chris Lattnerf14a67f2012-01-26 02:31:22 +00002802}
Chris Lattnera3b94ba2010-03-30 20:48:48 +00002803
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002804//===----------------------------------------------------------------------===//
Pete Cooper5815b1f2015-06-24 18:55:24 +00002805// handleOperandChange implementations
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002806
Pete Cooper5815b1f2015-06-24 18:55:24 +00002807/// Update this constant array to change uses of
Chris Lattner913849b2007-08-21 00:55:23 +00002808/// 'From' to be uses of 'To'. This must update the uniquing data structures
2809/// etc.
2810///
2811/// Note that we intentionally replace all uses of From with To here. Consider
2812/// a large array that uses 'From' 1000 times. By handling this case all here,
Pete Cooper5815b1f2015-06-24 18:55:24 +00002813/// ConstantArray::handleOperandChange is only invoked once, and that
Chris Lattner913849b2007-08-21 00:55:23 +00002814/// single invocation handles all 1000 uses. Handling them one at a time would
2815/// work, but would be really slow because it would have to unique each updated
2816/// array instance.
Chris Lattner31b132c2009-10-28 00:01:44 +00002817///
Mehdi Amini8914d292016-02-10 22:47:15 +00002818void Constant::handleOperandChange(Value *From, Value *To) {
Pete Cooper5815b1f2015-06-24 18:55:24 +00002819 Value *Replacement = nullptr;
2820 switch (getValueID()) {
2821 default:
2822 llvm_unreachable("Not a constant!");
2823#define HANDLE_CONSTANT(Name) \
2824 case Value::Name##Val: \
Mehdi Amini8914d292016-02-10 22:47:15 +00002825 Replacement = cast<Name>(this)->handleOperandChangeImpl(From, To); \
Pete Cooper5815b1f2015-06-24 18:55:24 +00002826 break;
2827#include "llvm/IR/Value.def"
2828 }
2829
2830 // If handleOperandChangeImpl returned nullptr, then it handled
2831 // replacing itself and we don't want to delete or replace anything else here.
2832 if (!Replacement)
2833 return;
2834
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002835 // I do need to replace this with an existing value.
2836 assert(Replacement != this && "I didn't contain From!");
2837
2838 // Everyone using this now uses the replacement.
2839 replaceAllUsesWith(Replacement);
2840
2841 // Delete the old constant!
2842 destroyConstant();
2843}
2844
Mehdi Amini8914d292016-02-10 22:47:15 +00002845Value *ConstantArray::handleOperandChangeImpl(Value *From, Value *To) {
Owen Andersonc2c79322009-07-28 18:32:17 +00002846 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2847 Constant *ToC = cast<Constant>(To);
2848
Talin46e9b442012-02-05 20:54:10 +00002849 SmallVector<Constant*, 8> Values;
Owen Andersonc2c79322009-07-28 18:32:17 +00002850 Values.reserve(getNumOperands()); // Build replacement array.
2851
Galina Kistanovafc259902012-07-13 01:25:27 +00002852 // Fill values with the modified operands of the constant array. Also,
Owen Andersonc2c79322009-07-28 18:32:17 +00002853 // compute whether this turns into an all-zeros array.
Owen Andersonc2c79322009-07-28 18:32:17 +00002854 unsigned NumUpdated = 0;
Galina Kistanovafc259902012-07-13 01:25:27 +00002855
Chris Lattnerf14a67f2012-01-26 02:31:22 +00002856 // Keep track of whether all the values in the array are "ToC".
2857 bool AllSame = true;
Pete Cooper74510a42015-06-12 17:48:05 +00002858 Use *OperandList = getOperandList();
Mehdi Amini8914d292016-02-10 22:47:15 +00002859 unsigned OperandNo = 0;
Chris Lattnerf14a67f2012-01-26 02:31:22 +00002860 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2861 Constant *Val = cast<Constant>(O->get());
2862 if (Val == From) {
Mehdi Amini8914d292016-02-10 22:47:15 +00002863 OperandNo = (O - OperandList);
Chris Lattnerf14a67f2012-01-26 02:31:22 +00002864 Val = ToC;
2865 ++NumUpdated;
Owen Andersonc2c79322009-07-28 18:32:17 +00002866 }
Chris Lattnerf14a67f2012-01-26 02:31:22 +00002867 Values.push_back(Val);
Talin46e9b442012-02-05 20:54:10 +00002868 AllSame &= Val == ToC;
Owen Andersonc2c79322009-07-28 18:32:17 +00002869 }
Galina Kistanovafc259902012-07-13 01:25:27 +00002870
Pete Cooper5815b1f2015-06-24 18:55:24 +00002871 if (AllSame && ToC->isNullValue())
2872 return ConstantAggregateZero::get(getType());
2873
2874 if (AllSame && isa<UndefValue>(ToC))
2875 return UndefValue::get(getType());
Aaron Ballmane4b91dc2014-08-19 14:59:02 +00002876
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002877 // Check for any other type of constant-folding.
Pete Cooper5815b1f2015-06-24 18:55:24 +00002878 if (Constant *C = getImpl(getType(), Values))
2879 return C;
Aaron Ballmane4b91dc2014-08-19 14:59:02 +00002880
Duncan P. N. Exon Smith909620a2014-08-19 19:13:30 +00002881 // Update to the new value.
Pete Cooper5815b1f2015-06-24 18:55:24 +00002882 return getContext().pImpl->ArrayConstants.replaceOperandsInPlace(
Mehdi Amini8914d292016-02-10 22:47:15 +00002883 Values, this, From, ToC, NumUpdated, OperandNo);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002884}
2885
Mehdi Amini8914d292016-02-10 22:47:15 +00002886Value *ConstantStruct::handleOperandChangeImpl(Value *From, Value *To) {
Owen Anderson45308b52009-07-27 22:29:26 +00002887 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2888 Constant *ToC = cast<Constant>(To);
2889
Pete Cooper74510a42015-06-12 17:48:05 +00002890 Use *OperandList = getOperandList();
Owen Anderson45308b52009-07-27 22:29:26 +00002891
Talin46e9b442012-02-05 20:54:10 +00002892 SmallVector<Constant*, 8> Values;
Owen Anderson45308b52009-07-27 22:29:26 +00002893 Values.reserve(getNumOperands()); // Build replacement struct.
Galina Kistanovafc259902012-07-13 01:25:27 +00002894
2895 // Fill values with the modified operands of the constant struct. Also,
Owen Anderson45308b52009-07-27 22:29:26 +00002896 // compute whether this turns into an all-zeros struct.
Mehdi Amini8914d292016-02-10 22:47:15 +00002897 unsigned NumUpdated = 0;
2898 bool AllSame = true;
2899 unsigned OperandNo = 0;
2900 for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O) {
2901 Constant *Val = cast<Constant>(O->get());
2902 if (Val == From) {
2903 OperandNo = (O - OperandList);
2904 Val = ToC;
2905 ++NumUpdated;
Owen Anderson45308b52009-07-27 22:29:26 +00002906 }
Mehdi Amini8914d292016-02-10 22:47:15 +00002907 Values.push_back(Val);
2908 AllSame &= Val == ToC;
Owen Anderson45308b52009-07-27 22:29:26 +00002909 }
Galina Kistanovafc259902012-07-13 01:25:27 +00002910
Mehdi Amini8914d292016-02-10 22:47:15 +00002911 if (AllSame && ToC->isNullValue())
Pete Cooper5815b1f2015-06-24 18:55:24 +00002912 return ConstantAggregateZero::get(getType());
2913
Mehdi Amini8914d292016-02-10 22:47:15 +00002914 if (AllSame && isa<UndefValue>(ToC))
Pete Cooper5815b1f2015-06-24 18:55:24 +00002915 return UndefValue::get(getType());
Galina Kistanovafc259902012-07-13 01:25:27 +00002916
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002917 // Update to the new value.
Pete Cooper5815b1f2015-06-24 18:55:24 +00002918 return getContext().pImpl->StructConstants.replaceOperandsInPlace(
Mehdi Amini8914d292016-02-10 22:47:15 +00002919 Values, this, From, ToC, NumUpdated, OperandNo);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002920}
2921
Mehdi Amini8914d292016-02-10 22:47:15 +00002922Value *ConstantVector::handleOperandChangeImpl(Value *From, Value *To) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002923 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002924 Constant *ToC = cast<Constant>(To);
Galina Kistanovafc259902012-07-13 01:25:27 +00002925
Chris Lattnera474bb22012-01-26 20:40:56 +00002926 SmallVector<Constant*, 8> Values;
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002927 Values.reserve(getNumOperands()); // Build replacement array...
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002928 unsigned NumUpdated = 0;
Mehdi Amini8914d292016-02-10 22:47:15 +00002929 unsigned OperandNo = 0;
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002930 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2931 Constant *Val = getOperand(i);
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002932 if (Val == From) {
Mehdi Amini8914d292016-02-10 22:47:15 +00002933 OperandNo = i;
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002934 ++NumUpdated;
2935 Val = ToC;
2936 }
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002937 Values.push_back(Val);
2938 }
Galina Kistanovafc259902012-07-13 01:25:27 +00002939
Pete Cooper5815b1f2015-06-24 18:55:24 +00002940 if (Constant *C = getImpl(Values))
2941 return C;
Duncan P. N. Exon Smith687744d2014-08-19 02:24:46 +00002942
Duncan P. N. Exon Smith909620a2014-08-19 19:13:30 +00002943 // Update to the new value.
Pete Cooper5815b1f2015-06-24 18:55:24 +00002944 return getContext().pImpl->VectorConstants.replaceOperandsInPlace(
Mehdi Amini8914d292016-02-10 22:47:15 +00002945 Values, this, From, ToC, NumUpdated, OperandNo);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002946}
2947
Mehdi Amini8914d292016-02-10 22:47:15 +00002948Value *ConstantExpr::handleOperandChangeImpl(Value *From, Value *ToV) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002949 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2950 Constant *To = cast<Constant>(ToV);
Galina Kistanovafc259902012-07-13 01:25:27 +00002951
Chris Lattner37e38352012-01-26 20:37:11 +00002952 SmallVector<Constant*, 8> NewOps;
Duncan P. N. Exon Smith33de00c2014-08-19 20:03:35 +00002953 unsigned NumUpdated = 0;
Mehdi Amini8914d292016-02-10 22:47:15 +00002954 unsigned OperandNo = 0;
Chris Lattner37e38352012-01-26 20:37:11 +00002955 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2956 Constant *Op = getOperand(i);
Duncan P. N. Exon Smith33de00c2014-08-19 20:03:35 +00002957 if (Op == From) {
Mehdi Amini8914d292016-02-10 22:47:15 +00002958 OperandNo = i;
Duncan P. N. Exon Smith33de00c2014-08-19 20:03:35 +00002959 ++NumUpdated;
2960 Op = To;
2961 }
2962 NewOps.push_back(Op);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002963 }
Duncan P. N. Exon Smith33de00c2014-08-19 20:03:35 +00002964 assert(NumUpdated && "I didn't contain From!");
Galina Kistanovafc259902012-07-13 01:25:27 +00002965
Pete Cooper5815b1f2015-06-24 18:55:24 +00002966 if (Constant *C = getWithOperands(NewOps, getType(), true))
2967 return C;
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002968
Duncan P. N. Exon Smith33de00c2014-08-19 20:03:35 +00002969 // Update to the new value.
Pete Cooper5815b1f2015-06-24 18:55:24 +00002970 return getContext().pImpl->ExprConstants.replaceOperandsInPlace(
Mehdi Amini8914d292016-02-10 22:47:15 +00002971 NewOps, this, From, To, NumUpdated, OperandNo);
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002972}
2973
James Molloyce545682012-11-17 17:56:30 +00002974Instruction *ConstantExpr::getAsInstruction() {
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +00002975 SmallVector<Value *, 4> ValueOperands(op_begin(), op_end());
James Molloyce545682012-11-17 17:56:30 +00002976 ArrayRef<Value*> Ops(ValueOperands);
2977
2978 switch (getOpcode()) {
2979 case Instruction::Trunc:
2980 case Instruction::ZExt:
2981 case Instruction::SExt:
2982 case Instruction::FPTrunc:
2983 case Instruction::FPExt:
2984 case Instruction::UIToFP:
2985 case Instruction::SIToFP:
2986 case Instruction::FPToUI:
2987 case Instruction::FPToSI:
2988 case Instruction::PtrToInt:
2989 case Instruction::IntToPtr:
2990 case Instruction::BitCast:
Eli Bendersky157a97a2014-01-18 22:54:33 +00002991 case Instruction::AddrSpaceCast:
James Molloyce545682012-11-17 17:56:30 +00002992 return CastInst::Create((Instruction::CastOps)getOpcode(),
2993 Ops[0], getType());
2994 case Instruction::Select:
2995 return SelectInst::Create(Ops[0], Ops[1], Ops[2]);
2996 case Instruction::InsertElement:
2997 return InsertElementInst::Create(Ops[0], Ops[1], Ops[2]);
2998 case Instruction::ExtractElement:
2999 return ExtractElementInst::Create(Ops[0], Ops[1]);
3000 case Instruction::InsertValue:
3001 return InsertValueInst::Create(Ops[0], Ops[1], getIndices());
3002 case Instruction::ExtractValue:
3003 return ExtractValueInst::Create(Ops[0], getIndices());
3004 case Instruction::ShuffleVector:
3005 return new ShuffleVectorInst(Ops[0], Ops[1], Ops[2]);
3006
David Blaikie741c8f82015-03-14 01:53:18 +00003007 case Instruction::GetElementPtr: {
3008 const auto *GO = cast<GEPOperator>(this);
3009 if (GO->isInBounds())
3010 return GetElementPtrInst::CreateInBounds(GO->getSourceElementType(),
3011 Ops[0], Ops.slice(1));
3012 return GetElementPtrInst::Create(GO->getSourceElementType(), Ops[0],
3013 Ops.slice(1));
3014 }
James Molloyce545682012-11-17 17:56:30 +00003015 case Instruction::ICmp:
3016 case Instruction::FCmp:
3017 return CmpInst::Create((Instruction::OtherOps)getOpcode(),
Craig Topper1c3f2832015-12-15 06:11:33 +00003018 (CmpInst::Predicate)getPredicate(), Ops[0], Ops[1]);
James Molloyce545682012-11-17 17:56:30 +00003019
3020 default:
3021 assert(getNumOperands() == 2 && "Must be binary operator?");
3022 BinaryOperator *BO =
3023 BinaryOperator::Create((Instruction::BinaryOps)getOpcode(),
3024 Ops[0], Ops[1]);
3025 if (isa<OverflowingBinaryOperator>(BO)) {
3026 BO->setHasNoUnsignedWrap(SubclassOptionalData &
3027 OverflowingBinaryOperator::NoUnsignedWrap);
3028 BO->setHasNoSignedWrap(SubclassOptionalData &
3029 OverflowingBinaryOperator::NoSignedWrap);
3030 }
3031 if (isa<PossiblyExactOperator>(BO))
3032 BO->setIsExact(SubclassOptionalData & PossiblyExactOperator::IsExact);
3033 return BO;
3034 }
3035}