blob: ff551da29ae6b5200e7046d391b06268c68d7b90 [file] [log] [blame]
Chris Lattner2b383d2e2003-05-13 21:37:02 +00001//===-- Constants.cpp - Implement Constant nodes --------------------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Misha Brukmanb1c93172005-04-21 23:48:37 +00006//
John Criswell482202a2003-10-20 19:43:21 +00007//===----------------------------------------------------------------------===//
Chris Lattner2f7c9632001-06-06 20:29:01 +00008//
Chris Lattnere17322b2011-02-07 20:03:14 +00009// This file implements the Constant* classes.
Chris Lattner2f7c9632001-06-06 20:29:01 +000010//
11//===----------------------------------------------------------------------===//
12
Chandler Carruth9fb823b2013-01-02 11:36:10 +000013#include "llvm/IR/Constants.h"
Chris Lattner33e93b82007-02-27 03:05:06 +000014#include "ConstantFold.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000015#include "LLVMContextImpl.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000016#include "llvm/ADT/STLExtras.h"
17#include "llvm/ADT/SmallVector.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000018#include "llvm/ADT/StringMap.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000019#include "llvm/IR/DerivedTypes.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000020#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000021#include "llvm/IR/GlobalValue.h"
22#include "llvm/IR/Instructions.h"
23#include "llvm/IR/Module.h"
24#include "llvm/IR/Operator.h"
Bill Wendling6a462f12006-11-17 08:03:48 +000025#include "llvm/Support/Debug.h"
Torok Edwinccb29cd2009-07-11 13:10:19 +000026#include "llvm/Support/ErrorHandling.h"
Chris Lattner69edc982006-09-28 00:35:06 +000027#include "llvm/Support/ManagedStatic.h"
Bill Wendling6a462f12006-11-17 08:03:48 +000028#include "llvm/Support/MathExtras.h"
Chris Lattner78683a72009-08-23 04:02:03 +000029#include "llvm/Support/raw_ostream.h"
Chris Lattner2f7c9632001-06-06 20:29:01 +000030#include <algorithm>
Serge Gueltone38003f2017-05-09 19:31:13 +000031
Chris Lattner189d19f2003-11-21 20:23:48 +000032using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000033
Chris Lattner2f7c9632001-06-06 20:29:01 +000034//===----------------------------------------------------------------------===//
Chris Lattner3462ae32001-12-03 22:26:30 +000035// Constant Class
Chris Lattner2f7c9632001-06-06 20:29:01 +000036//===----------------------------------------------------------------------===//
37
Chris Lattnerac5fb562011-07-15 05:58:04 +000038bool Constant::isNegativeZeroValue() const {
39 // Floating point values have an explicit -0.0 value.
40 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
41 return CFP->isZero() && CFP->isNegative();
Galina Kistanovafc259902012-07-13 01:25:27 +000042
David Tweed5493fee2013-03-18 11:54:44 +000043 // Equivalent for a vector of -0.0's.
44 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
Craig Topper0b4b4e32017-07-15 22:06:19 +000045 if (CV->getElementType()->isFloatingPointTy() && CV->isSplat())
46 if (CV->getElementAsAPFloat(0).isNegZero())
David Tweed5493fee2013-03-18 11:54:44 +000047 return true;
48
Owen Anderson8e851302015-11-20 22:34:48 +000049 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
50 if (ConstantFP *SplatCFP = dyn_cast_or_null<ConstantFP>(CV->getSplatValue()))
51 if (SplatCFP && SplatCFP->isZero() && SplatCFP->isNegative())
52 return true;
53
David Tweed298e4192013-03-19 10:16:40 +000054 // We've already handled true FP case; any other FP vectors can't represent -0.0.
55 if (getType()->isFPOrFPVectorTy())
56 return false;
David Tweed5493fee2013-03-18 11:54:44 +000057
Chris Lattnerac5fb562011-07-15 05:58:04 +000058 // Otherwise, just use +0.0.
59 return isNullValue();
60}
61
Shuxin Yang9ca562e2013-01-09 00:53:25 +000062// Return true iff this constant is positive zero (floating point), negative
63// zero (floating point), or a null value.
Shuxin Yangf0537ab2013-01-09 00:13:41 +000064bool Constant::isZeroValue() const {
65 // Floating point values have an explicit -0.0 value.
66 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
67 return CFP->isZero();
68
Owen Anderson630077e2015-11-20 08:16:13 +000069 // Equivalent for a vector of -0.0's.
70 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
Craig Topper0b4b4e32017-07-15 22:06:19 +000071 if (CV->getElementType()->isFloatingPointTy() && CV->isSplat())
72 if (CV->getElementAsAPFloat(0).isZero())
Owen Anderson630077e2015-11-20 08:16:13 +000073 return true;
74
Owen Anderson8e851302015-11-20 22:34:48 +000075 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
76 if (ConstantFP *SplatCFP = dyn_cast_or_null<ConstantFP>(CV->getSplatValue()))
77 if (SplatCFP && SplatCFP->isZero())
78 return true;
79
Shuxin Yangf0537ab2013-01-09 00:13:41 +000080 // Otherwise, just use +0.0.
81 return isNullValue();
82}
83
Chris Lattnerbe6610c2011-07-15 06:14:08 +000084bool Constant::isNullValue() const {
85 // 0 is null.
86 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
87 return CI->isZero();
Galina Kistanovafc259902012-07-13 01:25:27 +000088
Chris Lattnerbe6610c2011-07-15 06:14:08 +000089 // +0.0 is null.
90 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
91 return CFP->isZero() && !CFP->isNegative();
92
David Majnemerf0f224d2015-11-11 21:57:16 +000093 // constant zero is zero for aggregates, cpnull is null for pointers, none for
94 // tokens.
95 return isa<ConstantAggregateZero>(this) || isa<ConstantPointerNull>(this) ||
96 isa<ConstantTokenNone>(this);
Chris Lattnerbe6610c2011-07-15 06:14:08 +000097}
98
Nadav Rotem365af6f2011-08-24 20:18:38 +000099bool Constant::isAllOnesValue() const {
100 // Check for -1 integers
101 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
102 return CI->isMinusOne();
103
104 // Check for FP which are bitcasted from -1 integers
105 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
106 return CFP->getValueAPF().bitcastToAPInt().isAllOnesValue();
107
Benjamin Kramer42d098e2011-11-14 19:12:20 +0000108 // Check for constant vectors which are splats of -1 values.
Nadav Rotem365af6f2011-08-24 20:18:38 +0000109 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
Benjamin Kramer42d098e2011-11-14 19:12:20 +0000110 if (Constant *Splat = CV->getSplatValue())
111 return Splat->isAllOnesValue();
Nadav Rotem365af6f2011-08-24 20:18:38 +0000112
Chris Lattnerf14a67f2012-01-26 02:31:22 +0000113 // Check for constant vectors which are splats of -1 values.
Craig Topper0b4b4e32017-07-15 22:06:19 +0000114 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this)) {
115 if (CV->isSplat()) {
116 if (CV->getElementType()->isFloatingPointTy())
117 return CV->getElementAsAPFloat(0).bitcastToAPInt().isAllOnesValue();
118 return CV->getElementAsAPInt(0).isAllOnesValue();
119 }
120 }
Chris Lattnerf14a67f2012-01-26 02:31:22 +0000121
Nadav Rotem365af6f2011-08-24 20:18:38 +0000122 return false;
123}
Benjamin Kramer42d098e2011-11-14 19:12:20 +0000124
David Majnemer1a0bbc82014-08-16 09:23:42 +0000125bool Constant::isOneValue() const {
126 // Check for 1 integers
127 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
128 return CI->isOne();
129
130 // Check for FP which are bitcasted from 1 integers
131 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
Craig Topper93ac6e12017-06-07 00:58:02 +0000132 return CFP->getValueAPF().bitcastToAPInt().isOneValue();
David Majnemer1a0bbc82014-08-16 09:23:42 +0000133
134 // Check for constant vectors which are splats of 1 values.
135 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
136 if (Constant *Splat = CV->getSplatValue())
137 return Splat->isOneValue();
138
139 // Check for constant vectors which are splats of 1 values.
Craig Topper0b4b4e32017-07-15 22:06:19 +0000140 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this)) {
141 if (CV->isSplat()) {
142 if (CV->getElementType()->isFloatingPointTy())
143 return CV->getElementAsAPFloat(0).bitcastToAPInt().isOneValue();
144 return CV->getElementAsAPInt(0).isOneValue();
145 }
146 }
David Majnemer1a0bbc82014-08-16 09:23:42 +0000147
148 return false;
149}
150
David Majnemerbdeef602014-07-02 06:07:09 +0000151bool Constant::isMinSignedValue() const {
152 // Check for INT_MIN integers
153 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
154 return CI->isMinValue(/*isSigned=*/true);
155
156 // Check for FP which are bitcasted from INT_MIN integers
157 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
158 return CFP->getValueAPF().bitcastToAPInt().isMinSignedValue();
159
160 // Check for constant vectors which are splats of INT_MIN values.
161 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
162 if (Constant *Splat = CV->getSplatValue())
163 return Splat->isMinSignedValue();
164
165 // Check for constant vectors which are splats of INT_MIN values.
Craig Topper0b4b4e32017-07-15 22:06:19 +0000166 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this)) {
167 if (CV->isSplat()) {
168 if (CV->getElementType()->isFloatingPointTy())
169 return CV->getElementAsAPFloat(0).bitcastToAPInt().isMinSignedValue();
170 return CV->getElementAsAPInt(0).isMinSignedValue();
171 }
172 }
David Majnemerbdeef602014-07-02 06:07:09 +0000173
174 return false;
175}
176
David Majnemer0e6c9862014-08-22 16:41:23 +0000177bool Constant::isNotMinSignedValue() const {
178 // Check for INT_MIN integers
179 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
180 return !CI->isMinValue(/*isSigned=*/true);
181
182 // Check for FP which are bitcasted from INT_MIN integers
183 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
184 return !CFP->getValueAPF().bitcastToAPInt().isMinSignedValue();
185
Nikita Popov0c5d6cc2018-12-01 10:58:34 +0000186 // Check that vectors don't contain INT_MIN
187 if (this->getType()->isVectorTy()) {
188 unsigned NumElts = this->getType()->getVectorNumElements();
189 for (unsigned i = 0; i != NumElts; ++i) {
190 Constant *Elt = this->getAggregateElement(i);
191 if (!Elt || !Elt->isNotMinSignedValue())
192 return false;
Craig Topper0b4b4e32017-07-15 22:06:19 +0000193 }
Nikita Popov0c5d6cc2018-12-01 10:58:34 +0000194 return true;
Craig Topper0b4b4e32017-07-15 22:06:19 +0000195 }
David Majnemer0e6c9862014-08-22 16:41:23 +0000196
197 // It *may* contain INT_MIN, we can't tell.
198 return false;
199}
200
Sanjay Patel08868e4942018-02-16 22:32:54 +0000201bool Constant::isFiniteNonZeroFP() const {
202 if (auto *CFP = dyn_cast<ConstantFP>(this))
203 return CFP->getValueAPF().isFiniteNonZero();
204 if (!getType()->isVectorTy())
205 return false;
206 for (unsigned i = 0, e = getType()->getVectorNumElements(); i != e; ++i) {
207 auto *CFP = dyn_cast_or_null<ConstantFP>(this->getAggregateElement(i));
208 if (!CFP || !CFP->getValueAPF().isFiniteNonZero())
209 return false;
210 }
211 return true;
212}
213
214bool Constant::isNormalFP() const {
215 if (auto *CFP = dyn_cast<ConstantFP>(this))
216 return CFP->getValueAPF().isNormal();
217 if (!getType()->isVectorTy())
218 return false;
219 for (unsigned i = 0, e = getType()->getVectorNumElements(); i != e; ++i) {
220 auto *CFP = dyn_cast_or_null<ConstantFP>(this->getAggregateElement(i));
221 if (!CFP || !CFP->getValueAPF().isNormal())
222 return false;
223 }
224 return true;
225}
226
Sanjay Patel90f4c8e2018-02-20 16:08:15 +0000227bool Constant::hasExactInverseFP() const {
228 if (auto *CFP = dyn_cast<ConstantFP>(this))
229 return CFP->getValueAPF().getExactInverse(nullptr);
230 if (!getType()->isVectorTy())
231 return false;
232 for (unsigned i = 0, e = getType()->getVectorNumElements(); i != e; ++i) {
233 auto *CFP = dyn_cast_or_null<ConstantFP>(this->getAggregateElement(i));
234 if (!CFP || !CFP->getValueAPF().getExactInverse(nullptr))
235 return false;
236 }
237 return true;
238}
239
Sanjay Patel46b083e2018-03-02 18:36:08 +0000240bool Constant::isNaN() const {
241 if (auto *CFP = dyn_cast<ConstantFP>(this))
242 return CFP->isNaN();
243 if (!getType()->isVectorTy())
244 return false;
245 for (unsigned i = 0, e = getType()->getVectorNumElements(); i != e; ++i) {
246 auto *CFP = dyn_cast_or_null<ConstantFP>(this->getAggregateElement(i));
247 if (!CFP || !CFP->isNaN())
248 return false;
249 }
250 return true;
251}
252
Sanjay Patele6dda2f2018-07-06 14:52:36 +0000253bool Constant::containsUndefElement() const {
254 if (!getType()->isVectorTy())
255 return false;
256 for (unsigned i = 0, e = getType()->getVectorNumElements(); i != e; ++i)
257 if (isa<UndefValue>(getAggregateElement(i)))
258 return true;
259
260 return false;
261}
262
Sanjay Patelde1d5d32019-03-14 19:22:08 +0000263bool Constant::containsConstantExpression() const {
264 if (!getType()->isVectorTy())
265 return false;
266 for (unsigned i = 0, e = getType()->getVectorNumElements(); i != e; ++i)
267 if (isa<ConstantExpr>(getAggregateElement(i)))
268 return true;
269
270 return false;
271}
272
Sanjay Patel1d0ac7c2016-04-29 22:03:27 +0000273/// Constructor to create a '0' constant of arbitrary type.
Chris Lattner229907c2011-07-18 04:54:35 +0000274Constant *Constant::getNullValue(Type *Ty) {
Owen Anderson5a1acd92009-07-31 20:28:14 +0000275 switch (Ty->getTypeID()) {
276 case Type::IntegerTyID:
277 return ConstantInt::get(Ty, 0);
Dan Gohman518cda42011-12-17 00:04:22 +0000278 case Type::HalfTyID:
279 return ConstantFP::get(Ty->getContext(),
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000280 APFloat::getZero(APFloat::IEEEhalf()));
Owen Anderson5a1acd92009-07-31 20:28:14 +0000281 case Type::FloatTyID:
Benjamin Kramer8ceebfa2010-12-04 14:22:24 +0000282 return ConstantFP::get(Ty->getContext(),
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000283 APFloat::getZero(APFloat::IEEEsingle()));
Owen Anderson5a1acd92009-07-31 20:28:14 +0000284 case Type::DoubleTyID:
Benjamin Kramer8ceebfa2010-12-04 14:22:24 +0000285 return ConstantFP::get(Ty->getContext(),
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000286 APFloat::getZero(APFloat::IEEEdouble()));
Owen Anderson5a1acd92009-07-31 20:28:14 +0000287 case Type::X86_FP80TyID:
Benjamin Kramer8ceebfa2010-12-04 14:22:24 +0000288 return ConstantFP::get(Ty->getContext(),
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000289 APFloat::getZero(APFloat::x87DoubleExtended()));
Owen Anderson5a1acd92009-07-31 20:28:14 +0000290 case Type::FP128TyID:
291 return ConstantFP::get(Ty->getContext(),
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000292 APFloat::getZero(APFloat::IEEEquad()));
Owen Anderson5a1acd92009-07-31 20:28:14 +0000293 case Type::PPC_FP128TyID:
Benjamin Kramer8ceebfa2010-12-04 14:22:24 +0000294 return ConstantFP::get(Ty->getContext(),
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000295 APFloat(APFloat::PPCDoubleDouble(),
Tim Northover29178a32013-01-22 09:46:31 +0000296 APInt::getNullValue(128)));
Owen Anderson5a1acd92009-07-31 20:28:14 +0000297 case Type::PointerTyID:
298 return ConstantPointerNull::get(cast<PointerType>(Ty));
299 case Type::StructTyID:
300 case Type::ArrayTyID:
301 case Type::VectorTyID:
302 return ConstantAggregateZero::get(Ty);
David Majnemerf0f224d2015-11-11 21:57:16 +0000303 case Type::TokenTyID:
304 return ConstantTokenNone::get(Ty->getContext());
Owen Anderson5a1acd92009-07-31 20:28:14 +0000305 default:
306 // Function, Label, or Opaque type?
Craig Topperc514b542012-02-05 22:14:15 +0000307 llvm_unreachable("Cannot create a null constant of that type!");
Owen Anderson5a1acd92009-07-31 20:28:14 +0000308 }
309}
310
Chris Lattner229907c2011-07-18 04:54:35 +0000311Constant *Constant::getIntegerValue(Type *Ty, const APInt &V) {
312 Type *ScalarTy = Ty->getScalarType();
Dan Gohmanf011f5a2009-08-03 22:07:33 +0000313
314 // Create the base integer constant.
315 Constant *C = ConstantInt::get(Ty->getContext(), V);
316
317 // Convert an integer to a pointer, if necessary.
Chris Lattner229907c2011-07-18 04:54:35 +0000318 if (PointerType *PTy = dyn_cast<PointerType>(ScalarTy))
Dan Gohmanf011f5a2009-08-03 22:07:33 +0000319 C = ConstantExpr::getIntToPtr(C, PTy);
320
321 // Broadcast a scalar to a vector, if necessary.
Chris Lattner229907c2011-07-18 04:54:35 +0000322 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
Chris Lattnere9eed292012-01-25 05:19:54 +0000323 C = ConstantVector::getSplat(VTy->getNumElements(), C);
Dan Gohmanf011f5a2009-08-03 22:07:33 +0000324
325 return C;
326}
327
Chris Lattner229907c2011-07-18 04:54:35 +0000328Constant *Constant::getAllOnesValue(Type *Ty) {
329 if (IntegerType *ITy = dyn_cast<IntegerType>(Ty))
Owen Anderson5a1acd92009-07-31 20:28:14 +0000330 return ConstantInt::get(Ty->getContext(),
331 APInt::getAllOnesValue(ITy->getBitWidth()));
Nadav Rotem7cc6d122011-02-17 21:22:27 +0000332
333 if (Ty->isFloatingPointTy()) {
334 APFloat FL = APFloat::getAllOnesValue(Ty->getPrimitiveSizeInBits(),
335 !Ty->isPPC_FP128Ty());
336 return ConstantFP::get(Ty->getContext(), FL);
337 }
338
Chris Lattner229907c2011-07-18 04:54:35 +0000339 VectorType *VTy = cast<VectorType>(Ty);
Chris Lattnere9eed292012-01-25 05:19:54 +0000340 return ConstantVector::getSplat(VTy->getNumElements(),
341 getAllOnesValue(VTy->getElementType()));
Owen Anderson5a1acd92009-07-31 20:28:14 +0000342}
343
Chris Lattner7e683d12012-01-25 06:16:32 +0000344Constant *Constant::getAggregateElement(unsigned Elt) const {
Duncan P. N. Exon Smith1de3c7e2016-04-05 21:10:45 +0000345 if (const ConstantAggregate *CC = dyn_cast<ConstantAggregate>(this))
346 return Elt < CC->getNumOperands() ? CC->getOperand(Elt) : nullptr;
Galina Kistanovafc259902012-07-13 01:25:27 +0000347
David Majnemer9b529a72015-02-16 04:02:09 +0000348 if (const ConstantAggregateZero *CAZ = dyn_cast<ConstantAggregateZero>(this))
349 return Elt < CAZ->getNumElements() ? CAZ->getElementValue(Elt) : nullptr;
Galina Kistanovafc259902012-07-13 01:25:27 +0000350
Chris Lattner7e683d12012-01-25 06:16:32 +0000351 if (const UndefValue *UV = dyn_cast<UndefValue>(this))
David Majnemer9b529a72015-02-16 04:02:09 +0000352 return Elt < UV->getNumElements() ? UV->getElementValue(Elt) : nullptr;
Galina Kistanovafc259902012-07-13 01:25:27 +0000353
Chris Lattner8326bd82012-01-26 00:42:34 +0000354 if (const ConstantDataSequential *CDS =dyn_cast<ConstantDataSequential>(this))
Craig Topperc6207612014-04-09 06:08:46 +0000355 return Elt < CDS->getNumElements() ? CDS->getElementAsConstant(Elt)
356 : nullptr;
357 return nullptr;
Chris Lattner7e683d12012-01-25 06:16:32 +0000358}
359
360Constant *Constant::getAggregateElement(Constant *Elt) const {
361 assert(isa<IntegerType>(Elt->getType()) && "Index must be an integer");
Florian Hahncc419ad2018-12-12 02:22:12 +0000362 if (ConstantInt *CI = dyn_cast<ConstantInt>(Elt)) {
363 // Check if the constant fits into an uint64_t.
364 if (CI->getValue().getActiveBits() > 64)
365 return nullptr;
Chris Lattner7e683d12012-01-25 06:16:32 +0000366 return getAggregateElement(CI->getZExtValue());
Florian Hahncc419ad2018-12-12 02:22:12 +0000367 }
Craig Topperc6207612014-04-09 06:08:46 +0000368 return nullptr;
Chris Lattner7e683d12012-01-25 06:16:32 +0000369}
370
Pete Cooper86dd4cf2015-06-23 21:55:11 +0000371void Constant::destroyConstant() {
372 /// First call destroyConstantImpl on the subclass. This gives the subclass
373 /// a chance to remove the constant from any maps/pools it's contained in.
374 switch (getValueID()) {
375 default:
376 llvm_unreachable("Not a constant!");
377#define HANDLE_CONSTANT(Name) \
378 case Value::Name##Val: \
379 cast<Name>(this)->destroyConstantImpl(); \
380 break;
381#include "llvm/IR/Value.def"
382 }
Chris Lattner7e683d12012-01-25 06:16:32 +0000383
Chris Lattner3462ae32001-12-03 22:26:30 +0000384 // When a Constant is destroyed, there may be lingering
Chris Lattnerd7a73302001-10-13 06:57:33 +0000385 // references to the constant by other constants in the constant pool. These
Misha Brukmanbe372b92003-08-21 22:14:26 +0000386 // constants are implicitly dependent on the module that is being deleted,
Chris Lattnerd7a73302001-10-13 06:57:33 +0000387 // but they don't know that. Because we only find out when the CPV is
388 // deleted, we must now notify all of our users (that should only be
Chris Lattner3462ae32001-12-03 22:26:30 +0000389 // Constants) that they are, in fact, invalid now and should be deleted.
Chris Lattnerd7a73302001-10-13 06:57:33 +0000390 //
391 while (!use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000392 Value *V = user_back();
Pete Cooper86dd4cf2015-06-23 21:55:11 +0000393#ifndef NDEBUG // Only in -g mode...
Chris Lattner78683a72009-08-23 04:02:03 +0000394 if (!isa<Constant>(V)) {
David Greene1e27a132010-01-05 01:29:19 +0000395 dbgs() << "While deleting: " << *this
Pete Cooper86dd4cf2015-06-23 21:55:11 +0000396 << "\n\nUse still stuck around after Def is destroyed: " << *V
397 << "\n\n";
Chris Lattner78683a72009-08-23 04:02:03 +0000398 }
Chris Lattnerd7a73302001-10-13 06:57:33 +0000399#endif
Vikram S. Adve4e537b22002-07-14 23:13:17 +0000400 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
Chris Lattner8326bd82012-01-26 00:42:34 +0000401 cast<Constant>(V)->destroyConstant();
Chris Lattnerd7a73302001-10-13 06:57:33 +0000402
403 // The constant should remove itself from our use list...
Chandler Carruthcdf47882014-03-09 03:16:01 +0000404 assert((use_empty() || user_back() != V) && "Constant not removed!");
Chris Lattnerd7a73302001-10-13 06:57:33 +0000405 }
406
407 // Value has no outstanding references it is safe to delete it now...
408 delete this;
Chris Lattner38569342001-10-01 20:11:19 +0000409}
Chris Lattner2f7c9632001-06-06 20:29:01 +0000410
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +0000411static bool canTrapImpl(const Constant *C,
Craig Topper71b7b682014-08-21 05:55:13 +0000412 SmallPtrSetImpl<const ConstantExpr *> &NonTrappingOps) {
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +0000413 assert(C->getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
Chris Lattner23dd1f62006-10-20 00:27:06 +0000414 // The only thing that could possibly trap are constant exprs.
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +0000415 const ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
416 if (!CE)
417 return false;
Galina Kistanovafc259902012-07-13 01:25:27 +0000418
419 // ConstantExpr traps if any operands can trap.
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +0000420 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) {
421 if (ConstantExpr *Op = dyn_cast<ConstantExpr>(CE->getOperand(i))) {
David Blaikie70573dc2014-11-19 07:49:26 +0000422 if (NonTrappingOps.insert(Op).second && canTrapImpl(Op, NonTrappingOps))
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +0000423 return true;
424 }
425 }
Chris Lattner23dd1f62006-10-20 00:27:06 +0000426
427 // Otherwise, only specific operations can trap.
428 switch (CE->getOpcode()) {
429 default:
430 return false;
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000431 case Instruction::UDiv:
432 case Instruction::SDiv:
Reid Spencer7eb55b32006-11-02 01:53:59 +0000433 case Instruction::URem:
434 case Instruction::SRem:
Chris Lattner23dd1f62006-10-20 00:27:06 +0000435 // Div and rem can trap if the RHS is not known to be non-zero.
Chris Lattnera91a5632009-10-28 05:14:34 +0000436 if (!isa<ConstantInt>(CE->getOperand(1)) ||CE->getOperand(1)->isNullValue())
Chris Lattner23dd1f62006-10-20 00:27:06 +0000437 return true;
438 return false;
439 }
440}
441
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +0000442bool Constant::canTrap() const {
443 SmallPtrSet<const ConstantExpr *, 4> NonTrappingOps;
444 return canTrapImpl(this, NonTrappingOps);
445}
446
Hans Wennborg4dc89512014-06-20 00:38:12 +0000447/// Check if C contains a GlobalValue for which Predicate is true.
448static bool
449ConstHasGlobalValuePredicate(const Constant *C,
450 bool (*Predicate)(const GlobalValue *)) {
451 SmallPtrSet<const Constant *, 8> Visited;
452 SmallVector<const Constant *, 8> WorkList;
453 WorkList.push_back(C);
454 Visited.insert(C);
Hans Wennborg709e0152012-11-15 11:40:00 +0000455
456 while (!WorkList.empty()) {
Hans Wennborg4dc89512014-06-20 00:38:12 +0000457 const Constant *WorkItem = WorkList.pop_back_val();
458 if (const auto *GV = dyn_cast<GlobalValue>(WorkItem))
459 if (Predicate(GV))
Hans Wennborg709e0152012-11-15 11:40:00 +0000460 return true;
Hans Wennborg4dc89512014-06-20 00:38:12 +0000461 for (const Value *Op : WorkItem->operands()) {
462 const Constant *ConstOp = dyn_cast<Constant>(Op);
463 if (!ConstOp)
Hans Wennborg18aa12402012-11-16 10:33:25 +0000464 continue;
David Blaikie70573dc2014-11-19 07:49:26 +0000465 if (Visited.insert(ConstOp).second)
Hans Wennborg4dc89512014-06-20 00:38:12 +0000466 WorkList.push_back(ConstOp);
Hans Wennborg709e0152012-11-15 11:40:00 +0000467 }
468 }
Hans Wennborg709e0152012-11-15 11:40:00 +0000469 return false;
470}
471
Hans Wennborg4dc89512014-06-20 00:38:12 +0000472bool Constant::isThreadDependent() const {
473 auto DLLImportPredicate = [](const GlobalValue *GV) {
474 return GV->isThreadLocal();
475 };
476 return ConstHasGlobalValuePredicate(this, DLLImportPredicate);
477}
478
479bool Constant::isDLLImportDependent() const {
480 auto DLLImportPredicate = [](const GlobalValue *GV) {
481 return GV->hasDLLImportStorageClass();
482 };
483 return ConstHasGlobalValuePredicate(this, DLLImportPredicate);
484}
485
Chris Lattner253bc772009-11-01 18:11:50 +0000486bool Constant::isConstantUsed() const {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000487 for (const User *U : users()) {
488 const Constant *UC = dyn_cast<Constant>(U);
Craig Topperc6207612014-04-09 06:08:46 +0000489 if (!UC || isa<GlobalValue>(UC))
Chris Lattner253bc772009-11-01 18:11:50 +0000490 return true;
Galina Kistanovafc259902012-07-13 01:25:27 +0000491
Chris Lattner253bc772009-11-01 18:11:50 +0000492 if (UC->isConstantUsed())
493 return true;
494 }
495 return false;
496}
497
Rafael Espindola65e49022015-11-17 00:51:23 +0000498bool Constant::needsRelocation() const {
499 if (isa<GlobalValue>(this))
500 return true; // Global reference.
501
Chris Lattner2cb85b42009-10-28 04:12:16 +0000502 if (const BlockAddress *BA = dyn_cast<BlockAddress>(this))
Rafael Espindola65e49022015-11-17 00:51:23 +0000503 return BA->getFunction()->needsRelocation();
504
Chris Lattnera7cfc432010-01-03 18:09:40 +0000505 // While raw uses of blockaddress need to be relocated, differences between
506 // two of them don't when they are for labels in the same function. This is a
507 // common idiom when creating a table for the indirect goto extension, so we
508 // handle it efficiently here.
509 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(this))
510 if (CE->getOpcode() == Instruction::Sub) {
511 ConstantExpr *LHS = dyn_cast<ConstantExpr>(CE->getOperand(0));
512 ConstantExpr *RHS = dyn_cast<ConstantExpr>(CE->getOperand(1));
Rafael Espindola65e49022015-11-17 00:51:23 +0000513 if (LHS && RHS && LHS->getOpcode() == Instruction::PtrToInt &&
Chris Lattnera7cfc432010-01-03 18:09:40 +0000514 RHS->getOpcode() == Instruction::PtrToInt &&
515 isa<BlockAddress>(LHS->getOperand(0)) &&
516 isa<BlockAddress>(RHS->getOperand(0)) &&
517 cast<BlockAddress>(LHS->getOperand(0))->getFunction() ==
Rafael Espindola65e49022015-11-17 00:51:23 +0000518 cast<BlockAddress>(RHS->getOperand(0))->getFunction())
519 return false;
Chris Lattnera7cfc432010-01-03 18:09:40 +0000520 }
Galina Kistanovafc259902012-07-13 01:25:27 +0000521
Rafael Espindola65e49022015-11-17 00:51:23 +0000522 bool Result = false;
Evan Chengf9e003b2007-03-08 00:59:12 +0000523 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
Rafael Espindola65e49022015-11-17 00:51:23 +0000524 Result |= cast<Constant>(getOperand(i))->needsRelocation();
Galina Kistanovafc259902012-07-13 01:25:27 +0000525
Chris Lattner4565ef52009-07-22 00:05:44 +0000526 return Result;
Evan Chengf9e003b2007-03-08 00:59:12 +0000527}
528
Sanjay Patel1d0ac7c2016-04-29 22:03:27 +0000529/// If the specified constantexpr is dead, remove it. This involves recursively
530/// eliminating any dead users of the constantexpr.
Chris Lattner84886402011-02-18 04:41:42 +0000531static bool removeDeadUsersOfConstant(const Constant *C) {
532 if (isa<GlobalValue>(C)) return false; // Cannot remove this
Galina Kistanovafc259902012-07-13 01:25:27 +0000533
Chris Lattner84886402011-02-18 04:41:42 +0000534 while (!C->use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000535 const Constant *User = dyn_cast<Constant>(C->user_back());
Chris Lattner84886402011-02-18 04:41:42 +0000536 if (!User) return false; // Non-constant usage;
537 if (!removeDeadUsersOfConstant(User))
538 return false; // Constant wasn't dead
539 }
Galina Kistanovafc259902012-07-13 01:25:27 +0000540
Chris Lattner84886402011-02-18 04:41:42 +0000541 const_cast<Constant*>(C)->destroyConstant();
542 return true;
543}
544
545
Chris Lattner84886402011-02-18 04:41:42 +0000546void Constant::removeDeadConstantUsers() const {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000547 Value::const_user_iterator I = user_begin(), E = user_end();
548 Value::const_user_iterator LastNonDeadUser = E;
Chris Lattner84886402011-02-18 04:41:42 +0000549 while (I != E) {
550 const Constant *User = dyn_cast<Constant>(*I);
Craig Topperc6207612014-04-09 06:08:46 +0000551 if (!User) {
Chris Lattner84886402011-02-18 04:41:42 +0000552 LastNonDeadUser = I;
553 ++I;
554 continue;
555 }
Galina Kistanovafc259902012-07-13 01:25:27 +0000556
Chris Lattner84886402011-02-18 04:41:42 +0000557 if (!removeDeadUsersOfConstant(User)) {
558 // If the constant wasn't dead, remember that this was the last live use
559 // and move on to the next constant.
560 LastNonDeadUser = I;
561 ++I;
562 continue;
563 }
Galina Kistanovafc259902012-07-13 01:25:27 +0000564
Chris Lattner84886402011-02-18 04:41:42 +0000565 // If the constant was dead, then the iterator is invalidated.
566 if (LastNonDeadUser == E) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000567 I = user_begin();
Chris Lattner84886402011-02-18 04:41:42 +0000568 if (I == E) break;
569 } else {
570 I = LastNonDeadUser;
571 ++I;
572 }
573 }
574}
575
576
Chris Lattner2105d662008-07-10 00:28:11 +0000577
Chris Lattner2f7c9632001-06-06 20:29:01 +0000578//===----------------------------------------------------------------------===//
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000579// ConstantInt
Chris Lattner2f7c9632001-06-06 20:29:01 +0000580//===----------------------------------------------------------------------===//
581
Duncan P. N. Exon Smithb6452792016-02-21 02:39:49 +0000582ConstantInt::ConstantInt(IntegerType *Ty, const APInt &V)
583 : ConstantData(Ty, ConstantIntVal), Val(V) {
Reid Spencerb31bffe2007-02-26 23:54:03 +0000584 assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
Chris Lattner2f7c9632001-06-06 20:29:01 +0000585}
586
Nick Lewycky92db8e82011-03-06 03:36:19 +0000587ConstantInt *ConstantInt::getTrue(LLVMContext &Context) {
Owen Anderson23a204d2009-07-31 17:39:07 +0000588 LLVMContextImpl *pImpl = Context.pImpl;
Benjamin Kramerddd1b7b2010-11-20 18:43:35 +0000589 if (!pImpl->TheTrueVal)
590 pImpl->TheTrueVal = ConstantInt::get(Type::getInt1Ty(Context), 1);
591 return pImpl->TheTrueVal;
Owen Anderson23a204d2009-07-31 17:39:07 +0000592}
593
Nick Lewycky92db8e82011-03-06 03:36:19 +0000594ConstantInt *ConstantInt::getFalse(LLVMContext &Context) {
Owen Anderson23a204d2009-07-31 17:39:07 +0000595 LLVMContextImpl *pImpl = Context.pImpl;
Benjamin Kramerddd1b7b2010-11-20 18:43:35 +0000596 if (!pImpl->TheFalseVal)
597 pImpl->TheFalseVal = ConstantInt::get(Type::getInt1Ty(Context), 0);
598 return pImpl->TheFalseVal;
Owen Anderson23a204d2009-07-31 17:39:07 +0000599}
600
Chris Lattner229907c2011-07-18 04:54:35 +0000601Constant *ConstantInt::getTrue(Type *Ty) {
Craig Topperfde47232017-07-09 07:04:03 +0000602 assert(Ty->isIntOrIntVectorTy(1) && "Type not i1 or vector of i1.");
Sanjay Patel70a575a2017-04-16 17:00:21 +0000603 ConstantInt *TrueC = ConstantInt::getTrue(Ty->getContext());
604 if (auto *VTy = dyn_cast<VectorType>(Ty))
605 return ConstantVector::getSplat(VTy->getNumElements(), TrueC);
606 return TrueC;
Nick Lewycky92db8e82011-03-06 03:36:19 +0000607}
608
Chris Lattner229907c2011-07-18 04:54:35 +0000609Constant *ConstantInt::getFalse(Type *Ty) {
Craig Topperfde47232017-07-09 07:04:03 +0000610 assert(Ty->isIntOrIntVectorTy(1) && "Type not i1 or vector of i1.");
Sanjay Patel70a575a2017-04-16 17:00:21 +0000611 ConstantInt *FalseC = ConstantInt::getFalse(Ty->getContext());
612 if (auto *VTy = dyn_cast<VectorType>(Ty))
613 return ConstantVector::getSplat(VTy->getNumElements(), FalseC);
614 return FalseC;
Nick Lewycky92db8e82011-03-06 03:36:19 +0000615}
616
Benjamin Kramer8e5dc532014-12-06 13:12:56 +0000617// Get a ConstantInt from an APInt.
Nick Lewycky92db8e82011-03-06 03:36:19 +0000618ConstantInt *ConstantInt::get(LLVMContext &Context, const APInt &V) {
Owen Andersonedb4a702009-07-24 23:12:02 +0000619 // get an existing value or the insertion position
Benjamin Kramer320682f2013-06-01 17:51:03 +0000620 LLVMContextImpl *pImpl = Context.pImpl;
Justin Lebar611c5c22016-10-10 16:26:13 +0000621 std::unique_ptr<ConstantInt> &Slot = pImpl->IntConstants[V];
Benjamin Kramer8e5dc532014-12-06 13:12:56 +0000622 if (!Slot) {
623 // Get the corresponding integer type for the bit width of the value.
624 IntegerType *ITy = IntegerType::get(Context, V.getBitWidth());
Justin Lebar611c5c22016-10-10 16:26:13 +0000625 Slot.reset(new ConstantInt(ITy, V));
Benjamin Kramer8e5dc532014-12-06 13:12:56 +0000626 }
627 assert(Slot->getType() == IntegerType::get(Context, V.getBitWidth()));
Justin Lebar611c5c22016-10-10 16:26:13 +0000628 return Slot.get();
Owen Andersonedb4a702009-07-24 23:12:02 +0000629}
630
Chris Lattner229907c2011-07-18 04:54:35 +0000631Constant *ConstantInt::get(Type *Ty, uint64_t V, bool isSigned) {
Nick Lewycky92db8e82011-03-06 03:36:19 +0000632 Constant *C = get(cast<IntegerType>(Ty->getScalarType()), V, isSigned);
Owen Andersonedb4a702009-07-24 23:12:02 +0000633
634 // For vectors, broadcast the value.
Chris Lattner229907c2011-07-18 04:54:35 +0000635 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
Chris Lattnere9eed292012-01-25 05:19:54 +0000636 return ConstantVector::getSplat(VTy->getNumElements(), C);
Owen Andersonedb4a702009-07-24 23:12:02 +0000637
638 return C;
639}
640
Sanjay Patelf3587ec2016-05-18 22:05:28 +0000641ConstantInt *ConstantInt::get(IntegerType *Ty, uint64_t V, bool isSigned) {
Owen Andersonedb4a702009-07-24 23:12:02 +0000642 return get(Ty->getContext(), APInt(Ty->getBitWidth(), V, isSigned));
643}
644
Chris Lattner0256be92012-01-27 03:08:05 +0000645ConstantInt *ConstantInt::getSigned(IntegerType *Ty, int64_t V) {
Owen Andersonedb4a702009-07-24 23:12:02 +0000646 return get(Ty, V, true);
647}
648
Chris Lattner229907c2011-07-18 04:54:35 +0000649Constant *ConstantInt::getSigned(Type *Ty, int64_t V) {
Owen Andersonedb4a702009-07-24 23:12:02 +0000650 return get(Ty, V, true);
651}
652
Chris Lattner0256be92012-01-27 03:08:05 +0000653Constant *ConstantInt::get(Type *Ty, const APInt& V) {
Owen Andersonedb4a702009-07-24 23:12:02 +0000654 ConstantInt *C = get(Ty->getContext(), V);
655 assert(C->getType() == Ty->getScalarType() &&
656 "ConstantInt type doesn't match the type implied by its value!");
657
658 // For vectors, broadcast the value.
Chris Lattner229907c2011-07-18 04:54:35 +0000659 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
Chris Lattnere9eed292012-01-25 05:19:54 +0000660 return ConstantVector::getSplat(VTy->getNumElements(), C);
Owen Andersonedb4a702009-07-24 23:12:02 +0000661
662 return C;
663}
664
Sanjay Patelf3587ec2016-05-18 22:05:28 +0000665ConstantInt *ConstantInt::get(IntegerType* Ty, StringRef Str, uint8_t radix) {
Erick Tryzelaarfc2280d2009-08-16 23:36:33 +0000666 return get(Ty->getContext(), APInt(Ty->getBitWidth(), Str, radix));
667}
668
Pete Cooper86dd4cf2015-06-23 21:55:11 +0000669/// Remove the constant from the constant table.
670void ConstantInt::destroyConstantImpl() {
671 llvm_unreachable("You can't ConstantInt->destroyConstantImpl()!");
672}
673
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000674//===----------------------------------------------------------------------===//
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000675// ConstantFP
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000676//===----------------------------------------------------------------------===//
677
Chris Lattner229907c2011-07-18 04:54:35 +0000678static const fltSemantics *TypeToFloatSemantics(Type *Ty) {
Dan Gohman518cda42011-12-17 00:04:22 +0000679 if (Ty->isHalfTy())
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000680 return &APFloat::IEEEhalf();
Chris Lattnerfdd87902009-10-05 05:54:46 +0000681 if (Ty->isFloatTy())
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000682 return &APFloat::IEEEsingle();
Chris Lattnerfdd87902009-10-05 05:54:46 +0000683 if (Ty->isDoubleTy())
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000684 return &APFloat::IEEEdouble();
Chris Lattnerfdd87902009-10-05 05:54:46 +0000685 if (Ty->isX86_FP80Ty())
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000686 return &APFloat::x87DoubleExtended();
Chris Lattnerfdd87902009-10-05 05:54:46 +0000687 else if (Ty->isFP128Ty())
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000688 return &APFloat::IEEEquad();
Galina Kistanovafc259902012-07-13 01:25:27 +0000689
Chris Lattnerfdd87902009-10-05 05:54:46 +0000690 assert(Ty->isPPC_FP128Ty() && "Unknown FP format");
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000691 return &APFloat::PPCDoubleDouble();
Rafael Espindolaf5d53d42009-07-15 17:40:42 +0000692}
693
Chris Lattner0256be92012-01-27 03:08:05 +0000694Constant *ConstantFP::get(Type *Ty, double V) {
Owen Anderson69c464d2009-07-27 20:59:43 +0000695 LLVMContext &Context = Ty->getContext();
Galina Kistanovafc259902012-07-13 01:25:27 +0000696
Owen Anderson69c464d2009-07-27 20:59:43 +0000697 APFloat FV(V);
698 bool ignored;
699 FV.convert(*TypeToFloatSemantics(Ty->getScalarType()),
700 APFloat::rmNearestTiesToEven, &ignored);
701 Constant *C = get(Context, FV);
702
703 // For vectors, broadcast the value.
Chris Lattner229907c2011-07-18 04:54:35 +0000704 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
Chris Lattnere9eed292012-01-25 05:19:54 +0000705 return ConstantVector::getSplat(VTy->getNumElements(), C);
Owen Anderson69c464d2009-07-27 20:59:43 +0000706
707 return C;
708}
709
Sanjay Patel6a0f6672018-02-15 13:55:52 +0000710Constant *ConstantFP::get(Type *Ty, const APFloat &V) {
711 ConstantFP *C = get(Ty->getContext(), V);
712 assert(C->getType() == Ty->getScalarType() &&
713 "ConstantFP type doesn't match the type implied by its value!");
714
715 // For vectors, broadcast the value.
716 if (auto *VTy = dyn_cast<VectorType>(Ty))
717 return ConstantVector::getSplat(VTy->getNumElements(), C);
718
719 return C;
720}
Erick Tryzelaarfc2280d2009-08-16 23:36:33 +0000721
Chris Lattner0256be92012-01-27 03:08:05 +0000722Constant *ConstantFP::get(Type *Ty, StringRef Str) {
Erick Tryzelaarfc2280d2009-08-16 23:36:33 +0000723 LLVMContext &Context = Ty->getContext();
724
725 APFloat FV(*TypeToFloatSemantics(Ty->getScalarType()), Str);
726 Constant *C = get(Context, FV);
727
728 // For vectors, broadcast the value.
Chris Lattner229907c2011-07-18 04:54:35 +0000729 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
Chris Lattnere9eed292012-01-25 05:19:54 +0000730 return ConstantVector::getSplat(VTy->getNumElements(), C);
Erick Tryzelaarfc2280d2009-08-16 23:36:33 +0000731
Bjorn Petterssonaa025802018-07-03 12:39:52 +0000732 return C;
Erick Tryzelaarfc2280d2009-08-16 23:36:33 +0000733}
734
JF Bastien69f60982018-12-10 19:27:38 +0000735Constant *ConstantFP::getNaN(Type *Ty, bool Negative, uint64_t Payload) {
Tom Stellard67246d12015-04-20 19:38:24 +0000736 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
JF Bastien69f60982018-12-10 19:27:38 +0000737 APFloat NaN = APFloat::getNaN(Semantics, Negative, Payload);
Tom Stellard67246d12015-04-20 19:38:24 +0000738 Constant *C = get(Ty->getContext(), NaN);
739
740 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
741 return ConstantVector::getSplat(VTy->getNumElements(), C);
742
743 return C;
744}
745
JF Bastien69f60982018-12-10 19:27:38 +0000746Constant *ConstantFP::getQNaN(Type *Ty, bool Negative, APInt *Payload) {
747 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
748 APFloat NaN = APFloat::getQNaN(Semantics, Negative, Payload);
749 Constant *C = get(Ty->getContext(), NaN);
750
751 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
752 return ConstantVector::getSplat(VTy->getNumElements(), C);
753
754 return C;
755}
756
757Constant *ConstantFP::getSNaN(Type *Ty, bool Negative, APInt *Payload) {
758 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
759 APFloat NaN = APFloat::getSNaN(Semantics, Negative, Payload);
760 Constant *C = get(Ty->getContext(), NaN);
761
762 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
763 return ConstantVector::getSplat(VTy->getNumElements(), C);
764
765 return C;
766}
767
Benjamin Kramer5d2ff222014-01-18 16:43:06 +0000768Constant *ConstantFP::getNegativeZero(Type *Ty) {
769 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
770 APFloat NegZero = APFloat::getZero(Semantics, /*Negative=*/true);
771 Constant *C = get(Ty->getContext(), NegZero);
Erick Tryzelaarfc2280d2009-08-16 23:36:33 +0000772
Benjamin Kramer5d2ff222014-01-18 16:43:06 +0000773 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
774 return ConstantVector::getSplat(VTy->getNumElements(), C);
775
776 return C;
Owen Anderson69c464d2009-07-27 20:59:43 +0000777}
778
779
Chris Lattnere9eed292012-01-25 05:19:54 +0000780Constant *ConstantFP::getZeroValueForNegation(Type *Ty) {
Benjamin Kramer5d2ff222014-01-18 16:43:06 +0000781 if (Ty->isFPOrFPVectorTy())
782 return getNegativeZero(Ty);
Owen Anderson69c464d2009-07-27 20:59:43 +0000783
Owen Anderson5a1acd92009-07-31 20:28:14 +0000784 return Constant::getNullValue(Ty);
Owen Anderson69c464d2009-07-27 20:59:43 +0000785}
786
787
788// ConstantFP accessors.
789ConstantFP* ConstantFP::get(LLVMContext &Context, const APFloat& V) {
Owen Anderson69c464d2009-07-27 20:59:43 +0000790 LLVMContextImpl* pImpl = Context.pImpl;
Galina Kistanovafc259902012-07-13 01:25:27 +0000791
Justin Lebar611c5c22016-10-10 16:26:13 +0000792 std::unique_ptr<ConstantFP> &Slot = pImpl->FPConstants[V];
Galina Kistanovafc259902012-07-13 01:25:27 +0000793
Owen Anderson69c464d2009-07-27 20:59:43 +0000794 if (!Slot) {
Chris Lattner229907c2011-07-18 04:54:35 +0000795 Type *Ty;
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000796 if (&V.getSemantics() == &APFloat::IEEEhalf())
Dan Gohman518cda42011-12-17 00:04:22 +0000797 Ty = Type::getHalfTy(Context);
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000798 else if (&V.getSemantics() == &APFloat::IEEEsingle())
Owen Anderson5dab84c2009-10-19 20:11:52 +0000799 Ty = Type::getFloatTy(Context);
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000800 else if (&V.getSemantics() == &APFloat::IEEEdouble())
Owen Anderson5dab84c2009-10-19 20:11:52 +0000801 Ty = Type::getDoubleTy(Context);
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000802 else if (&V.getSemantics() == &APFloat::x87DoubleExtended())
Owen Anderson5dab84c2009-10-19 20:11:52 +0000803 Ty = Type::getX86_FP80Ty(Context);
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000804 else if (&V.getSemantics() == &APFloat::IEEEquad())
Owen Anderson5dab84c2009-10-19 20:11:52 +0000805 Ty = Type::getFP128Ty(Context);
806 else {
Bjorn Petterssonaa025802018-07-03 12:39:52 +0000807 assert(&V.getSemantics() == &APFloat::PPCDoubleDouble() &&
Owen Anderson5dab84c2009-10-19 20:11:52 +0000808 "Unknown FP format");
809 Ty = Type::getPPC_FP128Ty(Context);
Owen Anderson69c464d2009-07-27 20:59:43 +0000810 }
Justin Lebar611c5c22016-10-10 16:26:13 +0000811 Slot.reset(new ConstantFP(Ty, V));
Owen Anderson69c464d2009-07-27 20:59:43 +0000812 }
Galina Kistanovafc259902012-07-13 01:25:27 +0000813
Justin Lebar611c5c22016-10-10 16:26:13 +0000814 return Slot.get();
Owen Anderson69c464d2009-07-27 20:59:43 +0000815}
816
Benjamin Kramer5d2ff222014-01-18 16:43:06 +0000817Constant *ConstantFP::getInfinity(Type *Ty, bool Negative) {
818 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
819 Constant *C = get(Ty->getContext(), APFloat::getInf(Semantics, Negative));
820
821 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
822 return ConstantVector::getSplat(VTy->getNumElements(), C);
823
824 return C;
Dan Gohmanfeb50212009-09-25 23:00:48 +0000825}
826
Duncan P. N. Exon Smithb6452792016-02-21 02:39:49 +0000827ConstantFP::ConstantFP(Type *Ty, const APFloat &V)
828 : ConstantData(Ty, ConstantFPVal), Val(V) {
Chris Lattner98bd9392008-04-09 06:38:30 +0000829 assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
830 "FP type Mismatch");
Chris Lattner2f7c9632001-06-06 20:29:01 +0000831}
832
Chris Lattnerbe6610c2011-07-15 06:14:08 +0000833bool ConstantFP::isExactlyValue(const APFloat &V) const {
Dale Johannesend246b2c2007-08-30 00:23:21 +0000834 return Val.bitwiseIsEqual(V);
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000835}
836
Pete Cooper86dd4cf2015-06-23 21:55:11 +0000837/// Remove the constant from the constant table.
838void ConstantFP::destroyConstantImpl() {
Craig Topperccbb8102017-06-27 19:57:51 +0000839 llvm_unreachable("You can't ConstantFP->destroyConstantImpl()!");
Pete Cooper86dd4cf2015-06-23 21:55:11 +0000840}
841
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000842//===----------------------------------------------------------------------===//
Chris Lattner030af792012-01-24 05:42:11 +0000843// ConstantAggregateZero Implementation
844//===----------------------------------------------------------------------===//
845
Chris Lattner7e683d12012-01-25 06:16:32 +0000846Constant *ConstantAggregateZero::getSequentialElement() const {
Chris Lattner8326bd82012-01-26 00:42:34 +0000847 return Constant::getNullValue(getType()->getSequentialElementType());
Chris Lattner030af792012-01-24 05:42:11 +0000848}
849
Chris Lattner7e683d12012-01-25 06:16:32 +0000850Constant *ConstantAggregateZero::getStructElement(unsigned Elt) const {
Chris Lattner8326bd82012-01-26 00:42:34 +0000851 return Constant::getNullValue(getType()->getStructElementType(Elt));
Chris Lattner030af792012-01-24 05:42:11 +0000852}
853
Chris Lattner7e683d12012-01-25 06:16:32 +0000854Constant *ConstantAggregateZero::getElementValue(Constant *C) const {
Chris Lattner030af792012-01-24 05:42:11 +0000855 if (isa<SequentialType>(getType()))
856 return getSequentialElement();
857 return getStructElement(cast<ConstantInt>(C)->getZExtValue());
858}
859
Chris Lattner7e683d12012-01-25 06:16:32 +0000860Constant *ConstantAggregateZero::getElementValue(unsigned Idx) const {
Chris Lattnerf7eb5432012-01-24 07:54:10 +0000861 if (isa<SequentialType>(getType()))
862 return getSequentialElement();
863 return getStructElement(Idx);
864}
865
David Majnemer9b529a72015-02-16 04:02:09 +0000866unsigned ConstantAggregateZero::getNumElements() const {
Craig Toppere3dcce92015-08-01 22:20:21 +0000867 Type *Ty = getType();
868 if (auto *AT = dyn_cast<ArrayType>(Ty))
David Majnemer9b529a72015-02-16 04:02:09 +0000869 return AT->getNumElements();
Craig Toppere3dcce92015-08-01 22:20:21 +0000870 if (auto *VT = dyn_cast<VectorType>(Ty))
David Majnemer9b529a72015-02-16 04:02:09 +0000871 return VT->getNumElements();
872 return Ty->getStructNumElements();
873}
Chris Lattnerf7eb5432012-01-24 07:54:10 +0000874
Chris Lattner030af792012-01-24 05:42:11 +0000875//===----------------------------------------------------------------------===//
876// UndefValue Implementation
877//===----------------------------------------------------------------------===//
878
Chris Lattner7e683d12012-01-25 06:16:32 +0000879UndefValue *UndefValue::getSequentialElement() const {
Chris Lattner8326bd82012-01-26 00:42:34 +0000880 return UndefValue::get(getType()->getSequentialElementType());
Chris Lattner030af792012-01-24 05:42:11 +0000881}
882
Chris Lattner7e683d12012-01-25 06:16:32 +0000883UndefValue *UndefValue::getStructElement(unsigned Elt) const {
Chris Lattner8326bd82012-01-26 00:42:34 +0000884 return UndefValue::get(getType()->getStructElementType(Elt));
Chris Lattner030af792012-01-24 05:42:11 +0000885}
886
Chris Lattner7e683d12012-01-25 06:16:32 +0000887UndefValue *UndefValue::getElementValue(Constant *C) const {
Chris Lattner030af792012-01-24 05:42:11 +0000888 if (isa<SequentialType>(getType()))
889 return getSequentialElement();
890 return getStructElement(cast<ConstantInt>(C)->getZExtValue());
891}
892
Chris Lattner7e683d12012-01-25 06:16:32 +0000893UndefValue *UndefValue::getElementValue(unsigned Idx) const {
Chris Lattnerf7eb5432012-01-24 07:54:10 +0000894 if (isa<SequentialType>(getType()))
895 return getSequentialElement();
896 return getStructElement(Idx);
897}
898
David Majnemer9b529a72015-02-16 04:02:09 +0000899unsigned UndefValue::getNumElements() const {
Craig Toppere3dcce92015-08-01 22:20:21 +0000900 Type *Ty = getType();
Peter Collingbournebc070522016-12-02 03:20:58 +0000901 if (auto *ST = dyn_cast<SequentialType>(Ty))
902 return ST->getNumElements();
David Majnemer9b529a72015-02-16 04:02:09 +0000903 return Ty->getStructNumElements();
904}
Chris Lattner030af792012-01-24 05:42:11 +0000905
906//===----------------------------------------------------------------------===//
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000907// ConstantXXX Classes
908//===----------------------------------------------------------------------===//
909
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000910template <typename ItTy, typename EltTy>
911static bool rangeOnlyContains(ItTy Start, ItTy End, EltTy Elt) {
912 for (; Start != End; ++Start)
913 if (*Start != Elt)
914 return false;
915 return true;
916}
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000917
Justin Bogner909e1c02015-12-01 20:20:49 +0000918template <typename SequentialTy, typename ElementTy>
919static Constant *getIntSequenceIfElementsMatch(ArrayRef<Constant *> V) {
920 assert(!V.empty() && "Cannot get empty int sequence.");
921
922 SmallVector<ElementTy, 16> Elts;
923 for (Constant *C : V)
924 if (auto *CI = dyn_cast<ConstantInt>(C))
925 Elts.push_back(CI->getZExtValue());
926 else
927 return nullptr;
928 return SequentialTy::get(V[0]->getContext(), Elts);
929}
930
931template <typename SequentialTy, typename ElementTy>
932static Constant *getFPSequenceIfElementsMatch(ArrayRef<Constant *> V) {
933 assert(!V.empty() && "Cannot get empty FP sequence.");
934
935 SmallVector<ElementTy, 16> Elts;
936 for (Constant *C : V)
937 if (auto *CFP = dyn_cast<ConstantFP>(C))
938 Elts.push_back(CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
939 else
940 return nullptr;
941 return SequentialTy::getFP(V[0]->getContext(), Elts);
942}
943
944template <typename SequenceTy>
945static Constant *getSequenceIfElementsMatch(Constant *C,
946 ArrayRef<Constant *> V) {
947 // We speculatively build the elements here even if it turns out that there is
948 // a constantexpr or something else weird, since it is so uncommon for that to
949 // happen.
950 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
951 if (CI->getType()->isIntegerTy(8))
952 return getIntSequenceIfElementsMatch<SequenceTy, uint8_t>(V);
953 else if (CI->getType()->isIntegerTy(16))
954 return getIntSequenceIfElementsMatch<SequenceTy, uint16_t>(V);
955 else if (CI->getType()->isIntegerTy(32))
956 return getIntSequenceIfElementsMatch<SequenceTy, uint32_t>(V);
957 else if (CI->getType()->isIntegerTy(64))
958 return getIntSequenceIfElementsMatch<SequenceTy, uint64_t>(V);
959 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
Justin Bogner0ebc8602015-12-08 03:01:16 +0000960 if (CFP->getType()->isHalfTy())
961 return getFPSequenceIfElementsMatch<SequenceTy, uint16_t>(V);
962 else if (CFP->getType()->isFloatTy())
Justin Bogner909e1c02015-12-01 20:20:49 +0000963 return getFPSequenceIfElementsMatch<SequenceTy, uint32_t>(V);
964 else if (CFP->getType()->isDoubleTy())
965 return getFPSequenceIfElementsMatch<SequenceTy, uint64_t>(V);
966 }
967
968 return nullptr;
969}
970
Duncan P. N. Exon Smith1de3c7e2016-04-05 21:10:45 +0000971ConstantAggregate::ConstantAggregate(CompositeType *T, ValueTy VT,
972 ArrayRef<Constant *> V)
973 : Constant(T, VT, OperandTraits<ConstantAggregate>::op_end(this) - V.size(),
974 V.size()) {
Fangrui Song75709322018-11-17 01:44:25 +0000975 llvm::copy(V, op_begin());
Duncan P. N. Exon Smith1de3c7e2016-04-05 21:10:45 +0000976
977 // Check that types match, unless this is an opaque struct.
978 if (auto *ST = dyn_cast<StructType>(T))
979 if (ST->isOpaque())
980 return;
981 for (unsigned I = 0, E = V.size(); I != E; ++I)
982 assert(V[I]->getType() == T->getTypeAtIndex(I) &&
983 "Initializer for composite element doesn't match!");
984}
985
986ConstantArray::ConstantArray(ArrayType *T, ArrayRef<Constant *> V)
987 : ConstantAggregate(T, ConstantArrayVal, V) {
988 assert(V.size() == T->getNumElements() &&
989 "Invalid initializer for constant array");
Chris Lattner2f7c9632001-06-06 20:29:01 +0000990}
991
Chris Lattner229907c2011-07-18 04:54:35 +0000992Constant *ConstantArray::get(ArrayType *Ty, ArrayRef<Constant*> V) {
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +0000993 if (Constant *C = getImpl(Ty, V))
994 return C;
995 return Ty->getContext().pImpl->ArrayConstants.getOrCreate(Ty, V);
996}
Justin Bogner909e1c02015-12-01 20:20:49 +0000997
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +0000998Constant *ConstantArray::getImpl(ArrayType *Ty, ArrayRef<Constant*> V) {
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000999 // Empty arrays are canonicalized to ConstantAggregateZero.
1000 if (V.empty())
1001 return ConstantAggregateZero::get(Ty);
1002
Jeffrey Yasskin8ce67f82009-09-30 21:08:08 +00001003 for (unsigned i = 0, e = V.size(); i != e; ++i) {
1004 assert(V[i]->getType() == Ty->getElementType() &&
1005 "Wrong type in array element initializer");
1006 }
Galina Kistanovafc259902012-07-13 01:25:27 +00001007
Chris Lattnercf9e8f62012-02-05 02:29:43 +00001008 // If this is an all-zero array, return a ConstantAggregateZero object. If
1009 // all undef, return an UndefValue, if "all simple", then return a
1010 // ConstantDataArray.
1011 Constant *C = V[0];
1012 if (isa<UndefValue>(C) && rangeOnlyContains(V.begin(), V.end(), C))
1013 return UndefValue::get(Ty);
Chris Lattnerf14a67f2012-01-26 02:31:22 +00001014
Chris Lattnercf9e8f62012-02-05 02:29:43 +00001015 if (C->isNullValue() && rangeOnlyContains(V.begin(), V.end(), C))
1016 return ConstantAggregateZero::get(Ty);
1017
1018 // Check to see if all of the elements are ConstantFP or ConstantInt and if
1019 // the element type is compatible with ConstantDataVector. If so, use it.
Justin Bogner909e1c02015-12-01 20:20:49 +00001020 if (ConstantDataSequential::isElementTypeCompatible(C->getType()))
1021 return getSequenceIfElementsMatch<ConstantDataArray>(C, V);
Chris Lattnerf14a67f2012-01-26 02:31:22 +00001022
Chris Lattnercf9e8f62012-02-05 02:29:43 +00001023 // Otherwise, we really do want to create a ConstantArray.
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00001024 return nullptr;
Owen Andersonc2c79322009-07-28 18:32:17 +00001025}
1026
Chris Lattnercc19efa2011-06-20 04:01:31 +00001027StructType *ConstantStruct::getTypeForElements(LLVMContext &Context,
1028 ArrayRef<Constant*> V,
1029 bool Packed) {
Bill Wendling3ae7dd32012-02-07 01:27:51 +00001030 unsigned VecSize = V.size();
1031 SmallVector<Type*, 16> EltTypes(VecSize);
1032 for (unsigned i = 0; i != VecSize; ++i)
1033 EltTypes[i] = V[i]->getType();
Galina Kistanovafc259902012-07-13 01:25:27 +00001034
Chris Lattnercc19efa2011-06-20 04:01:31 +00001035 return StructType::get(Context, EltTypes, Packed);
1036}
1037
1038
1039StructType *ConstantStruct::getTypeForElements(ArrayRef<Constant*> V,
1040 bool Packed) {
1041 assert(!V.empty() &&
1042 "ConstantStruct::getTypeForElements cannot be called on empty list");
1043 return getTypeForElements(V[0]->getContext(), V, Packed);
1044}
1045
Jay Foad89d9b812011-07-25 10:14:44 +00001046ConstantStruct::ConstantStruct(StructType *T, ArrayRef<Constant *> V)
Duncan P. N. Exon Smith1de3c7e2016-04-05 21:10:45 +00001047 : ConstantAggregate(T, ConstantStructVal, V) {
1048 assert((T->isOpaque() || V.size() == T->getNumElements()) &&
1049 "Invalid initializer for constant struct");
Chris Lattner2f7c9632001-06-06 20:29:01 +00001050}
1051
Owen Anderson45308b52009-07-27 22:29:26 +00001052// ConstantStruct accessors.
Chris Lattner229907c2011-07-18 04:54:35 +00001053Constant *ConstantStruct::get(StructType *ST, ArrayRef<Constant*> V) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001054 assert((ST->isOpaque() || ST->getNumElements() == V.size()) &&
1055 "Incorrect # elements specified to ConstantStruct::get");
Chris Lattnerf14a67f2012-01-26 02:31:22 +00001056
1057 // Create a ConstantAggregateZero value if all elements are zeros.
1058 bool isZero = true;
1059 bool isUndef = false;
Bjorn Petterssonaa025802018-07-03 12:39:52 +00001060
Chris Lattnerf14a67f2012-01-26 02:31:22 +00001061 if (!V.empty()) {
1062 isUndef = isa<UndefValue>(V[0]);
1063 isZero = V[0]->isNullValue();
1064 if (isUndef || isZero) {
1065 for (unsigned i = 0, e = V.size(); i != e; ++i) {
1066 if (!V[i]->isNullValue())
1067 isZero = false;
1068 if (!isa<UndefValue>(V[i]))
1069 isUndef = false;
1070 }
1071 }
Galina Kistanovafc259902012-07-13 01:25:27 +00001072 }
Chris Lattnerf14a67f2012-01-26 02:31:22 +00001073 if (isZero)
1074 return ConstantAggregateZero::get(ST);
1075 if (isUndef)
1076 return UndefValue::get(ST);
Galina Kistanovafc259902012-07-13 01:25:27 +00001077
Chris Lattnerf14a67f2012-01-26 02:31:22 +00001078 return ST->getContext().pImpl->StructConstants.getOrCreate(ST, V);
Owen Anderson45308b52009-07-27 22:29:26 +00001079}
1080
Jay Foad89d9b812011-07-25 10:14:44 +00001081ConstantVector::ConstantVector(VectorType *T, ArrayRef<Constant *> V)
Duncan P. N. Exon Smith1de3c7e2016-04-05 21:10:45 +00001082 : ConstantAggregate(T, ConstantVectorVal, V) {
Duncan P. N. Exon Smithdb63bda2016-04-05 20:53:47 +00001083 assert(V.size() == T->getNumElements() &&
Duncan P. N. Exon Smith1de3c7e2016-04-05 21:10:45 +00001084 "Invalid initializer for constant vector");
Brian Gaeke02209042004-08-20 06:00:58 +00001085}
1086
Owen Anderson4aa32952009-07-28 21:19:26 +00001087// ConstantVector accessors.
Jay Foadb8a8bed32011-06-22 09:10:19 +00001088Constant *ConstantVector::get(ArrayRef<Constant*> V) {
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00001089 if (Constant *C = getImpl(V))
1090 return C;
1091 VectorType *Ty = VectorType::get(V.front()->getType(), V.size());
1092 return Ty->getContext().pImpl->VectorConstants.getOrCreate(Ty, V);
1093}
Justin Bogner909e1c02015-12-01 20:20:49 +00001094
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00001095Constant *ConstantVector::getImpl(ArrayRef<Constant*> V) {
Jay Foad9f32cfd2011-01-27 14:44:55 +00001096 assert(!V.empty() && "Vectors can't be empty");
Chris Lattner229907c2011-07-18 04:54:35 +00001097 VectorType *T = VectorType::get(V.front()->getType(), V.size());
Jay Foad9f32cfd2011-01-27 14:44:55 +00001098
Chris Lattner69229312011-02-15 00:14:00 +00001099 // If this is an all-undef or all-zero vector, return a
Owen Anderson4aa32952009-07-28 21:19:26 +00001100 // ConstantAggregateZero or UndefValue.
1101 Constant *C = V[0];
1102 bool isZero = C->isNullValue();
1103 bool isUndef = isa<UndefValue>(C);
1104
1105 if (isZero || isUndef) {
1106 for (unsigned i = 1, e = V.size(); i != e; ++i)
1107 if (V[i] != C) {
1108 isZero = isUndef = false;
1109 break;
1110 }
1111 }
Galina Kistanovafc259902012-07-13 01:25:27 +00001112
Owen Anderson4aa32952009-07-28 21:19:26 +00001113 if (isZero)
Owen Andersonb292b8c2009-07-30 23:03:37 +00001114 return ConstantAggregateZero::get(T);
Owen Anderson4aa32952009-07-28 21:19:26 +00001115 if (isUndef)
Owen Andersonb292b8c2009-07-30 23:03:37 +00001116 return UndefValue::get(T);
Galina Kistanovafc259902012-07-13 01:25:27 +00001117
Chris Lattner978fe0c2012-01-30 06:21:21 +00001118 // Check to see if all of the elements are ConstantFP or ConstantInt and if
1119 // the element type is compatible with ConstantDataVector. If so, use it.
Justin Bogner909e1c02015-12-01 20:20:49 +00001120 if (ConstantDataSequential::isElementTypeCompatible(C->getType()))
1121 return getSequenceIfElementsMatch<ConstantDataVector>(C, V);
Galina Kistanovafc259902012-07-13 01:25:27 +00001122
Chris Lattner978fe0c2012-01-30 06:21:21 +00001123 // Otherwise, the element type isn't compatible with ConstantDataVector, or
Craig Topperdf907262017-04-11 06:41:55 +00001124 // the operand list contains a ConstantExpr or something else strange.
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00001125 return nullptr;
Owen Anderson4aa32952009-07-28 21:19:26 +00001126}
1127
Chris Lattnere9eed292012-01-25 05:19:54 +00001128Constant *ConstantVector::getSplat(unsigned NumElts, Constant *V) {
Chris Lattner978fe0c2012-01-30 06:21:21 +00001129 // If this splat is compatible with ConstantDataVector, use it instead of
1130 // ConstantVector.
1131 if ((isa<ConstantFP>(V) || isa<ConstantInt>(V)) &&
1132 ConstantDataSequential::isElementTypeCompatible(V->getType()))
1133 return ConstantDataVector::getSplat(NumElts, V);
Galina Kistanovafc259902012-07-13 01:25:27 +00001134
Chris Lattnere9eed292012-01-25 05:19:54 +00001135 SmallVector<Constant*, 32> Elts(NumElts, V);
1136 return get(Elts);
1137}
1138
David Majnemerf0f224d2015-11-11 21:57:16 +00001139ConstantTokenNone *ConstantTokenNone::get(LLVMContext &Context) {
1140 LLVMContextImpl *pImpl = Context.pImpl;
1141 if (!pImpl->TheNoneToken)
David Majnemer2dd41c52015-11-16 20:55:57 +00001142 pImpl->TheNoneToken.reset(new ConstantTokenNone(Context));
1143 return pImpl->TheNoneToken.get();
David Majnemerf0f224d2015-11-11 21:57:16 +00001144}
1145
1146/// Remove the constant from the constant table.
1147void ConstantTokenNone::destroyConstantImpl() {
1148 llvm_unreachable("You can't ConstantTokenNone->destroyConstantImpl()!");
1149}
Chris Lattnere9eed292012-01-25 05:19:54 +00001150
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001151// Utility function for determining if a ConstantExpr is a CastOp or not. This
1152// can't be inline because we don't want to #include Instruction.h into
1153// Constant.h
1154bool ConstantExpr::isCast() const {
1155 return Instruction::isCast(getOpcode());
1156}
1157
Reid Spenceree3c9912006-12-04 05:19:50 +00001158bool ConstantExpr::isCompare() const {
Nick Lewyckya21d3da2009-07-08 03:04:38 +00001159 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
Reid Spenceree3c9912006-12-04 05:19:50 +00001160}
1161
Dan Gohman7190d482009-09-10 23:37:55 +00001162bool ConstantExpr::isGEPWithNoNotionalOverIndexing() const {
1163 if (getOpcode() != Instruction::GetElementPtr) return false;
1164
1165 gep_type_iterator GEPI = gep_type_begin(this), E = gep_type_end(this);
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001166 User::const_op_iterator OI = std::next(this->op_begin());
Dan Gohman7190d482009-09-10 23:37:55 +00001167
Sanjay Patel81ed3492016-12-11 20:07:02 +00001168 // The remaining indices may be compile-time known integers within the bounds
1169 // of the corresponding notional static array types.
Dan Gohman7190d482009-09-10 23:37:55 +00001170 for (; GEPI != E; ++GEPI, ++OI) {
Sanjay Patel81ed3492016-12-11 20:07:02 +00001171 if (isa<UndefValue>(*OI))
1172 continue;
1173 auto *CI = dyn_cast<ConstantInt>(*OI);
1174 if (!CI || (GEPI.isBoundedSequential() &&
1175 (CI->getValue().getActiveBits() > 64 ||
1176 CI->getZExtValue() >= GEPI.getSequentialNumElements())))
Peter Collingbourneab85225b2016-12-02 02:24:42 +00001177 return false;
Dan Gohman7190d482009-09-10 23:37:55 +00001178 }
1179
1180 // All the indices checked out.
1181 return true;
1182}
1183
Dan Gohman1ecaf452008-05-31 00:58:22 +00001184bool ConstantExpr::hasIndices() const {
1185 return getOpcode() == Instruction::ExtractValue ||
1186 getOpcode() == Instruction::InsertValue;
1187}
1188
Jay Foad0091fe82011-04-13 15:22:40 +00001189ArrayRef<unsigned> ConstantExpr::getIndices() const {
Dan Gohman1ecaf452008-05-31 00:58:22 +00001190 if (const ExtractValueConstantExpr *EVCE =
1191 dyn_cast<ExtractValueConstantExpr>(this))
1192 return EVCE->Indices;
Dan Gohmana469bdb2008-06-23 16:39:44 +00001193
1194 return cast<InsertValueConstantExpr>(this)->Indices;
Dan Gohman1ecaf452008-05-31 00:58:22 +00001195}
1196
Reid Spencer10fbf0e2006-12-03 05:48:19 +00001197unsigned ConstantExpr::getPredicate() const {
Craig Toppercc03b492015-12-15 06:11:36 +00001198 return cast<CompareConstantExpr>(this)->predicate;
Reid Spencer10fbf0e2006-12-03 05:48:19 +00001199}
Chris Lattner60e0dd72001-10-03 06:12:09 +00001200
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001201Constant *
1202ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
Chris Lattner7c1018a2006-07-14 19:37:40 +00001203 assert(Op->getType() == getOperand(OpNo)->getType() &&
1204 "Replacing operand with value of different type!");
Chris Lattner227816342006-07-14 22:20:01 +00001205 if (getOperand(OpNo) == Op)
1206 return const_cast<ConstantExpr*>(this);
Chris Lattner37e38352012-01-26 20:37:11 +00001207
1208 SmallVector<Constant*, 8> NewOps;
1209 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1210 NewOps.push_back(i == OpNo ? Op : getOperand(i));
Galina Kistanovafc259902012-07-13 01:25:27 +00001211
Chris Lattner37e38352012-01-26 20:37:11 +00001212 return getWithOperands(NewOps);
Chris Lattner227816342006-07-14 22:20:01 +00001213}
1214
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001215Constant *ConstantExpr::getWithOperands(ArrayRef<Constant *> Ops, Type *Ty,
David Blaikie88208842015-08-21 20:16:51 +00001216 bool OnlyIfReduced, Type *SrcTy) const {
Jay Foad5c984e562011-04-13 13:46:01 +00001217 assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
Galina Kistanovafc259902012-07-13 01:25:27 +00001218
Benjamin Kramer8008e9f2015-03-02 11:57:04 +00001219 // If no operands changed return self.
1220 if (Ty == getType() && std::equal(Ops.begin(), Ops.end(), op_begin()))
Chris Lattner227816342006-07-14 22:20:01 +00001221 return const_cast<ConstantExpr*>(this);
1222
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001223 Type *OnlyIfReducedTy = OnlyIfReduced ? Ty : nullptr;
Chris Lattner227816342006-07-14 22:20:01 +00001224 switch (getOpcode()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001225 case Instruction::Trunc:
1226 case Instruction::ZExt:
1227 case Instruction::SExt:
1228 case Instruction::FPTrunc:
1229 case Instruction::FPExt:
1230 case Instruction::UIToFP:
1231 case Instruction::SIToFP:
1232 case Instruction::FPToUI:
1233 case Instruction::FPToSI:
1234 case Instruction::PtrToInt:
1235 case Instruction::IntToPtr:
1236 case Instruction::BitCast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00001237 case Instruction::AddrSpaceCast:
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001238 return ConstantExpr::getCast(getOpcode(), Ops[0], Ty, OnlyIfReduced);
Chris Lattner227816342006-07-14 22:20:01 +00001239 case Instruction::Select:
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001240 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2], OnlyIfReducedTy);
Chris Lattner227816342006-07-14 22:20:01 +00001241 case Instruction::InsertElement:
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001242 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2],
1243 OnlyIfReducedTy);
Chris Lattner227816342006-07-14 22:20:01 +00001244 case Instruction::ExtractElement:
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001245 return ConstantExpr::getExtractElement(Ops[0], Ops[1], OnlyIfReducedTy);
Chris Lattner37e38352012-01-26 20:37:11 +00001246 case Instruction::InsertValue:
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001247 return ConstantExpr::getInsertValue(Ops[0], Ops[1], getIndices(),
1248 OnlyIfReducedTy);
Chris Lattner37e38352012-01-26 20:37:11 +00001249 case Instruction::ExtractValue:
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001250 return ConstantExpr::getExtractValue(Ops[0], getIndices(), OnlyIfReducedTy);
Chris Lattner227816342006-07-14 22:20:01 +00001251 case Instruction::ShuffleVector:
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001252 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2],
1253 OnlyIfReducedTy);
David Blaikie88208842015-08-21 20:16:51 +00001254 case Instruction::GetElementPtr: {
1255 auto *GEPO = cast<GEPOperator>(this);
1256 assert(SrcTy || (Ops[0]->getType() == getOperand(0)->getType()));
1257 return ConstantExpr::getGetElementPtr(
1258 SrcTy ? SrcTy : GEPO->getSourceElementType(), Ops[0], Ops.slice(1),
Peter Collingbourned93620b2016-11-10 22:34:55 +00001259 GEPO->isInBounds(), GEPO->getInRangeIndex(), OnlyIfReducedTy);
David Blaikie88208842015-08-21 20:16:51 +00001260 }
Reid Spencer266e42b2006-12-23 06:05:41 +00001261 case Instruction::ICmp:
1262 case Instruction::FCmp:
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001263 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1],
1264 OnlyIfReducedTy);
Chris Lattner227816342006-07-14 22:20:01 +00001265 default:
1266 assert(getNumOperands() == 2 && "Must be binary operator?");
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001267 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1], SubclassOptionalData,
1268 OnlyIfReducedTy);
Chris Lattner7c1018a2006-07-14 19:37:40 +00001269 }
1270}
1271
Chris Lattner2f7c9632001-06-06 20:29:01 +00001272
1273//===----------------------------------------------------------------------===//
Chris Lattner2f7c9632001-06-06 20:29:01 +00001274// isValueValidForType implementations
1275
Chris Lattner229907c2011-07-18 04:54:35 +00001276bool ConstantInt::isValueValidForType(Type *Ty, uint64_t Val) {
Chris Lattner8326bd82012-01-26 00:42:34 +00001277 unsigned NumBits = Ty->getIntegerBitWidth(); // assert okay
1278 if (Ty->isIntegerTy(1))
Reid Spencer7a9c62b2007-01-12 07:05:14 +00001279 return Val == 0 || Val == 1;
Craig Topper50b1e512017-06-07 00:58:05 +00001280 return isUIntN(NumBits, Val);
Reid Spencere7334722006-12-19 01:28:19 +00001281}
1282
Chris Lattner229907c2011-07-18 04:54:35 +00001283bool ConstantInt::isValueValidForType(Type *Ty, int64_t Val) {
Chris Lattner8326bd82012-01-26 00:42:34 +00001284 unsigned NumBits = Ty->getIntegerBitWidth();
1285 if (Ty->isIntegerTy(1))
Reid Spencera94d3942007-01-19 21:13:56 +00001286 return Val == 0 || Val == 1 || Val == -1;
Craig Topper50b1e512017-06-07 00:58:05 +00001287 return isIntN(NumBits, Val);
Chris Lattner2f7c9632001-06-06 20:29:01 +00001288}
1289
Chris Lattner229907c2011-07-18 04:54:35 +00001290bool ConstantFP::isValueValidForType(Type *Ty, const APFloat& Val) {
Dale Johannesend246b2c2007-08-30 00:23:21 +00001291 // convert modifies in place, so make a copy.
1292 APFloat Val2 = APFloat(Val);
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001293 bool losesInfo;
Chris Lattner6b727592004-06-17 18:19:28 +00001294 switch (Ty->getTypeID()) {
Chris Lattner2f7c9632001-06-06 20:29:01 +00001295 default:
1296 return false; // These can't be represented as floating point!
1297
Dale Johannesend246b2c2007-08-30 00:23:21 +00001298 // FIXME rounding mode needs to be more flexible
Dan Gohman518cda42011-12-17 00:04:22 +00001299 case Type::HalfTyID: {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001300 if (&Val2.getSemantics() == &APFloat::IEEEhalf())
Dan Gohman518cda42011-12-17 00:04:22 +00001301 return true;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001302 Val2.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven, &losesInfo);
Dan Gohman518cda42011-12-17 00:04:22 +00001303 return !losesInfo;
1304 }
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001305 case Type::FloatTyID: {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001306 if (&Val2.getSemantics() == &APFloat::IEEEsingle())
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001307 return true;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001308 Val2.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, &losesInfo);
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001309 return !losesInfo;
1310 }
1311 case Type::DoubleTyID: {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001312 if (&Val2.getSemantics() == &APFloat::IEEEhalf() ||
1313 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
1314 &Val2.getSemantics() == &APFloat::IEEEdouble())
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001315 return true;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001316 Val2.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven, &losesInfo);
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001317 return !losesInfo;
1318 }
Dale Johannesenbdad8092007-08-09 22:51:36 +00001319 case Type::X86_FP80TyID:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001320 return &Val2.getSemantics() == &APFloat::IEEEhalf() ||
Bjorn Petterssonaa025802018-07-03 12:39:52 +00001321 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001322 &Val2.getSemantics() == &APFloat::IEEEdouble() ||
1323 &Val2.getSemantics() == &APFloat::x87DoubleExtended();
Dale Johannesenbdad8092007-08-09 22:51:36 +00001324 case Type::FP128TyID:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001325 return &Val2.getSemantics() == &APFloat::IEEEhalf() ||
Bjorn Petterssonaa025802018-07-03 12:39:52 +00001326 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001327 &Val2.getSemantics() == &APFloat::IEEEdouble() ||
1328 &Val2.getSemantics() == &APFloat::IEEEquad();
Dale Johannesen007aa372007-10-11 18:07:22 +00001329 case Type::PPC_FP128TyID:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001330 return &Val2.getSemantics() == &APFloat::IEEEhalf() ||
Bjorn Petterssonaa025802018-07-03 12:39:52 +00001331 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001332 &Val2.getSemantics() == &APFloat::IEEEdouble() ||
1333 &Val2.getSemantics() == &APFloat::PPCDoubleDouble();
Chris Lattner2f7c9632001-06-06 20:29:01 +00001334 }
Chris Lattneraa2372562006-05-24 17:04:05 +00001335}
Chris Lattner9655e542001-07-20 19:16:02 +00001336
Chris Lattner030af792012-01-24 05:42:11 +00001337
Chris Lattner49d855c2001-09-07 16:46:31 +00001338//===----------------------------------------------------------------------===//
Chris Lattner49d855c2001-09-07 16:46:31 +00001339// Factory Function Implementation
1340
Chris Lattnerc7f9fd42012-01-23 15:20:12 +00001341ConstantAggregateZero *ConstantAggregateZero::get(Type *Ty) {
Chris Lattner13ee7952010-08-28 04:09:24 +00001342 assert((Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()) &&
Owen Andersonb292b8c2009-07-30 23:03:37 +00001343 "Cannot create an aggregate zero of non-aggregate type!");
David Blaikie899b85a2014-11-25 02:13:54 +00001344
Justin Lebar611c5c22016-10-10 16:26:13 +00001345 std::unique_ptr<ConstantAggregateZero> &Entry =
1346 Ty->getContext().pImpl->CAZConstants[Ty];
1347 if (!Entry)
1348 Entry.reset(new ConstantAggregateZero(Ty));
1349
1350 return Entry.get();
Owen Andersonb292b8c2009-07-30 23:03:37 +00001351}
1352
Sanjay Patel1d0ac7c2016-04-29 22:03:27 +00001353/// Remove the constant from the constant table.
Pete Cooper86dd4cf2015-06-23 21:55:11 +00001354void ConstantAggregateZero::destroyConstantImpl() {
Chris Lattnerc7f9fd42012-01-23 15:20:12 +00001355 getContext().pImpl->CAZConstants.erase(getType());
Chris Lattner9fba3da2004-02-15 05:53:04 +00001356}
1357
Sanjay Patel1d0ac7c2016-04-29 22:03:27 +00001358/// Remove the constant from the constant table.
Pete Cooper86dd4cf2015-06-23 21:55:11 +00001359void ConstantArray::destroyConstantImpl() {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001360 getType()->getContext().pImpl->ArrayConstants.remove(this);
Chris Lattner98fa07b2003-05-23 20:03:32 +00001361}
1362
Chris Lattner81fabb02002-08-26 17:53:56 +00001363
Chris Lattner3462ae32001-12-03 22:26:30 +00001364//---- ConstantStruct::get() implementation...
Chris Lattner49d855c2001-09-07 16:46:31 +00001365//
Chris Lattnerb50d1352003-10-05 00:17:43 +00001366
Sanjay Patel1d0ac7c2016-04-29 22:03:27 +00001367/// Remove the constant from the constant table.
Pete Cooper86dd4cf2015-06-23 21:55:11 +00001368void ConstantStruct::destroyConstantImpl() {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001369 getType()->getContext().pImpl->StructConstants.remove(this);
Chris Lattnerd7a73302001-10-13 06:57:33 +00001370}
Chris Lattner883ad0b2001-10-03 15:39:36 +00001371
Sanjay Patel1d0ac7c2016-04-29 22:03:27 +00001372/// Remove the constant from the constant table.
Pete Cooper86dd4cf2015-06-23 21:55:11 +00001373void ConstantVector::destroyConstantImpl() {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001374 getType()->getContext().pImpl->VectorConstants.remove(this);
Brian Gaeke02209042004-08-20 06:00:58 +00001375}
1376
Duncan Sandse6beec62012-11-13 12:59:33 +00001377Constant *Constant::getSplatValue() const {
1378 assert(this->getType()->isVectorTy() && "Only valid for vectors!");
1379 if (isa<ConstantAggregateZero>(this))
1380 return getNullValue(this->getType()->getVectorElementType());
1381 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
1382 return CV->getSplatValue();
1383 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
1384 return CV->getSplatValue();
Craig Topperc6207612014-04-09 06:08:46 +00001385 return nullptr;
Duncan Sandse6beec62012-11-13 12:59:33 +00001386}
1387
Duncan Sandscf0ff032011-02-01 08:39:12 +00001388Constant *ConstantVector::getSplatValue() const {
Dan Gohman07159202007-10-17 17:51:30 +00001389 // Check out first element.
1390 Constant *Elt = getOperand(0);
1391 // Then make sure all remaining elements point to the same value.
1392 for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
Chris Lattnerd04e32d2011-07-17 06:01:30 +00001393 if (getOperand(I) != Elt)
Craig Topperc6207612014-04-09 06:08:46 +00001394 return nullptr;
Dan Gohman07159202007-10-17 17:51:30 +00001395 return Elt;
1396}
1397
Duncan Sandse6beec62012-11-13 12:59:33 +00001398const APInt &Constant::getUniqueInteger() const {
1399 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
1400 return CI->getValue();
1401 assert(this->getSplatValue() && "Doesn't contain a unique integer!");
1402 const Constant *C = this->getAggregateElement(0U);
1403 assert(C && isa<ConstantInt>(C) && "Not a vector of numbers!");
1404 return cast<ConstantInt>(C)->getValue();
1405}
1406
Chris Lattner31b132c2009-10-28 00:01:44 +00001407//---- ConstantPointerNull::get() implementation.
Chris Lattnerd7a73302001-10-13 06:57:33 +00001408//
Chris Lattner98fa07b2003-05-23 20:03:32 +00001409
Chris Lattner229907c2011-07-18 04:54:35 +00001410ConstantPointerNull *ConstantPointerNull::get(PointerType *Ty) {
Justin Lebar611c5c22016-10-10 16:26:13 +00001411 std::unique_ptr<ConstantPointerNull> &Entry =
1412 Ty->getContext().pImpl->CPNConstants[Ty];
Craig Topperc6207612014-04-09 06:08:46 +00001413 if (!Entry)
Justin Lebar611c5c22016-10-10 16:26:13 +00001414 Entry.reset(new ConstantPointerNull(Ty));
Galina Kistanovafc259902012-07-13 01:25:27 +00001415
Justin Lebar611c5c22016-10-10 16:26:13 +00001416 return Entry.get();
Chris Lattner883ad0b2001-10-03 15:39:36 +00001417}
1418
Sanjay Patel1d0ac7c2016-04-29 22:03:27 +00001419/// Remove the constant from the constant table.
Pete Cooper86dd4cf2015-06-23 21:55:11 +00001420void ConstantPointerNull::destroyConstantImpl() {
Chris Lattnerc7f9fd42012-01-23 15:20:12 +00001421 getContext().pImpl->CPNConstants.erase(getType());
Chris Lattner0c6e0b92002-08-18 00:40:04 +00001422}
1423
Chris Lattner229907c2011-07-18 04:54:35 +00001424UndefValue *UndefValue::get(Type *Ty) {
Justin Lebar611c5c22016-10-10 16:26:13 +00001425 std::unique_ptr<UndefValue> &Entry = Ty->getContext().pImpl->UVConstants[Ty];
Craig Topperc6207612014-04-09 06:08:46 +00001426 if (!Entry)
Justin Lebar611c5c22016-10-10 16:26:13 +00001427 Entry.reset(new UndefValue(Ty));
Galina Kistanovafc259902012-07-13 01:25:27 +00001428
Justin Lebar611c5c22016-10-10 16:26:13 +00001429 return Entry.get();
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001430}
1431
Sanjay Patel1d0ac7c2016-04-29 22:03:27 +00001432/// Remove the constant from the constant table.
Pete Cooper86dd4cf2015-06-23 21:55:11 +00001433void UndefValue::destroyConstantImpl() {
Chris Lattnerc7f9fd42012-01-23 15:20:12 +00001434 // Free the constant and any dangling references to it.
1435 getContext().pImpl->UVConstants.erase(getType());
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001436}
1437
Chris Lattner31b132c2009-10-28 00:01:44 +00001438BlockAddress *BlockAddress::get(BasicBlock *BB) {
Craig Topper2617dcc2014-04-15 06:32:26 +00001439 assert(BB->getParent() && "Block must have a parent");
Chris Lattner31b132c2009-10-28 00:01:44 +00001440 return get(BB->getParent(), BB);
1441}
1442
1443BlockAddress *BlockAddress::get(Function *F, BasicBlock *BB) {
1444 BlockAddress *&BA =
1445 F->getContext().pImpl->BlockAddresses[std::make_pair(F, BB)];
Craig Topperc6207612014-04-09 06:08:46 +00001446 if (!BA)
Chris Lattner31b132c2009-10-28 00:01:44 +00001447 BA = new BlockAddress(F, BB);
Galina Kistanovafc259902012-07-13 01:25:27 +00001448
Chris Lattner31b132c2009-10-28 00:01:44 +00001449 assert(BA->getFunction() == F && "Basic block moved between functions");
1450 return BA;
1451}
1452
1453BlockAddress::BlockAddress(Function *F, BasicBlock *BB)
1454: Constant(Type::getInt8PtrTy(F->getContext()), Value::BlockAddressVal,
1455 &Op<0>(), 2) {
Chris Lattnerc559a9f2009-11-01 03:03:03 +00001456 setOperand(0, F);
1457 setOperand(1, BB);
Chris Lattneraa99c942009-11-01 01:27:45 +00001458 BB->AdjustBlockAddressRefCount(1);
Chris Lattner31b132c2009-10-28 00:01:44 +00001459}
1460
Chandler Carruth6a936922014-01-19 02:13:50 +00001461BlockAddress *BlockAddress::lookup(const BasicBlock *BB) {
1462 if (!BB->hasAddressTaken())
Craig Topperc6207612014-04-09 06:08:46 +00001463 return nullptr;
Chandler Carruth6a936922014-01-19 02:13:50 +00001464
1465 const Function *F = BB->getParent();
Craig Topper2617dcc2014-04-15 06:32:26 +00001466 assert(F && "Block must have a parent");
Chandler Carruth6a936922014-01-19 02:13:50 +00001467 BlockAddress *BA =
1468 F->getContext().pImpl->BlockAddresses.lookup(std::make_pair(F, BB));
1469 assert(BA && "Refcount and block address map disagree!");
1470 return BA;
1471}
Chris Lattner31b132c2009-10-28 00:01:44 +00001472
Sanjay Patel1d0ac7c2016-04-29 22:03:27 +00001473/// Remove the constant from the constant table.
Pete Cooper86dd4cf2015-06-23 21:55:11 +00001474void BlockAddress::destroyConstantImpl() {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001475 getFunction()->getType()->getContext().pImpl
Chris Lattner31b132c2009-10-28 00:01:44 +00001476 ->BlockAddresses.erase(std::make_pair(getFunction(), getBasicBlock()));
Chris Lattneraa99c942009-11-01 01:27:45 +00001477 getBasicBlock()->AdjustBlockAddressRefCount(-1);
Chris Lattner31b132c2009-10-28 00:01:44 +00001478}
1479
Mehdi Amini8914d292016-02-10 22:47:15 +00001480Value *BlockAddress::handleOperandChangeImpl(Value *From, Value *To) {
Chris Lattner31b132c2009-10-28 00:01:44 +00001481 // This could be replacing either the Basic Block or the Function. In either
1482 // case, we have to remove the map entry.
1483 Function *NewF = getFunction();
1484 BasicBlock *NewBB = getBasicBlock();
Galina Kistanovafc259902012-07-13 01:25:27 +00001485
Mehdi Amini8914d292016-02-10 22:47:15 +00001486 if (From == NewF)
Derek Schuffec9dc012013-06-13 19:51:17 +00001487 NewF = cast<Function>(To->stripPointerCasts());
Mehdi Amini8914d292016-02-10 22:47:15 +00001488 else {
1489 assert(From == NewBB && "From does not match any operand");
Chris Lattner31b132c2009-10-28 00:01:44 +00001490 NewBB = cast<BasicBlock>(To);
Mehdi Amini8914d292016-02-10 22:47:15 +00001491 }
Galina Kistanovafc259902012-07-13 01:25:27 +00001492
Chris Lattner31b132c2009-10-28 00:01:44 +00001493 // See if the 'new' entry already exists, if not, just update this in place
1494 // and return early.
1495 BlockAddress *&NewBA =
1496 getContext().pImpl->BlockAddresses[std::make_pair(NewF, NewBB)];
Pete Cooper5815b1f2015-06-24 18:55:24 +00001497 if (NewBA)
1498 return NewBA;
Chris Lattner31b132c2009-10-28 00:01:44 +00001499
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00001500 getBasicBlock()->AdjustBlockAddressRefCount(-1);
Galina Kistanovafc259902012-07-13 01:25:27 +00001501
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00001502 // Remove the old entry, this can't cause the map to rehash (just a
1503 // tombstone will get added).
1504 getContext().pImpl->BlockAddresses.erase(std::make_pair(getFunction(),
1505 getBasicBlock()));
1506 NewBA = this;
1507 setOperand(0, NewF);
1508 setOperand(1, NewBB);
1509 getBasicBlock()->AdjustBlockAddressRefCount(1);
Pete Cooper5815b1f2015-06-24 18:55:24 +00001510
1511 // If we just want to keep the existing value, then return null.
1512 // Callers know that this means we shouldn't delete this value.
1513 return nullptr;
Chris Lattner31b132c2009-10-28 00:01:44 +00001514}
1515
1516//---- ConstantExpr::get() implementations.
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001517//
Reid Spencer8d9336d2006-12-31 05:26:44 +00001518
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001519/// This is a utility function to handle folding of casts and lookup of the
Duncan Sands7d6c8ae2008-03-30 19:38:55 +00001520/// cast in the ExprConstants map. It is used by the various get* methods below.
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001521static Constant *getFoldedCast(Instruction::CastOps opc, Constant *C, Type *Ty,
1522 bool OnlyIfReduced = false) {
Chris Lattner815ae2b2003-10-07 22:19:19 +00001523 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001524 // Fold a few common cases
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00001525 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001526 return FC;
Chris Lattneracdbe712003-04-17 19:24:48 +00001527
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001528 if (OnlyIfReduced)
1529 return nullptr;
1530
Owen Anderson1584a292009-08-04 20:25:11 +00001531 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
1532
Nadav Rotem88330432013-03-07 01:30:40 +00001533 // Look up the constant in the table first to ensure uniqueness.
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00001534 ConstantExprKeyType Key(opc, C);
Galina Kistanovafc259902012-07-13 01:25:27 +00001535
Owen Anderson1584a292009-08-04 20:25:11 +00001536 return pImpl->ExprConstants.getOrCreate(Ty, Key);
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001537}
Galina Kistanovafc259902012-07-13 01:25:27 +00001538
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001539Constant *ConstantExpr::getCast(unsigned oc, Constant *C, Type *Ty,
1540 bool OnlyIfReduced) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001541 Instruction::CastOps opc = Instruction::CastOps(oc);
1542 assert(Instruction::isCast(opc) && "opcode out of range");
1543 assert(C && Ty && "Null arguments to getCast");
Chris Lattner37bc78a2010-01-26 21:51:43 +00001544 assert(CastInst::castIsValid(opc, C, Ty) && "Invalid constantexpr cast!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001545
1546 switch (opc) {
Chris Lattner37bc78a2010-01-26 21:51:43 +00001547 default:
1548 llvm_unreachable("Invalid cast opcode");
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001549 case Instruction::Trunc:
1550 return getTrunc(C, Ty, OnlyIfReduced);
1551 case Instruction::ZExt:
1552 return getZExt(C, Ty, OnlyIfReduced);
1553 case Instruction::SExt:
1554 return getSExt(C, Ty, OnlyIfReduced);
1555 case Instruction::FPTrunc:
1556 return getFPTrunc(C, Ty, OnlyIfReduced);
1557 case Instruction::FPExt:
1558 return getFPExtend(C, Ty, OnlyIfReduced);
1559 case Instruction::UIToFP:
1560 return getUIToFP(C, Ty, OnlyIfReduced);
1561 case Instruction::SIToFP:
1562 return getSIToFP(C, Ty, OnlyIfReduced);
1563 case Instruction::FPToUI:
1564 return getFPToUI(C, Ty, OnlyIfReduced);
1565 case Instruction::FPToSI:
1566 return getFPToSI(C, Ty, OnlyIfReduced);
1567 case Instruction::PtrToInt:
1568 return getPtrToInt(C, Ty, OnlyIfReduced);
1569 case Instruction::IntToPtr:
1570 return getIntToPtr(C, Ty, OnlyIfReduced);
1571 case Instruction::BitCast:
1572 return getBitCast(C, Ty, OnlyIfReduced);
1573 case Instruction::AddrSpaceCast:
1574 return getAddrSpaceCast(C, Ty, OnlyIfReduced);
Chris Lattner1ece6f82005-01-01 15:59:57 +00001575 }
Galina Kistanovafc259902012-07-13 01:25:27 +00001576}
Reid Spencerf37dc652006-12-05 19:14:13 +00001577
Chris Lattner229907c2011-07-18 04:54:35 +00001578Constant *ConstantExpr::getZExtOrBitCast(Constant *C, Type *Ty) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001579 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
Dan Gohman3cdcc3f2010-04-12 22:12:29 +00001580 return getBitCast(C, Ty);
1581 return getZExt(C, Ty);
Reid Spencer5c140882006-12-04 20:17:56 +00001582}
1583
Chris Lattner229907c2011-07-18 04:54:35 +00001584Constant *ConstantExpr::getSExtOrBitCast(Constant *C, Type *Ty) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001585 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
Dan Gohman3cdcc3f2010-04-12 22:12:29 +00001586 return getBitCast(C, Ty);
1587 return getSExt(C, Ty);
Reid Spencer5c140882006-12-04 20:17:56 +00001588}
1589
Chris Lattner229907c2011-07-18 04:54:35 +00001590Constant *ConstantExpr::getTruncOrBitCast(Constant *C, Type *Ty) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001591 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
Dan Gohman3cdcc3f2010-04-12 22:12:29 +00001592 return getBitCast(C, Ty);
1593 return getTrunc(C, Ty);
Reid Spencer5c140882006-12-04 20:17:56 +00001594}
1595
Chris Lattner229907c2011-07-18 04:54:35 +00001596Constant *ConstantExpr::getPointerCast(Constant *S, Type *Ty) {
Evgeniy Stepanov23382642013-01-16 14:41:46 +00001597 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
1598 assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
1599 "Invalid cast");
Reid Spencerbc245a02006-12-05 03:25:26 +00001600
Evgeniy Stepanov23382642013-01-16 14:41:46 +00001601 if (Ty->isIntOrIntVectorTy())
Dan Gohman3cdcc3f2010-04-12 22:12:29 +00001602 return getPtrToInt(S, Ty);
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00001603
1604 unsigned SrcAS = S->getType()->getPointerAddressSpace();
1605 if (Ty->isPtrOrPtrVectorTy() && SrcAS != Ty->getPointerAddressSpace())
1606 return getAddrSpaceCast(S, Ty);
1607
Dan Gohman3cdcc3f2010-04-12 22:12:29 +00001608 return getBitCast(S, Ty);
Reid Spencerbc245a02006-12-05 03:25:26 +00001609}
1610
Matt Arsenault21f38f42013-12-07 02:58:41 +00001611Constant *ConstantExpr::getPointerBitCastOrAddrSpaceCast(Constant *S,
1612 Type *Ty) {
1613 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
1614 assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast");
1615
1616 if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace())
1617 return getAddrSpaceCast(S, Ty);
1618
1619 return getBitCast(S, Ty);
1620}
1621
Sanjay Patelf3587ec2016-05-18 22:05:28 +00001622Constant *ConstantExpr::getIntegerCast(Constant *C, Type *Ty, bool isSigned) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00001623 assert(C->getType()->isIntOrIntVectorTy() &&
1624 Ty->isIntOrIntVectorTy() && "Invalid cast");
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001625 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1626 unsigned DstBits = Ty->getScalarSizeInBits();
Reid Spencer56521c42006-12-12 00:51:07 +00001627 Instruction::CastOps opcode =
1628 (SrcBits == DstBits ? Instruction::BitCast :
1629 (SrcBits > DstBits ? Instruction::Trunc :
1630 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1631 return getCast(opcode, C, Ty);
1632}
1633
Chris Lattner229907c2011-07-18 04:54:35 +00001634Constant *ConstantExpr::getFPCast(Constant *C, Type *Ty) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00001635 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
Reid Spencer56521c42006-12-12 00:51:07 +00001636 "Invalid cast");
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001637 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1638 unsigned DstBits = Ty->getScalarSizeInBits();
Reid Spencerca104e82006-12-12 05:38:50 +00001639 if (SrcBits == DstBits)
1640 return C; // Avoid a useless cast
Reid Spencer56521c42006-12-12 00:51:07 +00001641 Instruction::CastOps opcode =
Jay Foad9f32cfd2011-01-27 14:44:55 +00001642 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
Reid Spencer56521c42006-12-12 00:51:07 +00001643 return getCast(opcode, C, Ty);
1644}
1645
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001646Constant *ConstantExpr::getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001647#ifndef NDEBUG
1648 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1649 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1650#endif
1651 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001652 assert(C->getType()->isIntOrIntVectorTy() && "Trunc operand must be integer");
1653 assert(Ty->isIntOrIntVectorTy() && "Trunc produces only integral");
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001654 assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001655 "SrcTy must be larger than DestTy for Trunc!");
1656
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001657 return getFoldedCast(Instruction::Trunc, C, Ty, OnlyIfReduced);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001658}
1659
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001660Constant *ConstantExpr::getSExt(Constant *C, Type *Ty, bool OnlyIfReduced) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001661#ifndef NDEBUG
1662 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1663 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1664#endif
1665 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001666 assert(C->getType()->isIntOrIntVectorTy() && "SExt operand must be integral");
1667 assert(Ty->isIntOrIntVectorTy() && "SExt produces only integer");
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001668 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001669 "SrcTy must be smaller than DestTy for SExt!");
1670
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001671 return getFoldedCast(Instruction::SExt, C, Ty, OnlyIfReduced);
Chris Lattnerdd284742004-04-04 23:20:30 +00001672}
1673
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001674Constant *ConstantExpr::getZExt(Constant *C, Type *Ty, bool OnlyIfReduced) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001675#ifndef NDEBUG
1676 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1677 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1678#endif
1679 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001680 assert(C->getType()->isIntOrIntVectorTy() && "ZEXt operand must be integral");
1681 assert(Ty->isIntOrIntVectorTy() && "ZExt produces only integer");
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001682 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001683 "SrcTy must be smaller than DestTy for ZExt!");
1684
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001685 return getFoldedCast(Instruction::ZExt, C, Ty, OnlyIfReduced);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001686}
1687
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001688Constant *ConstantExpr::getFPTrunc(Constant *C, Type *Ty, bool OnlyIfReduced) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001689#ifndef NDEBUG
1690 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1691 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1692#endif
1693 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001694 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001695 C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001696 "This is an illegal floating point truncation!");
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001697 return getFoldedCast(Instruction::FPTrunc, C, Ty, OnlyIfReduced);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001698}
1699
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001700Constant *ConstantExpr::getFPExtend(Constant *C, Type *Ty, bool OnlyIfReduced) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001701#ifndef NDEBUG
1702 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1703 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1704#endif
1705 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001706 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001707 C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001708 "This is an illegal floating point extension!");
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001709 return getFoldedCast(Instruction::FPExt, C, Ty, OnlyIfReduced);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001710}
1711
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001712Constant *ConstantExpr::getUIToFP(Constant *C, Type *Ty, bool OnlyIfReduced) {
Devang Pateld26344d2008-11-03 23:20:04 +00001713#ifndef NDEBUG
Nate Begemand4d45c22007-11-17 03:58:34 +00001714 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1715 bool toVec = Ty->getTypeID() == Type::VectorTyID;
Devang Pateld26344d2008-11-03 23:20:04 +00001716#endif
Nate Begemand4d45c22007-11-17 03:58:34 +00001717 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001718 assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
Nate Begemand4d45c22007-11-17 03:58:34 +00001719 "This is an illegal uint to floating point cast!");
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001720 return getFoldedCast(Instruction::UIToFP, C, Ty, OnlyIfReduced);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001721}
1722
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001723Constant *ConstantExpr::getSIToFP(Constant *C, Type *Ty, bool OnlyIfReduced) {
Devang Pateld26344d2008-11-03 23:20:04 +00001724#ifndef NDEBUG
Nate Begemand4d45c22007-11-17 03:58:34 +00001725 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1726 bool toVec = Ty->getTypeID() == Type::VectorTyID;
Devang Pateld26344d2008-11-03 23:20:04 +00001727#endif
Nate Begemand4d45c22007-11-17 03:58:34 +00001728 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001729 assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001730 "This is an illegal sint to floating point cast!");
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001731 return getFoldedCast(Instruction::SIToFP, C, Ty, OnlyIfReduced);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001732}
1733
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001734Constant *ConstantExpr::getFPToUI(Constant *C, Type *Ty, bool OnlyIfReduced) {
Devang Pateld26344d2008-11-03 23:20:04 +00001735#ifndef NDEBUG
Nate Begemand4d45c22007-11-17 03:58:34 +00001736 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1737 bool toVec = Ty->getTypeID() == Type::VectorTyID;
Devang Pateld26344d2008-11-03 23:20:04 +00001738#endif
Nate Begemand4d45c22007-11-17 03:58:34 +00001739 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001740 assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
Nate Begemand4d45c22007-11-17 03:58:34 +00001741 "This is an illegal floating point to uint cast!");
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001742 return getFoldedCast(Instruction::FPToUI, C, Ty, OnlyIfReduced);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001743}
1744
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001745Constant *ConstantExpr::getFPToSI(Constant *C, Type *Ty, bool OnlyIfReduced) {
Devang Pateld26344d2008-11-03 23:20:04 +00001746#ifndef NDEBUG
Nate Begemand4d45c22007-11-17 03:58:34 +00001747 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1748 bool toVec = Ty->getTypeID() == Type::VectorTyID;
Devang Pateld26344d2008-11-03 23:20:04 +00001749#endif
Nate Begemand4d45c22007-11-17 03:58:34 +00001750 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001751 assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
Nate Begemand4d45c22007-11-17 03:58:34 +00001752 "This is an illegal floating point to sint cast!");
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001753 return getFoldedCast(Instruction::FPToSI, C, Ty, OnlyIfReduced);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001754}
1755
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001756Constant *ConstantExpr::getPtrToInt(Constant *C, Type *DstTy,
1757 bool OnlyIfReduced) {
Craig Topper95d23472017-07-09 07:04:00 +00001758 assert(C->getType()->isPtrOrPtrVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00001759 "PtrToInt source must be pointer or pointer vector");
Craig Topper95d23472017-07-09 07:04:00 +00001760 assert(DstTy->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00001761 "PtrToInt destination must be integer or integer vector");
Chris Lattner8a3df542012-01-25 01:32:59 +00001762 assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
Nick Lewyckyff509622012-01-25 03:20:12 +00001763 if (isa<VectorType>(C->getType()))
Chris Lattner8326bd82012-01-26 00:42:34 +00001764 assert(C->getType()->getVectorNumElements()==DstTy->getVectorNumElements()&&
Chris Lattner8a3df542012-01-25 01:32:59 +00001765 "Invalid cast between a different number of vector elements");
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001766 return getFoldedCast(Instruction::PtrToInt, C, DstTy, OnlyIfReduced);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001767}
1768
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001769Constant *ConstantExpr::getIntToPtr(Constant *C, Type *DstTy,
1770 bool OnlyIfReduced) {
Craig Topper95d23472017-07-09 07:04:00 +00001771 assert(C->getType()->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00001772 "IntToPtr source must be integer or integer vector");
Craig Topper95d23472017-07-09 07:04:00 +00001773 assert(DstTy->isPtrOrPtrVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00001774 "IntToPtr destination must be a pointer or pointer vector");
Chris Lattner8a3df542012-01-25 01:32:59 +00001775 assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
Nick Lewyckyff509622012-01-25 03:20:12 +00001776 if (isa<VectorType>(C->getType()))
Chris Lattner8326bd82012-01-26 00:42:34 +00001777 assert(C->getType()->getVectorNumElements()==DstTy->getVectorNumElements()&&
Chris Lattner8a3df542012-01-25 01:32:59 +00001778 "Invalid cast between a different number of vector elements");
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001779 return getFoldedCast(Instruction::IntToPtr, C, DstTy, OnlyIfReduced);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001780}
1781
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001782Constant *ConstantExpr::getBitCast(Constant *C, Type *DstTy,
1783 bool OnlyIfReduced) {
Chris Lattner37bc78a2010-01-26 21:51:43 +00001784 assert(CastInst::castIsValid(Instruction::BitCast, C, DstTy) &&
1785 "Invalid constantexpr bitcast!");
Galina Kistanovafc259902012-07-13 01:25:27 +00001786
Chris Lattnercbeda872009-03-21 06:55:54 +00001787 // It is common to ask for a bitcast of a value to its own type, handle this
1788 // speedily.
1789 if (C->getType() == DstTy) return C;
Galina Kistanovafc259902012-07-13 01:25:27 +00001790
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001791 return getFoldedCast(Instruction::BitCast, C, DstTy, OnlyIfReduced);
Chris Lattnerdd284742004-04-04 23:20:30 +00001792}
1793
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001794Constant *ConstantExpr::getAddrSpaceCast(Constant *C, Type *DstTy,
1795 bool OnlyIfReduced) {
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00001796 assert(CastInst::castIsValid(Instruction::AddrSpaceCast, C, DstTy) &&
1797 "Invalid constantexpr addrspacecast!");
1798
Jingyue Wubaabe502014-06-15 21:40:57 +00001799 // Canonicalize addrspacecasts between different pointer types by first
1800 // bitcasting the pointer type and then converting the address space.
1801 PointerType *SrcScalarTy = cast<PointerType>(C->getType()->getScalarType());
1802 PointerType *DstScalarTy = cast<PointerType>(DstTy->getScalarType());
1803 Type *DstElemTy = DstScalarTy->getElementType();
1804 if (SrcScalarTy->getElementType() != DstElemTy) {
1805 Type *MidTy = PointerType::get(DstElemTy, SrcScalarTy->getAddressSpace());
1806 if (VectorType *VT = dyn_cast<VectorType>(DstTy)) {
1807 // Handle vectors of pointers.
1808 MidTy = VectorType::get(MidTy, VT->getNumElements());
1809 }
1810 C = getBitCast(C, MidTy);
1811 }
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001812 return getFoldedCast(Instruction::AddrSpaceCast, C, DstTy, OnlyIfReduced);
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00001813}
1814
Cameron McInallycbde0d92018-11-13 18:15:47 +00001815Constant *ConstantExpr::get(unsigned Opcode, Constant *C, unsigned Flags,
1816 Type *OnlyIfReducedTy) {
1817 // Check the operands for consistency first.
1818 assert(Instruction::isUnaryOp(Opcode) &&
1819 "Invalid opcode in unary constant expression");
1820
1821#ifndef NDEBUG
1822 switch (Opcode) {
1823 case Instruction::FNeg:
1824 assert(C->getType()->isFPOrFPVectorTy() &&
1825 "Tried to create a floating-point operation on a "
1826 "non-floating-point type!");
1827 break;
1828 default:
1829 break;
1830 }
1831#endif
1832
Cameron McInally1d0c8452019-05-05 16:07:09 +00001833 if (Constant *FC = ConstantFoldUnaryInstruction(Opcode, C))
1834 return FC;
Cameron McInallycbde0d92018-11-13 18:15:47 +00001835
1836 if (OnlyIfReducedTy == C->getType())
1837 return nullptr;
1838
1839 Constant *ArgVec[] = { C };
1840 ConstantExprKeyType Key(Opcode, ArgVec, 0, Flags);
1841
1842 LLVMContextImpl *pImpl = C->getContext().pImpl;
1843 return pImpl->ExprConstants.getOrCreate(C->getType(), Key);
1844}
1845
Chris Lattner887ecac2011-07-09 18:23:52 +00001846Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2,
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001847 unsigned Flags, Type *OnlyIfReducedTy) {
Chris Lattner887ecac2011-07-09 18:23:52 +00001848 // Check the operands for consistency first.
Simon Pilgrime0a6eb12018-06-22 10:48:02 +00001849 assert(Instruction::isBinaryOp(Opcode) &&
Chris Lattner38a9bcd2003-05-21 17:49:25 +00001850 "Invalid opcode in binary constant expression");
1851 assert(C1->getType() == C2->getType() &&
1852 "Operand types in binary constant expression should match");
Galina Kistanovafc259902012-07-13 01:25:27 +00001853
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001854#ifndef NDEBUG
1855 switch (Opcode) {
Dan Gohmana5b96452009-06-04 22:49:04 +00001856 case Instruction::Add:
Reid Spencer7eb55b32006-11-02 01:53:59 +00001857 case Instruction::Sub:
Dan Gohmana5b96452009-06-04 22:49:04 +00001858 case Instruction::Mul:
Craig Topper41c999b2019-05-05 17:19:16 +00001859 case Instruction::UDiv:
1860 case Instruction::SDiv:
1861 case Instruction::URem:
1862 case Instruction::SRem:
Duncan Sands9dff9be2010-02-15 16:12:20 +00001863 assert(C1->getType()->isIntOrIntVectorTy() &&
Dan Gohmana5b96452009-06-04 22:49:04 +00001864 "Tried to create an integer operation on a non-integer type!");
1865 break;
1866 case Instruction::FAdd:
1867 case Instruction::FSub:
1868 case Instruction::FMul:
Craig Topper41c999b2019-05-05 17:19:16 +00001869 case Instruction::FDiv:
1870 case Instruction::FRem:
Duncan Sands9dff9be2010-02-15 16:12:20 +00001871 assert(C1->getType()->isFPOrFPVectorTy() &&
Dan Gohmana5b96452009-06-04 22:49:04 +00001872 "Tried to create a floating-point operation on a "
1873 "non-floating-point type!");
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001874 break;
1875 case Instruction::And:
1876 case Instruction::Or:
1877 case Instruction::Xor:
Duncan Sands9dff9be2010-02-15 16:12:20 +00001878 assert(C1->getType()->isIntOrIntVectorTy() &&
Misha Brukman3852f652005-01-27 06:46:38 +00001879 "Tried to create a logical operation on a non-integral type!");
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001880 break;
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001881 case Instruction::Shl:
Reid Spencerfdff9382006-11-08 06:47:33 +00001882 case Instruction::LShr:
1883 case Instruction::AShr:
Duncan Sands9dff9be2010-02-15 16:12:20 +00001884 assert(C1->getType()->isIntOrIntVectorTy() &&
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001885 "Tried to create a shift operation on a non-integer type!");
1886 break;
1887 default:
1888 break;
1889 }
1890#endif
1891
Chris Lattner887ecac2011-07-09 18:23:52 +00001892 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
Cameron McInally1d0c8452019-05-05 16:07:09 +00001893 return FC;
Galina Kistanovafc259902012-07-13 01:25:27 +00001894
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001895 if (OnlyIfReducedTy == C1->getType())
1896 return nullptr;
1897
Benjamin Kramer324322b2013-03-07 20:53:34 +00001898 Constant *ArgVec[] = { C1, C2 };
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00001899 ConstantExprKeyType Key(Opcode, ArgVec, 0, Flags);
Galina Kistanovafc259902012-07-13 01:25:27 +00001900
Chris Lattner887ecac2011-07-09 18:23:52 +00001901 LLVMContextImpl *pImpl = C1->getContext().pImpl;
1902 return pImpl->ExprConstants.getOrCreate(C1->getType(), Key);
Reid Spencera009d0d2006-12-04 21:35:24 +00001903}
1904
Chris Lattner229907c2011-07-18 04:54:35 +00001905Constant *ConstantExpr::getSizeOf(Type* Ty) {
Owen Anderson487375e2009-07-29 18:55:55 +00001906 // sizeof is implemented as: (i64) gep (Ty*)null, 1
1907 // Note that a non-inbounds gep is used, as null isn't within any object.
Owen Anderson55f1c092009-08-13 21:58:54 +00001908 Constant *GEPIdx = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
Owen Anderson487375e2009-07-29 18:55:55 +00001909 Constant *GEP = getGetElementPtr(
David Blaikie4a2e73b2015-04-02 18:55:32 +00001910 Ty, Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx);
Bjorn Petterssonaa025802018-07-03 12:39:52 +00001911 return getPtrToInt(GEP,
Dan Gohman3cdcc3f2010-04-12 22:12:29 +00001912 Type::getInt64Ty(Ty->getContext()));
Owen Anderson487375e2009-07-29 18:55:55 +00001913}
1914
Chris Lattner229907c2011-07-18 04:54:35 +00001915Constant *ConstantExpr::getAlignOf(Type* Ty) {
Dan Gohmancf913832010-01-28 02:15:55 +00001916 // alignof is implemented as: (i64) gep ({i1,Ty}*)null, 0, 1
Dan Gohman50c09d02009-08-11 17:57:01 +00001917 // Note that a non-inbounds gep is used, as null isn't within any object.
Serge Gueltone38003f2017-05-09 19:31:13 +00001918 Type *AligningTy = StructType::get(Type::getInt1Ty(Ty->getContext()), Ty);
Matt Arsenaultbe558882014-04-23 20:58:57 +00001919 Constant *NullPtr = Constant::getNullValue(AligningTy->getPointerTo(0));
Dan Gohmana9be7392010-01-28 02:43:22 +00001920 Constant *Zero = ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0);
Owen Anderson55f1c092009-08-13 21:58:54 +00001921 Constant *One = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
Owen Anderson487375e2009-07-29 18:55:55 +00001922 Constant *Indices[2] = { Zero, One };
David Blaikie4a2e73b2015-04-02 18:55:32 +00001923 Constant *GEP = getGetElementPtr(AligningTy, NullPtr, Indices);
Dan Gohman3cdcc3f2010-04-12 22:12:29 +00001924 return getPtrToInt(GEP,
1925 Type::getInt64Ty(Ty->getContext()));
Owen Anderson487375e2009-07-29 18:55:55 +00001926}
1927
Chris Lattner229907c2011-07-18 04:54:35 +00001928Constant *ConstantExpr::getOffsetOf(StructType* STy, unsigned FieldNo) {
Dan Gohmanede94e62010-02-01 16:37:38 +00001929 return getOffsetOf(STy, ConstantInt::get(Type::getInt32Ty(STy->getContext()),
1930 FieldNo));
1931}
1932
Chris Lattner229907c2011-07-18 04:54:35 +00001933Constant *ConstantExpr::getOffsetOf(Type* Ty, Constant *FieldNo) {
Dan Gohmanff3af7252009-08-16 21:26:11 +00001934 // offsetof is implemented as: (i64) gep (Ty*)null, 0, FieldNo
1935 // Note that a non-inbounds gep is used, as null isn't within any object.
1936 Constant *GEPIdx[] = {
Dan Gohmanede94e62010-02-01 16:37:38 +00001937 ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0),
1938 FieldNo
Dan Gohmanff3af7252009-08-16 21:26:11 +00001939 };
1940 Constant *GEP = getGetElementPtr(
David Blaikie4a2e73b2015-04-02 18:55:32 +00001941 Ty, Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx);
Dan Gohman3cdcc3f2010-04-12 22:12:29 +00001942 return getPtrToInt(GEP,
1943 Type::getInt64Ty(Ty->getContext()));
Dan Gohmanff3af7252009-08-16 21:26:11 +00001944}
Owen Anderson487375e2009-07-29 18:55:55 +00001945
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001946Constant *ConstantExpr::getCompare(unsigned short Predicate, Constant *C1,
1947 Constant *C2, bool OnlyIfReduced) {
Reid Spencera009d0d2006-12-04 21:35:24 +00001948 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Galina Kistanovafc259902012-07-13 01:25:27 +00001949
Chris Lattner887ecac2011-07-09 18:23:52 +00001950 switch (Predicate) {
1951 default: llvm_unreachable("Invalid CmpInst predicate");
1952 case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
1953 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
1954 case CmpInst::FCMP_ONE: case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
1955 case CmpInst::FCMP_UEQ: case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
1956 case CmpInst::FCMP_ULT: case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
1957 case CmpInst::FCMP_TRUE:
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001958 return getFCmp(Predicate, C1, C2, OnlyIfReduced);
Galina Kistanovafc259902012-07-13 01:25:27 +00001959
Chris Lattner887ecac2011-07-09 18:23:52 +00001960 case CmpInst::ICMP_EQ: case CmpInst::ICMP_NE: case CmpInst::ICMP_UGT:
1961 case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
1962 case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
1963 case CmpInst::ICMP_SLE:
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001964 return getICmp(Predicate, C1, C2, OnlyIfReduced);
Chris Lattner887ecac2011-07-09 18:23:52 +00001965 }
Chris Lattner29ca2c62004-08-04 18:50:09 +00001966}
1967
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001968Constant *ConstantExpr::getSelect(Constant *C, Constant *V1, Constant *V2,
1969 Type *OnlyIfReducedTy) {
Chris Lattner41632132008-12-29 00:16:12 +00001970 assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
Chris Lattner6e415c02004-03-12 05:54:04 +00001971
Chris Lattner887ecac2011-07-09 18:23:52 +00001972 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1973 return SC; // Fold common cases
Chris Lattner6e415c02004-03-12 05:54:04 +00001974
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001975 if (OnlyIfReducedTy == V1->getType())
1976 return nullptr;
1977
Benjamin Kramer324322b2013-03-07 20:53:34 +00001978 Constant *ArgVec[] = { C, V1, V2 };
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00001979 ConstantExprKeyType Key(Instruction::Select, ArgVec);
Galina Kistanovafc259902012-07-13 01:25:27 +00001980
Chris Lattner887ecac2011-07-09 18:23:52 +00001981 LLVMContextImpl *pImpl = C->getContext().pImpl;
1982 return pImpl->ExprConstants.getOrCreate(V1->getType(), Key);
Chris Lattner6e415c02004-03-12 05:54:04 +00001983}
1984
David Blaikie4a2e73b2015-04-02 18:55:32 +00001985Constant *ConstantExpr::getGetElementPtr(Type *Ty, Constant *C,
1986 ArrayRef<Value *> Idxs, bool InBounds,
Peter Collingbourned93620b2016-11-10 22:34:55 +00001987 Optional<unsigned> InRangeIndex,
David Blaikie4a2e73b2015-04-02 18:55:32 +00001988 Type *OnlyIfReducedTy) {
David Blaikie4a2e73b2015-04-02 18:55:32 +00001989 if (!Ty)
1990 Ty = cast<PointerType>(C->getType()->getScalarType())->getElementType();
1991 else
James Y Knight62df5ee2019-01-10 16:07:20 +00001992 assert(Ty ==
1993 cast<PointerType>(C->getType()->getScalarType())->getElementType());
David Blaikied9d900c2015-05-07 17:28:58 +00001994
Peter Collingbourned93620b2016-11-10 22:34:55 +00001995 if (Constant *FC =
1996 ConstantFoldGetElementPtr(Ty, C, InBounds, InRangeIndex, Idxs))
David Blaikied9d900c2015-05-07 17:28:58 +00001997 return FC; // Fold a few common cases.
1998
Chris Lattner887ecac2011-07-09 18:23:52 +00001999 // Get the result type of the getelementptr!
David Blaikie4a2e73b2015-04-02 18:55:32 +00002000 Type *DestTy = GetElementPtrInst::getIndexedType(Ty, Idxs);
2001 assert(DestTy && "GEP indices invalid!");
Chris Lattner8326bd82012-01-26 00:42:34 +00002002 unsigned AS = C->getType()->getPointerAddressSpace();
David Blaikie4a2e73b2015-04-02 18:55:32 +00002003 Type *ReqTy = DestTy->getPointerTo(AS);
Elena Demikhovskyee004bc2016-05-15 12:30:25 +00002004
2005 unsigned NumVecElts = 0;
2006 if (C->getType()->isVectorTy())
2007 NumVecElts = C->getType()->getVectorNumElements();
2008 else for (auto Idx : Idxs)
2009 if (Idx->getType()->isVectorTy())
2010 NumVecElts = Idx->getType()->getVectorNumElements();
2011
2012 if (NumVecElts)
2013 ReqTy = VectorType::get(ReqTy, NumVecElts);
Galina Kistanovafc259902012-07-13 01:25:27 +00002014
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002015 if (OnlyIfReducedTy == ReqTy)
2016 return nullptr;
2017
Dan Gohman1b849082009-09-07 23:54:19 +00002018 // Look up the constant in the table first to ensure uniqueness
2019 std::vector<Constant*> ArgVec;
Jay Foaded8db7d2011-07-21 14:31:17 +00002020 ArgVec.reserve(1 + Idxs.size());
Dan Gohman1b849082009-09-07 23:54:19 +00002021 ArgVec.push_back(C);
Duncan Sandse6beec62012-11-13 12:59:33 +00002022 for (unsigned i = 0, e = Idxs.size(); i != e; ++i) {
Duncan Sandse6beec62012-11-13 12:59:33 +00002023 assert((!Idxs[i]->getType()->isVectorTy() ||
Elena Demikhovskyee004bc2016-05-15 12:30:25 +00002024 Idxs[i]->getType()->getVectorNumElements() == NumVecElts) &&
Duncan Sandse6beec62012-11-13 12:59:33 +00002025 "getelementptr index type missmatch");
Elena Demikhovskyee004bc2016-05-15 12:30:25 +00002026
2027 Constant *Idx = cast<Constant>(Idxs[i]);
2028 if (NumVecElts && !Idxs[i]->getType()->isVectorTy())
2029 Idx = ConstantVector::getSplat(NumVecElts, Idx);
2030 ArgVec.push_back(Idx);
Duncan Sandse6beec62012-11-13 12:59:33 +00002031 }
Peter Collingbourned93620b2016-11-10 22:34:55 +00002032
2033 unsigned SubClassOptionalData = InBounds ? GEPOperator::IsInBounds : 0;
2034 if (InRangeIndex && *InRangeIndex < 63)
2035 SubClassOptionalData |= (*InRangeIndex + 1) << 1;
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002036 const ConstantExprKeyType Key(Instruction::GetElementPtr, ArgVec, 0,
Peter Collingbourned93620b2016-11-10 22:34:55 +00002037 SubClassOptionalData, None, Ty);
Galina Kistanovafc259902012-07-13 01:25:27 +00002038
Chris Lattner887ecac2011-07-09 18:23:52 +00002039 LLVMContextImpl *pImpl = C->getContext().pImpl;
Dan Gohman1b849082009-09-07 23:54:19 +00002040 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
2041}
2042
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002043Constant *ConstantExpr::getICmp(unsigned short pred, Constant *LHS,
2044 Constant *RHS, bool OnlyIfReduced) {
Reid Spenceree3c9912006-12-04 05:19:50 +00002045 assert(LHS->getType() == RHS->getType());
Craig Topper45844762017-07-05 23:35:46 +00002046 assert(CmpInst::isIntPredicate((CmpInst::Predicate)pred) &&
2047 "Invalid ICmp Predicate");
Reid Spenceree3c9912006-12-04 05:19:50 +00002048
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00002049 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
Reid Spenceree3c9912006-12-04 05:19:50 +00002050 return FC; // Fold a few common cases...
2051
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002052 if (OnlyIfReduced)
2053 return nullptr;
2054
Reid Spenceree3c9912006-12-04 05:19:50 +00002055 // Look up the constant in the table first to ensure uniqueness
Benjamin Kramer324322b2013-03-07 20:53:34 +00002056 Constant *ArgVec[] = { LHS, RHS };
Reid Spencerb1537492006-12-24 18:42:29 +00002057 // Get the key type with both the opcode and predicate
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002058 const ConstantExprKeyType Key(Instruction::ICmp, ArgVec, pred);
Owen Anderson61794042009-06-17 20:10:08 +00002059
Chris Lattner229907c2011-07-18 04:54:35 +00002060 Type *ResultTy = Type::getInt1Ty(LHS->getContext());
2061 if (VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
Nick Lewycky9e26c1c2010-01-21 07:03:21 +00002062 ResultTy = VectorType::get(ResultTy, VT->getNumElements());
2063
Owen Anderson1584a292009-08-04 20:25:11 +00002064 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
Nick Lewycky9e26c1c2010-01-21 07:03:21 +00002065 return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
Reid Spenceree3c9912006-12-04 05:19:50 +00002066}
2067
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002068Constant *ConstantExpr::getFCmp(unsigned short pred, Constant *LHS,
2069 Constant *RHS, bool OnlyIfReduced) {
Reid Spenceree3c9912006-12-04 05:19:50 +00002070 assert(LHS->getType() == RHS->getType());
Craig Topper45844762017-07-05 23:35:46 +00002071 assert(CmpInst::isFPPredicate((CmpInst::Predicate)pred) &&
2072 "Invalid FCmp Predicate");
Reid Spenceree3c9912006-12-04 05:19:50 +00002073
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00002074 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
Reid Spenceree3c9912006-12-04 05:19:50 +00002075 return FC; // Fold a few common cases...
2076
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002077 if (OnlyIfReduced)
2078 return nullptr;
2079
Reid Spenceree3c9912006-12-04 05:19:50 +00002080 // Look up the constant in the table first to ensure uniqueness
Benjamin Kramer324322b2013-03-07 20:53:34 +00002081 Constant *ArgVec[] = { LHS, RHS };
Reid Spencerb1537492006-12-24 18:42:29 +00002082 // Get the key type with both the opcode and predicate
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002083 const ConstantExprKeyType Key(Instruction::FCmp, ArgVec, pred);
Nick Lewycky9e26c1c2010-01-21 07:03:21 +00002084
Chris Lattner229907c2011-07-18 04:54:35 +00002085 Type *ResultTy = Type::getInt1Ty(LHS->getContext());
2086 if (VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
Nick Lewycky9e26c1c2010-01-21 07:03:21 +00002087 ResultTy = VectorType::get(ResultTy, VT->getNumElements());
2088
Owen Anderson1584a292009-08-04 20:25:11 +00002089 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
Nick Lewycky9e26c1c2010-01-21 07:03:21 +00002090 return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
Reid Spenceree3c9912006-12-04 05:19:50 +00002091}
2092
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002093Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx,
2094 Type *OnlyIfReducedTy) {
Duncan Sands19d0b472010-02-16 11:11:14 +00002095 assert(Val->getType()->isVectorTy() &&
Reid Spencer09575ba2007-02-15 03:39:18 +00002096 "Tried to create extractelement operation on non-vector type!");
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002097 assert(Idx->getType()->isIntegerTy() &&
2098 "Extractelement index must be an integer type!");
Galina Kistanovafc259902012-07-13 01:25:27 +00002099
Chris Lattner887ecac2011-07-09 18:23:52 +00002100 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
Chris Lattner09660c92009-12-30 20:25:09 +00002101 return FC; // Fold a few common cases.
Galina Kistanovafc259902012-07-13 01:25:27 +00002102
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002103 Type *ReqTy = Val->getType()->getVectorElementType();
2104 if (OnlyIfReducedTy == ReqTy)
2105 return nullptr;
2106
Robert Bocchinoca27f032006-01-17 20:07:22 +00002107 // Look up the constant in the table first to ensure uniqueness
Benjamin Kramer324322b2013-03-07 20:53:34 +00002108 Constant *ArgVec[] = { Val, Idx };
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002109 const ConstantExprKeyType Key(Instruction::ExtractElement, ArgVec);
Galina Kistanovafc259902012-07-13 01:25:27 +00002110
Chris Lattner887ecac2011-07-09 18:23:52 +00002111 LLVMContextImpl *pImpl = Val->getContext().pImpl;
Owen Anderson1584a292009-08-04 20:25:11 +00002112 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
Robert Bocchinoca27f032006-01-17 20:07:22 +00002113}
2114
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002115Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
2116 Constant *Idx, Type *OnlyIfReducedTy) {
Duncan Sands19d0b472010-02-16 11:11:14 +00002117 assert(Val->getType()->isVectorTy() &&
Reid Spencer09575ba2007-02-15 03:39:18 +00002118 "Tried to create insertelement operation on non-vector type!");
Chris Lattner8326bd82012-01-26 00:42:34 +00002119 assert(Elt->getType() == Val->getType()->getVectorElementType() &&
2120 "Insertelement types must match!");
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002121 assert(Idx->getType()->isIntegerTy() &&
Reid Spencer2546b762007-01-26 07:37:34 +00002122 "Insertelement index must be i32 type!");
Robert Bocchinoca27f032006-01-17 20:07:22 +00002123
Chris Lattner887ecac2011-07-09 18:23:52 +00002124 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
2125 return FC; // Fold a few common cases.
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002126
2127 if (OnlyIfReducedTy == Val->getType())
2128 return nullptr;
2129
Chris Lattnerbbe0a422006-04-08 01:18:18 +00002130 // Look up the constant in the table first to ensure uniqueness
Benjamin Kramer324322b2013-03-07 20:53:34 +00002131 Constant *ArgVec[] = { Val, Elt, Idx };
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002132 const ConstantExprKeyType Key(Instruction::InsertElement, ArgVec);
Galina Kistanovafc259902012-07-13 01:25:27 +00002133
Chris Lattner887ecac2011-07-09 18:23:52 +00002134 LLVMContextImpl *pImpl = Val->getContext().pImpl;
2135 return pImpl->ExprConstants.getOrCreate(Val->getType(), Key);
Chris Lattnerbbe0a422006-04-08 01:18:18 +00002136}
2137
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002138Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
2139 Constant *Mask, Type *OnlyIfReducedTy) {
Chris Lattnerbbe0a422006-04-08 01:18:18 +00002140 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
2141 "Invalid shuffle vector constant expr operands!");
Nate Begeman94aa38d2009-02-12 21:28:33 +00002142
Chris Lattner887ecac2011-07-09 18:23:52 +00002143 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
2144 return FC; // Fold a few common cases.
2145
Chris Lattner8326bd82012-01-26 00:42:34 +00002146 unsigned NElts = Mask->getType()->getVectorNumElements();
2147 Type *EltTy = V1->getType()->getVectorElementType();
Chris Lattner229907c2011-07-18 04:54:35 +00002148 Type *ShufTy = VectorType::get(EltTy, NElts);
Chris Lattner887ecac2011-07-09 18:23:52 +00002149
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002150 if (OnlyIfReducedTy == ShufTy)
2151 return nullptr;
2152
Chris Lattner887ecac2011-07-09 18:23:52 +00002153 // Look up the constant in the table first to ensure uniqueness
Benjamin Kramer324322b2013-03-07 20:53:34 +00002154 Constant *ArgVec[] = { V1, V2, Mask };
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002155 const ConstantExprKeyType Key(Instruction::ShuffleVector, ArgVec);
Galina Kistanovafc259902012-07-13 01:25:27 +00002156
Chris Lattner887ecac2011-07-09 18:23:52 +00002157 LLVMContextImpl *pImpl = ShufTy->getContext().pImpl;
2158 return pImpl->ExprConstants.getOrCreate(ShufTy, Key);
Chris Lattnerbbe0a422006-04-08 01:18:18 +00002159}
2160
Chris Lattner887ecac2011-07-09 18:23:52 +00002161Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002162 ArrayRef<unsigned> Idxs,
2163 Type *OnlyIfReducedTy) {
Hal Finkelb31366d2013-07-10 22:51:01 +00002164 assert(Agg->getType()->isFirstClassType() &&
2165 "Non-first-class type for constant insertvalue expression");
2166
Jay Foad57aa6362011-07-13 10:26:04 +00002167 assert(ExtractValueInst::getIndexedType(Agg->getType(),
2168 Idxs) == Val->getType() &&
Dan Gohman12fce772008-05-15 19:50:34 +00002169 "insertvalue indices invalid!");
Hal Finkelb31366d2013-07-10 22:51:01 +00002170 Type *ReqTy = Val->getType();
2171
2172 if (Constant *FC = ConstantFoldInsertValueInstruction(Agg, Val, Idxs))
2173 return FC;
2174
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002175 if (OnlyIfReducedTy == ReqTy)
2176 return nullptr;
2177
Hal Finkelb31366d2013-07-10 22:51:01 +00002178 Constant *ArgVec[] = { Agg, Val };
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002179 const ConstantExprKeyType Key(Instruction::InsertValue, ArgVec, 0, 0, Idxs);
Hal Finkelb31366d2013-07-10 22:51:01 +00002180
2181 LLVMContextImpl *pImpl = Agg->getContext().pImpl;
2182 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
Dan Gohman12fce772008-05-15 19:50:34 +00002183}
2184
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002185Constant *ConstantExpr::getExtractValue(Constant *Agg, ArrayRef<unsigned> Idxs,
2186 Type *OnlyIfReducedTy) {
Dan Gohman0752bff2008-05-23 00:36:11 +00002187 assert(Agg->getType()->isFirstClassType() &&
Chris Lattner887ecac2011-07-09 18:23:52 +00002188 "Tried to create extractelement operation on non-first-class type!");
Dan Gohman12fce772008-05-15 19:50:34 +00002189
Chris Lattner229907c2011-07-18 04:54:35 +00002190 Type *ReqTy = ExtractValueInst::getIndexedType(Agg->getType(), Idxs);
Chandler Carruth9db56b82011-07-10 09:45:35 +00002191 (void)ReqTy;
Chris Lattner887ecac2011-07-09 18:23:52 +00002192 assert(ReqTy && "extractvalue indices invalid!");
Galina Kistanovafc259902012-07-13 01:25:27 +00002193
Dan Gohman0752bff2008-05-23 00:36:11 +00002194 assert(Agg->getType()->isFirstClassType() &&
2195 "Non-first-class type for constant extractvalue expression");
Hal Finkelb31366d2013-07-10 22:51:01 +00002196 if (Constant *FC = ConstantFoldExtractValueInstruction(Agg, Idxs))
2197 return FC;
2198
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002199 if (OnlyIfReducedTy == ReqTy)
2200 return nullptr;
2201
Hal Finkelb31366d2013-07-10 22:51:01 +00002202 Constant *ArgVec[] = { Agg };
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002203 const ConstantExprKeyType Key(Instruction::ExtractValue, ArgVec, 0, 0, Idxs);
Hal Finkelb31366d2013-07-10 22:51:01 +00002204
2205 LLVMContextImpl *pImpl = Agg->getContext().pImpl;
2206 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
Dan Gohman12fce772008-05-15 19:50:34 +00002207}
2208
Chris Lattnere9b4ad72011-02-10 07:01:55 +00002209Constant *ConstantExpr::getNeg(Constant *C, bool HasNUW, bool HasNSW) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00002210 assert(C->getType()->isIntOrIntVectorTy() &&
Owen Anderson487375e2009-07-29 18:55:55 +00002211 "Cannot NEG a nonintegral value!");
Chris Lattnere9b4ad72011-02-10 07:01:55 +00002212 return getSub(ConstantFP::getZeroValueForNegation(C->getType()),
2213 C, HasNUW, HasNSW);
Owen Anderson487375e2009-07-29 18:55:55 +00002214}
2215
Chris Lattnera676c0f2011-02-07 16:40:21 +00002216Constant *ConstantExpr::getFNeg(Constant *C) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00002217 assert(C->getType()->isFPOrFPVectorTy() &&
Owen Anderson487375e2009-07-29 18:55:55 +00002218 "Cannot FNEG a non-floating-point value!");
Cameron McInally1d0c8452019-05-05 16:07:09 +00002219 return get(Instruction::FNeg, C);
Owen Anderson487375e2009-07-29 18:55:55 +00002220}
2221
Chris Lattnera676c0f2011-02-07 16:40:21 +00002222Constant *ConstantExpr::getNot(Constant *C) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00002223 assert(C->getType()->isIntOrIntVectorTy() &&
Owen Anderson487375e2009-07-29 18:55:55 +00002224 "Cannot NOT a nonintegral value!");
Owen Anderson5a1acd92009-07-31 20:28:14 +00002225 return get(Instruction::Xor, C, Constant::getAllOnesValue(C->getType()));
Owen Anderson487375e2009-07-29 18:55:55 +00002226}
2227
Chris Lattnere9b4ad72011-02-10 07:01:55 +00002228Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2,
2229 bool HasNUW, bool HasNSW) {
2230 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2231 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2232 return get(Instruction::Add, C1, C2, Flags);
Owen Anderson487375e2009-07-29 18:55:55 +00002233}
2234
Chris Lattnera676c0f2011-02-07 16:40:21 +00002235Constant *ConstantExpr::getFAdd(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002236 return get(Instruction::FAdd, C1, C2);
2237}
2238
Chris Lattnere9b4ad72011-02-10 07:01:55 +00002239Constant *ConstantExpr::getSub(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::Sub, C1, C2, Flags);
Owen Anderson487375e2009-07-29 18:55:55 +00002244}
2245
Chris Lattnera676c0f2011-02-07 16:40:21 +00002246Constant *ConstantExpr::getFSub(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002247 return get(Instruction::FSub, C1, C2);
2248}
2249
Chris Lattnere9b4ad72011-02-10 07:01:55 +00002250Constant *ConstantExpr::getMul(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::Mul, C1, C2, Flags);
Owen Anderson487375e2009-07-29 18:55:55 +00002255}
2256
Chris Lattnera676c0f2011-02-07 16:40:21 +00002257Constant *ConstantExpr::getFMul(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002258 return get(Instruction::FMul, C1, C2);
2259}
2260
Chris Lattner0d75eac2011-02-09 16:43:07 +00002261Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2, bool isExact) {
2262 return get(Instruction::UDiv, C1, C2,
2263 isExact ? PossiblyExactOperator::IsExact : 0);
Owen Anderson487375e2009-07-29 18:55:55 +00002264}
2265
Chris Lattner0d75eac2011-02-09 16:43:07 +00002266Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2, bool isExact) {
2267 return get(Instruction::SDiv, C1, C2,
2268 isExact ? PossiblyExactOperator::IsExact : 0);
Owen Anderson487375e2009-07-29 18:55:55 +00002269}
2270
Chris Lattnera676c0f2011-02-07 16:40:21 +00002271Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002272 return get(Instruction::FDiv, C1, C2);
2273}
2274
Chris Lattnera676c0f2011-02-07 16:40:21 +00002275Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002276 return get(Instruction::URem, C1, C2);
2277}
2278
Chris Lattnera676c0f2011-02-07 16:40:21 +00002279Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002280 return get(Instruction::SRem, C1, C2);
2281}
2282
Chris Lattnera676c0f2011-02-07 16:40:21 +00002283Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002284 return get(Instruction::FRem, C1, C2);
2285}
2286
Chris Lattnera676c0f2011-02-07 16:40:21 +00002287Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002288 return get(Instruction::And, C1, C2);
2289}
2290
Chris Lattnera676c0f2011-02-07 16:40:21 +00002291Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002292 return get(Instruction::Or, C1, C2);
2293}
2294
Chris Lattnera676c0f2011-02-07 16:40:21 +00002295Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002296 return get(Instruction::Xor, C1, C2);
2297}
2298
Chris Lattnere9b4ad72011-02-10 07:01:55 +00002299Constant *ConstantExpr::getShl(Constant *C1, Constant *C2,
2300 bool HasNUW, bool HasNSW) {
2301 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2302 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2303 return get(Instruction::Shl, C1, C2, Flags);
Owen Anderson487375e2009-07-29 18:55:55 +00002304}
2305
Chris Lattner0d75eac2011-02-09 16:43:07 +00002306Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2, bool isExact) {
2307 return get(Instruction::LShr, C1, C2,
2308 isExact ? PossiblyExactOperator::IsExact : 0);
Owen Anderson487375e2009-07-29 18:55:55 +00002309}
2310
Chris Lattner0d75eac2011-02-09 16:43:07 +00002311Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2, bool isExact) {
2312 return get(Instruction::AShr, C1, C2,
2313 isExact ? PossiblyExactOperator::IsExact : 0);
Owen Anderson487375e2009-07-29 18:55:55 +00002314}
2315
Sanjay Patele85a3002018-07-06 15:18:58 +00002316Constant *ConstantExpr::getBinOpIdentity(unsigned Opcode, Type *Ty,
2317 bool AllowRHSConstant) {
2318 assert(Instruction::isBinaryOp(Opcode) && "Only binops allowed");
2319
2320 // Commutative opcodes: it does not matter if AllowRHSConstant is set.
2321 if (Instruction::isCommutative(Opcode)) {
2322 switch (Opcode) {
2323 case Instruction::Add: // X + 0 = X
2324 case Instruction::Or: // X | 0 = X
2325 case Instruction::Xor: // X ^ 0 = X
2326 return Constant::getNullValue(Ty);
2327 case Instruction::Mul: // X * 1 = X
2328 return ConstantInt::get(Ty, 1);
2329 case Instruction::And: // X & -1 = X
2330 return Constant::getAllOnesValue(Ty);
2331 case Instruction::FAdd: // X + -0.0 = X
2332 // TODO: If the fadd has 'nsz', should we return +0.0?
2333 return ConstantFP::getNegativeZero(Ty);
2334 case Instruction::FMul: // X * 1.0 = X
2335 return ConstantFP::get(Ty, 1.0);
2336 default:
2337 llvm_unreachable("Every commutative binop has an identity constant");
2338 }
2339 }
2340
2341 // Non-commutative opcodes: AllowRHSConstant must be set.
2342 if (!AllowRHSConstant)
Craig Topperc6207612014-04-09 06:08:46 +00002343 return nullptr;
Duncan Sands318a89d2012-06-13 09:42:13 +00002344
Sanjay Patele85a3002018-07-06 15:18:58 +00002345 switch (Opcode) {
2346 case Instruction::Sub: // X - 0 = X
2347 case Instruction::Shl: // X << 0 = X
2348 case Instruction::LShr: // X >>u 0 = X
2349 case Instruction::AShr: // X >> 0 = X
2350 case Instruction::FSub: // X - 0.0 = X
2351 return Constant::getNullValue(Ty);
2352 case Instruction::SDiv: // X / 1 = X
2353 case Instruction::UDiv: // X /u 1 = X
2354 return ConstantInt::get(Ty, 1);
2355 case Instruction::FDiv: // X / 1.0 = X
2356 return ConstantFP::get(Ty, 1.0);
2357 default:
2358 return nullptr;
Duncan Sandsd7aeefe2012-06-12 14:33:56 +00002359 }
2360}
2361
Duncan Sands318a89d2012-06-13 09:42:13 +00002362Constant *ConstantExpr::getBinOpAbsorber(unsigned Opcode, Type *Ty) {
2363 switch (Opcode) {
2364 default:
2365 // Doesn't have an absorber.
Craig Topperc6207612014-04-09 06:08:46 +00002366 return nullptr;
Duncan Sands318a89d2012-06-13 09:42:13 +00002367
2368 case Instruction::Or:
2369 return Constant::getAllOnesValue(Ty);
2370
2371 case Instruction::And:
2372 case Instruction::Mul:
2373 return Constant::getNullValue(Ty);
2374 }
2375}
2376
Sanjay Patel1d0ac7c2016-04-29 22:03:27 +00002377/// Remove the constant from the constant table.
Pete Cooper86dd4cf2015-06-23 21:55:11 +00002378void ConstantExpr::destroyConstantImpl() {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002379 getType()->getContext().pImpl->ExprConstants.remove(this);
Vikram S. Adve4e537b22002-07-14 23:13:17 +00002380}
2381
Chris Lattner3cd8c562002-07-30 18:54:25 +00002382const char *ConstantExpr::getOpcodeName() const {
2383 return Instruction::getOpcodeName(getOpcode());
Vikram S. Adve4e537b22002-07-14 23:13:17 +00002384}
Reid Spencer1ebe1ab2004-07-17 23:48:33 +00002385
David Blaikie60310f22015-05-08 00:42:26 +00002386GetElementPtrConstantExpr::GetElementPtrConstantExpr(
2387 Type *SrcElementTy, Constant *C, ArrayRef<Constant *> IdxList, Type *DestTy)
2388 : ConstantExpr(DestTy, Instruction::GetElementPtr,
2389 OperandTraits<GetElementPtrConstantExpr>::op_end(this) -
2390 (IdxList.size() + 1),
2391 IdxList.size() + 1),
Eduard Burtescu19eb0312016-01-19 17:28:00 +00002392 SrcElementTy(SrcElementTy),
2393 ResElementTy(GetElementPtrInst::getIndexedType(SrcElementTy, IdxList)) {
Pete Coopereb31b682015-05-21 22:48:54 +00002394 Op<0>() = C;
Pete Cooper74510a42015-06-12 17:48:05 +00002395 Use *OperandList = getOperandList();
Chris Lattnera3b94ba2010-03-30 20:48:48 +00002396 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
2397 OperandList[i+1] = IdxList[i];
2398}
2399
David Blaikie60310f22015-05-08 00:42:26 +00002400Type *GetElementPtrConstantExpr::getSourceElementType() const {
2401 return SrcElementTy;
2402}
2403
Eduard Burtescu19eb0312016-01-19 17:28:00 +00002404Type *GetElementPtrConstantExpr::getResultElementType() const {
2405 return ResElementTy;
2406}
2407
Chris Lattner3756b912012-01-23 22:57:10 +00002408//===----------------------------------------------------------------------===//
2409// ConstantData* implementations
2410
Chris Lattnere4f3f102012-01-24 04:43:41 +00002411Type *ConstantDataSequential::getElementType() const {
2412 return getType()->getElementType();
2413}
2414
Chris Lattner5d4497b2012-01-24 09:31:43 +00002415StringRef ConstantDataSequential::getRawDataValues() const {
Chris Lattner00245f42012-01-24 13:41:11 +00002416 return StringRef(DataElements, getNumElements()*getElementByteSize());
Chris Lattner5d4497b2012-01-24 09:31:43 +00002417}
2418
Craig Toppere3dcce92015-08-01 22:20:21 +00002419bool ConstantDataSequential::isElementTypeCompatible(Type *Ty) {
Justin Bogner0ebc8602015-12-08 03:01:16 +00002420 if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy()) return true;
Craig Toppere3dcce92015-08-01 22:20:21 +00002421 if (auto *IT = dyn_cast<IntegerType>(Ty)) {
Chris Lattnere4f3f102012-01-24 04:43:41 +00002422 switch (IT->getBitWidth()) {
2423 case 8:
2424 case 16:
2425 case 32:
2426 case 64:
2427 return true;
2428 default: break;
2429 }
2430 }
2431 return false;
2432}
2433
Chris Lattner00245f42012-01-24 13:41:11 +00002434unsigned ConstantDataSequential::getNumElements() const {
Chris Lattner8a3df542012-01-25 01:32:59 +00002435 if (ArrayType *AT = dyn_cast<ArrayType>(getType()))
2436 return AT->getNumElements();
Chris Lattner8326bd82012-01-26 00:42:34 +00002437 return getType()->getVectorNumElements();
Chris Lattner00245f42012-01-24 13:41:11 +00002438}
2439
2440
Chris Lattnere4f3f102012-01-24 04:43:41 +00002441uint64_t ConstantDataSequential::getElementByteSize() const {
2442 return getElementType()->getPrimitiveSizeInBits()/8;
2443}
2444
Sanjay Patel1d0ac7c2016-04-29 22:03:27 +00002445/// Return the start of the specified element.
Chris Lattnere4f3f102012-01-24 04:43:41 +00002446const char *ConstantDataSequential::getElementPointer(unsigned Elt) const {
Chris Lattner00245f42012-01-24 13:41:11 +00002447 assert(Elt < getNumElements() && "Invalid Elt");
Chris Lattnere4f3f102012-01-24 04:43:41 +00002448 return DataElements+Elt*getElementByteSize();
2449}
2450
2451
Sanjay Patel1d0ac7c2016-04-29 22:03:27 +00002452/// Return true if the array is empty or all zeros.
Chris Lattner3756b912012-01-23 22:57:10 +00002453static bool isAllZeros(StringRef Arr) {
Benjamin Krameraf28e7d2016-06-26 14:10:56 +00002454 for (char I : Arr)
2455 if (I != 0)
Chris Lattner3756b912012-01-23 22:57:10 +00002456 return false;
2457 return true;
2458}
Chris Lattner030af792012-01-24 05:42:11 +00002459
Sanjay Patel1d0ac7c2016-04-29 22:03:27 +00002460/// This is the underlying implementation of all of the
Chris Lattner3756b912012-01-23 22:57:10 +00002461/// ConstantDataSequential::get methods. They all thunk down to here, providing
Chris Lattnerf06039b2012-01-30 18:19:30 +00002462/// the correct element type. We take the bytes in as a StringRef because
Chris Lattner3756b912012-01-23 22:57:10 +00002463/// we *want* an underlying "char*" to avoid TBAA type punning violations.
2464Constant *ConstantDataSequential::getImpl(StringRef Elements, Type *Ty) {
Chris Lattner8326bd82012-01-26 00:42:34 +00002465 assert(isElementTypeCompatible(Ty->getSequentialElementType()));
Chris Lattner139822f2012-01-24 14:17:05 +00002466 // If the elements are all zero or there are no elements, return a CAZ, which
2467 // is more dense and canonical.
Chris Lattner3756b912012-01-23 22:57:10 +00002468 if (isAllZeros(Elements))
2469 return ConstantAggregateZero::get(Ty);
2470
2471 // Do a lookup to see if we have already formed one of these.
David Blaikie5106ce72014-11-19 05:49:42 +00002472 auto &Slot =
2473 *Ty->getContext()
2474 .pImpl->CDSConstants.insert(std::make_pair(Elements, nullptr))
2475 .first;
Galina Kistanovafc259902012-07-13 01:25:27 +00002476
Chris Lattner3756b912012-01-23 22:57:10 +00002477 // The bucket can point to a linked list of different CDS's that have the same
2478 // body but different types. For example, 0,0,0,1 could be a 4 element array
2479 // of i8, or a 1-element array of i32. They'll both end up in the same
2480 /// StringMap bucket, linked up by their Next pointers. Walk the list.
David Blaikie5106ce72014-11-19 05:49:42 +00002481 ConstantDataSequential **Entry = &Slot.second;
Craig Topperc6207612014-04-09 06:08:46 +00002482 for (ConstantDataSequential *Node = *Entry; Node;
Chris Lattner3756b912012-01-23 22:57:10 +00002483 Entry = &Node->Next, Node = *Entry)
2484 if (Node->getType() == Ty)
2485 return Node;
Galina Kistanovafc259902012-07-13 01:25:27 +00002486
Chris Lattner3756b912012-01-23 22:57:10 +00002487 // Okay, we didn't get a hit. Create a node of the right class, link it in,
2488 // and return it.
2489 if (isa<ArrayType>(Ty))
David Blaikie5106ce72014-11-19 05:49:42 +00002490 return *Entry = new ConstantDataArray(Ty, Slot.first().data());
Chris Lattner3756b912012-01-23 22:57:10 +00002491
2492 assert(isa<VectorType>(Ty));
David Blaikie5106ce72014-11-19 05:49:42 +00002493 return *Entry = new ConstantDataVector(Ty, Slot.first().data());
Chris Lattner3756b912012-01-23 22:57:10 +00002494}
2495
Pete Cooper86dd4cf2015-06-23 21:55:11 +00002496void ConstantDataSequential::destroyConstantImpl() {
Chris Lattner3756b912012-01-23 22:57:10 +00002497 // Remove the constant from the StringMap.
Bjorn Petterssonaa025802018-07-03 12:39:52 +00002498 StringMap<ConstantDataSequential*> &CDSConstants =
Chris Lattner3756b912012-01-23 22:57:10 +00002499 getType()->getContext().pImpl->CDSConstants;
Galina Kistanovafc259902012-07-13 01:25:27 +00002500
Chris Lattner3756b912012-01-23 22:57:10 +00002501 StringMap<ConstantDataSequential*>::iterator Slot =
Chris Lattner5d4497b2012-01-24 09:31:43 +00002502 CDSConstants.find(getRawDataValues());
Chris Lattner3756b912012-01-23 22:57:10 +00002503
2504 assert(Slot != CDSConstants.end() && "CDS not found in uniquing table");
2505
2506 ConstantDataSequential **Entry = &Slot->getValue();
2507
2508 // Remove the entry from the hash table.
Craig Topperc6207612014-04-09 06:08:46 +00002509 if (!(*Entry)->Next) {
Chris Lattner3756b912012-01-23 22:57:10 +00002510 // If there is only one value in the bucket (common case) it must be this
2511 // entry, and removing the entry should remove the bucket completely.
2512 assert((*Entry) == this && "Hash mismatch in ConstantDataSequential");
2513 getContext().pImpl->CDSConstants.erase(Slot);
2514 } else {
Bjorn Petterssonaa025802018-07-03 12:39:52 +00002515 // Otherwise, there are multiple entries linked off the bucket, unlink the
Chris Lattner3756b912012-01-23 22:57:10 +00002516 // node we care about but keep the bucket around.
2517 for (ConstantDataSequential *Node = *Entry; ;
2518 Entry = &Node->Next, Node = *Entry) {
2519 assert(Node && "Didn't find entry in its uniquing hash table!");
2520 // If we found our entry, unlink it from the list and we're done.
2521 if (Node == this) {
2522 *Entry = Node->Next;
2523 break;
2524 }
2525 }
2526 }
Galina Kistanovafc259902012-07-13 01:25:27 +00002527
Chris Lattner3756b912012-01-23 22:57:10 +00002528 // If we were part of a list, make sure that we don't delete the list that is
2529 // still owned by the uniquing map.
Craig Topperc6207612014-04-09 06:08:46 +00002530 Next = nullptr;
Chris Lattner3756b912012-01-23 22:57:10 +00002531}
2532
Rafael Espindola8c97e192015-02-19 16:08:20 +00002533/// getFP() constructors - Return a constant with array type with an element
2534/// count and element type of float with precision matching the number of
2535/// bits in the ArrayRef passed in. (i.e. half for 16bits, float for 32bits,
2536/// double for 64bits) Note that this can return a ConstantAggregateZero
2537/// object.
2538Constant *ConstantDataArray::getFP(LLVMContext &Context,
2539 ArrayRef<uint16_t> Elts) {
Justin Bognerb7389d6712015-12-09 21:21:07 +00002540 Type *Ty = ArrayType::get(Type::getHalfTy(Context), Elts.size());
Rafael Espindola8c97e192015-02-19 16:08:20 +00002541 const char *Data = reinterpret_cast<const char *>(Elts.data());
Craig Topper393ce692017-07-11 15:52:21 +00002542 return getImpl(StringRef(Data, Elts.size() * 2), Ty);
Rafael Espindola8c97e192015-02-19 16:08:20 +00002543}
2544Constant *ConstantDataArray::getFP(LLVMContext &Context,
2545 ArrayRef<uint32_t> Elts) {
2546 Type *Ty = ArrayType::get(Type::getFloatTy(Context), Elts.size());
2547 const char *Data = reinterpret_cast<const char *>(Elts.data());
Craig Topper393ce692017-07-11 15:52:21 +00002548 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
Rafael Espindola8c97e192015-02-19 16:08:20 +00002549}
2550Constant *ConstantDataArray::getFP(LLVMContext &Context,
2551 ArrayRef<uint64_t> Elts) {
2552 Type *Ty = ArrayType::get(Type::getDoubleTy(Context), Elts.size());
2553 const char *Data = reinterpret_cast<const char *>(Elts.data());
Craig Topper393ce692017-07-11 15:52:21 +00002554 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
Chris Lattner3756b912012-01-23 22:57:10 +00002555}
2556
Chris Lattner20683932012-01-24 14:04:40 +00002557Constant *ConstantDataArray::getString(LLVMContext &Context,
2558 StringRef Str, bool AddNull) {
Galina Kistanovafc259902012-07-13 01:25:27 +00002559 if (!AddNull) {
Fangrui Song6a0746a2019-04-07 03:58:42 +00002560 const uint8_t *Data = Str.bytes_begin();
Craig Topper393ce692017-07-11 15:52:21 +00002561 return get(Context, makeArrayRef(Data, Str.size()));
Galina Kistanovafc259902012-07-13 01:25:27 +00002562 }
2563
Chris Lattner20683932012-01-24 14:04:40 +00002564 SmallVector<uint8_t, 64> ElementVals;
2565 ElementVals.append(Str.begin(), Str.end());
2566 ElementVals.push_back(0);
2567 return get(Context, ElementVals);
2568}
Chris Lattner3756b912012-01-23 22:57:10 +00002569
2570/// get() constructors - Return a constant with vector type with an element
2571/// count and element type matching the ArrayRef passed in. Note that this
2572/// can return a ConstantAggregateZero object.
Chris Lattner20683932012-01-24 14:04:40 +00002573Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint8_t> Elts){
Chris Lattner3756b912012-01-23 22:57:10 +00002574 Type *Ty = VectorType::get(Type::getInt8Ty(Context), Elts.size());
Galina Kistanovafc259902012-07-13 01:25:27 +00002575 const char *Data = reinterpret_cast<const char *>(Elts.data());
Craig Topper393ce692017-07-11 15:52:21 +00002576 return getImpl(StringRef(Data, Elts.size() * 1), Ty);
Chris Lattner3756b912012-01-23 22:57:10 +00002577}
Chris Lattner20683932012-01-24 14:04:40 +00002578Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint16_t> Elts){
Chris Lattner3756b912012-01-23 22:57:10 +00002579 Type *Ty = VectorType::get(Type::getInt16Ty(Context), Elts.size());
Galina Kistanovafc259902012-07-13 01:25:27 +00002580 const char *Data = reinterpret_cast<const char *>(Elts.data());
Craig Topper393ce692017-07-11 15:52:21 +00002581 return getImpl(StringRef(Data, Elts.size() * 2), Ty);
Chris Lattner3756b912012-01-23 22:57:10 +00002582}
Chris Lattner20683932012-01-24 14:04:40 +00002583Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint32_t> Elts){
Chris Lattner3756b912012-01-23 22:57:10 +00002584 Type *Ty = VectorType::get(Type::getInt32Ty(Context), Elts.size());
Galina Kistanovafc259902012-07-13 01:25:27 +00002585 const char *Data = reinterpret_cast<const char *>(Elts.data());
Craig Topper393ce692017-07-11 15:52:21 +00002586 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
Chris Lattner3756b912012-01-23 22:57:10 +00002587}
Chris Lattner20683932012-01-24 14:04:40 +00002588Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint64_t> Elts){
Chris Lattner3756b912012-01-23 22:57:10 +00002589 Type *Ty = VectorType::get(Type::getInt64Ty(Context), Elts.size());
Galina Kistanovafc259902012-07-13 01:25:27 +00002590 const char *Data = reinterpret_cast<const char *>(Elts.data());
Craig Topper393ce692017-07-11 15:52:21 +00002591 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
Chris Lattner3756b912012-01-23 22:57:10 +00002592}
Chris Lattner20683932012-01-24 14:04:40 +00002593Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<float> Elts) {
Chris Lattner3756b912012-01-23 22:57:10 +00002594 Type *Ty = VectorType::get(Type::getFloatTy(Context), Elts.size());
Galina Kistanovafc259902012-07-13 01:25:27 +00002595 const char *Data = reinterpret_cast<const char *>(Elts.data());
Craig Topper393ce692017-07-11 15:52:21 +00002596 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
Chris Lattner3756b912012-01-23 22:57:10 +00002597}
Chris Lattner20683932012-01-24 14:04:40 +00002598Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<double> Elts) {
Chris Lattner3756b912012-01-23 22:57:10 +00002599 Type *Ty = VectorType::get(Type::getDoubleTy(Context), Elts.size());
Galina Kistanovafc259902012-07-13 01:25:27 +00002600 const char *Data = reinterpret_cast<const char *>(Elts.data());
Craig Topper393ce692017-07-11 15:52:21 +00002601 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
Rafael Espindola8c97e192015-02-19 16:08:20 +00002602}
2603
2604/// getFP() constructors - Return a constant with vector type with an element
2605/// count and element type of float with the precision matching the number of
2606/// bits in the ArrayRef passed in. (i.e. half for 16bits, float for 32bits,
2607/// double for 64bits) Note that this can return a ConstantAggregateZero
2608/// object.
2609Constant *ConstantDataVector::getFP(LLVMContext &Context,
2610 ArrayRef<uint16_t> Elts) {
2611 Type *Ty = VectorType::get(Type::getHalfTy(Context), Elts.size());
2612 const char *Data = reinterpret_cast<const char *>(Elts.data());
Craig Topper393ce692017-07-11 15:52:21 +00002613 return getImpl(StringRef(Data, Elts.size() * 2), Ty);
Rafael Espindola8c97e192015-02-19 16:08:20 +00002614}
2615Constant *ConstantDataVector::getFP(LLVMContext &Context,
2616 ArrayRef<uint32_t> Elts) {
2617 Type *Ty = VectorType::get(Type::getFloatTy(Context), Elts.size());
2618 const char *Data = reinterpret_cast<const char *>(Elts.data());
Craig Topper393ce692017-07-11 15:52:21 +00002619 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
Rafael Espindola8c97e192015-02-19 16:08:20 +00002620}
2621Constant *ConstantDataVector::getFP(LLVMContext &Context,
2622 ArrayRef<uint64_t> Elts) {
2623 Type *Ty = VectorType::get(Type::getDoubleTy(Context), Elts.size());
2624 const char *Data = reinterpret_cast<const char *>(Elts.data());
Craig Topper393ce692017-07-11 15:52:21 +00002625 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
Chris Lattner3756b912012-01-23 22:57:10 +00002626}
2627
Chris Lattnere9eed292012-01-25 05:19:54 +00002628Constant *ConstantDataVector::getSplat(unsigned NumElts, Constant *V) {
2629 assert(isElementTypeCompatible(V->getType()) &&
2630 "Element type not compatible with ConstantData");
2631 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
2632 if (CI->getType()->isIntegerTy(8)) {
2633 SmallVector<uint8_t, 16> Elts(NumElts, CI->getZExtValue());
2634 return get(V->getContext(), Elts);
2635 }
2636 if (CI->getType()->isIntegerTy(16)) {
2637 SmallVector<uint16_t, 16> Elts(NumElts, CI->getZExtValue());
2638 return get(V->getContext(), Elts);
2639 }
2640 if (CI->getType()->isIntegerTy(32)) {
2641 SmallVector<uint32_t, 16> Elts(NumElts, CI->getZExtValue());
2642 return get(V->getContext(), Elts);
2643 }
2644 assert(CI->getType()->isIntegerTy(64) && "Unsupported ConstantData type");
2645 SmallVector<uint64_t, 16> Elts(NumElts, CI->getZExtValue());
2646 return get(V->getContext(), Elts);
2647 }
2648
Chris Lattner978fe0c2012-01-30 06:21:21 +00002649 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
Justin Bogner0ebc8602015-12-08 03:01:16 +00002650 if (CFP->getType()->isHalfTy()) {
2651 SmallVector<uint16_t, 16> Elts(
2652 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
2653 return getFP(V->getContext(), Elts);
2654 }
Chris Lattner978fe0c2012-01-30 06:21:21 +00002655 if (CFP->getType()->isFloatTy()) {
Rafael Espindola8c97e192015-02-19 16:08:20 +00002656 SmallVector<uint32_t, 16> Elts(
2657 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
2658 return getFP(V->getContext(), Elts);
Chris Lattner978fe0c2012-01-30 06:21:21 +00002659 }
2660 if (CFP->getType()->isDoubleTy()) {
Rafael Espindola8c97e192015-02-19 16:08:20 +00002661 SmallVector<uint64_t, 16> Elts(
2662 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
2663 return getFP(V->getContext(), Elts);
Chris Lattner978fe0c2012-01-30 06:21:21 +00002664 }
Chris Lattnere9eed292012-01-25 05:19:54 +00002665 }
Chris Lattner978fe0c2012-01-30 06:21:21 +00002666 return ConstantVector::getSplat(NumElts, V);
Chris Lattnere9eed292012-01-25 05:19:54 +00002667}
2668
2669
Chris Lattnere4f3f102012-01-24 04:43:41 +00002670uint64_t ConstantDataSequential::getElementAsInteger(unsigned Elt) const {
2671 assert(isa<IntegerType>(getElementType()) &&
2672 "Accessor can only be used when element is an integer");
2673 const char *EltPtr = getElementPointer(Elt);
Galina Kistanovafc259902012-07-13 01:25:27 +00002674
Chris Lattnere4f3f102012-01-24 04:43:41 +00002675 // The data is stored in host byte order, make sure to cast back to the right
2676 // type to load with the right endianness.
Chris Lattner8326bd82012-01-26 00:42:34 +00002677 switch (getElementType()->getIntegerBitWidth()) {
Craig Topperc514b542012-02-05 22:14:15 +00002678 default: llvm_unreachable("Invalid bitwidth for CDS");
Galina Kistanovafc259902012-07-13 01:25:27 +00002679 case 8:
Craig Topper393ce692017-07-11 15:52:21 +00002680 return *reinterpret_cast<const uint8_t *>(EltPtr);
Galina Kistanovafc259902012-07-13 01:25:27 +00002681 case 16:
Craig Topper393ce692017-07-11 15:52:21 +00002682 return *reinterpret_cast<const uint16_t *>(EltPtr);
Galina Kistanovafc259902012-07-13 01:25:27 +00002683 case 32:
Craig Topper393ce692017-07-11 15:52:21 +00002684 return *reinterpret_cast<const uint32_t *>(EltPtr);
Galina Kistanovafc259902012-07-13 01:25:27 +00002685 case 64:
Craig Topper393ce692017-07-11 15:52:21 +00002686 return *reinterpret_cast<const uint64_t *>(EltPtr);
Chris Lattnere4f3f102012-01-24 04:43:41 +00002687 }
2688}
2689
Craig Topper0b4b4e32017-07-15 22:06:19 +00002690APInt ConstantDataSequential::getElementAsAPInt(unsigned Elt) const {
2691 assert(isa<IntegerType>(getElementType()) &&
2692 "Accessor can only be used when element is an integer");
2693 const char *EltPtr = getElementPointer(Elt);
2694
2695 // The data is stored in host byte order, make sure to cast back to the right
2696 // type to load with the right endianness.
2697 switch (getElementType()->getIntegerBitWidth()) {
2698 default: llvm_unreachable("Invalid bitwidth for CDS");
2699 case 8: {
2700 auto EltVal = *reinterpret_cast<const uint8_t *>(EltPtr);
2701 return APInt(8, EltVal);
2702 }
2703 case 16: {
2704 auto EltVal = *reinterpret_cast<const uint16_t *>(EltPtr);
2705 return APInt(16, EltVal);
2706 }
2707 case 32: {
2708 auto EltVal = *reinterpret_cast<const uint32_t *>(EltPtr);
2709 return APInt(32, EltVal);
2710 }
2711 case 64: {
2712 auto EltVal = *reinterpret_cast<const uint64_t *>(EltPtr);
2713 return APInt(64, EltVal);
2714 }
2715 }
2716}
2717
Chris Lattnere4f3f102012-01-24 04:43:41 +00002718APFloat ConstantDataSequential::getElementAsAPFloat(unsigned Elt) const {
2719 const char *EltPtr = getElementPointer(Elt);
2720
2721 switch (getElementType()->getTypeID()) {
Nick Lewyckyff509622012-01-25 03:20:12 +00002722 default:
Craig Topperc514b542012-02-05 22:14:15 +00002723 llvm_unreachable("Accessor can only be used when element is float/double!");
Justin Bogner0ebc8602015-12-08 03:01:16 +00002724 case Type::HalfTyID: {
2725 auto EltVal = *reinterpret_cast<const uint16_t *>(EltPtr);
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002726 return APFloat(APFloat::IEEEhalf(), APInt(16, EltVal));
Justin Bogner0ebc8602015-12-08 03:01:16 +00002727 }
Benjamin Kramer7af984b2015-02-20 15:11:55 +00002728 case Type::FloatTyID: {
2729 auto EltVal = *reinterpret_cast<const uint32_t *>(EltPtr);
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002730 return APFloat(APFloat::IEEEsingle(), APInt(32, EltVal));
Benjamin Kramer7af984b2015-02-20 15:11:55 +00002731 }
2732 case Type::DoubleTyID: {
2733 auto EltVal = *reinterpret_cast<const uint64_t *>(EltPtr);
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002734 return APFloat(APFloat::IEEEdouble(), APInt(64, EltVal));
Chris Lattnere4f3f102012-01-24 04:43:41 +00002735 }
Benjamin Kramer7af984b2015-02-20 15:11:55 +00002736 }
Chris Lattnere4f3f102012-01-24 04:43:41 +00002737}
2738
Chris Lattnere4f3f102012-01-24 04:43:41 +00002739float ConstantDataSequential::getElementAsFloat(unsigned Elt) const {
2740 assert(getElementType()->isFloatTy() &&
2741 "Accessor can only be used when element is a 'float'");
Craig Topper393ce692017-07-11 15:52:21 +00002742 return *reinterpret_cast<const float *>(getElementPointer(Elt));
Chris Lattnere4f3f102012-01-24 04:43:41 +00002743}
2744
Chris Lattnere4f3f102012-01-24 04:43:41 +00002745double ConstantDataSequential::getElementAsDouble(unsigned Elt) const {
2746 assert(getElementType()->isDoubleTy() &&
2747 "Accessor can only be used when element is a 'float'");
Craig Topper393ce692017-07-11 15:52:21 +00002748 return *reinterpret_cast<const double *>(getElementPointer(Elt));
Chris Lattnere4f3f102012-01-24 04:43:41 +00002749}
2750
Chris Lattnere4f3f102012-01-24 04:43:41 +00002751Constant *ConstantDataSequential::getElementAsConstant(unsigned Elt) const {
Justin Bogner0ebc8602015-12-08 03:01:16 +00002752 if (getElementType()->isHalfTy() || getElementType()->isFloatTy() ||
2753 getElementType()->isDoubleTy())
Chris Lattnere4f3f102012-01-24 04:43:41 +00002754 return ConstantFP::get(getContext(), getElementAsAPFloat(Elt));
Galina Kistanovafc259902012-07-13 01:25:27 +00002755
Chris Lattnere4f3f102012-01-24 04:43:41 +00002756 return ConstantInt::get(getElementType(), getElementAsInteger(Elt));
2757}
2758
Matthias Braun50ec0b52017-05-19 22:37:09 +00002759bool ConstantDataSequential::isString(unsigned CharSize) const {
2760 return isa<ArrayType>(getType()) && getElementType()->isIntegerTy(CharSize);
Chris Lattner5dd4d872012-01-24 09:01:07 +00002761}
Chris Lattner3756b912012-01-23 22:57:10 +00002762
Chris Lattner5dd4d872012-01-24 09:01:07 +00002763bool ConstantDataSequential::isCString() const {
2764 if (!isString())
2765 return false;
Galina Kistanovafc259902012-07-13 01:25:27 +00002766
Chris Lattner5dd4d872012-01-24 09:01:07 +00002767 StringRef Str = getAsString();
Galina Kistanovafc259902012-07-13 01:25:27 +00002768
Chris Lattner5dd4d872012-01-24 09:01:07 +00002769 // The last value must be nul.
2770 if (Str.back() != 0) return false;
Galina Kistanovafc259902012-07-13 01:25:27 +00002771
Chris Lattner5dd4d872012-01-24 09:01:07 +00002772 // Other elements must be non-nul.
2773 return Str.drop_back().find(0) == StringRef::npos;
2774}
Chris Lattner3756b912012-01-23 22:57:10 +00002775
Craig Topper0b4b4e32017-07-15 22:06:19 +00002776bool ConstantDataVector::isSplat() const {
Chris Lattnerf14a67f2012-01-26 02:31:22 +00002777 const char *Base = getRawDataValues().data();
Galina Kistanovafc259902012-07-13 01:25:27 +00002778
Chris Lattnerf14a67f2012-01-26 02:31:22 +00002779 // Compare elements 1+ to the 0'th element.
2780 unsigned EltSize = getElementByteSize();
2781 for (unsigned i = 1, e = getNumElements(); i != e; ++i)
2782 if (memcmp(Base, Base+i*EltSize, EltSize))
Craig Topper0b4b4e32017-07-15 22:06:19 +00002783 return false;
Galina Kistanovafc259902012-07-13 01:25:27 +00002784
Craig Topper0b4b4e32017-07-15 22:06:19 +00002785 return true;
2786}
2787
2788Constant *ConstantDataVector::getSplatValue() const {
Chris Lattnerf14a67f2012-01-26 02:31:22 +00002789 // If they're all the same, return the 0th one as a representative.
Craig Topper0b4b4e32017-07-15 22:06:19 +00002790 return isSplat() ? getElementAsConstant(0) : nullptr;
Chris Lattnerf14a67f2012-01-26 02:31:22 +00002791}
Chris Lattnera3b94ba2010-03-30 20:48:48 +00002792
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002793//===----------------------------------------------------------------------===//
Pete Cooper5815b1f2015-06-24 18:55:24 +00002794// handleOperandChange implementations
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002795
Pete Cooper5815b1f2015-06-24 18:55:24 +00002796/// Update this constant array to change uses of
Chris Lattner913849b2007-08-21 00:55:23 +00002797/// 'From' to be uses of 'To'. This must update the uniquing data structures
2798/// etc.
2799///
2800/// Note that we intentionally replace all uses of From with To here. Consider
2801/// a large array that uses 'From' 1000 times. By handling this case all here,
Pete Cooper5815b1f2015-06-24 18:55:24 +00002802/// ConstantArray::handleOperandChange is only invoked once, and that
Chris Lattner913849b2007-08-21 00:55:23 +00002803/// single invocation handles all 1000 uses. Handling them one at a time would
2804/// work, but would be really slow because it would have to unique each updated
2805/// array instance.
Chris Lattner31b132c2009-10-28 00:01:44 +00002806///
Mehdi Amini8914d292016-02-10 22:47:15 +00002807void Constant::handleOperandChange(Value *From, Value *To) {
Pete Cooper5815b1f2015-06-24 18:55:24 +00002808 Value *Replacement = nullptr;
2809 switch (getValueID()) {
2810 default:
2811 llvm_unreachable("Not a constant!");
2812#define HANDLE_CONSTANT(Name) \
2813 case Value::Name##Val: \
Mehdi Amini8914d292016-02-10 22:47:15 +00002814 Replacement = cast<Name>(this)->handleOperandChangeImpl(From, To); \
Pete Cooper5815b1f2015-06-24 18:55:24 +00002815 break;
2816#include "llvm/IR/Value.def"
2817 }
2818
2819 // If handleOperandChangeImpl returned nullptr, then it handled
2820 // replacing itself and we don't want to delete or replace anything else here.
2821 if (!Replacement)
2822 return;
2823
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002824 // I do need to replace this with an existing value.
2825 assert(Replacement != this && "I didn't contain From!");
2826
2827 // Everyone using this now uses the replacement.
2828 replaceAllUsesWith(Replacement);
2829
2830 // Delete the old constant!
2831 destroyConstant();
2832}
2833
Mehdi Amini8914d292016-02-10 22:47:15 +00002834Value *ConstantArray::handleOperandChangeImpl(Value *From, Value *To) {
Owen Andersonc2c79322009-07-28 18:32:17 +00002835 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2836 Constant *ToC = cast<Constant>(To);
2837
Talin46e9b442012-02-05 20:54:10 +00002838 SmallVector<Constant*, 8> Values;
Owen Andersonc2c79322009-07-28 18:32:17 +00002839 Values.reserve(getNumOperands()); // Build replacement array.
2840
Galina Kistanovafc259902012-07-13 01:25:27 +00002841 // Fill values with the modified operands of the constant array. Also,
Owen Andersonc2c79322009-07-28 18:32:17 +00002842 // compute whether this turns into an all-zeros array.
Owen Andersonc2c79322009-07-28 18:32:17 +00002843 unsigned NumUpdated = 0;
Galina Kistanovafc259902012-07-13 01:25:27 +00002844
Chris Lattnerf14a67f2012-01-26 02:31:22 +00002845 // Keep track of whether all the values in the array are "ToC".
2846 bool AllSame = true;
Pete Cooper74510a42015-06-12 17:48:05 +00002847 Use *OperandList = getOperandList();
Mehdi Amini8914d292016-02-10 22:47:15 +00002848 unsigned OperandNo = 0;
Chris Lattnerf14a67f2012-01-26 02:31:22 +00002849 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2850 Constant *Val = cast<Constant>(O->get());
2851 if (Val == From) {
Mehdi Amini8914d292016-02-10 22:47:15 +00002852 OperandNo = (O - OperandList);
Chris Lattnerf14a67f2012-01-26 02:31:22 +00002853 Val = ToC;
2854 ++NumUpdated;
Owen Andersonc2c79322009-07-28 18:32:17 +00002855 }
Chris Lattnerf14a67f2012-01-26 02:31:22 +00002856 Values.push_back(Val);
Talin46e9b442012-02-05 20:54:10 +00002857 AllSame &= Val == ToC;
Owen Andersonc2c79322009-07-28 18:32:17 +00002858 }
Galina Kistanovafc259902012-07-13 01:25:27 +00002859
Pete Cooper5815b1f2015-06-24 18:55:24 +00002860 if (AllSame && ToC->isNullValue())
2861 return ConstantAggregateZero::get(getType());
2862
2863 if (AllSame && isa<UndefValue>(ToC))
2864 return UndefValue::get(getType());
Aaron Ballmane4b91dc2014-08-19 14:59:02 +00002865
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002866 // Check for any other type of constant-folding.
Pete Cooper5815b1f2015-06-24 18:55:24 +00002867 if (Constant *C = getImpl(getType(), Values))
2868 return C;
Aaron Ballmane4b91dc2014-08-19 14:59:02 +00002869
Duncan P. N. Exon Smith909620a2014-08-19 19:13:30 +00002870 // Update to the new value.
Pete Cooper5815b1f2015-06-24 18:55:24 +00002871 return getContext().pImpl->ArrayConstants.replaceOperandsInPlace(
Mehdi Amini8914d292016-02-10 22:47:15 +00002872 Values, this, From, ToC, NumUpdated, OperandNo);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002873}
2874
Mehdi Amini8914d292016-02-10 22:47:15 +00002875Value *ConstantStruct::handleOperandChangeImpl(Value *From, Value *To) {
Owen Anderson45308b52009-07-27 22:29:26 +00002876 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2877 Constant *ToC = cast<Constant>(To);
2878
Pete Cooper74510a42015-06-12 17:48:05 +00002879 Use *OperandList = getOperandList();
Owen Anderson45308b52009-07-27 22:29:26 +00002880
Talin46e9b442012-02-05 20:54:10 +00002881 SmallVector<Constant*, 8> Values;
Owen Anderson45308b52009-07-27 22:29:26 +00002882 Values.reserve(getNumOperands()); // Build replacement struct.
Galina Kistanovafc259902012-07-13 01:25:27 +00002883
2884 // Fill values with the modified operands of the constant struct. Also,
Owen Anderson45308b52009-07-27 22:29:26 +00002885 // compute whether this turns into an all-zeros struct.
Mehdi Amini8914d292016-02-10 22:47:15 +00002886 unsigned NumUpdated = 0;
2887 bool AllSame = true;
2888 unsigned OperandNo = 0;
2889 for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O) {
2890 Constant *Val = cast<Constant>(O->get());
2891 if (Val == From) {
2892 OperandNo = (O - OperandList);
2893 Val = ToC;
2894 ++NumUpdated;
Owen Anderson45308b52009-07-27 22:29:26 +00002895 }
Mehdi Amini8914d292016-02-10 22:47:15 +00002896 Values.push_back(Val);
2897 AllSame &= Val == ToC;
Owen Anderson45308b52009-07-27 22:29:26 +00002898 }
Galina Kistanovafc259902012-07-13 01:25:27 +00002899
Mehdi Amini8914d292016-02-10 22:47:15 +00002900 if (AllSame && ToC->isNullValue())
Pete Cooper5815b1f2015-06-24 18:55:24 +00002901 return ConstantAggregateZero::get(getType());
2902
Mehdi Amini8914d292016-02-10 22:47:15 +00002903 if (AllSame && isa<UndefValue>(ToC))
Pete Cooper5815b1f2015-06-24 18:55:24 +00002904 return UndefValue::get(getType());
Galina Kistanovafc259902012-07-13 01:25:27 +00002905
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002906 // Update to the new value.
Pete Cooper5815b1f2015-06-24 18:55:24 +00002907 return getContext().pImpl->StructConstants.replaceOperandsInPlace(
Mehdi Amini8914d292016-02-10 22:47:15 +00002908 Values, this, From, ToC, NumUpdated, OperandNo);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002909}
2910
Mehdi Amini8914d292016-02-10 22:47:15 +00002911Value *ConstantVector::handleOperandChangeImpl(Value *From, Value *To) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002912 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002913 Constant *ToC = cast<Constant>(To);
Galina Kistanovafc259902012-07-13 01:25:27 +00002914
Chris Lattnera474bb22012-01-26 20:40:56 +00002915 SmallVector<Constant*, 8> Values;
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002916 Values.reserve(getNumOperands()); // Build replacement array...
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002917 unsigned NumUpdated = 0;
Mehdi Amini8914d292016-02-10 22:47:15 +00002918 unsigned OperandNo = 0;
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002919 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2920 Constant *Val = getOperand(i);
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002921 if (Val == From) {
Mehdi Amini8914d292016-02-10 22:47:15 +00002922 OperandNo = i;
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002923 ++NumUpdated;
2924 Val = ToC;
2925 }
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002926 Values.push_back(Val);
2927 }
Galina Kistanovafc259902012-07-13 01:25:27 +00002928
Pete Cooper5815b1f2015-06-24 18:55:24 +00002929 if (Constant *C = getImpl(Values))
2930 return C;
Duncan P. N. Exon Smith687744d2014-08-19 02:24:46 +00002931
Duncan P. N. Exon Smith909620a2014-08-19 19:13:30 +00002932 // Update to the new value.
Pete Cooper5815b1f2015-06-24 18:55:24 +00002933 return getContext().pImpl->VectorConstants.replaceOperandsInPlace(
Mehdi Amini8914d292016-02-10 22:47:15 +00002934 Values, this, From, ToC, NumUpdated, OperandNo);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002935}
2936
Mehdi Amini8914d292016-02-10 22:47:15 +00002937Value *ConstantExpr::handleOperandChangeImpl(Value *From, Value *ToV) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002938 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2939 Constant *To = cast<Constant>(ToV);
Galina Kistanovafc259902012-07-13 01:25:27 +00002940
Chris Lattner37e38352012-01-26 20:37:11 +00002941 SmallVector<Constant*, 8> NewOps;
Duncan P. N. Exon Smith33de00c2014-08-19 20:03:35 +00002942 unsigned NumUpdated = 0;
Mehdi Amini8914d292016-02-10 22:47:15 +00002943 unsigned OperandNo = 0;
Chris Lattner37e38352012-01-26 20:37:11 +00002944 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2945 Constant *Op = getOperand(i);
Duncan P. N. Exon Smith33de00c2014-08-19 20:03:35 +00002946 if (Op == From) {
Mehdi Amini8914d292016-02-10 22:47:15 +00002947 OperandNo = i;
Duncan P. N. Exon Smith33de00c2014-08-19 20:03:35 +00002948 ++NumUpdated;
2949 Op = To;
2950 }
2951 NewOps.push_back(Op);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002952 }
Duncan P. N. Exon Smith33de00c2014-08-19 20:03:35 +00002953 assert(NumUpdated && "I didn't contain From!");
Galina Kistanovafc259902012-07-13 01:25:27 +00002954
Pete Cooper5815b1f2015-06-24 18:55:24 +00002955 if (Constant *C = getWithOperands(NewOps, getType(), true))
2956 return C;
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002957
Duncan P. N. Exon Smith33de00c2014-08-19 20:03:35 +00002958 // Update to the new value.
Pete Cooper5815b1f2015-06-24 18:55:24 +00002959 return getContext().pImpl->ExprConstants.replaceOperandsInPlace(
Mehdi Amini8914d292016-02-10 22:47:15 +00002960 NewOps, this, From, To, NumUpdated, OperandNo);
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002961}
2962
James Molloyce545682012-11-17 17:56:30 +00002963Instruction *ConstantExpr::getAsInstruction() {
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +00002964 SmallVector<Value *, 4> ValueOperands(op_begin(), op_end());
James Molloyce545682012-11-17 17:56:30 +00002965 ArrayRef<Value*> Ops(ValueOperands);
2966
2967 switch (getOpcode()) {
2968 case Instruction::Trunc:
2969 case Instruction::ZExt:
2970 case Instruction::SExt:
2971 case Instruction::FPTrunc:
2972 case Instruction::FPExt:
2973 case Instruction::UIToFP:
2974 case Instruction::SIToFP:
2975 case Instruction::FPToUI:
2976 case Instruction::FPToSI:
2977 case Instruction::PtrToInt:
2978 case Instruction::IntToPtr:
2979 case Instruction::BitCast:
Eli Bendersky157a97a2014-01-18 22:54:33 +00002980 case Instruction::AddrSpaceCast:
James Molloyce545682012-11-17 17:56:30 +00002981 return CastInst::Create((Instruction::CastOps)getOpcode(),
2982 Ops[0], getType());
2983 case Instruction::Select:
2984 return SelectInst::Create(Ops[0], Ops[1], Ops[2]);
2985 case Instruction::InsertElement:
2986 return InsertElementInst::Create(Ops[0], Ops[1], Ops[2]);
2987 case Instruction::ExtractElement:
2988 return ExtractElementInst::Create(Ops[0], Ops[1]);
2989 case Instruction::InsertValue:
2990 return InsertValueInst::Create(Ops[0], Ops[1], getIndices());
2991 case Instruction::ExtractValue:
2992 return ExtractValueInst::Create(Ops[0], getIndices());
2993 case Instruction::ShuffleVector:
2994 return new ShuffleVectorInst(Ops[0], Ops[1], Ops[2]);
2995
David Blaikie741c8f82015-03-14 01:53:18 +00002996 case Instruction::GetElementPtr: {
2997 const auto *GO = cast<GEPOperator>(this);
2998 if (GO->isInBounds())
2999 return GetElementPtrInst::CreateInBounds(GO->getSourceElementType(),
3000 Ops[0], Ops.slice(1));
3001 return GetElementPtrInst::Create(GO->getSourceElementType(), Ops[0],
3002 Ops.slice(1));
3003 }
James Molloyce545682012-11-17 17:56:30 +00003004 case Instruction::ICmp:
3005 case Instruction::FCmp:
3006 return CmpInst::Create((Instruction::OtherOps)getOpcode(),
Craig Topper1c3f2832015-12-15 06:11:33 +00003007 (CmpInst::Predicate)getPredicate(), Ops[0], Ops[1]);
Cameron McInally1d0c8452019-05-05 16:07:09 +00003008 case Instruction::FNeg:
3009 return UnaryOperator::Create((Instruction::UnaryOps)getOpcode(), Ops[0]);
James Molloyce545682012-11-17 17:56:30 +00003010 default:
3011 assert(getNumOperands() == 2 && "Must be binary operator?");
3012 BinaryOperator *BO =
3013 BinaryOperator::Create((Instruction::BinaryOps)getOpcode(),
3014 Ops[0], Ops[1]);
3015 if (isa<OverflowingBinaryOperator>(BO)) {
3016 BO->setHasNoUnsignedWrap(SubclassOptionalData &
3017 OverflowingBinaryOperator::NoUnsignedWrap);
3018 BO->setHasNoSignedWrap(SubclassOptionalData &
3019 OverflowingBinaryOperator::NoSignedWrap);
3020 }
3021 if (isa<PossiblyExactOperator>(BO))
3022 BO->setIsExact(SubclassOptionalData & PossiblyExactOperator::IsExact);
3023 return BO;
3024 }
3025}