blob: 7368a4c8571ae075fe1ad7d054e7200946dea125 [file] [log] [blame]
Chris Lattner2b383d2e2003-05-13 21:37:02 +00001//===-- Constants.cpp - Implement Constant nodes --------------------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner2f7c9632001-06-06 20:29:01 +00009//
Chris Lattnere17322b2011-02-07 20:03:14 +000010// This file implements the Constant* classes.
Chris Lattner2f7c9632001-06-06 20:29:01 +000011//
12//===----------------------------------------------------------------------===//
13
Chandler Carruth9fb823b2013-01-02 11:36:10 +000014#include "llvm/IR/Constants.h"
Chris Lattner33e93b82007-02-27 03:05:06 +000015#include "ConstantFold.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000016#include "LLVMContextImpl.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000017#include "llvm/ADT/STLExtras.h"
18#include "llvm/ADT/SmallVector.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000019#include "llvm/ADT/StringMap.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000020#include "llvm/IR/DerivedTypes.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000021#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000022#include "llvm/IR/GlobalValue.h"
23#include "llvm/IR/Instructions.h"
24#include "llvm/IR/Module.h"
25#include "llvm/IR/Operator.h"
Bill Wendling6a462f12006-11-17 08:03:48 +000026#include "llvm/Support/Debug.h"
Torok Edwinccb29cd2009-07-11 13:10:19 +000027#include "llvm/Support/ErrorHandling.h"
Chris Lattner69edc982006-09-28 00:35:06 +000028#include "llvm/Support/ManagedStatic.h"
Bill Wendling6a462f12006-11-17 08:03:48 +000029#include "llvm/Support/MathExtras.h"
Chris Lattner78683a72009-08-23 04:02:03 +000030#include "llvm/Support/raw_ostream.h"
Chris Lattner2f7c9632001-06-06 20:29:01 +000031#include <algorithm>
Serge Gueltone38003f2017-05-09 19:31:13 +000032
Chris Lattner189d19f2003-11-21 20:23:48 +000033using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000034
Chris Lattner2f7c9632001-06-06 20:29:01 +000035//===----------------------------------------------------------------------===//
Chris Lattner3462ae32001-12-03 22:26:30 +000036// Constant Class
Chris Lattner2f7c9632001-06-06 20:29:01 +000037//===----------------------------------------------------------------------===//
38
Chris Lattnerac5fb562011-07-15 05:58:04 +000039bool Constant::isNegativeZeroValue() const {
40 // Floating point values have an explicit -0.0 value.
41 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
42 return CFP->isZero() && CFP->isNegative();
Galina Kistanovafc259902012-07-13 01:25:27 +000043
David Tweed5493fee2013-03-18 11:54:44 +000044 // Equivalent for a vector of -0.0's.
45 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
Craig Topper0b4b4e32017-07-15 22:06:19 +000046 if (CV->getElementType()->isFloatingPointTy() && CV->isSplat())
47 if (CV->getElementAsAPFloat(0).isNegZero())
David Tweed5493fee2013-03-18 11:54:44 +000048 return true;
49
Owen Anderson8e851302015-11-20 22:34:48 +000050 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
51 if (ConstantFP *SplatCFP = dyn_cast_or_null<ConstantFP>(CV->getSplatValue()))
52 if (SplatCFP && SplatCFP->isZero() && SplatCFP->isNegative())
53 return true;
54
David Tweed298e4192013-03-19 10:16:40 +000055 // We've already handled true FP case; any other FP vectors can't represent -0.0.
56 if (getType()->isFPOrFPVectorTy())
57 return false;
David Tweed5493fee2013-03-18 11:54:44 +000058
Chris Lattnerac5fb562011-07-15 05:58:04 +000059 // Otherwise, just use +0.0.
60 return isNullValue();
61}
62
Shuxin Yang9ca562e2013-01-09 00:53:25 +000063// Return true iff this constant is positive zero (floating point), negative
64// zero (floating point), or a null value.
Shuxin Yangf0537ab2013-01-09 00:13:41 +000065bool Constant::isZeroValue() const {
66 // Floating point values have an explicit -0.0 value.
67 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
68 return CFP->isZero();
69
Owen Anderson630077e2015-11-20 08:16:13 +000070 // Equivalent for a vector of -0.0's.
71 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
Craig Topper0b4b4e32017-07-15 22:06:19 +000072 if (CV->getElementType()->isFloatingPointTy() && CV->isSplat())
73 if (CV->getElementAsAPFloat(0).isZero())
Owen Anderson630077e2015-11-20 08:16:13 +000074 return true;
75
Owen Anderson8e851302015-11-20 22:34:48 +000076 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
77 if (ConstantFP *SplatCFP = dyn_cast_or_null<ConstantFP>(CV->getSplatValue()))
78 if (SplatCFP && SplatCFP->isZero())
79 return true;
80
Shuxin Yangf0537ab2013-01-09 00:13:41 +000081 // Otherwise, just use +0.0.
82 return isNullValue();
83}
84
Chris Lattnerbe6610c2011-07-15 06:14:08 +000085bool Constant::isNullValue() const {
86 // 0 is null.
87 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
88 return CI->isZero();
Galina Kistanovafc259902012-07-13 01:25:27 +000089
Chris Lattnerbe6610c2011-07-15 06:14:08 +000090 // +0.0 is null.
91 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
92 return CFP->isZero() && !CFP->isNegative();
93
David Majnemerf0f224d2015-11-11 21:57:16 +000094 // constant zero is zero for aggregates, cpnull is null for pointers, none for
95 // tokens.
96 return isa<ConstantAggregateZero>(this) || isa<ConstantPointerNull>(this) ||
97 isa<ConstantTokenNone>(this);
Chris Lattnerbe6610c2011-07-15 06:14:08 +000098}
99
Nadav Rotem365af6f2011-08-24 20:18:38 +0000100bool Constant::isAllOnesValue() const {
101 // Check for -1 integers
102 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
103 return CI->isMinusOne();
104
105 // Check for FP which are bitcasted from -1 integers
106 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
107 return CFP->getValueAPF().bitcastToAPInt().isAllOnesValue();
108
Benjamin Kramer42d098e2011-11-14 19:12:20 +0000109 // Check for constant vectors which are splats of -1 values.
Nadav Rotem365af6f2011-08-24 20:18:38 +0000110 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
Benjamin Kramer42d098e2011-11-14 19:12:20 +0000111 if (Constant *Splat = CV->getSplatValue())
112 return Splat->isAllOnesValue();
Nadav Rotem365af6f2011-08-24 20:18:38 +0000113
Chris Lattnerf14a67f2012-01-26 02:31:22 +0000114 // Check for constant vectors which are splats of -1 values.
Craig Topper0b4b4e32017-07-15 22:06:19 +0000115 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this)) {
116 if (CV->isSplat()) {
117 if (CV->getElementType()->isFloatingPointTy())
118 return CV->getElementAsAPFloat(0).bitcastToAPInt().isAllOnesValue();
119 return CV->getElementAsAPInt(0).isAllOnesValue();
120 }
121 }
Chris Lattnerf14a67f2012-01-26 02:31:22 +0000122
Nadav Rotem365af6f2011-08-24 20:18:38 +0000123 return false;
124}
Benjamin Kramer42d098e2011-11-14 19:12:20 +0000125
David Majnemer1a0bbc82014-08-16 09:23:42 +0000126bool Constant::isOneValue() const {
127 // Check for 1 integers
128 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
129 return CI->isOne();
130
131 // Check for FP which are bitcasted from 1 integers
132 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
Craig Topper93ac6e12017-06-07 00:58:02 +0000133 return CFP->getValueAPF().bitcastToAPInt().isOneValue();
David Majnemer1a0bbc82014-08-16 09:23:42 +0000134
135 // Check for constant vectors which are splats of 1 values.
136 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
137 if (Constant *Splat = CV->getSplatValue())
138 return Splat->isOneValue();
139
140 // Check for constant vectors which are splats of 1 values.
Craig Topper0b4b4e32017-07-15 22:06:19 +0000141 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this)) {
142 if (CV->isSplat()) {
143 if (CV->getElementType()->isFloatingPointTy())
144 return CV->getElementAsAPFloat(0).bitcastToAPInt().isOneValue();
145 return CV->getElementAsAPInt(0).isOneValue();
146 }
147 }
David Majnemer1a0bbc82014-08-16 09:23:42 +0000148
149 return false;
150}
151
David Majnemerbdeef602014-07-02 06:07:09 +0000152bool Constant::isMinSignedValue() const {
153 // Check for INT_MIN integers
154 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
155 return CI->isMinValue(/*isSigned=*/true);
156
157 // Check for FP which are bitcasted from INT_MIN integers
158 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
159 return CFP->getValueAPF().bitcastToAPInt().isMinSignedValue();
160
161 // Check for constant vectors which are splats of INT_MIN values.
162 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
163 if (Constant *Splat = CV->getSplatValue())
164 return Splat->isMinSignedValue();
165
166 // Check for constant vectors which are splats of INT_MIN values.
Craig Topper0b4b4e32017-07-15 22:06:19 +0000167 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this)) {
168 if (CV->isSplat()) {
169 if (CV->getElementType()->isFloatingPointTy())
170 return CV->getElementAsAPFloat(0).bitcastToAPInt().isMinSignedValue();
171 return CV->getElementAsAPInt(0).isMinSignedValue();
172 }
173 }
David Majnemerbdeef602014-07-02 06:07:09 +0000174
175 return false;
176}
177
David Majnemer0e6c9862014-08-22 16:41:23 +0000178bool Constant::isNotMinSignedValue() const {
179 // Check for INT_MIN integers
180 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
181 return !CI->isMinValue(/*isSigned=*/true);
182
183 // Check for FP which are bitcasted from INT_MIN integers
184 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
185 return !CFP->getValueAPF().bitcastToAPInt().isMinSignedValue();
186
187 // Check for constant vectors which are splats of INT_MIN values.
188 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
189 if (Constant *Splat = CV->getSplatValue())
190 return Splat->isNotMinSignedValue();
191
192 // Check for constant vectors which are splats of INT_MIN values.
Craig Topper0b4b4e32017-07-15 22:06:19 +0000193 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this)) {
194 if (CV->isSplat()) {
195 if (CV->getElementType()->isFloatingPointTy())
196 return !CV->getElementAsAPFloat(0).bitcastToAPInt().isMinSignedValue();
197 return !CV->getElementAsAPInt(0).isMinSignedValue();
198 }
199 }
David Majnemer0e6c9862014-08-22 16:41:23 +0000200
201 // It *may* contain INT_MIN, we can't tell.
202 return false;
203}
204
Sanjay Patel08868e4942018-02-16 22:32:54 +0000205bool Constant::isFiniteNonZeroFP() const {
206 if (auto *CFP = dyn_cast<ConstantFP>(this))
207 return CFP->getValueAPF().isFiniteNonZero();
208 if (!getType()->isVectorTy())
209 return false;
210 for (unsigned i = 0, e = getType()->getVectorNumElements(); i != e; ++i) {
211 auto *CFP = dyn_cast_or_null<ConstantFP>(this->getAggregateElement(i));
212 if (!CFP || !CFP->getValueAPF().isFiniteNonZero())
213 return false;
214 }
215 return true;
216}
217
218bool Constant::isNormalFP() const {
219 if (auto *CFP = dyn_cast<ConstantFP>(this))
220 return CFP->getValueAPF().isNormal();
221 if (!getType()->isVectorTy())
222 return false;
223 for (unsigned i = 0, e = getType()->getVectorNumElements(); i != e; ++i) {
224 auto *CFP = dyn_cast_or_null<ConstantFP>(this->getAggregateElement(i));
225 if (!CFP || !CFP->getValueAPF().isNormal())
226 return false;
227 }
228 return true;
229}
230
Sanjay Patel90f4c8e2018-02-20 16:08:15 +0000231bool Constant::hasExactInverseFP() const {
232 if (auto *CFP = dyn_cast<ConstantFP>(this))
233 return CFP->getValueAPF().getExactInverse(nullptr);
234 if (!getType()->isVectorTy())
235 return false;
236 for (unsigned i = 0, e = getType()->getVectorNumElements(); i != e; ++i) {
237 auto *CFP = dyn_cast_or_null<ConstantFP>(this->getAggregateElement(i));
238 if (!CFP || !CFP->getValueAPF().getExactInverse(nullptr))
239 return false;
240 }
241 return true;
242}
243
Sanjay Patel46b083e2018-03-02 18:36:08 +0000244bool Constant::isNaN() const {
245 if (auto *CFP = dyn_cast<ConstantFP>(this))
246 return CFP->isNaN();
247 if (!getType()->isVectorTy())
248 return false;
249 for (unsigned i = 0, e = getType()->getVectorNumElements(); i != e; ++i) {
250 auto *CFP = dyn_cast_or_null<ConstantFP>(this->getAggregateElement(i));
251 if (!CFP || !CFP->isNaN())
252 return false;
253 }
254 return true;
255}
256
Sanjay Patele6dda2f2018-07-06 14:52:36 +0000257bool Constant::containsUndefElement() const {
258 if (!getType()->isVectorTy())
259 return false;
260 for (unsigned i = 0, e = getType()->getVectorNumElements(); i != e; ++i)
261 if (isa<UndefValue>(getAggregateElement(i)))
262 return true;
263
264 return false;
265}
266
Sanjay Patel1d0ac7c2016-04-29 22:03:27 +0000267/// Constructor to create a '0' constant of arbitrary type.
Chris Lattner229907c2011-07-18 04:54:35 +0000268Constant *Constant::getNullValue(Type *Ty) {
Owen Anderson5a1acd92009-07-31 20:28:14 +0000269 switch (Ty->getTypeID()) {
270 case Type::IntegerTyID:
271 return ConstantInt::get(Ty, 0);
Dan Gohman518cda42011-12-17 00:04:22 +0000272 case Type::HalfTyID:
273 return ConstantFP::get(Ty->getContext(),
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000274 APFloat::getZero(APFloat::IEEEhalf()));
Owen Anderson5a1acd92009-07-31 20:28:14 +0000275 case Type::FloatTyID:
Benjamin Kramer8ceebfa2010-12-04 14:22:24 +0000276 return ConstantFP::get(Ty->getContext(),
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000277 APFloat::getZero(APFloat::IEEEsingle()));
Owen Anderson5a1acd92009-07-31 20:28:14 +0000278 case Type::DoubleTyID:
Benjamin Kramer8ceebfa2010-12-04 14:22:24 +0000279 return ConstantFP::get(Ty->getContext(),
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000280 APFloat::getZero(APFloat::IEEEdouble()));
Owen Anderson5a1acd92009-07-31 20:28:14 +0000281 case Type::X86_FP80TyID:
Benjamin Kramer8ceebfa2010-12-04 14:22:24 +0000282 return ConstantFP::get(Ty->getContext(),
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000283 APFloat::getZero(APFloat::x87DoubleExtended()));
Owen Anderson5a1acd92009-07-31 20:28:14 +0000284 case Type::FP128TyID:
285 return ConstantFP::get(Ty->getContext(),
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000286 APFloat::getZero(APFloat::IEEEquad()));
Owen Anderson5a1acd92009-07-31 20:28:14 +0000287 case Type::PPC_FP128TyID:
Benjamin Kramer8ceebfa2010-12-04 14:22:24 +0000288 return ConstantFP::get(Ty->getContext(),
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000289 APFloat(APFloat::PPCDoubleDouble(),
Tim Northover29178a32013-01-22 09:46:31 +0000290 APInt::getNullValue(128)));
Owen Anderson5a1acd92009-07-31 20:28:14 +0000291 case Type::PointerTyID:
292 return ConstantPointerNull::get(cast<PointerType>(Ty));
293 case Type::StructTyID:
294 case Type::ArrayTyID:
295 case Type::VectorTyID:
296 return ConstantAggregateZero::get(Ty);
David Majnemerf0f224d2015-11-11 21:57:16 +0000297 case Type::TokenTyID:
298 return ConstantTokenNone::get(Ty->getContext());
Owen Anderson5a1acd92009-07-31 20:28:14 +0000299 default:
300 // Function, Label, or Opaque type?
Craig Topperc514b542012-02-05 22:14:15 +0000301 llvm_unreachable("Cannot create a null constant of that type!");
Owen Anderson5a1acd92009-07-31 20:28:14 +0000302 }
303}
304
Chris Lattner229907c2011-07-18 04:54:35 +0000305Constant *Constant::getIntegerValue(Type *Ty, const APInt &V) {
306 Type *ScalarTy = Ty->getScalarType();
Dan Gohmanf011f5a2009-08-03 22:07:33 +0000307
308 // Create the base integer constant.
309 Constant *C = ConstantInt::get(Ty->getContext(), V);
310
311 // Convert an integer to a pointer, if necessary.
Chris Lattner229907c2011-07-18 04:54:35 +0000312 if (PointerType *PTy = dyn_cast<PointerType>(ScalarTy))
Dan Gohmanf011f5a2009-08-03 22:07:33 +0000313 C = ConstantExpr::getIntToPtr(C, PTy);
314
315 // Broadcast a scalar to a vector, if necessary.
Chris Lattner229907c2011-07-18 04:54:35 +0000316 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
Chris Lattnere9eed292012-01-25 05:19:54 +0000317 C = ConstantVector::getSplat(VTy->getNumElements(), C);
Dan Gohmanf011f5a2009-08-03 22:07:33 +0000318
319 return C;
320}
321
Chris Lattner229907c2011-07-18 04:54:35 +0000322Constant *Constant::getAllOnesValue(Type *Ty) {
323 if (IntegerType *ITy = dyn_cast<IntegerType>(Ty))
Owen Anderson5a1acd92009-07-31 20:28:14 +0000324 return ConstantInt::get(Ty->getContext(),
325 APInt::getAllOnesValue(ITy->getBitWidth()));
Nadav Rotem7cc6d122011-02-17 21:22:27 +0000326
327 if (Ty->isFloatingPointTy()) {
328 APFloat FL = APFloat::getAllOnesValue(Ty->getPrimitiveSizeInBits(),
329 !Ty->isPPC_FP128Ty());
330 return ConstantFP::get(Ty->getContext(), FL);
331 }
332
Chris Lattner229907c2011-07-18 04:54:35 +0000333 VectorType *VTy = cast<VectorType>(Ty);
Chris Lattnere9eed292012-01-25 05:19:54 +0000334 return ConstantVector::getSplat(VTy->getNumElements(),
335 getAllOnesValue(VTy->getElementType()));
Owen Anderson5a1acd92009-07-31 20:28:14 +0000336}
337
Chris Lattner7e683d12012-01-25 06:16:32 +0000338Constant *Constant::getAggregateElement(unsigned Elt) const {
Duncan P. N. Exon Smith1de3c7e2016-04-05 21:10:45 +0000339 if (const ConstantAggregate *CC = dyn_cast<ConstantAggregate>(this))
340 return Elt < CC->getNumOperands() ? CC->getOperand(Elt) : nullptr;
Galina Kistanovafc259902012-07-13 01:25:27 +0000341
David Majnemer9b529a72015-02-16 04:02:09 +0000342 if (const ConstantAggregateZero *CAZ = dyn_cast<ConstantAggregateZero>(this))
343 return Elt < CAZ->getNumElements() ? CAZ->getElementValue(Elt) : nullptr;
Galina Kistanovafc259902012-07-13 01:25:27 +0000344
Chris Lattner7e683d12012-01-25 06:16:32 +0000345 if (const UndefValue *UV = dyn_cast<UndefValue>(this))
David Majnemer9b529a72015-02-16 04:02:09 +0000346 return Elt < UV->getNumElements() ? UV->getElementValue(Elt) : nullptr;
Galina Kistanovafc259902012-07-13 01:25:27 +0000347
Chris Lattner8326bd82012-01-26 00:42:34 +0000348 if (const ConstantDataSequential *CDS =dyn_cast<ConstantDataSequential>(this))
Craig Topperc6207612014-04-09 06:08:46 +0000349 return Elt < CDS->getNumElements() ? CDS->getElementAsConstant(Elt)
350 : nullptr;
351 return nullptr;
Chris Lattner7e683d12012-01-25 06:16:32 +0000352}
353
354Constant *Constant::getAggregateElement(Constant *Elt) const {
355 assert(isa<IntegerType>(Elt->getType()) && "Index must be an integer");
356 if (ConstantInt *CI = dyn_cast<ConstantInt>(Elt))
357 return getAggregateElement(CI->getZExtValue());
Craig Topperc6207612014-04-09 06:08:46 +0000358 return nullptr;
Chris Lattner7e683d12012-01-25 06:16:32 +0000359}
360
Pete Cooper86dd4cf2015-06-23 21:55:11 +0000361void Constant::destroyConstant() {
362 /// First call destroyConstantImpl on the subclass. This gives the subclass
363 /// a chance to remove the constant from any maps/pools it's contained in.
364 switch (getValueID()) {
365 default:
366 llvm_unreachable("Not a constant!");
367#define HANDLE_CONSTANT(Name) \
368 case Value::Name##Val: \
369 cast<Name>(this)->destroyConstantImpl(); \
370 break;
371#include "llvm/IR/Value.def"
372 }
Chris Lattner7e683d12012-01-25 06:16:32 +0000373
Chris Lattner3462ae32001-12-03 22:26:30 +0000374 // When a Constant is destroyed, there may be lingering
Chris Lattnerd7a73302001-10-13 06:57:33 +0000375 // references to the constant by other constants in the constant pool. These
Misha Brukmanbe372b92003-08-21 22:14:26 +0000376 // constants are implicitly dependent on the module that is being deleted,
Chris Lattnerd7a73302001-10-13 06:57:33 +0000377 // but they don't know that. Because we only find out when the CPV is
378 // deleted, we must now notify all of our users (that should only be
Chris Lattner3462ae32001-12-03 22:26:30 +0000379 // Constants) that they are, in fact, invalid now and should be deleted.
Chris Lattnerd7a73302001-10-13 06:57:33 +0000380 //
381 while (!use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000382 Value *V = user_back();
Pete Cooper86dd4cf2015-06-23 21:55:11 +0000383#ifndef NDEBUG // Only in -g mode...
Chris Lattner78683a72009-08-23 04:02:03 +0000384 if (!isa<Constant>(V)) {
David Greene1e27a132010-01-05 01:29:19 +0000385 dbgs() << "While deleting: " << *this
Pete Cooper86dd4cf2015-06-23 21:55:11 +0000386 << "\n\nUse still stuck around after Def is destroyed: " << *V
387 << "\n\n";
Chris Lattner78683a72009-08-23 04:02:03 +0000388 }
Chris Lattnerd7a73302001-10-13 06:57:33 +0000389#endif
Vikram S. Adve4e537b22002-07-14 23:13:17 +0000390 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
Chris Lattner8326bd82012-01-26 00:42:34 +0000391 cast<Constant>(V)->destroyConstant();
Chris Lattnerd7a73302001-10-13 06:57:33 +0000392
393 // The constant should remove itself from our use list...
Chandler Carruthcdf47882014-03-09 03:16:01 +0000394 assert((use_empty() || user_back() != V) && "Constant not removed!");
Chris Lattnerd7a73302001-10-13 06:57:33 +0000395 }
396
397 // Value has no outstanding references it is safe to delete it now...
398 delete this;
Chris Lattner38569342001-10-01 20:11:19 +0000399}
Chris Lattner2f7c9632001-06-06 20:29:01 +0000400
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +0000401static bool canTrapImpl(const Constant *C,
Craig Topper71b7b682014-08-21 05:55:13 +0000402 SmallPtrSetImpl<const ConstantExpr *> &NonTrappingOps) {
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +0000403 assert(C->getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
Chris Lattner23dd1f62006-10-20 00:27:06 +0000404 // The only thing that could possibly trap are constant exprs.
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +0000405 const ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
406 if (!CE)
407 return false;
Galina Kistanovafc259902012-07-13 01:25:27 +0000408
409 // ConstantExpr traps if any operands can trap.
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +0000410 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) {
411 if (ConstantExpr *Op = dyn_cast<ConstantExpr>(CE->getOperand(i))) {
David Blaikie70573dc2014-11-19 07:49:26 +0000412 if (NonTrappingOps.insert(Op).second && canTrapImpl(Op, NonTrappingOps))
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +0000413 return true;
414 }
415 }
Chris Lattner23dd1f62006-10-20 00:27:06 +0000416
417 // Otherwise, only specific operations can trap.
418 switch (CE->getOpcode()) {
419 default:
420 return false;
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000421 case Instruction::UDiv:
422 case Instruction::SDiv:
Reid Spencer7eb55b32006-11-02 01:53:59 +0000423 case Instruction::URem:
424 case Instruction::SRem:
Chris Lattner23dd1f62006-10-20 00:27:06 +0000425 // Div and rem can trap if the RHS is not known to be non-zero.
Chris Lattnera91a5632009-10-28 05:14:34 +0000426 if (!isa<ConstantInt>(CE->getOperand(1)) ||CE->getOperand(1)->isNullValue())
Chris Lattner23dd1f62006-10-20 00:27:06 +0000427 return true;
428 return false;
429 }
430}
431
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +0000432bool Constant::canTrap() const {
433 SmallPtrSet<const ConstantExpr *, 4> NonTrappingOps;
434 return canTrapImpl(this, NonTrappingOps);
435}
436
Hans Wennborg4dc89512014-06-20 00:38:12 +0000437/// Check if C contains a GlobalValue for which Predicate is true.
438static bool
439ConstHasGlobalValuePredicate(const Constant *C,
440 bool (*Predicate)(const GlobalValue *)) {
441 SmallPtrSet<const Constant *, 8> Visited;
442 SmallVector<const Constant *, 8> WorkList;
443 WorkList.push_back(C);
444 Visited.insert(C);
Hans Wennborg709e0152012-11-15 11:40:00 +0000445
446 while (!WorkList.empty()) {
Hans Wennborg4dc89512014-06-20 00:38:12 +0000447 const Constant *WorkItem = WorkList.pop_back_val();
448 if (const auto *GV = dyn_cast<GlobalValue>(WorkItem))
449 if (Predicate(GV))
Hans Wennborg709e0152012-11-15 11:40:00 +0000450 return true;
Hans Wennborg4dc89512014-06-20 00:38:12 +0000451 for (const Value *Op : WorkItem->operands()) {
452 const Constant *ConstOp = dyn_cast<Constant>(Op);
453 if (!ConstOp)
Hans Wennborg18aa12402012-11-16 10:33:25 +0000454 continue;
David Blaikie70573dc2014-11-19 07:49:26 +0000455 if (Visited.insert(ConstOp).second)
Hans Wennborg4dc89512014-06-20 00:38:12 +0000456 WorkList.push_back(ConstOp);
Hans Wennborg709e0152012-11-15 11:40:00 +0000457 }
458 }
Hans Wennborg709e0152012-11-15 11:40:00 +0000459 return false;
460}
461
Hans Wennborg4dc89512014-06-20 00:38:12 +0000462bool Constant::isThreadDependent() const {
463 auto DLLImportPredicate = [](const GlobalValue *GV) {
464 return GV->isThreadLocal();
465 };
466 return ConstHasGlobalValuePredicate(this, DLLImportPredicate);
467}
468
469bool Constant::isDLLImportDependent() const {
470 auto DLLImportPredicate = [](const GlobalValue *GV) {
471 return GV->hasDLLImportStorageClass();
472 };
473 return ConstHasGlobalValuePredicate(this, DLLImportPredicate);
474}
475
Chris Lattner253bc772009-11-01 18:11:50 +0000476bool Constant::isConstantUsed() const {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000477 for (const User *U : users()) {
478 const Constant *UC = dyn_cast<Constant>(U);
Craig Topperc6207612014-04-09 06:08:46 +0000479 if (!UC || isa<GlobalValue>(UC))
Chris Lattner253bc772009-11-01 18:11:50 +0000480 return true;
Galina Kistanovafc259902012-07-13 01:25:27 +0000481
Chris Lattner253bc772009-11-01 18:11:50 +0000482 if (UC->isConstantUsed())
483 return true;
484 }
485 return false;
486}
487
Rafael Espindola65e49022015-11-17 00:51:23 +0000488bool Constant::needsRelocation() const {
489 if (isa<GlobalValue>(this))
490 return true; // Global reference.
491
Chris Lattner2cb85b42009-10-28 04:12:16 +0000492 if (const BlockAddress *BA = dyn_cast<BlockAddress>(this))
Rafael Espindola65e49022015-11-17 00:51:23 +0000493 return BA->getFunction()->needsRelocation();
494
Chris Lattnera7cfc432010-01-03 18:09:40 +0000495 // While raw uses of blockaddress need to be relocated, differences between
496 // two of them don't when they are for labels in the same function. This is a
497 // common idiom when creating a table for the indirect goto extension, so we
498 // handle it efficiently here.
499 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(this))
500 if (CE->getOpcode() == Instruction::Sub) {
501 ConstantExpr *LHS = dyn_cast<ConstantExpr>(CE->getOperand(0));
502 ConstantExpr *RHS = dyn_cast<ConstantExpr>(CE->getOperand(1));
Rafael Espindola65e49022015-11-17 00:51:23 +0000503 if (LHS && RHS && LHS->getOpcode() == Instruction::PtrToInt &&
Chris Lattnera7cfc432010-01-03 18:09:40 +0000504 RHS->getOpcode() == Instruction::PtrToInt &&
505 isa<BlockAddress>(LHS->getOperand(0)) &&
506 isa<BlockAddress>(RHS->getOperand(0)) &&
507 cast<BlockAddress>(LHS->getOperand(0))->getFunction() ==
Rafael Espindola65e49022015-11-17 00:51:23 +0000508 cast<BlockAddress>(RHS->getOperand(0))->getFunction())
509 return false;
Chris Lattnera7cfc432010-01-03 18:09:40 +0000510 }
Galina Kistanovafc259902012-07-13 01:25:27 +0000511
Rafael Espindola65e49022015-11-17 00:51:23 +0000512 bool Result = false;
Evan Chengf9e003b2007-03-08 00:59:12 +0000513 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
Rafael Espindola65e49022015-11-17 00:51:23 +0000514 Result |= cast<Constant>(getOperand(i))->needsRelocation();
Galina Kistanovafc259902012-07-13 01:25:27 +0000515
Chris Lattner4565ef52009-07-22 00:05:44 +0000516 return Result;
Evan Chengf9e003b2007-03-08 00:59:12 +0000517}
518
Sanjay Patel1d0ac7c2016-04-29 22:03:27 +0000519/// If the specified constantexpr is dead, remove it. This involves recursively
520/// eliminating any dead users of the constantexpr.
Chris Lattner84886402011-02-18 04:41:42 +0000521static bool removeDeadUsersOfConstant(const Constant *C) {
522 if (isa<GlobalValue>(C)) return false; // Cannot remove this
Galina Kistanovafc259902012-07-13 01:25:27 +0000523
Chris Lattner84886402011-02-18 04:41:42 +0000524 while (!C->use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000525 const Constant *User = dyn_cast<Constant>(C->user_back());
Chris Lattner84886402011-02-18 04:41:42 +0000526 if (!User) return false; // Non-constant usage;
527 if (!removeDeadUsersOfConstant(User))
528 return false; // Constant wasn't dead
529 }
Galina Kistanovafc259902012-07-13 01:25:27 +0000530
Chris Lattner84886402011-02-18 04:41:42 +0000531 const_cast<Constant*>(C)->destroyConstant();
532 return true;
533}
534
535
Chris Lattner84886402011-02-18 04:41:42 +0000536void Constant::removeDeadConstantUsers() const {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000537 Value::const_user_iterator I = user_begin(), E = user_end();
538 Value::const_user_iterator LastNonDeadUser = E;
Chris Lattner84886402011-02-18 04:41:42 +0000539 while (I != E) {
540 const Constant *User = dyn_cast<Constant>(*I);
Craig Topperc6207612014-04-09 06:08:46 +0000541 if (!User) {
Chris Lattner84886402011-02-18 04:41:42 +0000542 LastNonDeadUser = I;
543 ++I;
544 continue;
545 }
Galina Kistanovafc259902012-07-13 01:25:27 +0000546
Chris Lattner84886402011-02-18 04:41:42 +0000547 if (!removeDeadUsersOfConstant(User)) {
548 // If the constant wasn't dead, remember that this was the last live use
549 // and move on to the next constant.
550 LastNonDeadUser = I;
551 ++I;
552 continue;
553 }
Galina Kistanovafc259902012-07-13 01:25:27 +0000554
Chris Lattner84886402011-02-18 04:41:42 +0000555 // If the constant was dead, then the iterator is invalidated.
556 if (LastNonDeadUser == E) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000557 I = user_begin();
Chris Lattner84886402011-02-18 04:41:42 +0000558 if (I == E) break;
559 } else {
560 I = LastNonDeadUser;
561 ++I;
562 }
563 }
564}
565
566
Chris Lattner2105d662008-07-10 00:28:11 +0000567
Chris Lattner2f7c9632001-06-06 20:29:01 +0000568//===----------------------------------------------------------------------===//
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000569// ConstantInt
Chris Lattner2f7c9632001-06-06 20:29:01 +0000570//===----------------------------------------------------------------------===//
571
Duncan P. N. Exon Smithb6452792016-02-21 02:39:49 +0000572ConstantInt::ConstantInt(IntegerType *Ty, const APInt &V)
573 : ConstantData(Ty, ConstantIntVal), Val(V) {
Reid Spencerb31bffe2007-02-26 23:54:03 +0000574 assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
Chris Lattner2f7c9632001-06-06 20:29:01 +0000575}
576
Nick Lewycky92db8e82011-03-06 03:36:19 +0000577ConstantInt *ConstantInt::getTrue(LLVMContext &Context) {
Owen Anderson23a204d2009-07-31 17:39:07 +0000578 LLVMContextImpl *pImpl = Context.pImpl;
Benjamin Kramerddd1b7b2010-11-20 18:43:35 +0000579 if (!pImpl->TheTrueVal)
580 pImpl->TheTrueVal = ConstantInt::get(Type::getInt1Ty(Context), 1);
581 return pImpl->TheTrueVal;
Owen Anderson23a204d2009-07-31 17:39:07 +0000582}
583
Nick Lewycky92db8e82011-03-06 03:36:19 +0000584ConstantInt *ConstantInt::getFalse(LLVMContext &Context) {
Owen Anderson23a204d2009-07-31 17:39:07 +0000585 LLVMContextImpl *pImpl = Context.pImpl;
Benjamin Kramerddd1b7b2010-11-20 18:43:35 +0000586 if (!pImpl->TheFalseVal)
587 pImpl->TheFalseVal = ConstantInt::get(Type::getInt1Ty(Context), 0);
588 return pImpl->TheFalseVal;
Owen Anderson23a204d2009-07-31 17:39:07 +0000589}
590
Chris Lattner229907c2011-07-18 04:54:35 +0000591Constant *ConstantInt::getTrue(Type *Ty) {
Craig Topperfde47232017-07-09 07:04:03 +0000592 assert(Ty->isIntOrIntVectorTy(1) && "Type not i1 or vector of i1.");
Sanjay Patel70a575a2017-04-16 17:00:21 +0000593 ConstantInt *TrueC = ConstantInt::getTrue(Ty->getContext());
594 if (auto *VTy = dyn_cast<VectorType>(Ty))
595 return ConstantVector::getSplat(VTy->getNumElements(), TrueC);
596 return TrueC;
Nick Lewycky92db8e82011-03-06 03:36:19 +0000597}
598
Chris Lattner229907c2011-07-18 04:54:35 +0000599Constant *ConstantInt::getFalse(Type *Ty) {
Craig Topperfde47232017-07-09 07:04:03 +0000600 assert(Ty->isIntOrIntVectorTy(1) && "Type not i1 or vector of i1.");
Sanjay Patel70a575a2017-04-16 17:00:21 +0000601 ConstantInt *FalseC = ConstantInt::getFalse(Ty->getContext());
602 if (auto *VTy = dyn_cast<VectorType>(Ty))
603 return ConstantVector::getSplat(VTy->getNumElements(), FalseC);
604 return FalseC;
Nick Lewycky92db8e82011-03-06 03:36:19 +0000605}
606
Benjamin Kramer8e5dc532014-12-06 13:12:56 +0000607// Get a ConstantInt from an APInt.
Nick Lewycky92db8e82011-03-06 03:36:19 +0000608ConstantInt *ConstantInt::get(LLVMContext &Context, const APInt &V) {
Owen Andersonedb4a702009-07-24 23:12:02 +0000609 // get an existing value or the insertion position
Benjamin Kramer320682f2013-06-01 17:51:03 +0000610 LLVMContextImpl *pImpl = Context.pImpl;
Justin Lebar611c5c22016-10-10 16:26:13 +0000611 std::unique_ptr<ConstantInt> &Slot = pImpl->IntConstants[V];
Benjamin Kramer8e5dc532014-12-06 13:12:56 +0000612 if (!Slot) {
613 // Get the corresponding integer type for the bit width of the value.
614 IntegerType *ITy = IntegerType::get(Context, V.getBitWidth());
Justin Lebar611c5c22016-10-10 16:26:13 +0000615 Slot.reset(new ConstantInt(ITy, V));
Benjamin Kramer8e5dc532014-12-06 13:12:56 +0000616 }
617 assert(Slot->getType() == IntegerType::get(Context, V.getBitWidth()));
Justin Lebar611c5c22016-10-10 16:26:13 +0000618 return Slot.get();
Owen Andersonedb4a702009-07-24 23:12:02 +0000619}
620
Chris Lattner229907c2011-07-18 04:54:35 +0000621Constant *ConstantInt::get(Type *Ty, uint64_t V, bool isSigned) {
Nick Lewycky92db8e82011-03-06 03:36:19 +0000622 Constant *C = get(cast<IntegerType>(Ty->getScalarType()), V, isSigned);
Owen Andersonedb4a702009-07-24 23:12:02 +0000623
624 // For vectors, broadcast the value.
Chris Lattner229907c2011-07-18 04:54:35 +0000625 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
Chris Lattnere9eed292012-01-25 05:19:54 +0000626 return ConstantVector::getSplat(VTy->getNumElements(), C);
Owen Andersonedb4a702009-07-24 23:12:02 +0000627
628 return C;
629}
630
Sanjay Patelf3587ec2016-05-18 22:05:28 +0000631ConstantInt *ConstantInt::get(IntegerType *Ty, uint64_t V, bool isSigned) {
Owen Andersonedb4a702009-07-24 23:12:02 +0000632 return get(Ty->getContext(), APInt(Ty->getBitWidth(), V, isSigned));
633}
634
Chris Lattner0256be92012-01-27 03:08:05 +0000635ConstantInt *ConstantInt::getSigned(IntegerType *Ty, int64_t V) {
Owen Andersonedb4a702009-07-24 23:12:02 +0000636 return get(Ty, V, true);
637}
638
Chris Lattner229907c2011-07-18 04:54:35 +0000639Constant *ConstantInt::getSigned(Type *Ty, int64_t V) {
Owen Andersonedb4a702009-07-24 23:12:02 +0000640 return get(Ty, V, true);
641}
642
Chris Lattner0256be92012-01-27 03:08:05 +0000643Constant *ConstantInt::get(Type *Ty, const APInt& V) {
Owen Andersonedb4a702009-07-24 23:12:02 +0000644 ConstantInt *C = get(Ty->getContext(), V);
645 assert(C->getType() == Ty->getScalarType() &&
646 "ConstantInt type doesn't match the type implied by its value!");
647
648 // For vectors, broadcast the value.
Chris Lattner229907c2011-07-18 04:54:35 +0000649 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
Chris Lattnere9eed292012-01-25 05:19:54 +0000650 return ConstantVector::getSplat(VTy->getNumElements(), C);
Owen Andersonedb4a702009-07-24 23:12:02 +0000651
652 return C;
653}
654
Sanjay Patelf3587ec2016-05-18 22:05:28 +0000655ConstantInt *ConstantInt::get(IntegerType* Ty, StringRef Str, uint8_t radix) {
Erick Tryzelaarfc2280d2009-08-16 23:36:33 +0000656 return get(Ty->getContext(), APInt(Ty->getBitWidth(), Str, radix));
657}
658
Pete Cooper86dd4cf2015-06-23 21:55:11 +0000659/// Remove the constant from the constant table.
660void ConstantInt::destroyConstantImpl() {
661 llvm_unreachable("You can't ConstantInt->destroyConstantImpl()!");
662}
663
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000664//===----------------------------------------------------------------------===//
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000665// ConstantFP
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000666//===----------------------------------------------------------------------===//
667
Chris Lattner229907c2011-07-18 04:54:35 +0000668static const fltSemantics *TypeToFloatSemantics(Type *Ty) {
Dan Gohman518cda42011-12-17 00:04:22 +0000669 if (Ty->isHalfTy())
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000670 return &APFloat::IEEEhalf();
Chris Lattnerfdd87902009-10-05 05:54:46 +0000671 if (Ty->isFloatTy())
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000672 return &APFloat::IEEEsingle();
Chris Lattnerfdd87902009-10-05 05:54:46 +0000673 if (Ty->isDoubleTy())
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000674 return &APFloat::IEEEdouble();
Chris Lattnerfdd87902009-10-05 05:54:46 +0000675 if (Ty->isX86_FP80Ty())
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000676 return &APFloat::x87DoubleExtended();
Chris Lattnerfdd87902009-10-05 05:54:46 +0000677 else if (Ty->isFP128Ty())
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000678 return &APFloat::IEEEquad();
Galina Kistanovafc259902012-07-13 01:25:27 +0000679
Chris Lattnerfdd87902009-10-05 05:54:46 +0000680 assert(Ty->isPPC_FP128Ty() && "Unknown FP format");
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000681 return &APFloat::PPCDoubleDouble();
Rafael Espindolaf5d53d42009-07-15 17:40:42 +0000682}
683
Chris Lattner0256be92012-01-27 03:08:05 +0000684Constant *ConstantFP::get(Type *Ty, double V) {
Owen Anderson69c464d2009-07-27 20:59:43 +0000685 LLVMContext &Context = Ty->getContext();
Galina Kistanovafc259902012-07-13 01:25:27 +0000686
Owen Anderson69c464d2009-07-27 20:59:43 +0000687 APFloat FV(V);
688 bool ignored;
689 FV.convert(*TypeToFloatSemantics(Ty->getScalarType()),
690 APFloat::rmNearestTiesToEven, &ignored);
691 Constant *C = get(Context, FV);
692
693 // For vectors, broadcast the value.
Chris Lattner229907c2011-07-18 04:54:35 +0000694 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
Chris Lattnere9eed292012-01-25 05:19:54 +0000695 return ConstantVector::getSplat(VTy->getNumElements(), C);
Owen Anderson69c464d2009-07-27 20:59:43 +0000696
697 return C;
698}
699
Sanjay Patel6a0f6672018-02-15 13:55:52 +0000700Constant *ConstantFP::get(Type *Ty, const APFloat &V) {
701 ConstantFP *C = get(Ty->getContext(), V);
702 assert(C->getType() == Ty->getScalarType() &&
703 "ConstantFP type doesn't match the type implied by its value!");
704
705 // For vectors, broadcast the value.
706 if (auto *VTy = dyn_cast<VectorType>(Ty))
707 return ConstantVector::getSplat(VTy->getNumElements(), C);
708
709 return C;
710}
Erick Tryzelaarfc2280d2009-08-16 23:36:33 +0000711
Chris Lattner0256be92012-01-27 03:08:05 +0000712Constant *ConstantFP::get(Type *Ty, StringRef Str) {
Erick Tryzelaarfc2280d2009-08-16 23:36:33 +0000713 LLVMContext &Context = Ty->getContext();
714
715 APFloat FV(*TypeToFloatSemantics(Ty->getScalarType()), Str);
716 Constant *C = get(Context, FV);
717
718 // For vectors, broadcast the value.
Chris Lattner229907c2011-07-18 04:54:35 +0000719 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
Chris Lattnere9eed292012-01-25 05:19:54 +0000720 return ConstantVector::getSplat(VTy->getNumElements(), C);
Erick Tryzelaarfc2280d2009-08-16 23:36:33 +0000721
Bjorn Petterssonaa025802018-07-03 12:39:52 +0000722 return C;
Erick Tryzelaarfc2280d2009-08-16 23:36:33 +0000723}
724
Tom Stellard67246d12015-04-20 19:38:24 +0000725Constant *ConstantFP::getNaN(Type *Ty, bool Negative, unsigned Type) {
726 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
727 APFloat NaN = APFloat::getNaN(Semantics, Negative, Type);
728 Constant *C = get(Ty->getContext(), NaN);
729
730 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
731 return ConstantVector::getSplat(VTy->getNumElements(), C);
732
733 return C;
734}
735
Benjamin Kramer5d2ff222014-01-18 16:43:06 +0000736Constant *ConstantFP::getNegativeZero(Type *Ty) {
737 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
738 APFloat NegZero = APFloat::getZero(Semantics, /*Negative=*/true);
739 Constant *C = get(Ty->getContext(), NegZero);
Erick Tryzelaarfc2280d2009-08-16 23:36:33 +0000740
Benjamin Kramer5d2ff222014-01-18 16:43:06 +0000741 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
742 return ConstantVector::getSplat(VTy->getNumElements(), C);
743
744 return C;
Owen Anderson69c464d2009-07-27 20:59:43 +0000745}
746
747
Chris Lattnere9eed292012-01-25 05:19:54 +0000748Constant *ConstantFP::getZeroValueForNegation(Type *Ty) {
Benjamin Kramer5d2ff222014-01-18 16:43:06 +0000749 if (Ty->isFPOrFPVectorTy())
750 return getNegativeZero(Ty);
Owen Anderson69c464d2009-07-27 20:59:43 +0000751
Owen Anderson5a1acd92009-07-31 20:28:14 +0000752 return Constant::getNullValue(Ty);
Owen Anderson69c464d2009-07-27 20:59:43 +0000753}
754
755
756// ConstantFP accessors.
757ConstantFP* ConstantFP::get(LLVMContext &Context, const APFloat& V) {
Owen Anderson69c464d2009-07-27 20:59:43 +0000758 LLVMContextImpl* pImpl = Context.pImpl;
Galina Kistanovafc259902012-07-13 01:25:27 +0000759
Justin Lebar611c5c22016-10-10 16:26:13 +0000760 std::unique_ptr<ConstantFP> &Slot = pImpl->FPConstants[V];
Galina Kistanovafc259902012-07-13 01:25:27 +0000761
Owen Anderson69c464d2009-07-27 20:59:43 +0000762 if (!Slot) {
Chris Lattner229907c2011-07-18 04:54:35 +0000763 Type *Ty;
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000764 if (&V.getSemantics() == &APFloat::IEEEhalf())
Dan Gohman518cda42011-12-17 00:04:22 +0000765 Ty = Type::getHalfTy(Context);
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000766 else if (&V.getSemantics() == &APFloat::IEEEsingle())
Owen Anderson5dab84c2009-10-19 20:11:52 +0000767 Ty = Type::getFloatTy(Context);
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000768 else if (&V.getSemantics() == &APFloat::IEEEdouble())
Owen Anderson5dab84c2009-10-19 20:11:52 +0000769 Ty = Type::getDoubleTy(Context);
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000770 else if (&V.getSemantics() == &APFloat::x87DoubleExtended())
Owen Anderson5dab84c2009-10-19 20:11:52 +0000771 Ty = Type::getX86_FP80Ty(Context);
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000772 else if (&V.getSemantics() == &APFloat::IEEEquad())
Owen Anderson5dab84c2009-10-19 20:11:52 +0000773 Ty = Type::getFP128Ty(Context);
774 else {
Bjorn Petterssonaa025802018-07-03 12:39:52 +0000775 assert(&V.getSemantics() == &APFloat::PPCDoubleDouble() &&
Owen Anderson5dab84c2009-10-19 20:11:52 +0000776 "Unknown FP format");
777 Ty = Type::getPPC_FP128Ty(Context);
Owen Anderson69c464d2009-07-27 20:59:43 +0000778 }
Justin Lebar611c5c22016-10-10 16:26:13 +0000779 Slot.reset(new ConstantFP(Ty, V));
Owen Anderson69c464d2009-07-27 20:59:43 +0000780 }
Galina Kistanovafc259902012-07-13 01:25:27 +0000781
Justin Lebar611c5c22016-10-10 16:26:13 +0000782 return Slot.get();
Owen Anderson69c464d2009-07-27 20:59:43 +0000783}
784
Benjamin Kramer5d2ff222014-01-18 16:43:06 +0000785Constant *ConstantFP::getInfinity(Type *Ty, bool Negative) {
786 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
787 Constant *C = get(Ty->getContext(), APFloat::getInf(Semantics, Negative));
788
789 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
790 return ConstantVector::getSplat(VTy->getNumElements(), C);
791
792 return C;
Dan Gohmanfeb50212009-09-25 23:00:48 +0000793}
794
Duncan P. N. Exon Smithb6452792016-02-21 02:39:49 +0000795ConstantFP::ConstantFP(Type *Ty, const APFloat &V)
796 : ConstantData(Ty, ConstantFPVal), Val(V) {
Chris Lattner98bd9392008-04-09 06:38:30 +0000797 assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
798 "FP type Mismatch");
Chris Lattner2f7c9632001-06-06 20:29:01 +0000799}
800
Chris Lattnerbe6610c2011-07-15 06:14:08 +0000801bool ConstantFP::isExactlyValue(const APFloat &V) const {
Dale Johannesend246b2c2007-08-30 00:23:21 +0000802 return Val.bitwiseIsEqual(V);
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000803}
804
Pete Cooper86dd4cf2015-06-23 21:55:11 +0000805/// Remove the constant from the constant table.
806void ConstantFP::destroyConstantImpl() {
Craig Topperccbb8102017-06-27 19:57:51 +0000807 llvm_unreachable("You can't ConstantFP->destroyConstantImpl()!");
Pete Cooper86dd4cf2015-06-23 21:55:11 +0000808}
809
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000810//===----------------------------------------------------------------------===//
Chris Lattner030af792012-01-24 05:42:11 +0000811// ConstantAggregateZero Implementation
812//===----------------------------------------------------------------------===//
813
Chris Lattner7e683d12012-01-25 06:16:32 +0000814Constant *ConstantAggregateZero::getSequentialElement() const {
Chris Lattner8326bd82012-01-26 00:42:34 +0000815 return Constant::getNullValue(getType()->getSequentialElementType());
Chris Lattner030af792012-01-24 05:42:11 +0000816}
817
Chris Lattner7e683d12012-01-25 06:16:32 +0000818Constant *ConstantAggregateZero::getStructElement(unsigned Elt) const {
Chris Lattner8326bd82012-01-26 00:42:34 +0000819 return Constant::getNullValue(getType()->getStructElementType(Elt));
Chris Lattner030af792012-01-24 05:42:11 +0000820}
821
Chris Lattner7e683d12012-01-25 06:16:32 +0000822Constant *ConstantAggregateZero::getElementValue(Constant *C) const {
Chris Lattner030af792012-01-24 05:42:11 +0000823 if (isa<SequentialType>(getType()))
824 return getSequentialElement();
825 return getStructElement(cast<ConstantInt>(C)->getZExtValue());
826}
827
Chris Lattner7e683d12012-01-25 06:16:32 +0000828Constant *ConstantAggregateZero::getElementValue(unsigned Idx) const {
Chris Lattnerf7eb5432012-01-24 07:54:10 +0000829 if (isa<SequentialType>(getType()))
830 return getSequentialElement();
831 return getStructElement(Idx);
832}
833
David Majnemer9b529a72015-02-16 04:02:09 +0000834unsigned ConstantAggregateZero::getNumElements() const {
Craig Toppere3dcce92015-08-01 22:20:21 +0000835 Type *Ty = getType();
836 if (auto *AT = dyn_cast<ArrayType>(Ty))
David Majnemer9b529a72015-02-16 04:02:09 +0000837 return AT->getNumElements();
Craig Toppere3dcce92015-08-01 22:20:21 +0000838 if (auto *VT = dyn_cast<VectorType>(Ty))
David Majnemer9b529a72015-02-16 04:02:09 +0000839 return VT->getNumElements();
840 return Ty->getStructNumElements();
841}
Chris Lattnerf7eb5432012-01-24 07:54:10 +0000842
Chris Lattner030af792012-01-24 05:42:11 +0000843//===----------------------------------------------------------------------===//
844// UndefValue Implementation
845//===----------------------------------------------------------------------===//
846
Chris Lattner7e683d12012-01-25 06:16:32 +0000847UndefValue *UndefValue::getSequentialElement() const {
Chris Lattner8326bd82012-01-26 00:42:34 +0000848 return UndefValue::get(getType()->getSequentialElementType());
Chris Lattner030af792012-01-24 05:42:11 +0000849}
850
Chris Lattner7e683d12012-01-25 06:16:32 +0000851UndefValue *UndefValue::getStructElement(unsigned Elt) const {
Chris Lattner8326bd82012-01-26 00:42:34 +0000852 return UndefValue::get(getType()->getStructElementType(Elt));
Chris Lattner030af792012-01-24 05:42:11 +0000853}
854
Chris Lattner7e683d12012-01-25 06:16:32 +0000855UndefValue *UndefValue::getElementValue(Constant *C) const {
Chris Lattner030af792012-01-24 05:42:11 +0000856 if (isa<SequentialType>(getType()))
857 return getSequentialElement();
858 return getStructElement(cast<ConstantInt>(C)->getZExtValue());
859}
860
Chris Lattner7e683d12012-01-25 06:16:32 +0000861UndefValue *UndefValue::getElementValue(unsigned Idx) const {
Chris Lattnerf7eb5432012-01-24 07:54:10 +0000862 if (isa<SequentialType>(getType()))
863 return getSequentialElement();
864 return getStructElement(Idx);
865}
866
David Majnemer9b529a72015-02-16 04:02:09 +0000867unsigned UndefValue::getNumElements() const {
Craig Toppere3dcce92015-08-01 22:20:21 +0000868 Type *Ty = getType();
Peter Collingbournebc070522016-12-02 03:20:58 +0000869 if (auto *ST = dyn_cast<SequentialType>(Ty))
870 return ST->getNumElements();
David Majnemer9b529a72015-02-16 04:02:09 +0000871 return Ty->getStructNumElements();
872}
Chris Lattner030af792012-01-24 05:42:11 +0000873
874//===----------------------------------------------------------------------===//
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000875// ConstantXXX Classes
876//===----------------------------------------------------------------------===//
877
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000878template <typename ItTy, typename EltTy>
879static bool rangeOnlyContains(ItTy Start, ItTy End, EltTy Elt) {
880 for (; Start != End; ++Start)
881 if (*Start != Elt)
882 return false;
883 return true;
884}
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000885
Justin Bogner909e1c02015-12-01 20:20:49 +0000886template <typename SequentialTy, typename ElementTy>
887static Constant *getIntSequenceIfElementsMatch(ArrayRef<Constant *> V) {
888 assert(!V.empty() && "Cannot get empty int sequence.");
889
890 SmallVector<ElementTy, 16> Elts;
891 for (Constant *C : V)
892 if (auto *CI = dyn_cast<ConstantInt>(C))
893 Elts.push_back(CI->getZExtValue());
894 else
895 return nullptr;
896 return SequentialTy::get(V[0]->getContext(), Elts);
897}
898
899template <typename SequentialTy, typename ElementTy>
900static Constant *getFPSequenceIfElementsMatch(ArrayRef<Constant *> V) {
901 assert(!V.empty() && "Cannot get empty FP sequence.");
902
903 SmallVector<ElementTy, 16> Elts;
904 for (Constant *C : V)
905 if (auto *CFP = dyn_cast<ConstantFP>(C))
906 Elts.push_back(CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
907 else
908 return nullptr;
909 return SequentialTy::getFP(V[0]->getContext(), Elts);
910}
911
912template <typename SequenceTy>
913static Constant *getSequenceIfElementsMatch(Constant *C,
914 ArrayRef<Constant *> V) {
915 // We speculatively build the elements here even if it turns out that there is
916 // a constantexpr or something else weird, since it is so uncommon for that to
917 // happen.
918 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
919 if (CI->getType()->isIntegerTy(8))
920 return getIntSequenceIfElementsMatch<SequenceTy, uint8_t>(V);
921 else if (CI->getType()->isIntegerTy(16))
922 return getIntSequenceIfElementsMatch<SequenceTy, uint16_t>(V);
923 else if (CI->getType()->isIntegerTy(32))
924 return getIntSequenceIfElementsMatch<SequenceTy, uint32_t>(V);
925 else if (CI->getType()->isIntegerTy(64))
926 return getIntSequenceIfElementsMatch<SequenceTy, uint64_t>(V);
927 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
Justin Bogner0ebc8602015-12-08 03:01:16 +0000928 if (CFP->getType()->isHalfTy())
929 return getFPSequenceIfElementsMatch<SequenceTy, uint16_t>(V);
930 else if (CFP->getType()->isFloatTy())
Justin Bogner909e1c02015-12-01 20:20:49 +0000931 return getFPSequenceIfElementsMatch<SequenceTy, uint32_t>(V);
932 else if (CFP->getType()->isDoubleTy())
933 return getFPSequenceIfElementsMatch<SequenceTy, uint64_t>(V);
934 }
935
936 return nullptr;
937}
938
Duncan P. N. Exon Smith1de3c7e2016-04-05 21:10:45 +0000939ConstantAggregate::ConstantAggregate(CompositeType *T, ValueTy VT,
940 ArrayRef<Constant *> V)
941 : Constant(T, VT, OperandTraits<ConstantAggregate>::op_end(this) - V.size(),
942 V.size()) {
Jay Foad89d9b812011-07-25 10:14:44 +0000943 std::copy(V.begin(), V.end(), op_begin());
Duncan P. N. Exon Smith1de3c7e2016-04-05 21:10:45 +0000944
945 // Check that types match, unless this is an opaque struct.
946 if (auto *ST = dyn_cast<StructType>(T))
947 if (ST->isOpaque())
948 return;
949 for (unsigned I = 0, E = V.size(); I != E; ++I)
950 assert(V[I]->getType() == T->getTypeAtIndex(I) &&
951 "Initializer for composite element doesn't match!");
952}
953
954ConstantArray::ConstantArray(ArrayType *T, ArrayRef<Constant *> V)
955 : ConstantAggregate(T, ConstantArrayVal, V) {
956 assert(V.size() == T->getNumElements() &&
957 "Invalid initializer for constant array");
Chris Lattner2f7c9632001-06-06 20:29:01 +0000958}
959
Chris Lattner229907c2011-07-18 04:54:35 +0000960Constant *ConstantArray::get(ArrayType *Ty, ArrayRef<Constant*> V) {
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +0000961 if (Constant *C = getImpl(Ty, V))
962 return C;
963 return Ty->getContext().pImpl->ArrayConstants.getOrCreate(Ty, V);
964}
Justin Bogner909e1c02015-12-01 20:20:49 +0000965
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +0000966Constant *ConstantArray::getImpl(ArrayType *Ty, ArrayRef<Constant*> V) {
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000967 // Empty arrays are canonicalized to ConstantAggregateZero.
968 if (V.empty())
969 return ConstantAggregateZero::get(Ty);
970
Jeffrey Yasskin8ce67f82009-09-30 21:08:08 +0000971 for (unsigned i = 0, e = V.size(); i != e; ++i) {
972 assert(V[i]->getType() == Ty->getElementType() &&
973 "Wrong type in array element initializer");
974 }
Galina Kistanovafc259902012-07-13 01:25:27 +0000975
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000976 // If this is an all-zero array, return a ConstantAggregateZero object. If
977 // all undef, return an UndefValue, if "all simple", then return a
978 // ConstantDataArray.
979 Constant *C = V[0];
980 if (isa<UndefValue>(C) && rangeOnlyContains(V.begin(), V.end(), C))
981 return UndefValue::get(Ty);
Chris Lattnerf14a67f2012-01-26 02:31:22 +0000982
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000983 if (C->isNullValue() && rangeOnlyContains(V.begin(), V.end(), C))
984 return ConstantAggregateZero::get(Ty);
985
986 // Check to see if all of the elements are ConstantFP or ConstantInt and if
987 // the element type is compatible with ConstantDataVector. If so, use it.
Justin Bogner909e1c02015-12-01 20:20:49 +0000988 if (ConstantDataSequential::isElementTypeCompatible(C->getType()))
989 return getSequenceIfElementsMatch<ConstantDataArray>(C, V);
Chris Lattnerf14a67f2012-01-26 02:31:22 +0000990
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000991 // Otherwise, we really do want to create a ConstantArray.
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +0000992 return nullptr;
Owen Andersonc2c79322009-07-28 18:32:17 +0000993}
994
Chris Lattnercc19efa2011-06-20 04:01:31 +0000995StructType *ConstantStruct::getTypeForElements(LLVMContext &Context,
996 ArrayRef<Constant*> V,
997 bool Packed) {
Bill Wendling3ae7dd32012-02-07 01:27:51 +0000998 unsigned VecSize = V.size();
999 SmallVector<Type*, 16> EltTypes(VecSize);
1000 for (unsigned i = 0; i != VecSize; ++i)
1001 EltTypes[i] = V[i]->getType();
Galina Kistanovafc259902012-07-13 01:25:27 +00001002
Chris Lattnercc19efa2011-06-20 04:01:31 +00001003 return StructType::get(Context, EltTypes, Packed);
1004}
1005
1006
1007StructType *ConstantStruct::getTypeForElements(ArrayRef<Constant*> V,
1008 bool Packed) {
1009 assert(!V.empty() &&
1010 "ConstantStruct::getTypeForElements cannot be called on empty list");
1011 return getTypeForElements(V[0]->getContext(), V, Packed);
1012}
1013
Jay Foad89d9b812011-07-25 10:14:44 +00001014ConstantStruct::ConstantStruct(StructType *T, ArrayRef<Constant *> V)
Duncan P. N. Exon Smith1de3c7e2016-04-05 21:10:45 +00001015 : ConstantAggregate(T, ConstantStructVal, V) {
1016 assert((T->isOpaque() || V.size() == T->getNumElements()) &&
1017 "Invalid initializer for constant struct");
Chris Lattner2f7c9632001-06-06 20:29:01 +00001018}
1019
Owen Anderson45308b52009-07-27 22:29:26 +00001020// ConstantStruct accessors.
Chris Lattner229907c2011-07-18 04:54:35 +00001021Constant *ConstantStruct::get(StructType *ST, ArrayRef<Constant*> V) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001022 assert((ST->isOpaque() || ST->getNumElements() == V.size()) &&
1023 "Incorrect # elements specified to ConstantStruct::get");
Chris Lattnerf14a67f2012-01-26 02:31:22 +00001024
1025 // Create a ConstantAggregateZero value if all elements are zeros.
1026 bool isZero = true;
1027 bool isUndef = false;
Bjorn Petterssonaa025802018-07-03 12:39:52 +00001028
Chris Lattnerf14a67f2012-01-26 02:31:22 +00001029 if (!V.empty()) {
1030 isUndef = isa<UndefValue>(V[0]);
1031 isZero = V[0]->isNullValue();
1032 if (isUndef || isZero) {
1033 for (unsigned i = 0, e = V.size(); i != e; ++i) {
1034 if (!V[i]->isNullValue())
1035 isZero = false;
1036 if (!isa<UndefValue>(V[i]))
1037 isUndef = false;
1038 }
1039 }
Galina Kistanovafc259902012-07-13 01:25:27 +00001040 }
Chris Lattnerf14a67f2012-01-26 02:31:22 +00001041 if (isZero)
1042 return ConstantAggregateZero::get(ST);
1043 if (isUndef)
1044 return UndefValue::get(ST);
Galina Kistanovafc259902012-07-13 01:25:27 +00001045
Chris Lattnerf14a67f2012-01-26 02:31:22 +00001046 return ST->getContext().pImpl->StructConstants.getOrCreate(ST, V);
Owen Anderson45308b52009-07-27 22:29:26 +00001047}
1048
Jay Foad89d9b812011-07-25 10:14:44 +00001049ConstantVector::ConstantVector(VectorType *T, ArrayRef<Constant *> V)
Duncan P. N. Exon Smith1de3c7e2016-04-05 21:10:45 +00001050 : ConstantAggregate(T, ConstantVectorVal, V) {
Duncan P. N. Exon Smithdb63bda2016-04-05 20:53:47 +00001051 assert(V.size() == T->getNumElements() &&
Duncan P. N. Exon Smith1de3c7e2016-04-05 21:10:45 +00001052 "Invalid initializer for constant vector");
Brian Gaeke02209042004-08-20 06:00:58 +00001053}
1054
Owen Anderson4aa32952009-07-28 21:19:26 +00001055// ConstantVector accessors.
Jay Foadb8a8bed32011-06-22 09:10:19 +00001056Constant *ConstantVector::get(ArrayRef<Constant*> V) {
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00001057 if (Constant *C = getImpl(V))
1058 return C;
1059 VectorType *Ty = VectorType::get(V.front()->getType(), V.size());
1060 return Ty->getContext().pImpl->VectorConstants.getOrCreate(Ty, V);
1061}
Justin Bogner909e1c02015-12-01 20:20:49 +00001062
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00001063Constant *ConstantVector::getImpl(ArrayRef<Constant*> V) {
Jay Foad9f32cfd2011-01-27 14:44:55 +00001064 assert(!V.empty() && "Vectors can't be empty");
Chris Lattner229907c2011-07-18 04:54:35 +00001065 VectorType *T = VectorType::get(V.front()->getType(), V.size());
Jay Foad9f32cfd2011-01-27 14:44:55 +00001066
Chris Lattner69229312011-02-15 00:14:00 +00001067 // If this is an all-undef or all-zero vector, return a
Owen Anderson4aa32952009-07-28 21:19:26 +00001068 // ConstantAggregateZero or UndefValue.
1069 Constant *C = V[0];
1070 bool isZero = C->isNullValue();
1071 bool isUndef = isa<UndefValue>(C);
1072
1073 if (isZero || isUndef) {
1074 for (unsigned i = 1, e = V.size(); i != e; ++i)
1075 if (V[i] != C) {
1076 isZero = isUndef = false;
1077 break;
1078 }
1079 }
Galina Kistanovafc259902012-07-13 01:25:27 +00001080
Owen Anderson4aa32952009-07-28 21:19:26 +00001081 if (isZero)
Owen Andersonb292b8c2009-07-30 23:03:37 +00001082 return ConstantAggregateZero::get(T);
Owen Anderson4aa32952009-07-28 21:19:26 +00001083 if (isUndef)
Owen Andersonb292b8c2009-07-30 23:03:37 +00001084 return UndefValue::get(T);
Galina Kistanovafc259902012-07-13 01:25:27 +00001085
Chris Lattner978fe0c2012-01-30 06:21:21 +00001086 // Check to see if all of the elements are ConstantFP or ConstantInt and if
1087 // the element type is compatible with ConstantDataVector. If so, use it.
Justin Bogner909e1c02015-12-01 20:20:49 +00001088 if (ConstantDataSequential::isElementTypeCompatible(C->getType()))
1089 return getSequenceIfElementsMatch<ConstantDataVector>(C, V);
Galina Kistanovafc259902012-07-13 01:25:27 +00001090
Chris Lattner978fe0c2012-01-30 06:21:21 +00001091 // Otherwise, the element type isn't compatible with ConstantDataVector, or
Craig Topperdf907262017-04-11 06:41:55 +00001092 // the operand list contains a ConstantExpr or something else strange.
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00001093 return nullptr;
Owen Anderson4aa32952009-07-28 21:19:26 +00001094}
1095
Chris Lattnere9eed292012-01-25 05:19:54 +00001096Constant *ConstantVector::getSplat(unsigned NumElts, Constant *V) {
Chris Lattner978fe0c2012-01-30 06:21:21 +00001097 // If this splat is compatible with ConstantDataVector, use it instead of
1098 // ConstantVector.
1099 if ((isa<ConstantFP>(V) || isa<ConstantInt>(V)) &&
1100 ConstantDataSequential::isElementTypeCompatible(V->getType()))
1101 return ConstantDataVector::getSplat(NumElts, V);
Galina Kistanovafc259902012-07-13 01:25:27 +00001102
Chris Lattnere9eed292012-01-25 05:19:54 +00001103 SmallVector<Constant*, 32> Elts(NumElts, V);
1104 return get(Elts);
1105}
1106
David Majnemerf0f224d2015-11-11 21:57:16 +00001107ConstantTokenNone *ConstantTokenNone::get(LLVMContext &Context) {
1108 LLVMContextImpl *pImpl = Context.pImpl;
1109 if (!pImpl->TheNoneToken)
David Majnemer2dd41c52015-11-16 20:55:57 +00001110 pImpl->TheNoneToken.reset(new ConstantTokenNone(Context));
1111 return pImpl->TheNoneToken.get();
David Majnemerf0f224d2015-11-11 21:57:16 +00001112}
1113
1114/// Remove the constant from the constant table.
1115void ConstantTokenNone::destroyConstantImpl() {
1116 llvm_unreachable("You can't ConstantTokenNone->destroyConstantImpl()!");
1117}
Chris Lattnere9eed292012-01-25 05:19:54 +00001118
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001119// Utility function for determining if a ConstantExpr is a CastOp or not. This
1120// can't be inline because we don't want to #include Instruction.h into
1121// Constant.h
1122bool ConstantExpr::isCast() const {
1123 return Instruction::isCast(getOpcode());
1124}
1125
Reid Spenceree3c9912006-12-04 05:19:50 +00001126bool ConstantExpr::isCompare() const {
Nick Lewyckya21d3da2009-07-08 03:04:38 +00001127 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
Reid Spenceree3c9912006-12-04 05:19:50 +00001128}
1129
Dan Gohman7190d482009-09-10 23:37:55 +00001130bool ConstantExpr::isGEPWithNoNotionalOverIndexing() const {
1131 if (getOpcode() != Instruction::GetElementPtr) return false;
1132
1133 gep_type_iterator GEPI = gep_type_begin(this), E = gep_type_end(this);
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001134 User::const_op_iterator OI = std::next(this->op_begin());
Dan Gohman7190d482009-09-10 23:37:55 +00001135
Sanjay Patel81ed3492016-12-11 20:07:02 +00001136 // The remaining indices may be compile-time known integers within the bounds
1137 // of the corresponding notional static array types.
Dan Gohman7190d482009-09-10 23:37:55 +00001138 for (; GEPI != E; ++GEPI, ++OI) {
Sanjay Patel81ed3492016-12-11 20:07:02 +00001139 if (isa<UndefValue>(*OI))
1140 continue;
1141 auto *CI = dyn_cast<ConstantInt>(*OI);
1142 if (!CI || (GEPI.isBoundedSequential() &&
1143 (CI->getValue().getActiveBits() > 64 ||
1144 CI->getZExtValue() >= GEPI.getSequentialNumElements())))
Peter Collingbourneab85225b2016-12-02 02:24:42 +00001145 return false;
Dan Gohman7190d482009-09-10 23:37:55 +00001146 }
1147
1148 // All the indices checked out.
1149 return true;
1150}
1151
Dan Gohman1ecaf452008-05-31 00:58:22 +00001152bool ConstantExpr::hasIndices() const {
1153 return getOpcode() == Instruction::ExtractValue ||
1154 getOpcode() == Instruction::InsertValue;
1155}
1156
Jay Foad0091fe82011-04-13 15:22:40 +00001157ArrayRef<unsigned> ConstantExpr::getIndices() const {
Dan Gohman1ecaf452008-05-31 00:58:22 +00001158 if (const ExtractValueConstantExpr *EVCE =
1159 dyn_cast<ExtractValueConstantExpr>(this))
1160 return EVCE->Indices;
Dan Gohmana469bdb2008-06-23 16:39:44 +00001161
1162 return cast<InsertValueConstantExpr>(this)->Indices;
Dan Gohman1ecaf452008-05-31 00:58:22 +00001163}
1164
Reid Spencer10fbf0e2006-12-03 05:48:19 +00001165unsigned ConstantExpr::getPredicate() const {
Craig Toppercc03b492015-12-15 06:11:36 +00001166 return cast<CompareConstantExpr>(this)->predicate;
Reid Spencer10fbf0e2006-12-03 05:48:19 +00001167}
Chris Lattner60e0dd72001-10-03 06:12:09 +00001168
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001169Constant *
1170ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
Chris Lattner7c1018a2006-07-14 19:37:40 +00001171 assert(Op->getType() == getOperand(OpNo)->getType() &&
1172 "Replacing operand with value of different type!");
Chris Lattner227816342006-07-14 22:20:01 +00001173 if (getOperand(OpNo) == Op)
1174 return const_cast<ConstantExpr*>(this);
Chris Lattner37e38352012-01-26 20:37:11 +00001175
1176 SmallVector<Constant*, 8> NewOps;
1177 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1178 NewOps.push_back(i == OpNo ? Op : getOperand(i));
Galina Kistanovafc259902012-07-13 01:25:27 +00001179
Chris Lattner37e38352012-01-26 20:37:11 +00001180 return getWithOperands(NewOps);
Chris Lattner227816342006-07-14 22:20:01 +00001181}
1182
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001183Constant *ConstantExpr::getWithOperands(ArrayRef<Constant *> Ops, Type *Ty,
David Blaikie88208842015-08-21 20:16:51 +00001184 bool OnlyIfReduced, Type *SrcTy) const {
Jay Foad5c984e562011-04-13 13:46:01 +00001185 assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
Galina Kistanovafc259902012-07-13 01:25:27 +00001186
Benjamin Kramer8008e9f2015-03-02 11:57:04 +00001187 // If no operands changed return self.
1188 if (Ty == getType() && std::equal(Ops.begin(), Ops.end(), op_begin()))
Chris Lattner227816342006-07-14 22:20:01 +00001189 return const_cast<ConstantExpr*>(this);
1190
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001191 Type *OnlyIfReducedTy = OnlyIfReduced ? Ty : nullptr;
Chris Lattner227816342006-07-14 22:20:01 +00001192 switch (getOpcode()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001193 case Instruction::Trunc:
1194 case Instruction::ZExt:
1195 case Instruction::SExt:
1196 case Instruction::FPTrunc:
1197 case Instruction::FPExt:
1198 case Instruction::UIToFP:
1199 case Instruction::SIToFP:
1200 case Instruction::FPToUI:
1201 case Instruction::FPToSI:
1202 case Instruction::PtrToInt:
1203 case Instruction::IntToPtr:
1204 case Instruction::BitCast:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00001205 case Instruction::AddrSpaceCast:
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001206 return ConstantExpr::getCast(getOpcode(), Ops[0], Ty, OnlyIfReduced);
Chris Lattner227816342006-07-14 22:20:01 +00001207 case Instruction::Select:
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001208 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2], OnlyIfReducedTy);
Chris Lattner227816342006-07-14 22:20:01 +00001209 case Instruction::InsertElement:
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001210 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2],
1211 OnlyIfReducedTy);
Chris Lattner227816342006-07-14 22:20:01 +00001212 case Instruction::ExtractElement:
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001213 return ConstantExpr::getExtractElement(Ops[0], Ops[1], OnlyIfReducedTy);
Chris Lattner37e38352012-01-26 20:37:11 +00001214 case Instruction::InsertValue:
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001215 return ConstantExpr::getInsertValue(Ops[0], Ops[1], getIndices(),
1216 OnlyIfReducedTy);
Chris Lattner37e38352012-01-26 20:37:11 +00001217 case Instruction::ExtractValue:
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001218 return ConstantExpr::getExtractValue(Ops[0], getIndices(), OnlyIfReducedTy);
Chris Lattner227816342006-07-14 22:20:01 +00001219 case Instruction::ShuffleVector:
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001220 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2],
1221 OnlyIfReducedTy);
David Blaikie88208842015-08-21 20:16:51 +00001222 case Instruction::GetElementPtr: {
1223 auto *GEPO = cast<GEPOperator>(this);
1224 assert(SrcTy || (Ops[0]->getType() == getOperand(0)->getType()));
1225 return ConstantExpr::getGetElementPtr(
1226 SrcTy ? SrcTy : GEPO->getSourceElementType(), Ops[0], Ops.slice(1),
Peter Collingbourned93620b2016-11-10 22:34:55 +00001227 GEPO->isInBounds(), GEPO->getInRangeIndex(), OnlyIfReducedTy);
David Blaikie88208842015-08-21 20:16:51 +00001228 }
Reid Spencer266e42b2006-12-23 06:05:41 +00001229 case Instruction::ICmp:
1230 case Instruction::FCmp:
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001231 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1],
1232 OnlyIfReducedTy);
Chris Lattner227816342006-07-14 22:20:01 +00001233 default:
1234 assert(getNumOperands() == 2 && "Must be binary operator?");
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001235 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1], SubclassOptionalData,
1236 OnlyIfReducedTy);
Chris Lattner7c1018a2006-07-14 19:37:40 +00001237 }
1238}
1239
Chris Lattner2f7c9632001-06-06 20:29:01 +00001240
1241//===----------------------------------------------------------------------===//
Chris Lattner2f7c9632001-06-06 20:29:01 +00001242// isValueValidForType implementations
1243
Chris Lattner229907c2011-07-18 04:54:35 +00001244bool ConstantInt::isValueValidForType(Type *Ty, uint64_t Val) {
Chris Lattner8326bd82012-01-26 00:42:34 +00001245 unsigned NumBits = Ty->getIntegerBitWidth(); // assert okay
1246 if (Ty->isIntegerTy(1))
Reid Spencer7a9c62b2007-01-12 07:05:14 +00001247 return Val == 0 || Val == 1;
Craig Topper50b1e512017-06-07 00:58:05 +00001248 return isUIntN(NumBits, Val);
Reid Spencere7334722006-12-19 01:28:19 +00001249}
1250
Chris Lattner229907c2011-07-18 04:54:35 +00001251bool ConstantInt::isValueValidForType(Type *Ty, int64_t Val) {
Chris Lattner8326bd82012-01-26 00:42:34 +00001252 unsigned NumBits = Ty->getIntegerBitWidth();
1253 if (Ty->isIntegerTy(1))
Reid Spencera94d3942007-01-19 21:13:56 +00001254 return Val == 0 || Val == 1 || Val == -1;
Craig Topper50b1e512017-06-07 00:58:05 +00001255 return isIntN(NumBits, Val);
Chris Lattner2f7c9632001-06-06 20:29:01 +00001256}
1257
Chris Lattner229907c2011-07-18 04:54:35 +00001258bool ConstantFP::isValueValidForType(Type *Ty, const APFloat& Val) {
Dale Johannesend246b2c2007-08-30 00:23:21 +00001259 // convert modifies in place, so make a copy.
1260 APFloat Val2 = APFloat(Val);
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001261 bool losesInfo;
Chris Lattner6b727592004-06-17 18:19:28 +00001262 switch (Ty->getTypeID()) {
Chris Lattner2f7c9632001-06-06 20:29:01 +00001263 default:
1264 return false; // These can't be represented as floating point!
1265
Dale Johannesend246b2c2007-08-30 00:23:21 +00001266 // FIXME rounding mode needs to be more flexible
Dan Gohman518cda42011-12-17 00:04:22 +00001267 case Type::HalfTyID: {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001268 if (&Val2.getSemantics() == &APFloat::IEEEhalf())
Dan Gohman518cda42011-12-17 00:04:22 +00001269 return true;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001270 Val2.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven, &losesInfo);
Dan Gohman518cda42011-12-17 00:04:22 +00001271 return !losesInfo;
1272 }
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001273 case Type::FloatTyID: {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001274 if (&Val2.getSemantics() == &APFloat::IEEEsingle())
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001275 return true;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001276 Val2.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, &losesInfo);
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001277 return !losesInfo;
1278 }
1279 case Type::DoubleTyID: {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001280 if (&Val2.getSemantics() == &APFloat::IEEEhalf() ||
1281 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
1282 &Val2.getSemantics() == &APFloat::IEEEdouble())
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001283 return true;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001284 Val2.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven, &losesInfo);
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001285 return !losesInfo;
1286 }
Dale Johannesenbdad8092007-08-09 22:51:36 +00001287 case Type::X86_FP80TyID:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001288 return &Val2.getSemantics() == &APFloat::IEEEhalf() ||
Bjorn Petterssonaa025802018-07-03 12:39:52 +00001289 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001290 &Val2.getSemantics() == &APFloat::IEEEdouble() ||
1291 &Val2.getSemantics() == &APFloat::x87DoubleExtended();
Dale Johannesenbdad8092007-08-09 22:51:36 +00001292 case Type::FP128TyID:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001293 return &Val2.getSemantics() == &APFloat::IEEEhalf() ||
Bjorn Petterssonaa025802018-07-03 12:39:52 +00001294 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001295 &Val2.getSemantics() == &APFloat::IEEEdouble() ||
1296 &Val2.getSemantics() == &APFloat::IEEEquad();
Dale Johannesen007aa372007-10-11 18:07:22 +00001297 case Type::PPC_FP128TyID:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001298 return &Val2.getSemantics() == &APFloat::IEEEhalf() ||
Bjorn Petterssonaa025802018-07-03 12:39:52 +00001299 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001300 &Val2.getSemantics() == &APFloat::IEEEdouble() ||
1301 &Val2.getSemantics() == &APFloat::PPCDoubleDouble();
Chris Lattner2f7c9632001-06-06 20:29:01 +00001302 }
Chris Lattneraa2372562006-05-24 17:04:05 +00001303}
Chris Lattner9655e542001-07-20 19:16:02 +00001304
Chris Lattner030af792012-01-24 05:42:11 +00001305
Chris Lattner49d855c2001-09-07 16:46:31 +00001306//===----------------------------------------------------------------------===//
Chris Lattner49d855c2001-09-07 16:46:31 +00001307// Factory Function Implementation
1308
Chris Lattnerc7f9fd42012-01-23 15:20:12 +00001309ConstantAggregateZero *ConstantAggregateZero::get(Type *Ty) {
Chris Lattner13ee7952010-08-28 04:09:24 +00001310 assert((Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()) &&
Owen Andersonb292b8c2009-07-30 23:03:37 +00001311 "Cannot create an aggregate zero of non-aggregate type!");
David Blaikie899b85a2014-11-25 02:13:54 +00001312
Justin Lebar611c5c22016-10-10 16:26:13 +00001313 std::unique_ptr<ConstantAggregateZero> &Entry =
1314 Ty->getContext().pImpl->CAZConstants[Ty];
1315 if (!Entry)
1316 Entry.reset(new ConstantAggregateZero(Ty));
1317
1318 return Entry.get();
Owen Andersonb292b8c2009-07-30 23:03:37 +00001319}
1320
Sanjay Patel1d0ac7c2016-04-29 22:03:27 +00001321/// Remove the constant from the constant table.
Pete Cooper86dd4cf2015-06-23 21:55:11 +00001322void ConstantAggregateZero::destroyConstantImpl() {
Chris Lattnerc7f9fd42012-01-23 15:20:12 +00001323 getContext().pImpl->CAZConstants.erase(getType());
Chris Lattner9fba3da2004-02-15 05:53:04 +00001324}
1325
Sanjay Patel1d0ac7c2016-04-29 22:03:27 +00001326/// Remove the constant from the constant table.
Pete Cooper86dd4cf2015-06-23 21:55:11 +00001327void ConstantArray::destroyConstantImpl() {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001328 getType()->getContext().pImpl->ArrayConstants.remove(this);
Chris Lattner98fa07b2003-05-23 20:03:32 +00001329}
1330
Chris Lattner81fabb02002-08-26 17:53:56 +00001331
Chris Lattner3462ae32001-12-03 22:26:30 +00001332//---- ConstantStruct::get() implementation...
Chris Lattner49d855c2001-09-07 16:46:31 +00001333//
Chris Lattnerb50d1352003-10-05 00:17:43 +00001334
Sanjay Patel1d0ac7c2016-04-29 22:03:27 +00001335/// Remove the constant from the constant table.
Pete Cooper86dd4cf2015-06-23 21:55:11 +00001336void ConstantStruct::destroyConstantImpl() {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001337 getType()->getContext().pImpl->StructConstants.remove(this);
Chris Lattnerd7a73302001-10-13 06:57:33 +00001338}
Chris Lattner883ad0b2001-10-03 15:39:36 +00001339
Sanjay Patel1d0ac7c2016-04-29 22:03:27 +00001340/// Remove the constant from the constant table.
Pete Cooper86dd4cf2015-06-23 21:55:11 +00001341void ConstantVector::destroyConstantImpl() {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001342 getType()->getContext().pImpl->VectorConstants.remove(this);
Brian Gaeke02209042004-08-20 06:00:58 +00001343}
1344
Duncan Sandse6beec62012-11-13 12:59:33 +00001345Constant *Constant::getSplatValue() const {
1346 assert(this->getType()->isVectorTy() && "Only valid for vectors!");
1347 if (isa<ConstantAggregateZero>(this))
1348 return getNullValue(this->getType()->getVectorElementType());
1349 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
1350 return CV->getSplatValue();
1351 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
1352 return CV->getSplatValue();
Craig Topperc6207612014-04-09 06:08:46 +00001353 return nullptr;
Duncan Sandse6beec62012-11-13 12:59:33 +00001354}
1355
Duncan Sandscf0ff032011-02-01 08:39:12 +00001356Constant *ConstantVector::getSplatValue() const {
Dan Gohman07159202007-10-17 17:51:30 +00001357 // Check out first element.
1358 Constant *Elt = getOperand(0);
1359 // Then make sure all remaining elements point to the same value.
1360 for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
Chris Lattnerd04e32d2011-07-17 06:01:30 +00001361 if (getOperand(I) != Elt)
Craig Topperc6207612014-04-09 06:08:46 +00001362 return nullptr;
Dan Gohman07159202007-10-17 17:51:30 +00001363 return Elt;
1364}
1365
Duncan Sandse6beec62012-11-13 12:59:33 +00001366const APInt &Constant::getUniqueInteger() const {
1367 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
1368 return CI->getValue();
1369 assert(this->getSplatValue() && "Doesn't contain a unique integer!");
1370 const Constant *C = this->getAggregateElement(0U);
1371 assert(C && isa<ConstantInt>(C) && "Not a vector of numbers!");
1372 return cast<ConstantInt>(C)->getValue();
1373}
1374
Chris Lattner31b132c2009-10-28 00:01:44 +00001375//---- ConstantPointerNull::get() implementation.
Chris Lattnerd7a73302001-10-13 06:57:33 +00001376//
Chris Lattner98fa07b2003-05-23 20:03:32 +00001377
Chris Lattner229907c2011-07-18 04:54:35 +00001378ConstantPointerNull *ConstantPointerNull::get(PointerType *Ty) {
Justin Lebar611c5c22016-10-10 16:26:13 +00001379 std::unique_ptr<ConstantPointerNull> &Entry =
1380 Ty->getContext().pImpl->CPNConstants[Ty];
Craig Topperc6207612014-04-09 06:08:46 +00001381 if (!Entry)
Justin Lebar611c5c22016-10-10 16:26:13 +00001382 Entry.reset(new ConstantPointerNull(Ty));
Galina Kistanovafc259902012-07-13 01:25:27 +00001383
Justin Lebar611c5c22016-10-10 16:26:13 +00001384 return Entry.get();
Chris Lattner883ad0b2001-10-03 15:39:36 +00001385}
1386
Sanjay Patel1d0ac7c2016-04-29 22:03:27 +00001387/// Remove the constant from the constant table.
Pete Cooper86dd4cf2015-06-23 21:55:11 +00001388void ConstantPointerNull::destroyConstantImpl() {
Chris Lattnerc7f9fd42012-01-23 15:20:12 +00001389 getContext().pImpl->CPNConstants.erase(getType());
Chris Lattner0c6e0b92002-08-18 00:40:04 +00001390}
1391
Chris Lattner229907c2011-07-18 04:54:35 +00001392UndefValue *UndefValue::get(Type *Ty) {
Justin Lebar611c5c22016-10-10 16:26:13 +00001393 std::unique_ptr<UndefValue> &Entry = Ty->getContext().pImpl->UVConstants[Ty];
Craig Topperc6207612014-04-09 06:08:46 +00001394 if (!Entry)
Justin Lebar611c5c22016-10-10 16:26:13 +00001395 Entry.reset(new UndefValue(Ty));
Galina Kistanovafc259902012-07-13 01:25:27 +00001396
Justin Lebar611c5c22016-10-10 16:26:13 +00001397 return Entry.get();
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001398}
1399
Sanjay Patel1d0ac7c2016-04-29 22:03:27 +00001400/// Remove the constant from the constant table.
Pete Cooper86dd4cf2015-06-23 21:55:11 +00001401void UndefValue::destroyConstantImpl() {
Chris Lattnerc7f9fd42012-01-23 15:20:12 +00001402 // Free the constant and any dangling references to it.
1403 getContext().pImpl->UVConstants.erase(getType());
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001404}
1405
Chris Lattner31b132c2009-10-28 00:01:44 +00001406BlockAddress *BlockAddress::get(BasicBlock *BB) {
Craig Topper2617dcc2014-04-15 06:32:26 +00001407 assert(BB->getParent() && "Block must have a parent");
Chris Lattner31b132c2009-10-28 00:01:44 +00001408 return get(BB->getParent(), BB);
1409}
1410
1411BlockAddress *BlockAddress::get(Function *F, BasicBlock *BB) {
1412 BlockAddress *&BA =
1413 F->getContext().pImpl->BlockAddresses[std::make_pair(F, BB)];
Craig Topperc6207612014-04-09 06:08:46 +00001414 if (!BA)
Chris Lattner31b132c2009-10-28 00:01:44 +00001415 BA = new BlockAddress(F, BB);
Galina Kistanovafc259902012-07-13 01:25:27 +00001416
Chris Lattner31b132c2009-10-28 00:01:44 +00001417 assert(BA->getFunction() == F && "Basic block moved between functions");
1418 return BA;
1419}
1420
1421BlockAddress::BlockAddress(Function *F, BasicBlock *BB)
1422: Constant(Type::getInt8PtrTy(F->getContext()), Value::BlockAddressVal,
1423 &Op<0>(), 2) {
Chris Lattnerc559a9f2009-11-01 03:03:03 +00001424 setOperand(0, F);
1425 setOperand(1, BB);
Chris Lattneraa99c942009-11-01 01:27:45 +00001426 BB->AdjustBlockAddressRefCount(1);
Chris Lattner31b132c2009-10-28 00:01:44 +00001427}
1428
Chandler Carruth6a936922014-01-19 02:13:50 +00001429BlockAddress *BlockAddress::lookup(const BasicBlock *BB) {
1430 if (!BB->hasAddressTaken())
Craig Topperc6207612014-04-09 06:08:46 +00001431 return nullptr;
Chandler Carruth6a936922014-01-19 02:13:50 +00001432
1433 const Function *F = BB->getParent();
Craig Topper2617dcc2014-04-15 06:32:26 +00001434 assert(F && "Block must have a parent");
Chandler Carruth6a936922014-01-19 02:13:50 +00001435 BlockAddress *BA =
1436 F->getContext().pImpl->BlockAddresses.lookup(std::make_pair(F, BB));
1437 assert(BA && "Refcount and block address map disagree!");
1438 return BA;
1439}
Chris Lattner31b132c2009-10-28 00:01:44 +00001440
Sanjay Patel1d0ac7c2016-04-29 22:03:27 +00001441/// Remove the constant from the constant table.
Pete Cooper86dd4cf2015-06-23 21:55:11 +00001442void BlockAddress::destroyConstantImpl() {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001443 getFunction()->getType()->getContext().pImpl
Chris Lattner31b132c2009-10-28 00:01:44 +00001444 ->BlockAddresses.erase(std::make_pair(getFunction(), getBasicBlock()));
Chris Lattneraa99c942009-11-01 01:27:45 +00001445 getBasicBlock()->AdjustBlockAddressRefCount(-1);
Chris Lattner31b132c2009-10-28 00:01:44 +00001446}
1447
Mehdi Amini8914d292016-02-10 22:47:15 +00001448Value *BlockAddress::handleOperandChangeImpl(Value *From, Value *To) {
Chris Lattner31b132c2009-10-28 00:01:44 +00001449 // This could be replacing either the Basic Block or the Function. In either
1450 // case, we have to remove the map entry.
1451 Function *NewF = getFunction();
1452 BasicBlock *NewBB = getBasicBlock();
Galina Kistanovafc259902012-07-13 01:25:27 +00001453
Mehdi Amini8914d292016-02-10 22:47:15 +00001454 if (From == NewF)
Derek Schuffec9dc012013-06-13 19:51:17 +00001455 NewF = cast<Function>(To->stripPointerCasts());
Mehdi Amini8914d292016-02-10 22:47:15 +00001456 else {
1457 assert(From == NewBB && "From does not match any operand");
Chris Lattner31b132c2009-10-28 00:01:44 +00001458 NewBB = cast<BasicBlock>(To);
Mehdi Amini8914d292016-02-10 22:47:15 +00001459 }
Galina Kistanovafc259902012-07-13 01:25:27 +00001460
Chris Lattner31b132c2009-10-28 00:01:44 +00001461 // See if the 'new' entry already exists, if not, just update this in place
1462 // and return early.
1463 BlockAddress *&NewBA =
1464 getContext().pImpl->BlockAddresses[std::make_pair(NewF, NewBB)];
Pete Cooper5815b1f2015-06-24 18:55:24 +00001465 if (NewBA)
1466 return NewBA;
Chris Lattner31b132c2009-10-28 00:01:44 +00001467
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00001468 getBasicBlock()->AdjustBlockAddressRefCount(-1);
Galina Kistanovafc259902012-07-13 01:25:27 +00001469
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00001470 // Remove the old entry, this can't cause the map to rehash (just a
1471 // tombstone will get added).
1472 getContext().pImpl->BlockAddresses.erase(std::make_pair(getFunction(),
1473 getBasicBlock()));
1474 NewBA = this;
1475 setOperand(0, NewF);
1476 setOperand(1, NewBB);
1477 getBasicBlock()->AdjustBlockAddressRefCount(1);
Pete Cooper5815b1f2015-06-24 18:55:24 +00001478
1479 // If we just want to keep the existing value, then return null.
1480 // Callers know that this means we shouldn't delete this value.
1481 return nullptr;
Chris Lattner31b132c2009-10-28 00:01:44 +00001482}
1483
1484//---- ConstantExpr::get() implementations.
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001485//
Reid Spencer8d9336d2006-12-31 05:26:44 +00001486
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001487/// This is a utility function to handle folding of casts and lookup of the
Duncan Sands7d6c8ae2008-03-30 19:38:55 +00001488/// cast in the ExprConstants map. It is used by the various get* methods below.
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001489static Constant *getFoldedCast(Instruction::CastOps opc, Constant *C, Type *Ty,
1490 bool OnlyIfReduced = false) {
Chris Lattner815ae2b2003-10-07 22:19:19 +00001491 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001492 // Fold a few common cases
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00001493 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001494 return FC;
Chris Lattneracdbe712003-04-17 19:24:48 +00001495
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001496 if (OnlyIfReduced)
1497 return nullptr;
1498
Owen Anderson1584a292009-08-04 20:25:11 +00001499 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
1500
Nadav Rotem88330432013-03-07 01:30:40 +00001501 // Look up the constant in the table first to ensure uniqueness.
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00001502 ConstantExprKeyType Key(opc, C);
Galina Kistanovafc259902012-07-13 01:25:27 +00001503
Owen Anderson1584a292009-08-04 20:25:11 +00001504 return pImpl->ExprConstants.getOrCreate(Ty, Key);
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001505}
Galina Kistanovafc259902012-07-13 01:25:27 +00001506
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001507Constant *ConstantExpr::getCast(unsigned oc, Constant *C, Type *Ty,
1508 bool OnlyIfReduced) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001509 Instruction::CastOps opc = Instruction::CastOps(oc);
1510 assert(Instruction::isCast(opc) && "opcode out of range");
1511 assert(C && Ty && "Null arguments to getCast");
Chris Lattner37bc78a2010-01-26 21:51:43 +00001512 assert(CastInst::castIsValid(opc, C, Ty) && "Invalid constantexpr cast!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001513
1514 switch (opc) {
Chris Lattner37bc78a2010-01-26 21:51:43 +00001515 default:
1516 llvm_unreachable("Invalid cast opcode");
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001517 case Instruction::Trunc:
1518 return getTrunc(C, Ty, OnlyIfReduced);
1519 case Instruction::ZExt:
1520 return getZExt(C, Ty, OnlyIfReduced);
1521 case Instruction::SExt:
1522 return getSExt(C, Ty, OnlyIfReduced);
1523 case Instruction::FPTrunc:
1524 return getFPTrunc(C, Ty, OnlyIfReduced);
1525 case Instruction::FPExt:
1526 return getFPExtend(C, Ty, OnlyIfReduced);
1527 case Instruction::UIToFP:
1528 return getUIToFP(C, Ty, OnlyIfReduced);
1529 case Instruction::SIToFP:
1530 return getSIToFP(C, Ty, OnlyIfReduced);
1531 case Instruction::FPToUI:
1532 return getFPToUI(C, Ty, OnlyIfReduced);
1533 case Instruction::FPToSI:
1534 return getFPToSI(C, Ty, OnlyIfReduced);
1535 case Instruction::PtrToInt:
1536 return getPtrToInt(C, Ty, OnlyIfReduced);
1537 case Instruction::IntToPtr:
1538 return getIntToPtr(C, Ty, OnlyIfReduced);
1539 case Instruction::BitCast:
1540 return getBitCast(C, Ty, OnlyIfReduced);
1541 case Instruction::AddrSpaceCast:
1542 return getAddrSpaceCast(C, Ty, OnlyIfReduced);
Chris Lattner1ece6f82005-01-01 15:59:57 +00001543 }
Galina Kistanovafc259902012-07-13 01:25:27 +00001544}
Reid Spencerf37dc652006-12-05 19:14:13 +00001545
Chris Lattner229907c2011-07-18 04:54:35 +00001546Constant *ConstantExpr::getZExtOrBitCast(Constant *C, Type *Ty) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001547 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
Dan Gohman3cdcc3f2010-04-12 22:12:29 +00001548 return getBitCast(C, Ty);
1549 return getZExt(C, Ty);
Reid Spencer5c140882006-12-04 20:17:56 +00001550}
1551
Chris Lattner229907c2011-07-18 04:54:35 +00001552Constant *ConstantExpr::getSExtOrBitCast(Constant *C, Type *Ty) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001553 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
Dan Gohman3cdcc3f2010-04-12 22:12:29 +00001554 return getBitCast(C, Ty);
1555 return getSExt(C, Ty);
Reid Spencer5c140882006-12-04 20:17:56 +00001556}
1557
Chris Lattner229907c2011-07-18 04:54:35 +00001558Constant *ConstantExpr::getTruncOrBitCast(Constant *C, Type *Ty) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001559 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
Dan Gohman3cdcc3f2010-04-12 22:12:29 +00001560 return getBitCast(C, Ty);
1561 return getTrunc(C, Ty);
Reid Spencer5c140882006-12-04 20:17:56 +00001562}
1563
Chris Lattner229907c2011-07-18 04:54:35 +00001564Constant *ConstantExpr::getPointerCast(Constant *S, Type *Ty) {
Evgeniy Stepanov23382642013-01-16 14:41:46 +00001565 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
1566 assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
1567 "Invalid cast");
Reid Spencerbc245a02006-12-05 03:25:26 +00001568
Evgeniy Stepanov23382642013-01-16 14:41:46 +00001569 if (Ty->isIntOrIntVectorTy())
Dan Gohman3cdcc3f2010-04-12 22:12:29 +00001570 return getPtrToInt(S, Ty);
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00001571
1572 unsigned SrcAS = S->getType()->getPointerAddressSpace();
1573 if (Ty->isPtrOrPtrVectorTy() && SrcAS != Ty->getPointerAddressSpace())
1574 return getAddrSpaceCast(S, Ty);
1575
Dan Gohman3cdcc3f2010-04-12 22:12:29 +00001576 return getBitCast(S, Ty);
Reid Spencerbc245a02006-12-05 03:25:26 +00001577}
1578
Matt Arsenault21f38f42013-12-07 02:58:41 +00001579Constant *ConstantExpr::getPointerBitCastOrAddrSpaceCast(Constant *S,
1580 Type *Ty) {
1581 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
1582 assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast");
1583
1584 if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace())
1585 return getAddrSpaceCast(S, Ty);
1586
1587 return getBitCast(S, Ty);
1588}
1589
Sanjay Patelf3587ec2016-05-18 22:05:28 +00001590Constant *ConstantExpr::getIntegerCast(Constant *C, Type *Ty, bool isSigned) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00001591 assert(C->getType()->isIntOrIntVectorTy() &&
1592 Ty->isIntOrIntVectorTy() && "Invalid cast");
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001593 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1594 unsigned DstBits = Ty->getScalarSizeInBits();
Reid Spencer56521c42006-12-12 00:51:07 +00001595 Instruction::CastOps opcode =
1596 (SrcBits == DstBits ? Instruction::BitCast :
1597 (SrcBits > DstBits ? Instruction::Trunc :
1598 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1599 return getCast(opcode, C, Ty);
1600}
1601
Chris Lattner229907c2011-07-18 04:54:35 +00001602Constant *ConstantExpr::getFPCast(Constant *C, Type *Ty) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00001603 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
Reid Spencer56521c42006-12-12 00:51:07 +00001604 "Invalid cast");
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001605 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1606 unsigned DstBits = Ty->getScalarSizeInBits();
Reid Spencerca104e82006-12-12 05:38:50 +00001607 if (SrcBits == DstBits)
1608 return C; // Avoid a useless cast
Reid Spencer56521c42006-12-12 00:51:07 +00001609 Instruction::CastOps opcode =
Jay Foad9f32cfd2011-01-27 14:44:55 +00001610 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
Reid Spencer56521c42006-12-12 00:51:07 +00001611 return getCast(opcode, C, Ty);
1612}
1613
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001614Constant *ConstantExpr::getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001615#ifndef NDEBUG
1616 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1617 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1618#endif
1619 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001620 assert(C->getType()->isIntOrIntVectorTy() && "Trunc operand must be integer");
1621 assert(Ty->isIntOrIntVectorTy() && "Trunc produces only integral");
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001622 assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001623 "SrcTy must be larger than DestTy for Trunc!");
1624
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001625 return getFoldedCast(Instruction::Trunc, C, Ty, OnlyIfReduced);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001626}
1627
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001628Constant *ConstantExpr::getSExt(Constant *C, Type *Ty, bool OnlyIfReduced) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001629#ifndef NDEBUG
1630 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1631 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1632#endif
1633 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001634 assert(C->getType()->isIntOrIntVectorTy() && "SExt operand must be integral");
1635 assert(Ty->isIntOrIntVectorTy() && "SExt produces only integer");
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001636 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001637 "SrcTy must be smaller than DestTy for SExt!");
1638
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001639 return getFoldedCast(Instruction::SExt, C, Ty, OnlyIfReduced);
Chris Lattnerdd284742004-04-04 23:20:30 +00001640}
1641
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001642Constant *ConstantExpr::getZExt(Constant *C, Type *Ty, bool OnlyIfReduced) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001643#ifndef NDEBUG
1644 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1645 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1646#endif
1647 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001648 assert(C->getType()->isIntOrIntVectorTy() && "ZEXt operand must be integral");
1649 assert(Ty->isIntOrIntVectorTy() && "ZExt produces only integer");
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001650 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001651 "SrcTy must be smaller than DestTy for ZExt!");
1652
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001653 return getFoldedCast(Instruction::ZExt, C, Ty, OnlyIfReduced);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001654}
1655
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001656Constant *ConstantExpr::getFPTrunc(Constant *C, Type *Ty, bool OnlyIfReduced) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001657#ifndef NDEBUG
1658 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1659 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1660#endif
1661 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001662 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001663 C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001664 "This is an illegal floating point truncation!");
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001665 return getFoldedCast(Instruction::FPTrunc, C, Ty, OnlyIfReduced);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001666}
1667
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001668Constant *ConstantExpr::getFPExtend(Constant *C, Type *Ty, bool OnlyIfReduced) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001669#ifndef NDEBUG
1670 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1671 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1672#endif
1673 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001674 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001675 C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001676 "This is an illegal floating point extension!");
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001677 return getFoldedCast(Instruction::FPExt, C, Ty, OnlyIfReduced);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001678}
1679
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001680Constant *ConstantExpr::getUIToFP(Constant *C, Type *Ty, bool OnlyIfReduced) {
Devang Pateld26344d2008-11-03 23:20:04 +00001681#ifndef NDEBUG
Nate Begemand4d45c22007-11-17 03:58:34 +00001682 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1683 bool toVec = Ty->getTypeID() == Type::VectorTyID;
Devang Pateld26344d2008-11-03 23:20:04 +00001684#endif
Nate Begemand4d45c22007-11-17 03:58:34 +00001685 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001686 assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
Nate Begemand4d45c22007-11-17 03:58:34 +00001687 "This is an illegal uint to floating point cast!");
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001688 return getFoldedCast(Instruction::UIToFP, C, Ty, OnlyIfReduced);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001689}
1690
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001691Constant *ConstantExpr::getSIToFP(Constant *C, Type *Ty, bool OnlyIfReduced) {
Devang Pateld26344d2008-11-03 23:20:04 +00001692#ifndef NDEBUG
Nate Begemand4d45c22007-11-17 03:58:34 +00001693 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1694 bool toVec = Ty->getTypeID() == Type::VectorTyID;
Devang Pateld26344d2008-11-03 23:20:04 +00001695#endif
Nate Begemand4d45c22007-11-17 03:58:34 +00001696 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001697 assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001698 "This is an illegal sint to floating point cast!");
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001699 return getFoldedCast(Instruction::SIToFP, C, Ty, OnlyIfReduced);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001700}
1701
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001702Constant *ConstantExpr::getFPToUI(Constant *C, Type *Ty, bool OnlyIfReduced) {
Devang Pateld26344d2008-11-03 23:20:04 +00001703#ifndef NDEBUG
Nate Begemand4d45c22007-11-17 03:58:34 +00001704 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1705 bool toVec = Ty->getTypeID() == Type::VectorTyID;
Devang Pateld26344d2008-11-03 23:20:04 +00001706#endif
Nate Begemand4d45c22007-11-17 03:58:34 +00001707 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001708 assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
Nate Begemand4d45c22007-11-17 03:58:34 +00001709 "This is an illegal floating point to uint cast!");
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001710 return getFoldedCast(Instruction::FPToUI, C, Ty, OnlyIfReduced);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001711}
1712
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001713Constant *ConstantExpr::getFPToSI(Constant *C, Type *Ty, bool OnlyIfReduced) {
Devang Pateld26344d2008-11-03 23:20:04 +00001714#ifndef NDEBUG
Nate Begemand4d45c22007-11-17 03:58:34 +00001715 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1716 bool toVec = Ty->getTypeID() == Type::VectorTyID;
Devang Pateld26344d2008-11-03 23:20:04 +00001717#endif
Nate Begemand4d45c22007-11-17 03:58:34 +00001718 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001719 assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
Nate Begemand4d45c22007-11-17 03:58:34 +00001720 "This is an illegal floating point to sint cast!");
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001721 return getFoldedCast(Instruction::FPToSI, C, Ty, OnlyIfReduced);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001722}
1723
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001724Constant *ConstantExpr::getPtrToInt(Constant *C, Type *DstTy,
1725 bool OnlyIfReduced) {
Craig Topper95d23472017-07-09 07:04:00 +00001726 assert(C->getType()->isPtrOrPtrVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00001727 "PtrToInt source must be pointer or pointer vector");
Craig Topper95d23472017-07-09 07:04:00 +00001728 assert(DstTy->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00001729 "PtrToInt destination must be integer or integer vector");
Chris Lattner8a3df542012-01-25 01:32:59 +00001730 assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
Nick Lewyckyff509622012-01-25 03:20:12 +00001731 if (isa<VectorType>(C->getType()))
Chris Lattner8326bd82012-01-26 00:42:34 +00001732 assert(C->getType()->getVectorNumElements()==DstTy->getVectorNumElements()&&
Chris Lattner8a3df542012-01-25 01:32:59 +00001733 "Invalid cast between a different number of vector elements");
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001734 return getFoldedCast(Instruction::PtrToInt, C, DstTy, OnlyIfReduced);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001735}
1736
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001737Constant *ConstantExpr::getIntToPtr(Constant *C, Type *DstTy,
1738 bool OnlyIfReduced) {
Craig Topper95d23472017-07-09 07:04:00 +00001739 assert(C->getType()->isIntOrIntVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00001740 "IntToPtr source must be integer or integer vector");
Craig Topper95d23472017-07-09 07:04:00 +00001741 assert(DstTy->isPtrOrPtrVectorTy() &&
Nadav Rotem3924cb02011-12-05 06:29:09 +00001742 "IntToPtr destination must be a pointer or pointer vector");
Chris Lattner8a3df542012-01-25 01:32:59 +00001743 assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
Nick Lewyckyff509622012-01-25 03:20:12 +00001744 if (isa<VectorType>(C->getType()))
Chris Lattner8326bd82012-01-26 00:42:34 +00001745 assert(C->getType()->getVectorNumElements()==DstTy->getVectorNumElements()&&
Chris Lattner8a3df542012-01-25 01:32:59 +00001746 "Invalid cast between a different number of vector elements");
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001747 return getFoldedCast(Instruction::IntToPtr, C, DstTy, OnlyIfReduced);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001748}
1749
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001750Constant *ConstantExpr::getBitCast(Constant *C, Type *DstTy,
1751 bool OnlyIfReduced) {
Chris Lattner37bc78a2010-01-26 21:51:43 +00001752 assert(CastInst::castIsValid(Instruction::BitCast, C, DstTy) &&
1753 "Invalid constantexpr bitcast!");
Galina Kistanovafc259902012-07-13 01:25:27 +00001754
Chris Lattnercbeda872009-03-21 06:55:54 +00001755 // It is common to ask for a bitcast of a value to its own type, handle this
1756 // speedily.
1757 if (C->getType() == DstTy) return C;
Galina Kistanovafc259902012-07-13 01:25:27 +00001758
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001759 return getFoldedCast(Instruction::BitCast, C, DstTy, OnlyIfReduced);
Chris Lattnerdd284742004-04-04 23:20:30 +00001760}
1761
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001762Constant *ConstantExpr::getAddrSpaceCast(Constant *C, Type *DstTy,
1763 bool OnlyIfReduced) {
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00001764 assert(CastInst::castIsValid(Instruction::AddrSpaceCast, C, DstTy) &&
1765 "Invalid constantexpr addrspacecast!");
1766
Jingyue Wubaabe502014-06-15 21:40:57 +00001767 // Canonicalize addrspacecasts between different pointer types by first
1768 // bitcasting the pointer type and then converting the address space.
1769 PointerType *SrcScalarTy = cast<PointerType>(C->getType()->getScalarType());
1770 PointerType *DstScalarTy = cast<PointerType>(DstTy->getScalarType());
1771 Type *DstElemTy = DstScalarTy->getElementType();
1772 if (SrcScalarTy->getElementType() != DstElemTy) {
1773 Type *MidTy = PointerType::get(DstElemTy, SrcScalarTy->getAddressSpace());
1774 if (VectorType *VT = dyn_cast<VectorType>(DstTy)) {
1775 // Handle vectors of pointers.
1776 MidTy = VectorType::get(MidTy, VT->getNumElements());
1777 }
1778 C = getBitCast(C, MidTy);
1779 }
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001780 return getFoldedCast(Instruction::AddrSpaceCast, C, DstTy, OnlyIfReduced);
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00001781}
1782
Cameron McInallycbde0d92018-11-13 18:15:47 +00001783Constant *ConstantExpr::get(unsigned Opcode, Constant *C, unsigned Flags,
1784 Type *OnlyIfReducedTy) {
1785 // Check the operands for consistency first.
1786 assert(Instruction::isUnaryOp(Opcode) &&
1787 "Invalid opcode in unary constant expression");
1788
1789#ifndef NDEBUG
1790 switch (Opcode) {
1791 case Instruction::FNeg:
1792 assert(C->getType()->isFPOrFPVectorTy() &&
1793 "Tried to create a floating-point operation on a "
1794 "non-floating-point type!");
1795 break;
1796 default:
1797 break;
1798 }
1799#endif
1800
1801 // TODO: Try to constant fold operation.
1802
1803 if (OnlyIfReducedTy == C->getType())
1804 return nullptr;
1805
1806 Constant *ArgVec[] = { C };
1807 ConstantExprKeyType Key(Opcode, ArgVec, 0, Flags);
1808
1809 LLVMContextImpl *pImpl = C->getContext().pImpl;
1810 return pImpl->ExprConstants.getOrCreate(C->getType(), Key);
1811}
1812
Chris Lattner887ecac2011-07-09 18:23:52 +00001813Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2,
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001814 unsigned Flags, Type *OnlyIfReducedTy) {
Chris Lattner887ecac2011-07-09 18:23:52 +00001815 // Check the operands for consistency first.
Simon Pilgrime0a6eb12018-06-22 10:48:02 +00001816 assert(Instruction::isBinaryOp(Opcode) &&
Chris Lattner38a9bcd2003-05-21 17:49:25 +00001817 "Invalid opcode in binary constant expression");
1818 assert(C1->getType() == C2->getType() &&
1819 "Operand types in binary constant expression should match");
Galina Kistanovafc259902012-07-13 01:25:27 +00001820
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001821#ifndef NDEBUG
1822 switch (Opcode) {
Dan Gohmana5b96452009-06-04 22:49:04 +00001823 case Instruction::Add:
Reid Spencer7eb55b32006-11-02 01:53:59 +00001824 case Instruction::Sub:
Dan Gohmana5b96452009-06-04 22:49:04 +00001825 case Instruction::Mul:
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001826 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001827 assert(C1->getType()->isIntOrIntVectorTy() &&
Dan Gohmana5b96452009-06-04 22:49:04 +00001828 "Tried to create an integer operation on a non-integer type!");
1829 break;
1830 case Instruction::FAdd:
1831 case Instruction::FSub:
1832 case Instruction::FMul:
1833 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001834 assert(C1->getType()->isFPOrFPVectorTy() &&
Dan Gohmana5b96452009-06-04 22:49:04 +00001835 "Tried to create a floating-point operation on a "
1836 "non-floating-point type!");
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001837 break;
Bjorn Petterssonaa025802018-07-03 12:39:52 +00001838 case Instruction::UDiv:
1839 case Instruction::SDiv:
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001840 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001841 assert(C1->getType()->isIntOrIntVectorTy() &&
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001842 "Tried to create an arithmetic operation on a non-arithmetic type!");
1843 break;
1844 case Instruction::FDiv:
1845 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001846 assert(C1->getType()->isFPOrFPVectorTy() &&
Dan Gohman7889f2b2009-06-15 22:25:12 +00001847 "Tried to create an arithmetic operation on a non-arithmetic type!");
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001848 break;
Bjorn Petterssonaa025802018-07-03 12:39:52 +00001849 case Instruction::URem:
1850 case Instruction::SRem:
Reid Spencer7eb55b32006-11-02 01:53:59 +00001851 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001852 assert(C1->getType()->isIntOrIntVectorTy() &&
Reid Spencer7eb55b32006-11-02 01:53:59 +00001853 "Tried to create an arithmetic operation on a non-arithmetic type!");
1854 break;
1855 case Instruction::FRem:
1856 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001857 assert(C1->getType()->isFPOrFPVectorTy() &&
Dan Gohman7889f2b2009-06-15 22:25:12 +00001858 "Tried to create an arithmetic operation on a non-arithmetic type!");
Reid Spencer7eb55b32006-11-02 01:53:59 +00001859 break;
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001860 case Instruction::And:
1861 case Instruction::Or:
1862 case Instruction::Xor:
1863 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001864 assert(C1->getType()->isIntOrIntVectorTy() &&
Misha Brukman3852f652005-01-27 06:46:38 +00001865 "Tried to create a logical operation on a non-integral type!");
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001866 break;
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001867 case Instruction::Shl:
Reid Spencerfdff9382006-11-08 06:47:33 +00001868 case Instruction::LShr:
1869 case Instruction::AShr:
Reid Spencer2341c222007-02-02 02:16:23 +00001870 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001871 assert(C1->getType()->isIntOrIntVectorTy() &&
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001872 "Tried to create a shift operation on a non-integer type!");
1873 break;
1874 default:
1875 break;
1876 }
1877#endif
1878
Chris Lattner887ecac2011-07-09 18:23:52 +00001879 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1880 return FC; // Fold a few common cases.
Galina Kistanovafc259902012-07-13 01:25:27 +00001881
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001882 if (OnlyIfReducedTy == C1->getType())
1883 return nullptr;
1884
Benjamin Kramer324322b2013-03-07 20:53:34 +00001885 Constant *ArgVec[] = { C1, C2 };
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00001886 ConstantExprKeyType Key(Opcode, ArgVec, 0, Flags);
Galina Kistanovafc259902012-07-13 01:25:27 +00001887
Chris Lattner887ecac2011-07-09 18:23:52 +00001888 LLVMContextImpl *pImpl = C1->getContext().pImpl;
1889 return pImpl->ExprConstants.getOrCreate(C1->getType(), Key);
Reid Spencera009d0d2006-12-04 21:35:24 +00001890}
1891
Chris Lattner229907c2011-07-18 04:54:35 +00001892Constant *ConstantExpr::getSizeOf(Type* Ty) {
Owen Anderson487375e2009-07-29 18:55:55 +00001893 // sizeof is implemented as: (i64) gep (Ty*)null, 1
1894 // Note that a non-inbounds gep is used, as null isn't within any object.
Owen Anderson55f1c092009-08-13 21:58:54 +00001895 Constant *GEPIdx = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
Owen Anderson487375e2009-07-29 18:55:55 +00001896 Constant *GEP = getGetElementPtr(
David Blaikie4a2e73b2015-04-02 18:55:32 +00001897 Ty, Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx);
Bjorn Petterssonaa025802018-07-03 12:39:52 +00001898 return getPtrToInt(GEP,
Dan Gohman3cdcc3f2010-04-12 22:12:29 +00001899 Type::getInt64Ty(Ty->getContext()));
Owen Anderson487375e2009-07-29 18:55:55 +00001900}
1901
Chris Lattner229907c2011-07-18 04:54:35 +00001902Constant *ConstantExpr::getAlignOf(Type* Ty) {
Dan Gohmancf913832010-01-28 02:15:55 +00001903 // alignof is implemented as: (i64) gep ({i1,Ty}*)null, 0, 1
Dan Gohman50c09d02009-08-11 17:57:01 +00001904 // Note that a non-inbounds gep is used, as null isn't within any object.
Serge Gueltone38003f2017-05-09 19:31:13 +00001905 Type *AligningTy = StructType::get(Type::getInt1Ty(Ty->getContext()), Ty);
Matt Arsenaultbe558882014-04-23 20:58:57 +00001906 Constant *NullPtr = Constant::getNullValue(AligningTy->getPointerTo(0));
Dan Gohmana9be7392010-01-28 02:43:22 +00001907 Constant *Zero = ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0);
Owen Anderson55f1c092009-08-13 21:58:54 +00001908 Constant *One = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
Owen Anderson487375e2009-07-29 18:55:55 +00001909 Constant *Indices[2] = { Zero, One };
David Blaikie4a2e73b2015-04-02 18:55:32 +00001910 Constant *GEP = getGetElementPtr(AligningTy, NullPtr, Indices);
Dan Gohman3cdcc3f2010-04-12 22:12:29 +00001911 return getPtrToInt(GEP,
1912 Type::getInt64Ty(Ty->getContext()));
Owen Anderson487375e2009-07-29 18:55:55 +00001913}
1914
Chris Lattner229907c2011-07-18 04:54:35 +00001915Constant *ConstantExpr::getOffsetOf(StructType* STy, unsigned FieldNo) {
Dan Gohmanede94e62010-02-01 16:37:38 +00001916 return getOffsetOf(STy, ConstantInt::get(Type::getInt32Ty(STy->getContext()),
1917 FieldNo));
1918}
1919
Chris Lattner229907c2011-07-18 04:54:35 +00001920Constant *ConstantExpr::getOffsetOf(Type* Ty, Constant *FieldNo) {
Dan Gohmanff3af7252009-08-16 21:26:11 +00001921 // offsetof is implemented as: (i64) gep (Ty*)null, 0, FieldNo
1922 // Note that a non-inbounds gep is used, as null isn't within any object.
1923 Constant *GEPIdx[] = {
Dan Gohmanede94e62010-02-01 16:37:38 +00001924 ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0),
1925 FieldNo
Dan Gohmanff3af7252009-08-16 21:26:11 +00001926 };
1927 Constant *GEP = getGetElementPtr(
David Blaikie4a2e73b2015-04-02 18:55:32 +00001928 Ty, Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx);
Dan Gohman3cdcc3f2010-04-12 22:12:29 +00001929 return getPtrToInt(GEP,
1930 Type::getInt64Ty(Ty->getContext()));
Dan Gohmanff3af7252009-08-16 21:26:11 +00001931}
Owen Anderson487375e2009-07-29 18:55:55 +00001932
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001933Constant *ConstantExpr::getCompare(unsigned short Predicate, Constant *C1,
1934 Constant *C2, bool OnlyIfReduced) {
Reid Spencera009d0d2006-12-04 21:35:24 +00001935 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Galina Kistanovafc259902012-07-13 01:25:27 +00001936
Chris Lattner887ecac2011-07-09 18:23:52 +00001937 switch (Predicate) {
1938 default: llvm_unreachable("Invalid CmpInst predicate");
1939 case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
1940 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
1941 case CmpInst::FCMP_ONE: case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
1942 case CmpInst::FCMP_UEQ: case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
1943 case CmpInst::FCMP_ULT: case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
1944 case CmpInst::FCMP_TRUE:
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001945 return getFCmp(Predicate, C1, C2, OnlyIfReduced);
Galina Kistanovafc259902012-07-13 01:25:27 +00001946
Chris Lattner887ecac2011-07-09 18:23:52 +00001947 case CmpInst::ICMP_EQ: case CmpInst::ICMP_NE: case CmpInst::ICMP_UGT:
1948 case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
1949 case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
1950 case CmpInst::ICMP_SLE:
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001951 return getICmp(Predicate, C1, C2, OnlyIfReduced);
Chris Lattner887ecac2011-07-09 18:23:52 +00001952 }
Chris Lattner29ca2c62004-08-04 18:50:09 +00001953}
1954
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001955Constant *ConstantExpr::getSelect(Constant *C, Constant *V1, Constant *V2,
1956 Type *OnlyIfReducedTy) {
Chris Lattner41632132008-12-29 00:16:12 +00001957 assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
Chris Lattner6e415c02004-03-12 05:54:04 +00001958
Chris Lattner887ecac2011-07-09 18:23:52 +00001959 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1960 return SC; // Fold common cases
Chris Lattner6e415c02004-03-12 05:54:04 +00001961
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00001962 if (OnlyIfReducedTy == V1->getType())
1963 return nullptr;
1964
Benjamin Kramer324322b2013-03-07 20:53:34 +00001965 Constant *ArgVec[] = { C, V1, V2 };
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00001966 ConstantExprKeyType Key(Instruction::Select, ArgVec);
Galina Kistanovafc259902012-07-13 01:25:27 +00001967
Chris Lattner887ecac2011-07-09 18:23:52 +00001968 LLVMContextImpl *pImpl = C->getContext().pImpl;
1969 return pImpl->ExprConstants.getOrCreate(V1->getType(), Key);
Chris Lattner6e415c02004-03-12 05:54:04 +00001970}
1971
David Blaikie4a2e73b2015-04-02 18:55:32 +00001972Constant *ConstantExpr::getGetElementPtr(Type *Ty, Constant *C,
1973 ArrayRef<Value *> Idxs, bool InBounds,
Peter Collingbourned93620b2016-11-10 22:34:55 +00001974 Optional<unsigned> InRangeIndex,
David Blaikie4a2e73b2015-04-02 18:55:32 +00001975 Type *OnlyIfReducedTy) {
David Blaikie4a2e73b2015-04-02 18:55:32 +00001976 if (!Ty)
1977 Ty = cast<PointerType>(C->getType()->getScalarType())->getElementType();
1978 else
David Blaikied9d900c2015-05-07 17:28:58 +00001979 assert(
1980 Ty ==
1981 cast<PointerType>(C->getType()->getScalarType())->getContainedType(0u));
1982
Peter Collingbourned93620b2016-11-10 22:34:55 +00001983 if (Constant *FC =
1984 ConstantFoldGetElementPtr(Ty, C, InBounds, InRangeIndex, Idxs))
David Blaikied9d900c2015-05-07 17:28:58 +00001985 return FC; // Fold a few common cases.
1986
Chris Lattner887ecac2011-07-09 18:23:52 +00001987 // Get the result type of the getelementptr!
David Blaikie4a2e73b2015-04-02 18:55:32 +00001988 Type *DestTy = GetElementPtrInst::getIndexedType(Ty, Idxs);
1989 assert(DestTy && "GEP indices invalid!");
Chris Lattner8326bd82012-01-26 00:42:34 +00001990 unsigned AS = C->getType()->getPointerAddressSpace();
David Blaikie4a2e73b2015-04-02 18:55:32 +00001991 Type *ReqTy = DestTy->getPointerTo(AS);
Elena Demikhovskyee004bc2016-05-15 12:30:25 +00001992
1993 unsigned NumVecElts = 0;
1994 if (C->getType()->isVectorTy())
1995 NumVecElts = C->getType()->getVectorNumElements();
1996 else for (auto Idx : Idxs)
1997 if (Idx->getType()->isVectorTy())
1998 NumVecElts = Idx->getType()->getVectorNumElements();
1999
2000 if (NumVecElts)
2001 ReqTy = VectorType::get(ReqTy, NumVecElts);
Galina Kistanovafc259902012-07-13 01:25:27 +00002002
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002003 if (OnlyIfReducedTy == ReqTy)
2004 return nullptr;
2005
Dan Gohman1b849082009-09-07 23:54:19 +00002006 // Look up the constant in the table first to ensure uniqueness
2007 std::vector<Constant*> ArgVec;
Jay Foaded8db7d2011-07-21 14:31:17 +00002008 ArgVec.reserve(1 + Idxs.size());
Dan Gohman1b849082009-09-07 23:54:19 +00002009 ArgVec.push_back(C);
Duncan Sandse6beec62012-11-13 12:59:33 +00002010 for (unsigned i = 0, e = Idxs.size(); i != e; ++i) {
Duncan Sandse6beec62012-11-13 12:59:33 +00002011 assert((!Idxs[i]->getType()->isVectorTy() ||
Elena Demikhovskyee004bc2016-05-15 12:30:25 +00002012 Idxs[i]->getType()->getVectorNumElements() == NumVecElts) &&
Duncan Sandse6beec62012-11-13 12:59:33 +00002013 "getelementptr index type missmatch");
Elena Demikhovskyee004bc2016-05-15 12:30:25 +00002014
2015 Constant *Idx = cast<Constant>(Idxs[i]);
2016 if (NumVecElts && !Idxs[i]->getType()->isVectorTy())
2017 Idx = ConstantVector::getSplat(NumVecElts, Idx);
2018 ArgVec.push_back(Idx);
Duncan Sandse6beec62012-11-13 12:59:33 +00002019 }
Peter Collingbourned93620b2016-11-10 22:34:55 +00002020
2021 unsigned SubClassOptionalData = InBounds ? GEPOperator::IsInBounds : 0;
2022 if (InRangeIndex && *InRangeIndex < 63)
2023 SubClassOptionalData |= (*InRangeIndex + 1) << 1;
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002024 const ConstantExprKeyType Key(Instruction::GetElementPtr, ArgVec, 0,
Peter Collingbourned93620b2016-11-10 22:34:55 +00002025 SubClassOptionalData, None, Ty);
Galina Kistanovafc259902012-07-13 01:25:27 +00002026
Chris Lattner887ecac2011-07-09 18:23:52 +00002027 LLVMContextImpl *pImpl = C->getContext().pImpl;
Dan Gohman1b849082009-09-07 23:54:19 +00002028 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
2029}
2030
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002031Constant *ConstantExpr::getICmp(unsigned short pred, Constant *LHS,
2032 Constant *RHS, bool OnlyIfReduced) {
Reid Spenceree3c9912006-12-04 05:19:50 +00002033 assert(LHS->getType() == RHS->getType());
Craig Topper45844762017-07-05 23:35:46 +00002034 assert(CmpInst::isIntPredicate((CmpInst::Predicate)pred) &&
2035 "Invalid ICmp Predicate");
Reid Spenceree3c9912006-12-04 05:19:50 +00002036
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00002037 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
Reid Spenceree3c9912006-12-04 05:19:50 +00002038 return FC; // Fold a few common cases...
2039
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002040 if (OnlyIfReduced)
2041 return nullptr;
2042
Reid Spenceree3c9912006-12-04 05:19:50 +00002043 // Look up the constant in the table first to ensure uniqueness
Benjamin Kramer324322b2013-03-07 20:53:34 +00002044 Constant *ArgVec[] = { LHS, RHS };
Reid Spencerb1537492006-12-24 18:42:29 +00002045 // Get the key type with both the opcode and predicate
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002046 const ConstantExprKeyType Key(Instruction::ICmp, ArgVec, pred);
Owen Anderson61794042009-06-17 20:10:08 +00002047
Chris Lattner229907c2011-07-18 04:54:35 +00002048 Type *ResultTy = Type::getInt1Ty(LHS->getContext());
2049 if (VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
Nick Lewycky9e26c1c2010-01-21 07:03:21 +00002050 ResultTy = VectorType::get(ResultTy, VT->getNumElements());
2051
Owen Anderson1584a292009-08-04 20:25:11 +00002052 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
Nick Lewycky9e26c1c2010-01-21 07:03:21 +00002053 return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
Reid Spenceree3c9912006-12-04 05:19:50 +00002054}
2055
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002056Constant *ConstantExpr::getFCmp(unsigned short pred, Constant *LHS,
2057 Constant *RHS, bool OnlyIfReduced) {
Reid Spenceree3c9912006-12-04 05:19:50 +00002058 assert(LHS->getType() == RHS->getType());
Craig Topper45844762017-07-05 23:35:46 +00002059 assert(CmpInst::isFPPredicate((CmpInst::Predicate)pred) &&
2060 "Invalid FCmp Predicate");
Reid Spenceree3c9912006-12-04 05:19:50 +00002061
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00002062 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
Reid Spenceree3c9912006-12-04 05:19:50 +00002063 return FC; // Fold a few common cases...
2064
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002065 if (OnlyIfReduced)
2066 return nullptr;
2067
Reid Spenceree3c9912006-12-04 05:19:50 +00002068 // Look up the constant in the table first to ensure uniqueness
Benjamin Kramer324322b2013-03-07 20:53:34 +00002069 Constant *ArgVec[] = { LHS, RHS };
Reid Spencerb1537492006-12-24 18:42:29 +00002070 // Get the key type with both the opcode and predicate
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002071 const ConstantExprKeyType Key(Instruction::FCmp, ArgVec, pred);
Nick Lewycky9e26c1c2010-01-21 07:03:21 +00002072
Chris Lattner229907c2011-07-18 04:54:35 +00002073 Type *ResultTy = Type::getInt1Ty(LHS->getContext());
2074 if (VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
Nick Lewycky9e26c1c2010-01-21 07:03:21 +00002075 ResultTy = VectorType::get(ResultTy, VT->getNumElements());
2076
Owen Anderson1584a292009-08-04 20:25:11 +00002077 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
Nick Lewycky9e26c1c2010-01-21 07:03:21 +00002078 return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
Reid Spenceree3c9912006-12-04 05:19:50 +00002079}
2080
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002081Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx,
2082 Type *OnlyIfReducedTy) {
Duncan Sands19d0b472010-02-16 11:11:14 +00002083 assert(Val->getType()->isVectorTy() &&
Reid Spencer09575ba2007-02-15 03:39:18 +00002084 "Tried to create extractelement operation on non-vector type!");
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002085 assert(Idx->getType()->isIntegerTy() &&
2086 "Extractelement index must be an integer type!");
Galina Kistanovafc259902012-07-13 01:25:27 +00002087
Chris Lattner887ecac2011-07-09 18:23:52 +00002088 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
Chris Lattner09660c92009-12-30 20:25:09 +00002089 return FC; // Fold a few common cases.
Galina Kistanovafc259902012-07-13 01:25:27 +00002090
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002091 Type *ReqTy = Val->getType()->getVectorElementType();
2092 if (OnlyIfReducedTy == ReqTy)
2093 return nullptr;
2094
Robert Bocchinoca27f032006-01-17 20:07:22 +00002095 // Look up the constant in the table first to ensure uniqueness
Benjamin Kramer324322b2013-03-07 20:53:34 +00002096 Constant *ArgVec[] = { Val, Idx };
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002097 const ConstantExprKeyType Key(Instruction::ExtractElement, ArgVec);
Galina Kistanovafc259902012-07-13 01:25:27 +00002098
Chris Lattner887ecac2011-07-09 18:23:52 +00002099 LLVMContextImpl *pImpl = Val->getContext().pImpl;
Owen Anderson1584a292009-08-04 20:25:11 +00002100 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
Robert Bocchinoca27f032006-01-17 20:07:22 +00002101}
2102
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002103Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
2104 Constant *Idx, Type *OnlyIfReducedTy) {
Duncan Sands19d0b472010-02-16 11:11:14 +00002105 assert(Val->getType()->isVectorTy() &&
Reid Spencer09575ba2007-02-15 03:39:18 +00002106 "Tried to create insertelement operation on non-vector type!");
Chris Lattner8326bd82012-01-26 00:42:34 +00002107 assert(Elt->getType() == Val->getType()->getVectorElementType() &&
2108 "Insertelement types must match!");
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002109 assert(Idx->getType()->isIntegerTy() &&
Reid Spencer2546b762007-01-26 07:37:34 +00002110 "Insertelement index must be i32 type!");
Robert Bocchinoca27f032006-01-17 20:07:22 +00002111
Chris Lattner887ecac2011-07-09 18:23:52 +00002112 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
2113 return FC; // Fold a few common cases.
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002114
2115 if (OnlyIfReducedTy == Val->getType())
2116 return nullptr;
2117
Chris Lattnerbbe0a422006-04-08 01:18:18 +00002118 // Look up the constant in the table first to ensure uniqueness
Benjamin Kramer324322b2013-03-07 20:53:34 +00002119 Constant *ArgVec[] = { Val, Elt, Idx };
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002120 const ConstantExprKeyType Key(Instruction::InsertElement, ArgVec);
Galina Kistanovafc259902012-07-13 01:25:27 +00002121
Chris Lattner887ecac2011-07-09 18:23:52 +00002122 LLVMContextImpl *pImpl = Val->getContext().pImpl;
2123 return pImpl->ExprConstants.getOrCreate(Val->getType(), Key);
Chris Lattnerbbe0a422006-04-08 01:18:18 +00002124}
2125
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002126Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
2127 Constant *Mask, Type *OnlyIfReducedTy) {
Chris Lattnerbbe0a422006-04-08 01:18:18 +00002128 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
2129 "Invalid shuffle vector constant expr operands!");
Nate Begeman94aa38d2009-02-12 21:28:33 +00002130
Chris Lattner887ecac2011-07-09 18:23:52 +00002131 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
2132 return FC; // Fold a few common cases.
2133
Chris Lattner8326bd82012-01-26 00:42:34 +00002134 unsigned NElts = Mask->getType()->getVectorNumElements();
2135 Type *EltTy = V1->getType()->getVectorElementType();
Chris Lattner229907c2011-07-18 04:54:35 +00002136 Type *ShufTy = VectorType::get(EltTy, NElts);
Chris Lattner887ecac2011-07-09 18:23:52 +00002137
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002138 if (OnlyIfReducedTy == ShufTy)
2139 return nullptr;
2140
Chris Lattner887ecac2011-07-09 18:23:52 +00002141 // Look up the constant in the table first to ensure uniqueness
Benjamin Kramer324322b2013-03-07 20:53:34 +00002142 Constant *ArgVec[] = { V1, V2, Mask };
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002143 const ConstantExprKeyType Key(Instruction::ShuffleVector, ArgVec);
Galina Kistanovafc259902012-07-13 01:25:27 +00002144
Chris Lattner887ecac2011-07-09 18:23:52 +00002145 LLVMContextImpl *pImpl = ShufTy->getContext().pImpl;
2146 return pImpl->ExprConstants.getOrCreate(ShufTy, Key);
Chris Lattnerbbe0a422006-04-08 01:18:18 +00002147}
2148
Chris Lattner887ecac2011-07-09 18:23:52 +00002149Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002150 ArrayRef<unsigned> Idxs,
2151 Type *OnlyIfReducedTy) {
Hal Finkelb31366d2013-07-10 22:51:01 +00002152 assert(Agg->getType()->isFirstClassType() &&
2153 "Non-first-class type for constant insertvalue expression");
2154
Jay Foad57aa6362011-07-13 10:26:04 +00002155 assert(ExtractValueInst::getIndexedType(Agg->getType(),
2156 Idxs) == Val->getType() &&
Dan Gohman12fce772008-05-15 19:50:34 +00002157 "insertvalue indices invalid!");
Hal Finkelb31366d2013-07-10 22:51:01 +00002158 Type *ReqTy = Val->getType();
2159
2160 if (Constant *FC = ConstantFoldInsertValueInstruction(Agg, Val, Idxs))
2161 return FC;
2162
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002163 if (OnlyIfReducedTy == ReqTy)
2164 return nullptr;
2165
Hal Finkelb31366d2013-07-10 22:51:01 +00002166 Constant *ArgVec[] = { Agg, Val };
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002167 const ConstantExprKeyType Key(Instruction::InsertValue, ArgVec, 0, 0, Idxs);
Hal Finkelb31366d2013-07-10 22:51:01 +00002168
2169 LLVMContextImpl *pImpl = Agg->getContext().pImpl;
2170 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
Dan Gohman12fce772008-05-15 19:50:34 +00002171}
2172
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002173Constant *ConstantExpr::getExtractValue(Constant *Agg, ArrayRef<unsigned> Idxs,
2174 Type *OnlyIfReducedTy) {
Dan Gohman0752bff2008-05-23 00:36:11 +00002175 assert(Agg->getType()->isFirstClassType() &&
Chris Lattner887ecac2011-07-09 18:23:52 +00002176 "Tried to create extractelement operation on non-first-class type!");
Dan Gohman12fce772008-05-15 19:50:34 +00002177
Chris Lattner229907c2011-07-18 04:54:35 +00002178 Type *ReqTy = ExtractValueInst::getIndexedType(Agg->getType(), Idxs);
Chandler Carruth9db56b82011-07-10 09:45:35 +00002179 (void)ReqTy;
Chris Lattner887ecac2011-07-09 18:23:52 +00002180 assert(ReqTy && "extractvalue indices invalid!");
Galina Kistanovafc259902012-07-13 01:25:27 +00002181
Dan Gohman0752bff2008-05-23 00:36:11 +00002182 assert(Agg->getType()->isFirstClassType() &&
2183 "Non-first-class type for constant extractvalue expression");
Hal Finkelb31366d2013-07-10 22:51:01 +00002184 if (Constant *FC = ConstantFoldExtractValueInstruction(Agg, Idxs))
2185 return FC;
2186
Duncan P. N. Exon Smith170eb982014-08-19 19:45:37 +00002187 if (OnlyIfReducedTy == ReqTy)
2188 return nullptr;
2189
Hal Finkelb31366d2013-07-10 22:51:01 +00002190 Constant *ArgVec[] = { Agg };
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002191 const ConstantExprKeyType Key(Instruction::ExtractValue, ArgVec, 0, 0, Idxs);
Hal Finkelb31366d2013-07-10 22:51:01 +00002192
2193 LLVMContextImpl *pImpl = Agg->getContext().pImpl;
2194 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
Dan Gohman12fce772008-05-15 19:50:34 +00002195}
2196
Chris Lattnere9b4ad72011-02-10 07:01:55 +00002197Constant *ConstantExpr::getNeg(Constant *C, bool HasNUW, bool HasNSW) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00002198 assert(C->getType()->isIntOrIntVectorTy() &&
Owen Anderson487375e2009-07-29 18:55:55 +00002199 "Cannot NEG a nonintegral value!");
Chris Lattnere9b4ad72011-02-10 07:01:55 +00002200 return getSub(ConstantFP::getZeroValueForNegation(C->getType()),
2201 C, HasNUW, HasNSW);
Owen Anderson487375e2009-07-29 18:55:55 +00002202}
2203
Chris Lattnera676c0f2011-02-07 16:40:21 +00002204Constant *ConstantExpr::getFNeg(Constant *C) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00002205 assert(C->getType()->isFPOrFPVectorTy() &&
Owen Anderson487375e2009-07-29 18:55:55 +00002206 "Cannot FNEG a non-floating-point value!");
Chris Lattnere9b4ad72011-02-10 07:01:55 +00002207 return getFSub(ConstantFP::getZeroValueForNegation(C->getType()), C);
Owen Anderson487375e2009-07-29 18:55:55 +00002208}
2209
Chris Lattnera676c0f2011-02-07 16:40:21 +00002210Constant *ConstantExpr::getNot(Constant *C) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00002211 assert(C->getType()->isIntOrIntVectorTy() &&
Owen Anderson487375e2009-07-29 18:55:55 +00002212 "Cannot NOT a nonintegral value!");
Owen Anderson5a1acd92009-07-31 20:28:14 +00002213 return get(Instruction::Xor, C, Constant::getAllOnesValue(C->getType()));
Owen Anderson487375e2009-07-29 18:55:55 +00002214}
2215
Chris Lattnere9b4ad72011-02-10 07:01:55 +00002216Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2,
2217 bool HasNUW, bool HasNSW) {
2218 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2219 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2220 return get(Instruction::Add, C1, C2, Flags);
Owen Anderson487375e2009-07-29 18:55:55 +00002221}
2222
Chris Lattnera676c0f2011-02-07 16:40:21 +00002223Constant *ConstantExpr::getFAdd(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002224 return get(Instruction::FAdd, C1, C2);
2225}
2226
Chris Lattnere9b4ad72011-02-10 07:01:55 +00002227Constant *ConstantExpr::getSub(Constant *C1, Constant *C2,
2228 bool HasNUW, bool HasNSW) {
2229 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2230 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2231 return get(Instruction::Sub, C1, C2, Flags);
Owen Anderson487375e2009-07-29 18:55:55 +00002232}
2233
Chris Lattnera676c0f2011-02-07 16:40:21 +00002234Constant *ConstantExpr::getFSub(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002235 return get(Instruction::FSub, C1, C2);
2236}
2237
Chris Lattnere9b4ad72011-02-10 07:01:55 +00002238Constant *ConstantExpr::getMul(Constant *C1, Constant *C2,
2239 bool HasNUW, bool HasNSW) {
2240 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2241 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2242 return get(Instruction::Mul, C1, C2, Flags);
Owen Anderson487375e2009-07-29 18:55:55 +00002243}
2244
Chris Lattnera676c0f2011-02-07 16:40:21 +00002245Constant *ConstantExpr::getFMul(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002246 return get(Instruction::FMul, C1, C2);
2247}
2248
Chris Lattner0d75eac2011-02-09 16:43:07 +00002249Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2, bool isExact) {
2250 return get(Instruction::UDiv, C1, C2,
2251 isExact ? PossiblyExactOperator::IsExact : 0);
Owen Anderson487375e2009-07-29 18:55:55 +00002252}
2253
Chris Lattner0d75eac2011-02-09 16:43:07 +00002254Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2, bool isExact) {
2255 return get(Instruction::SDiv, C1, C2,
2256 isExact ? PossiblyExactOperator::IsExact : 0);
Owen Anderson487375e2009-07-29 18:55:55 +00002257}
2258
Chris Lattnera676c0f2011-02-07 16:40:21 +00002259Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002260 return get(Instruction::FDiv, C1, C2);
2261}
2262
Chris Lattnera676c0f2011-02-07 16:40:21 +00002263Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002264 return get(Instruction::URem, C1, C2);
2265}
2266
Chris Lattnera676c0f2011-02-07 16:40:21 +00002267Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002268 return get(Instruction::SRem, C1, C2);
2269}
2270
Chris Lattnera676c0f2011-02-07 16:40:21 +00002271Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002272 return get(Instruction::FRem, C1, C2);
2273}
2274
Chris Lattnera676c0f2011-02-07 16:40:21 +00002275Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002276 return get(Instruction::And, C1, C2);
2277}
2278
Chris Lattnera676c0f2011-02-07 16:40:21 +00002279Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002280 return get(Instruction::Or, C1, C2);
2281}
2282
Chris Lattnera676c0f2011-02-07 16:40:21 +00002283Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00002284 return get(Instruction::Xor, C1, C2);
2285}
2286
Chris Lattnere9b4ad72011-02-10 07:01:55 +00002287Constant *ConstantExpr::getShl(Constant *C1, Constant *C2,
2288 bool HasNUW, bool HasNSW) {
2289 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2290 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2291 return get(Instruction::Shl, C1, C2, Flags);
Owen Anderson487375e2009-07-29 18:55:55 +00002292}
2293
Chris Lattner0d75eac2011-02-09 16:43:07 +00002294Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2, bool isExact) {
2295 return get(Instruction::LShr, C1, C2,
2296 isExact ? PossiblyExactOperator::IsExact : 0);
Owen Anderson487375e2009-07-29 18:55:55 +00002297}
2298
Chris Lattner0d75eac2011-02-09 16:43:07 +00002299Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2, bool isExact) {
2300 return get(Instruction::AShr, C1, C2,
2301 isExact ? PossiblyExactOperator::IsExact : 0);
Owen Anderson487375e2009-07-29 18:55:55 +00002302}
2303
Sanjay Patele85a3002018-07-06 15:18:58 +00002304Constant *ConstantExpr::getBinOpIdentity(unsigned Opcode, Type *Ty,
2305 bool AllowRHSConstant) {
2306 assert(Instruction::isBinaryOp(Opcode) && "Only binops allowed");
2307
2308 // Commutative opcodes: it does not matter if AllowRHSConstant is set.
2309 if (Instruction::isCommutative(Opcode)) {
2310 switch (Opcode) {
2311 case Instruction::Add: // X + 0 = X
2312 case Instruction::Or: // X | 0 = X
2313 case Instruction::Xor: // X ^ 0 = X
2314 return Constant::getNullValue(Ty);
2315 case Instruction::Mul: // X * 1 = X
2316 return ConstantInt::get(Ty, 1);
2317 case Instruction::And: // X & -1 = X
2318 return Constant::getAllOnesValue(Ty);
2319 case Instruction::FAdd: // X + -0.0 = X
2320 // TODO: If the fadd has 'nsz', should we return +0.0?
2321 return ConstantFP::getNegativeZero(Ty);
2322 case Instruction::FMul: // X * 1.0 = X
2323 return ConstantFP::get(Ty, 1.0);
2324 default:
2325 llvm_unreachable("Every commutative binop has an identity constant");
2326 }
2327 }
2328
2329 // Non-commutative opcodes: AllowRHSConstant must be set.
2330 if (!AllowRHSConstant)
Craig Topperc6207612014-04-09 06:08:46 +00002331 return nullptr;
Duncan Sands318a89d2012-06-13 09:42:13 +00002332
Sanjay Patele85a3002018-07-06 15:18:58 +00002333 switch (Opcode) {
2334 case Instruction::Sub: // X - 0 = X
2335 case Instruction::Shl: // X << 0 = X
2336 case Instruction::LShr: // X >>u 0 = X
2337 case Instruction::AShr: // X >> 0 = X
2338 case Instruction::FSub: // X - 0.0 = X
2339 return Constant::getNullValue(Ty);
2340 case Instruction::SDiv: // X / 1 = X
2341 case Instruction::UDiv: // X /u 1 = X
2342 return ConstantInt::get(Ty, 1);
2343 case Instruction::FDiv: // X / 1.0 = X
2344 return ConstantFP::get(Ty, 1.0);
2345 default:
2346 return nullptr;
Duncan Sandsd7aeefe2012-06-12 14:33:56 +00002347 }
2348}
2349
Duncan Sands318a89d2012-06-13 09:42:13 +00002350Constant *ConstantExpr::getBinOpAbsorber(unsigned Opcode, Type *Ty) {
2351 switch (Opcode) {
2352 default:
2353 // Doesn't have an absorber.
Craig Topperc6207612014-04-09 06:08:46 +00002354 return nullptr;
Duncan Sands318a89d2012-06-13 09:42:13 +00002355
2356 case Instruction::Or:
2357 return Constant::getAllOnesValue(Ty);
2358
2359 case Instruction::And:
2360 case Instruction::Mul:
2361 return Constant::getNullValue(Ty);
2362 }
2363}
2364
Sanjay Patel1d0ac7c2016-04-29 22:03:27 +00002365/// Remove the constant from the constant table.
Pete Cooper86dd4cf2015-06-23 21:55:11 +00002366void ConstantExpr::destroyConstantImpl() {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002367 getType()->getContext().pImpl->ExprConstants.remove(this);
Vikram S. Adve4e537b22002-07-14 23:13:17 +00002368}
2369
Chris Lattner3cd8c562002-07-30 18:54:25 +00002370const char *ConstantExpr::getOpcodeName() const {
2371 return Instruction::getOpcodeName(getOpcode());
Vikram S. Adve4e537b22002-07-14 23:13:17 +00002372}
Reid Spencer1ebe1ab2004-07-17 23:48:33 +00002373
David Blaikie60310f22015-05-08 00:42:26 +00002374GetElementPtrConstantExpr::GetElementPtrConstantExpr(
2375 Type *SrcElementTy, Constant *C, ArrayRef<Constant *> IdxList, Type *DestTy)
2376 : ConstantExpr(DestTy, Instruction::GetElementPtr,
2377 OperandTraits<GetElementPtrConstantExpr>::op_end(this) -
2378 (IdxList.size() + 1),
2379 IdxList.size() + 1),
Eduard Burtescu19eb0312016-01-19 17:28:00 +00002380 SrcElementTy(SrcElementTy),
2381 ResElementTy(GetElementPtrInst::getIndexedType(SrcElementTy, IdxList)) {
Pete Coopereb31b682015-05-21 22:48:54 +00002382 Op<0>() = C;
Pete Cooper74510a42015-06-12 17:48:05 +00002383 Use *OperandList = getOperandList();
Chris Lattnera3b94ba2010-03-30 20:48:48 +00002384 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
2385 OperandList[i+1] = IdxList[i];
2386}
2387
David Blaikie60310f22015-05-08 00:42:26 +00002388Type *GetElementPtrConstantExpr::getSourceElementType() const {
2389 return SrcElementTy;
2390}
2391
Eduard Burtescu19eb0312016-01-19 17:28:00 +00002392Type *GetElementPtrConstantExpr::getResultElementType() const {
2393 return ResElementTy;
2394}
2395
Chris Lattner3756b912012-01-23 22:57:10 +00002396//===----------------------------------------------------------------------===//
2397// ConstantData* implementations
2398
Chris Lattnere4f3f102012-01-24 04:43:41 +00002399Type *ConstantDataSequential::getElementType() const {
2400 return getType()->getElementType();
2401}
2402
Chris Lattner5d4497b2012-01-24 09:31:43 +00002403StringRef ConstantDataSequential::getRawDataValues() const {
Chris Lattner00245f42012-01-24 13:41:11 +00002404 return StringRef(DataElements, getNumElements()*getElementByteSize());
Chris Lattner5d4497b2012-01-24 09:31:43 +00002405}
2406
Craig Toppere3dcce92015-08-01 22:20:21 +00002407bool ConstantDataSequential::isElementTypeCompatible(Type *Ty) {
Justin Bogner0ebc8602015-12-08 03:01:16 +00002408 if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy()) return true;
Craig Toppere3dcce92015-08-01 22:20:21 +00002409 if (auto *IT = dyn_cast<IntegerType>(Ty)) {
Chris Lattnere4f3f102012-01-24 04:43:41 +00002410 switch (IT->getBitWidth()) {
2411 case 8:
2412 case 16:
2413 case 32:
2414 case 64:
2415 return true;
2416 default: break;
2417 }
2418 }
2419 return false;
2420}
2421
Chris Lattner00245f42012-01-24 13:41:11 +00002422unsigned ConstantDataSequential::getNumElements() const {
Chris Lattner8a3df542012-01-25 01:32:59 +00002423 if (ArrayType *AT = dyn_cast<ArrayType>(getType()))
2424 return AT->getNumElements();
Chris Lattner8326bd82012-01-26 00:42:34 +00002425 return getType()->getVectorNumElements();
Chris Lattner00245f42012-01-24 13:41:11 +00002426}
2427
2428
Chris Lattnere4f3f102012-01-24 04:43:41 +00002429uint64_t ConstantDataSequential::getElementByteSize() const {
2430 return getElementType()->getPrimitiveSizeInBits()/8;
2431}
2432
Sanjay Patel1d0ac7c2016-04-29 22:03:27 +00002433/// Return the start of the specified element.
Chris Lattnere4f3f102012-01-24 04:43:41 +00002434const char *ConstantDataSequential::getElementPointer(unsigned Elt) const {
Chris Lattner00245f42012-01-24 13:41:11 +00002435 assert(Elt < getNumElements() && "Invalid Elt");
Chris Lattnere4f3f102012-01-24 04:43:41 +00002436 return DataElements+Elt*getElementByteSize();
2437}
2438
2439
Sanjay Patel1d0ac7c2016-04-29 22:03:27 +00002440/// Return true if the array is empty or all zeros.
Chris Lattner3756b912012-01-23 22:57:10 +00002441static bool isAllZeros(StringRef Arr) {
Benjamin Krameraf28e7d2016-06-26 14:10:56 +00002442 for (char I : Arr)
2443 if (I != 0)
Chris Lattner3756b912012-01-23 22:57:10 +00002444 return false;
2445 return true;
2446}
Chris Lattner030af792012-01-24 05:42:11 +00002447
Sanjay Patel1d0ac7c2016-04-29 22:03:27 +00002448/// This is the underlying implementation of all of the
Chris Lattner3756b912012-01-23 22:57:10 +00002449/// ConstantDataSequential::get methods. They all thunk down to here, providing
Chris Lattnerf06039b2012-01-30 18:19:30 +00002450/// the correct element type. We take the bytes in as a StringRef because
Chris Lattner3756b912012-01-23 22:57:10 +00002451/// we *want* an underlying "char*" to avoid TBAA type punning violations.
2452Constant *ConstantDataSequential::getImpl(StringRef Elements, Type *Ty) {
Chris Lattner8326bd82012-01-26 00:42:34 +00002453 assert(isElementTypeCompatible(Ty->getSequentialElementType()));
Chris Lattner139822f2012-01-24 14:17:05 +00002454 // If the elements are all zero or there are no elements, return a CAZ, which
2455 // is more dense and canonical.
Chris Lattner3756b912012-01-23 22:57:10 +00002456 if (isAllZeros(Elements))
2457 return ConstantAggregateZero::get(Ty);
2458
2459 // Do a lookup to see if we have already formed one of these.
David Blaikie5106ce72014-11-19 05:49:42 +00002460 auto &Slot =
2461 *Ty->getContext()
2462 .pImpl->CDSConstants.insert(std::make_pair(Elements, nullptr))
2463 .first;
Galina Kistanovafc259902012-07-13 01:25:27 +00002464
Chris Lattner3756b912012-01-23 22:57:10 +00002465 // The bucket can point to a linked list of different CDS's that have the same
2466 // body but different types. For example, 0,0,0,1 could be a 4 element array
2467 // of i8, or a 1-element array of i32. They'll both end up in the same
2468 /// StringMap bucket, linked up by their Next pointers. Walk the list.
David Blaikie5106ce72014-11-19 05:49:42 +00002469 ConstantDataSequential **Entry = &Slot.second;
Craig Topperc6207612014-04-09 06:08:46 +00002470 for (ConstantDataSequential *Node = *Entry; Node;
Chris Lattner3756b912012-01-23 22:57:10 +00002471 Entry = &Node->Next, Node = *Entry)
2472 if (Node->getType() == Ty)
2473 return Node;
Galina Kistanovafc259902012-07-13 01:25:27 +00002474
Chris Lattner3756b912012-01-23 22:57:10 +00002475 // Okay, we didn't get a hit. Create a node of the right class, link it in,
2476 // and return it.
2477 if (isa<ArrayType>(Ty))
David Blaikie5106ce72014-11-19 05:49:42 +00002478 return *Entry = new ConstantDataArray(Ty, Slot.first().data());
Chris Lattner3756b912012-01-23 22:57:10 +00002479
2480 assert(isa<VectorType>(Ty));
David Blaikie5106ce72014-11-19 05:49:42 +00002481 return *Entry = new ConstantDataVector(Ty, Slot.first().data());
Chris Lattner3756b912012-01-23 22:57:10 +00002482}
2483
Pete Cooper86dd4cf2015-06-23 21:55:11 +00002484void ConstantDataSequential::destroyConstantImpl() {
Chris Lattner3756b912012-01-23 22:57:10 +00002485 // Remove the constant from the StringMap.
Bjorn Petterssonaa025802018-07-03 12:39:52 +00002486 StringMap<ConstantDataSequential*> &CDSConstants =
Chris Lattner3756b912012-01-23 22:57:10 +00002487 getType()->getContext().pImpl->CDSConstants;
Galina Kistanovafc259902012-07-13 01:25:27 +00002488
Chris Lattner3756b912012-01-23 22:57:10 +00002489 StringMap<ConstantDataSequential*>::iterator Slot =
Chris Lattner5d4497b2012-01-24 09:31:43 +00002490 CDSConstants.find(getRawDataValues());
Chris Lattner3756b912012-01-23 22:57:10 +00002491
2492 assert(Slot != CDSConstants.end() && "CDS not found in uniquing table");
2493
2494 ConstantDataSequential **Entry = &Slot->getValue();
2495
2496 // Remove the entry from the hash table.
Craig Topperc6207612014-04-09 06:08:46 +00002497 if (!(*Entry)->Next) {
Chris Lattner3756b912012-01-23 22:57:10 +00002498 // If there is only one value in the bucket (common case) it must be this
2499 // entry, and removing the entry should remove the bucket completely.
2500 assert((*Entry) == this && "Hash mismatch in ConstantDataSequential");
2501 getContext().pImpl->CDSConstants.erase(Slot);
2502 } else {
Bjorn Petterssonaa025802018-07-03 12:39:52 +00002503 // Otherwise, there are multiple entries linked off the bucket, unlink the
Chris Lattner3756b912012-01-23 22:57:10 +00002504 // node we care about but keep the bucket around.
2505 for (ConstantDataSequential *Node = *Entry; ;
2506 Entry = &Node->Next, Node = *Entry) {
2507 assert(Node && "Didn't find entry in its uniquing hash table!");
2508 // If we found our entry, unlink it from the list and we're done.
2509 if (Node == this) {
2510 *Entry = Node->Next;
2511 break;
2512 }
2513 }
2514 }
Galina Kistanovafc259902012-07-13 01:25:27 +00002515
Chris Lattner3756b912012-01-23 22:57:10 +00002516 // If we were part of a list, make sure that we don't delete the list that is
2517 // still owned by the uniquing map.
Craig Topperc6207612014-04-09 06:08:46 +00002518 Next = nullptr;
Chris Lattner3756b912012-01-23 22:57:10 +00002519}
2520
Rafael Espindola8c97e192015-02-19 16:08:20 +00002521/// getFP() constructors - Return a constant with array type with an element
2522/// count and element type of float with precision matching the number of
2523/// bits in the ArrayRef passed in. (i.e. half for 16bits, float for 32bits,
2524/// double for 64bits) Note that this can return a ConstantAggregateZero
2525/// object.
2526Constant *ConstantDataArray::getFP(LLVMContext &Context,
2527 ArrayRef<uint16_t> Elts) {
Justin Bognerb7389d6712015-12-09 21:21:07 +00002528 Type *Ty = ArrayType::get(Type::getHalfTy(Context), Elts.size());
Rafael Espindola8c97e192015-02-19 16:08:20 +00002529 const char *Data = reinterpret_cast<const char *>(Elts.data());
Craig Topper393ce692017-07-11 15:52:21 +00002530 return getImpl(StringRef(Data, Elts.size() * 2), Ty);
Rafael Espindola8c97e192015-02-19 16:08:20 +00002531}
2532Constant *ConstantDataArray::getFP(LLVMContext &Context,
2533 ArrayRef<uint32_t> Elts) {
2534 Type *Ty = ArrayType::get(Type::getFloatTy(Context), Elts.size());
2535 const char *Data = reinterpret_cast<const char *>(Elts.data());
Craig Topper393ce692017-07-11 15:52:21 +00002536 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
Rafael Espindola8c97e192015-02-19 16:08:20 +00002537}
2538Constant *ConstantDataArray::getFP(LLVMContext &Context,
2539 ArrayRef<uint64_t> Elts) {
2540 Type *Ty = ArrayType::get(Type::getDoubleTy(Context), Elts.size());
2541 const char *Data = reinterpret_cast<const char *>(Elts.data());
Craig Topper393ce692017-07-11 15:52:21 +00002542 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
Chris Lattner3756b912012-01-23 22:57:10 +00002543}
2544
Chris Lattner20683932012-01-24 14:04:40 +00002545Constant *ConstantDataArray::getString(LLVMContext &Context,
2546 StringRef Str, bool AddNull) {
Galina Kistanovafc259902012-07-13 01:25:27 +00002547 if (!AddNull) {
2548 const uint8_t *Data = reinterpret_cast<const uint8_t *>(Str.data());
Craig Topper393ce692017-07-11 15:52:21 +00002549 return get(Context, makeArrayRef(Data, Str.size()));
Galina Kistanovafc259902012-07-13 01:25:27 +00002550 }
2551
Chris Lattner20683932012-01-24 14:04:40 +00002552 SmallVector<uint8_t, 64> ElementVals;
2553 ElementVals.append(Str.begin(), Str.end());
2554 ElementVals.push_back(0);
2555 return get(Context, ElementVals);
2556}
Chris Lattner3756b912012-01-23 22:57:10 +00002557
2558/// get() constructors - Return a constant with vector type with an element
2559/// count and element type matching the ArrayRef passed in. Note that this
2560/// can return a ConstantAggregateZero object.
Chris Lattner20683932012-01-24 14:04:40 +00002561Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint8_t> Elts){
Chris Lattner3756b912012-01-23 22:57:10 +00002562 Type *Ty = VectorType::get(Type::getInt8Ty(Context), Elts.size());
Galina Kistanovafc259902012-07-13 01:25:27 +00002563 const char *Data = reinterpret_cast<const char *>(Elts.data());
Craig Topper393ce692017-07-11 15:52:21 +00002564 return getImpl(StringRef(Data, Elts.size() * 1), Ty);
Chris Lattner3756b912012-01-23 22:57:10 +00002565}
Chris Lattner20683932012-01-24 14:04:40 +00002566Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint16_t> Elts){
Chris Lattner3756b912012-01-23 22:57:10 +00002567 Type *Ty = VectorType::get(Type::getInt16Ty(Context), Elts.size());
Galina Kistanovafc259902012-07-13 01:25:27 +00002568 const char *Data = reinterpret_cast<const char *>(Elts.data());
Craig Topper393ce692017-07-11 15:52:21 +00002569 return getImpl(StringRef(Data, Elts.size() * 2), Ty);
Chris Lattner3756b912012-01-23 22:57:10 +00002570}
Chris Lattner20683932012-01-24 14:04:40 +00002571Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint32_t> Elts){
Chris Lattner3756b912012-01-23 22:57:10 +00002572 Type *Ty = VectorType::get(Type::getInt32Ty(Context), Elts.size());
Galina Kistanovafc259902012-07-13 01:25:27 +00002573 const char *Data = reinterpret_cast<const char *>(Elts.data());
Craig Topper393ce692017-07-11 15:52:21 +00002574 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
Chris Lattner3756b912012-01-23 22:57:10 +00002575}
Chris Lattner20683932012-01-24 14:04:40 +00002576Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint64_t> Elts){
Chris Lattner3756b912012-01-23 22:57:10 +00002577 Type *Ty = VectorType::get(Type::getInt64Ty(Context), Elts.size());
Galina Kistanovafc259902012-07-13 01:25:27 +00002578 const char *Data = reinterpret_cast<const char *>(Elts.data());
Craig Topper393ce692017-07-11 15:52:21 +00002579 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
Chris Lattner3756b912012-01-23 22:57:10 +00002580}
Chris Lattner20683932012-01-24 14:04:40 +00002581Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<float> Elts) {
Chris Lattner3756b912012-01-23 22:57:10 +00002582 Type *Ty = VectorType::get(Type::getFloatTy(Context), Elts.size());
Galina Kistanovafc259902012-07-13 01:25:27 +00002583 const char *Data = reinterpret_cast<const char *>(Elts.data());
Craig Topper393ce692017-07-11 15:52:21 +00002584 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
Chris Lattner3756b912012-01-23 22:57:10 +00002585}
Chris Lattner20683932012-01-24 14:04:40 +00002586Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<double> Elts) {
Chris Lattner3756b912012-01-23 22:57:10 +00002587 Type *Ty = VectorType::get(Type::getDoubleTy(Context), Elts.size());
Galina Kistanovafc259902012-07-13 01:25:27 +00002588 const char *Data = reinterpret_cast<const char *>(Elts.data());
Craig Topper393ce692017-07-11 15:52:21 +00002589 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
Rafael Espindola8c97e192015-02-19 16:08:20 +00002590}
2591
2592/// getFP() constructors - Return a constant with vector type with an element
2593/// count and element type of float with the precision matching the number of
2594/// bits in the ArrayRef passed in. (i.e. half for 16bits, float for 32bits,
2595/// double for 64bits) Note that this can return a ConstantAggregateZero
2596/// object.
2597Constant *ConstantDataVector::getFP(LLVMContext &Context,
2598 ArrayRef<uint16_t> Elts) {
2599 Type *Ty = VectorType::get(Type::getHalfTy(Context), Elts.size());
2600 const char *Data = reinterpret_cast<const char *>(Elts.data());
Craig Topper393ce692017-07-11 15:52:21 +00002601 return getImpl(StringRef(Data, Elts.size() * 2), Ty);
Rafael Espindola8c97e192015-02-19 16:08:20 +00002602}
2603Constant *ConstantDataVector::getFP(LLVMContext &Context,
2604 ArrayRef<uint32_t> Elts) {
2605 Type *Ty = VectorType::get(Type::getFloatTy(Context), Elts.size());
2606 const char *Data = reinterpret_cast<const char *>(Elts.data());
Craig Topper393ce692017-07-11 15:52:21 +00002607 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
Rafael Espindola8c97e192015-02-19 16:08:20 +00002608}
2609Constant *ConstantDataVector::getFP(LLVMContext &Context,
2610 ArrayRef<uint64_t> Elts) {
2611 Type *Ty = VectorType::get(Type::getDoubleTy(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() * 8), Ty);
Chris Lattner3756b912012-01-23 22:57:10 +00002614}
2615
Chris Lattnere9eed292012-01-25 05:19:54 +00002616Constant *ConstantDataVector::getSplat(unsigned NumElts, Constant *V) {
2617 assert(isElementTypeCompatible(V->getType()) &&
2618 "Element type not compatible with ConstantData");
2619 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
2620 if (CI->getType()->isIntegerTy(8)) {
2621 SmallVector<uint8_t, 16> Elts(NumElts, CI->getZExtValue());
2622 return get(V->getContext(), Elts);
2623 }
2624 if (CI->getType()->isIntegerTy(16)) {
2625 SmallVector<uint16_t, 16> Elts(NumElts, CI->getZExtValue());
2626 return get(V->getContext(), Elts);
2627 }
2628 if (CI->getType()->isIntegerTy(32)) {
2629 SmallVector<uint32_t, 16> Elts(NumElts, CI->getZExtValue());
2630 return get(V->getContext(), Elts);
2631 }
2632 assert(CI->getType()->isIntegerTy(64) && "Unsupported ConstantData type");
2633 SmallVector<uint64_t, 16> Elts(NumElts, CI->getZExtValue());
2634 return get(V->getContext(), Elts);
2635 }
2636
Chris Lattner978fe0c2012-01-30 06:21:21 +00002637 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
Justin Bogner0ebc8602015-12-08 03:01:16 +00002638 if (CFP->getType()->isHalfTy()) {
2639 SmallVector<uint16_t, 16> Elts(
2640 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
2641 return getFP(V->getContext(), Elts);
2642 }
Chris Lattner978fe0c2012-01-30 06:21:21 +00002643 if (CFP->getType()->isFloatTy()) {
Rafael Espindola8c97e192015-02-19 16:08:20 +00002644 SmallVector<uint32_t, 16> Elts(
2645 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
2646 return getFP(V->getContext(), Elts);
Chris Lattner978fe0c2012-01-30 06:21:21 +00002647 }
2648 if (CFP->getType()->isDoubleTy()) {
Rafael Espindola8c97e192015-02-19 16:08:20 +00002649 SmallVector<uint64_t, 16> Elts(
2650 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
2651 return getFP(V->getContext(), Elts);
Chris Lattner978fe0c2012-01-30 06:21:21 +00002652 }
Chris Lattnere9eed292012-01-25 05:19:54 +00002653 }
Chris Lattner978fe0c2012-01-30 06:21:21 +00002654 return ConstantVector::getSplat(NumElts, V);
Chris Lattnere9eed292012-01-25 05:19:54 +00002655}
2656
2657
Chris Lattnere4f3f102012-01-24 04:43:41 +00002658uint64_t ConstantDataSequential::getElementAsInteger(unsigned Elt) const {
2659 assert(isa<IntegerType>(getElementType()) &&
2660 "Accessor can only be used when element is an integer");
2661 const char *EltPtr = getElementPointer(Elt);
Galina Kistanovafc259902012-07-13 01:25:27 +00002662
Chris Lattnere4f3f102012-01-24 04:43:41 +00002663 // The data is stored in host byte order, make sure to cast back to the right
2664 // type to load with the right endianness.
Chris Lattner8326bd82012-01-26 00:42:34 +00002665 switch (getElementType()->getIntegerBitWidth()) {
Craig Topperc514b542012-02-05 22:14:15 +00002666 default: llvm_unreachable("Invalid bitwidth for CDS");
Galina Kistanovafc259902012-07-13 01:25:27 +00002667 case 8:
Craig Topper393ce692017-07-11 15:52:21 +00002668 return *reinterpret_cast<const uint8_t *>(EltPtr);
Galina Kistanovafc259902012-07-13 01:25:27 +00002669 case 16:
Craig Topper393ce692017-07-11 15:52:21 +00002670 return *reinterpret_cast<const uint16_t *>(EltPtr);
Galina Kistanovafc259902012-07-13 01:25:27 +00002671 case 32:
Craig Topper393ce692017-07-11 15:52:21 +00002672 return *reinterpret_cast<const uint32_t *>(EltPtr);
Galina Kistanovafc259902012-07-13 01:25:27 +00002673 case 64:
Craig Topper393ce692017-07-11 15:52:21 +00002674 return *reinterpret_cast<const uint64_t *>(EltPtr);
Chris Lattnere4f3f102012-01-24 04:43:41 +00002675 }
2676}
2677
Craig Topper0b4b4e32017-07-15 22:06:19 +00002678APInt ConstantDataSequential::getElementAsAPInt(unsigned Elt) const {
2679 assert(isa<IntegerType>(getElementType()) &&
2680 "Accessor can only be used when element is an integer");
2681 const char *EltPtr = getElementPointer(Elt);
2682
2683 // The data is stored in host byte order, make sure to cast back to the right
2684 // type to load with the right endianness.
2685 switch (getElementType()->getIntegerBitWidth()) {
2686 default: llvm_unreachable("Invalid bitwidth for CDS");
2687 case 8: {
2688 auto EltVal = *reinterpret_cast<const uint8_t *>(EltPtr);
2689 return APInt(8, EltVal);
2690 }
2691 case 16: {
2692 auto EltVal = *reinterpret_cast<const uint16_t *>(EltPtr);
2693 return APInt(16, EltVal);
2694 }
2695 case 32: {
2696 auto EltVal = *reinterpret_cast<const uint32_t *>(EltPtr);
2697 return APInt(32, EltVal);
2698 }
2699 case 64: {
2700 auto EltVal = *reinterpret_cast<const uint64_t *>(EltPtr);
2701 return APInt(64, EltVal);
2702 }
2703 }
2704}
2705
Chris Lattnere4f3f102012-01-24 04:43:41 +00002706APFloat ConstantDataSequential::getElementAsAPFloat(unsigned Elt) const {
2707 const char *EltPtr = getElementPointer(Elt);
2708
2709 switch (getElementType()->getTypeID()) {
Nick Lewyckyff509622012-01-25 03:20:12 +00002710 default:
Craig Topperc514b542012-02-05 22:14:15 +00002711 llvm_unreachable("Accessor can only be used when element is float/double!");
Justin Bogner0ebc8602015-12-08 03:01:16 +00002712 case Type::HalfTyID: {
2713 auto EltVal = *reinterpret_cast<const uint16_t *>(EltPtr);
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002714 return APFloat(APFloat::IEEEhalf(), APInt(16, EltVal));
Justin Bogner0ebc8602015-12-08 03:01:16 +00002715 }
Benjamin Kramer7af984b2015-02-20 15:11:55 +00002716 case Type::FloatTyID: {
2717 auto EltVal = *reinterpret_cast<const uint32_t *>(EltPtr);
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002718 return APFloat(APFloat::IEEEsingle(), APInt(32, EltVal));
Benjamin Kramer7af984b2015-02-20 15:11:55 +00002719 }
2720 case Type::DoubleTyID: {
2721 auto EltVal = *reinterpret_cast<const uint64_t *>(EltPtr);
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002722 return APFloat(APFloat::IEEEdouble(), APInt(64, EltVal));
Chris Lattnere4f3f102012-01-24 04:43:41 +00002723 }
Benjamin Kramer7af984b2015-02-20 15:11:55 +00002724 }
Chris Lattnere4f3f102012-01-24 04:43:41 +00002725}
2726
Chris Lattnere4f3f102012-01-24 04:43:41 +00002727float ConstantDataSequential::getElementAsFloat(unsigned Elt) const {
2728 assert(getElementType()->isFloatTy() &&
2729 "Accessor can only be used when element is a 'float'");
Craig Topper393ce692017-07-11 15:52:21 +00002730 return *reinterpret_cast<const float *>(getElementPointer(Elt));
Chris Lattnere4f3f102012-01-24 04:43:41 +00002731}
2732
Chris Lattnere4f3f102012-01-24 04:43:41 +00002733double ConstantDataSequential::getElementAsDouble(unsigned Elt) const {
2734 assert(getElementType()->isDoubleTy() &&
2735 "Accessor can only be used when element is a 'float'");
Craig Topper393ce692017-07-11 15:52:21 +00002736 return *reinterpret_cast<const double *>(getElementPointer(Elt));
Chris Lattnere4f3f102012-01-24 04:43:41 +00002737}
2738
Chris Lattnere4f3f102012-01-24 04:43:41 +00002739Constant *ConstantDataSequential::getElementAsConstant(unsigned Elt) const {
Justin Bogner0ebc8602015-12-08 03:01:16 +00002740 if (getElementType()->isHalfTy() || getElementType()->isFloatTy() ||
2741 getElementType()->isDoubleTy())
Chris Lattnere4f3f102012-01-24 04:43:41 +00002742 return ConstantFP::get(getContext(), getElementAsAPFloat(Elt));
Galina Kistanovafc259902012-07-13 01:25:27 +00002743
Chris Lattnere4f3f102012-01-24 04:43:41 +00002744 return ConstantInt::get(getElementType(), getElementAsInteger(Elt));
2745}
2746
Matthias Braun50ec0b52017-05-19 22:37:09 +00002747bool ConstantDataSequential::isString(unsigned CharSize) const {
2748 return isa<ArrayType>(getType()) && getElementType()->isIntegerTy(CharSize);
Chris Lattner5dd4d872012-01-24 09:01:07 +00002749}
Chris Lattner3756b912012-01-23 22:57:10 +00002750
Chris Lattner5dd4d872012-01-24 09:01:07 +00002751bool ConstantDataSequential::isCString() const {
2752 if (!isString())
2753 return false;
Galina Kistanovafc259902012-07-13 01:25:27 +00002754
Chris Lattner5dd4d872012-01-24 09:01:07 +00002755 StringRef Str = getAsString();
Galina Kistanovafc259902012-07-13 01:25:27 +00002756
Chris Lattner5dd4d872012-01-24 09:01:07 +00002757 // The last value must be nul.
2758 if (Str.back() != 0) return false;
Galina Kistanovafc259902012-07-13 01:25:27 +00002759
Chris Lattner5dd4d872012-01-24 09:01:07 +00002760 // Other elements must be non-nul.
2761 return Str.drop_back().find(0) == StringRef::npos;
2762}
Chris Lattner3756b912012-01-23 22:57:10 +00002763
Craig Topper0b4b4e32017-07-15 22:06:19 +00002764bool ConstantDataVector::isSplat() const {
Chris Lattnerf14a67f2012-01-26 02:31:22 +00002765 const char *Base = getRawDataValues().data();
Galina Kistanovafc259902012-07-13 01:25:27 +00002766
Chris Lattnerf14a67f2012-01-26 02:31:22 +00002767 // Compare elements 1+ to the 0'th element.
2768 unsigned EltSize = getElementByteSize();
2769 for (unsigned i = 1, e = getNumElements(); i != e; ++i)
2770 if (memcmp(Base, Base+i*EltSize, EltSize))
Craig Topper0b4b4e32017-07-15 22:06:19 +00002771 return false;
Galina Kistanovafc259902012-07-13 01:25:27 +00002772
Craig Topper0b4b4e32017-07-15 22:06:19 +00002773 return true;
2774}
2775
2776Constant *ConstantDataVector::getSplatValue() const {
Chris Lattnerf14a67f2012-01-26 02:31:22 +00002777 // If they're all the same, return the 0th one as a representative.
Craig Topper0b4b4e32017-07-15 22:06:19 +00002778 return isSplat() ? getElementAsConstant(0) : nullptr;
Chris Lattnerf14a67f2012-01-26 02:31:22 +00002779}
Chris Lattnera3b94ba2010-03-30 20:48:48 +00002780
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002781//===----------------------------------------------------------------------===//
Pete Cooper5815b1f2015-06-24 18:55:24 +00002782// handleOperandChange implementations
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002783
Pete Cooper5815b1f2015-06-24 18:55:24 +00002784/// Update this constant array to change uses of
Chris Lattner913849b2007-08-21 00:55:23 +00002785/// 'From' to be uses of 'To'. This must update the uniquing data structures
2786/// etc.
2787///
2788/// Note that we intentionally replace all uses of From with To here. Consider
2789/// a large array that uses 'From' 1000 times. By handling this case all here,
Pete Cooper5815b1f2015-06-24 18:55:24 +00002790/// ConstantArray::handleOperandChange is only invoked once, and that
Chris Lattner913849b2007-08-21 00:55:23 +00002791/// single invocation handles all 1000 uses. Handling them one at a time would
2792/// work, but would be really slow because it would have to unique each updated
2793/// array instance.
Chris Lattner31b132c2009-10-28 00:01:44 +00002794///
Mehdi Amini8914d292016-02-10 22:47:15 +00002795void Constant::handleOperandChange(Value *From, Value *To) {
Pete Cooper5815b1f2015-06-24 18:55:24 +00002796 Value *Replacement = nullptr;
2797 switch (getValueID()) {
2798 default:
2799 llvm_unreachable("Not a constant!");
2800#define HANDLE_CONSTANT(Name) \
2801 case Value::Name##Val: \
Mehdi Amini8914d292016-02-10 22:47:15 +00002802 Replacement = cast<Name>(this)->handleOperandChangeImpl(From, To); \
Pete Cooper5815b1f2015-06-24 18:55:24 +00002803 break;
2804#include "llvm/IR/Value.def"
2805 }
2806
2807 // If handleOperandChangeImpl returned nullptr, then it handled
2808 // replacing itself and we don't want to delete or replace anything else here.
2809 if (!Replacement)
2810 return;
2811
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002812 // I do need to replace this with an existing value.
2813 assert(Replacement != this && "I didn't contain From!");
2814
2815 // Everyone using this now uses the replacement.
2816 replaceAllUsesWith(Replacement);
2817
2818 // Delete the old constant!
2819 destroyConstant();
2820}
2821
Mehdi Amini8914d292016-02-10 22:47:15 +00002822Value *ConstantArray::handleOperandChangeImpl(Value *From, Value *To) {
Owen Andersonc2c79322009-07-28 18:32:17 +00002823 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2824 Constant *ToC = cast<Constant>(To);
2825
Talin46e9b442012-02-05 20:54:10 +00002826 SmallVector<Constant*, 8> Values;
Owen Andersonc2c79322009-07-28 18:32:17 +00002827 Values.reserve(getNumOperands()); // Build replacement array.
2828
Galina Kistanovafc259902012-07-13 01:25:27 +00002829 // Fill values with the modified operands of the constant array. Also,
Owen Andersonc2c79322009-07-28 18:32:17 +00002830 // compute whether this turns into an all-zeros array.
Owen Andersonc2c79322009-07-28 18:32:17 +00002831 unsigned NumUpdated = 0;
Galina Kistanovafc259902012-07-13 01:25:27 +00002832
Chris Lattnerf14a67f2012-01-26 02:31:22 +00002833 // Keep track of whether all the values in the array are "ToC".
2834 bool AllSame = true;
Pete Cooper74510a42015-06-12 17:48:05 +00002835 Use *OperandList = getOperandList();
Mehdi Amini8914d292016-02-10 22:47:15 +00002836 unsigned OperandNo = 0;
Chris Lattnerf14a67f2012-01-26 02:31:22 +00002837 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2838 Constant *Val = cast<Constant>(O->get());
2839 if (Val == From) {
Mehdi Amini8914d292016-02-10 22:47:15 +00002840 OperandNo = (O - OperandList);
Chris Lattnerf14a67f2012-01-26 02:31:22 +00002841 Val = ToC;
2842 ++NumUpdated;
Owen Andersonc2c79322009-07-28 18:32:17 +00002843 }
Chris Lattnerf14a67f2012-01-26 02:31:22 +00002844 Values.push_back(Val);
Talin46e9b442012-02-05 20:54:10 +00002845 AllSame &= Val == ToC;
Owen Andersonc2c79322009-07-28 18:32:17 +00002846 }
Galina Kistanovafc259902012-07-13 01:25:27 +00002847
Pete Cooper5815b1f2015-06-24 18:55:24 +00002848 if (AllSame && ToC->isNullValue())
2849 return ConstantAggregateZero::get(getType());
2850
2851 if (AllSame && isa<UndefValue>(ToC))
2852 return UndefValue::get(getType());
Aaron Ballmane4b91dc2014-08-19 14:59:02 +00002853
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002854 // Check for any other type of constant-folding.
Pete Cooper5815b1f2015-06-24 18:55:24 +00002855 if (Constant *C = getImpl(getType(), Values))
2856 return C;
Aaron Ballmane4b91dc2014-08-19 14:59:02 +00002857
Duncan P. N. Exon Smith909620a2014-08-19 19:13:30 +00002858 // Update to the new value.
Pete Cooper5815b1f2015-06-24 18:55:24 +00002859 return getContext().pImpl->ArrayConstants.replaceOperandsInPlace(
Mehdi Amini8914d292016-02-10 22:47:15 +00002860 Values, this, From, ToC, NumUpdated, OperandNo);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002861}
2862
Mehdi Amini8914d292016-02-10 22:47:15 +00002863Value *ConstantStruct::handleOperandChangeImpl(Value *From, Value *To) {
Owen Anderson45308b52009-07-27 22:29:26 +00002864 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2865 Constant *ToC = cast<Constant>(To);
2866
Pete Cooper74510a42015-06-12 17:48:05 +00002867 Use *OperandList = getOperandList();
Owen Anderson45308b52009-07-27 22:29:26 +00002868
Talin46e9b442012-02-05 20:54:10 +00002869 SmallVector<Constant*, 8> Values;
Owen Anderson45308b52009-07-27 22:29:26 +00002870 Values.reserve(getNumOperands()); // Build replacement struct.
Galina Kistanovafc259902012-07-13 01:25:27 +00002871
2872 // Fill values with the modified operands of the constant struct. Also,
Owen Anderson45308b52009-07-27 22:29:26 +00002873 // compute whether this turns into an all-zeros struct.
Mehdi Amini8914d292016-02-10 22:47:15 +00002874 unsigned NumUpdated = 0;
2875 bool AllSame = true;
2876 unsigned OperandNo = 0;
2877 for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O) {
2878 Constant *Val = cast<Constant>(O->get());
2879 if (Val == From) {
2880 OperandNo = (O - OperandList);
2881 Val = ToC;
2882 ++NumUpdated;
Owen Anderson45308b52009-07-27 22:29:26 +00002883 }
Mehdi Amini8914d292016-02-10 22:47:15 +00002884 Values.push_back(Val);
2885 AllSame &= Val == ToC;
Owen Anderson45308b52009-07-27 22:29:26 +00002886 }
Galina Kistanovafc259902012-07-13 01:25:27 +00002887
Mehdi Amini8914d292016-02-10 22:47:15 +00002888 if (AllSame && ToC->isNullValue())
Pete Cooper5815b1f2015-06-24 18:55:24 +00002889 return ConstantAggregateZero::get(getType());
2890
Mehdi Amini8914d292016-02-10 22:47:15 +00002891 if (AllSame && isa<UndefValue>(ToC))
Pete Cooper5815b1f2015-06-24 18:55:24 +00002892 return UndefValue::get(getType());
Galina Kistanovafc259902012-07-13 01:25:27 +00002893
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002894 // Update to the new value.
Pete Cooper5815b1f2015-06-24 18:55:24 +00002895 return getContext().pImpl->StructConstants.replaceOperandsInPlace(
Mehdi Amini8914d292016-02-10 22:47:15 +00002896 Values, this, From, ToC, NumUpdated, OperandNo);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002897}
2898
Mehdi Amini8914d292016-02-10 22:47:15 +00002899Value *ConstantVector::handleOperandChangeImpl(Value *From, Value *To) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002900 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002901 Constant *ToC = cast<Constant>(To);
Galina Kistanovafc259902012-07-13 01:25:27 +00002902
Chris Lattnera474bb22012-01-26 20:40:56 +00002903 SmallVector<Constant*, 8> Values;
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002904 Values.reserve(getNumOperands()); // Build replacement array...
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002905 unsigned NumUpdated = 0;
Mehdi Amini8914d292016-02-10 22:47:15 +00002906 unsigned OperandNo = 0;
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002907 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2908 Constant *Val = getOperand(i);
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002909 if (Val == From) {
Mehdi Amini8914d292016-02-10 22:47:15 +00002910 OperandNo = i;
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002911 ++NumUpdated;
2912 Val = ToC;
2913 }
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002914 Values.push_back(Val);
2915 }
Galina Kistanovafc259902012-07-13 01:25:27 +00002916
Pete Cooper5815b1f2015-06-24 18:55:24 +00002917 if (Constant *C = getImpl(Values))
2918 return C;
Duncan P. N. Exon Smith687744d2014-08-19 02:24:46 +00002919
Duncan P. N. Exon Smith909620a2014-08-19 19:13:30 +00002920 // Update to the new value.
Pete Cooper5815b1f2015-06-24 18:55:24 +00002921 return getContext().pImpl->VectorConstants.replaceOperandsInPlace(
Mehdi Amini8914d292016-02-10 22:47:15 +00002922 Values, this, From, ToC, NumUpdated, OperandNo);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002923}
2924
Mehdi Amini8914d292016-02-10 22:47:15 +00002925Value *ConstantExpr::handleOperandChangeImpl(Value *From, Value *ToV) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002926 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2927 Constant *To = cast<Constant>(ToV);
Galina Kistanovafc259902012-07-13 01:25:27 +00002928
Chris Lattner37e38352012-01-26 20:37:11 +00002929 SmallVector<Constant*, 8> NewOps;
Duncan P. N. Exon Smith33de00c2014-08-19 20:03:35 +00002930 unsigned NumUpdated = 0;
Mehdi Amini8914d292016-02-10 22:47:15 +00002931 unsigned OperandNo = 0;
Chris Lattner37e38352012-01-26 20:37:11 +00002932 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2933 Constant *Op = getOperand(i);
Duncan P. N. Exon Smith33de00c2014-08-19 20:03:35 +00002934 if (Op == From) {
Mehdi Amini8914d292016-02-10 22:47:15 +00002935 OperandNo = i;
Duncan P. N. Exon Smith33de00c2014-08-19 20:03:35 +00002936 ++NumUpdated;
2937 Op = To;
2938 }
2939 NewOps.push_back(Op);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002940 }
Duncan P. N. Exon Smith33de00c2014-08-19 20:03:35 +00002941 assert(NumUpdated && "I didn't contain From!");
Galina Kistanovafc259902012-07-13 01:25:27 +00002942
Pete Cooper5815b1f2015-06-24 18:55:24 +00002943 if (Constant *C = getWithOperands(NewOps, getType(), true))
2944 return C;
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002945
Duncan P. N. Exon Smith33de00c2014-08-19 20:03:35 +00002946 // Update to the new value.
Pete Cooper5815b1f2015-06-24 18:55:24 +00002947 return getContext().pImpl->ExprConstants.replaceOperandsInPlace(
Mehdi Amini8914d292016-02-10 22:47:15 +00002948 NewOps, this, From, To, NumUpdated, OperandNo);
Duncan P. N. Exon Smith317c1392014-08-19 16:39:58 +00002949}
2950
James Molloyce545682012-11-17 17:56:30 +00002951Instruction *ConstantExpr::getAsInstruction() {
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +00002952 SmallVector<Value *, 4> ValueOperands(op_begin(), op_end());
James Molloyce545682012-11-17 17:56:30 +00002953 ArrayRef<Value*> Ops(ValueOperands);
2954
2955 switch (getOpcode()) {
2956 case Instruction::Trunc:
2957 case Instruction::ZExt:
2958 case Instruction::SExt:
2959 case Instruction::FPTrunc:
2960 case Instruction::FPExt:
2961 case Instruction::UIToFP:
2962 case Instruction::SIToFP:
2963 case Instruction::FPToUI:
2964 case Instruction::FPToSI:
2965 case Instruction::PtrToInt:
2966 case Instruction::IntToPtr:
2967 case Instruction::BitCast:
Eli Bendersky157a97a2014-01-18 22:54:33 +00002968 case Instruction::AddrSpaceCast:
James Molloyce545682012-11-17 17:56:30 +00002969 return CastInst::Create((Instruction::CastOps)getOpcode(),
2970 Ops[0], getType());
2971 case Instruction::Select:
2972 return SelectInst::Create(Ops[0], Ops[1], Ops[2]);
2973 case Instruction::InsertElement:
2974 return InsertElementInst::Create(Ops[0], Ops[1], Ops[2]);
2975 case Instruction::ExtractElement:
2976 return ExtractElementInst::Create(Ops[0], Ops[1]);
2977 case Instruction::InsertValue:
2978 return InsertValueInst::Create(Ops[0], Ops[1], getIndices());
2979 case Instruction::ExtractValue:
2980 return ExtractValueInst::Create(Ops[0], getIndices());
2981 case Instruction::ShuffleVector:
2982 return new ShuffleVectorInst(Ops[0], Ops[1], Ops[2]);
2983
David Blaikie741c8f82015-03-14 01:53:18 +00002984 case Instruction::GetElementPtr: {
2985 const auto *GO = cast<GEPOperator>(this);
2986 if (GO->isInBounds())
2987 return GetElementPtrInst::CreateInBounds(GO->getSourceElementType(),
2988 Ops[0], Ops.slice(1));
2989 return GetElementPtrInst::Create(GO->getSourceElementType(), Ops[0],
2990 Ops.slice(1));
2991 }
James Molloyce545682012-11-17 17:56:30 +00002992 case Instruction::ICmp:
2993 case Instruction::FCmp:
2994 return CmpInst::Create((Instruction::OtherOps)getOpcode(),
Craig Topper1c3f2832015-12-15 06:11:33 +00002995 (CmpInst::Predicate)getPredicate(), Ops[0], Ops[1]);
James Molloyce545682012-11-17 17:56:30 +00002996
2997 default:
2998 assert(getNumOperands() == 2 && "Must be binary operator?");
2999 BinaryOperator *BO =
3000 BinaryOperator::Create((Instruction::BinaryOps)getOpcode(),
3001 Ops[0], Ops[1]);
3002 if (isa<OverflowingBinaryOperator>(BO)) {
3003 BO->setHasNoUnsignedWrap(SubclassOptionalData &
3004 OverflowingBinaryOperator::NoUnsignedWrap);
3005 BO->setHasNoSignedWrap(SubclassOptionalData &
3006 OverflowingBinaryOperator::NoSignedWrap);
3007 }
3008 if (isa<PossiblyExactOperator>(BO))
3009 BO->setIsExact(SubclassOptionalData & PossiblyExactOperator::IsExact);
3010 return BO;
3011 }
3012}