blob: 8093a09749fb1d702461cd1de72601a02f52fa0f [file] [log] [blame]
Chris Lattner9bc02a42003-05-13 21:37:02 +00001//===-- Constants.cpp - Implement Constant nodes --------------------------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-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 Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner00950542001-06-06 20:29:01 +00009//
Chris Lattnereb59ca92011-02-07 20:03:14 +000010// This file implements the Constant* classes.
Chris Lattner00950542001-06-06 20:29:01 +000011//
12//===----------------------------------------------------------------------===//
13
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000014#include "llvm/IR/Constants.h"
Chris Lattner92f6fea2007-02-27 03:05:06 +000015#include "ConstantFold.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000016#include "LLVMContextImpl.h"
17#include "llvm/ADT/DenseMap.h"
18#include "llvm/ADT/FoldingSet.h"
19#include "llvm/ADT/STLExtras.h"
20#include "llvm/ADT/SmallVector.h"
21#include "llvm/ADT/StringExtras.h"
22#include "llvm/ADT/StringMap.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000023#include "llvm/IR/DerivedTypes.h"
24#include "llvm/IR/GlobalValue.h"
25#include "llvm/IR/Instructions.h"
26#include "llvm/IR/Module.h"
27#include "llvm/IR/Operator.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000028#include "llvm/Support/Compiler.h"
Bill Wendling2e3def12006-11-17 08:03:48 +000029#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000030#include "llvm/Support/ErrorHandling.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000031#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner8a94bf12006-09-28 00:35:06 +000032#include "llvm/Support/ManagedStatic.h"
Bill Wendling2e3def12006-11-17 08:03:48 +000033#include "llvm/Support/MathExtras.h"
Chris Lattner37f077a2009-08-23 04:02:03 +000034#include "llvm/Support/raw_ostream.h"
Chris Lattner00950542001-06-06 20:29:01 +000035#include <algorithm>
Talin41ee4e52011-02-28 23:53:27 +000036#include <cstdarg>
Chris Lattner31f84992003-11-21 20:23:48 +000037using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000038
Chris Lattner00950542001-06-06 20:29:01 +000039//===----------------------------------------------------------------------===//
Chris Lattnere9bb2df2001-12-03 22:26:30 +000040// Constant Class
Chris Lattner00950542001-06-06 20:29:01 +000041//===----------------------------------------------------------------------===//
42
David Blaikie2d24e2a2011-12-20 02:50:00 +000043void Constant::anchor() { }
44
Chris Lattnerb4473872011-07-15 05:58:04 +000045bool Constant::isNegativeZeroValue() const {
46 // Floating point values have an explicit -0.0 value.
47 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
48 return CFP->isZero() && CFP->isNegative();
Galina Kistanovaa46517e2012-07-13 01:25:27 +000049
Chris Lattnerb4473872011-07-15 05:58:04 +000050 // Otherwise, just use +0.0.
51 return isNullValue();
52}
53
Shuxin Yangc3d6de22013-01-09 00:53:25 +000054// Return true iff this constant is positive zero (floating point), negative
55// zero (floating point), or a null value.
Shuxin Yang935e35d2013-01-09 00:13:41 +000056bool Constant::isZeroValue() const {
57 // Floating point values have an explicit -0.0 value.
58 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
59 return CFP->isZero();
60
61 // Otherwise, just use +0.0.
62 return isNullValue();
63}
64
Chris Lattner032c6eb2011-07-15 06:14:08 +000065bool Constant::isNullValue() const {
66 // 0 is null.
67 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
68 return CI->isZero();
Galina Kistanovaa46517e2012-07-13 01:25:27 +000069
Chris Lattner032c6eb2011-07-15 06:14:08 +000070 // +0.0 is null.
71 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
72 return CFP->isZero() && !CFP->isNegative();
73
74 // constant zero is zero for aggregates and cpnull is null for pointers.
75 return isa<ConstantAggregateZero>(this) || isa<ConstantPointerNull>(this);
76}
77
Nadav Rotem4c7c0f22011-08-24 20:18:38 +000078bool Constant::isAllOnesValue() const {
79 // Check for -1 integers
80 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
81 return CI->isMinusOne();
82
83 // Check for FP which are bitcasted from -1 integers
84 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
85 return CFP->getValueAPF().bitcastToAPInt().isAllOnesValue();
86
Benjamin Kramerb518cae2011-11-14 19:12:20 +000087 // Check for constant vectors which are splats of -1 values.
Nadav Rotem4c7c0f22011-08-24 20:18:38 +000088 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
Benjamin Kramerb518cae2011-11-14 19:12:20 +000089 if (Constant *Splat = CV->getSplatValue())
90 return Splat->isAllOnesValue();
Nadav Rotem4c7c0f22011-08-24 20:18:38 +000091
Chris Lattnere150e2d2012-01-26 02:31:22 +000092 // Check for constant vectors which are splats of -1 values.
93 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
94 if (Constant *Splat = CV->getSplatValue())
95 return Splat->isAllOnesValue();
96
Nadav Rotem4c7c0f22011-08-24 20:18:38 +000097 return false;
98}
Benjamin Kramerb518cae2011-11-14 19:12:20 +000099
Owen Andersona7235ea2009-07-31 20:28:14 +0000100// Constructor to create a '0' constant of arbitrary type...
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000101Constant *Constant::getNullValue(Type *Ty) {
Owen Andersona7235ea2009-07-31 20:28:14 +0000102 switch (Ty->getTypeID()) {
103 case Type::IntegerTyID:
104 return ConstantInt::get(Ty, 0);
Dan Gohmance163392011-12-17 00:04:22 +0000105 case Type::HalfTyID:
106 return ConstantFP::get(Ty->getContext(),
107 APFloat::getZero(APFloat::IEEEhalf));
Owen Andersona7235ea2009-07-31 20:28:14 +0000108 case Type::FloatTyID:
Benjamin Kramer98383962010-12-04 14:22:24 +0000109 return ConstantFP::get(Ty->getContext(),
110 APFloat::getZero(APFloat::IEEEsingle));
Owen Andersona7235ea2009-07-31 20:28:14 +0000111 case Type::DoubleTyID:
Benjamin Kramer98383962010-12-04 14:22:24 +0000112 return ConstantFP::get(Ty->getContext(),
113 APFloat::getZero(APFloat::IEEEdouble));
Owen Andersona7235ea2009-07-31 20:28:14 +0000114 case Type::X86_FP80TyID:
Benjamin Kramer98383962010-12-04 14:22:24 +0000115 return ConstantFP::get(Ty->getContext(),
116 APFloat::getZero(APFloat::x87DoubleExtended));
Owen Andersona7235ea2009-07-31 20:28:14 +0000117 case Type::FP128TyID:
118 return ConstantFP::get(Ty->getContext(),
Benjamin Kramer98383962010-12-04 14:22:24 +0000119 APFloat::getZero(APFloat::IEEEquad));
Owen Andersona7235ea2009-07-31 20:28:14 +0000120 case Type::PPC_FP128TyID:
Benjamin Kramer98383962010-12-04 14:22:24 +0000121 return ConstantFP::get(Ty->getContext(),
Tim Northover0a29cb02013-01-22 09:46:31 +0000122 APFloat(APFloat::PPCDoubleDouble,
123 APInt::getNullValue(128)));
Owen Andersona7235ea2009-07-31 20:28:14 +0000124 case Type::PointerTyID:
125 return ConstantPointerNull::get(cast<PointerType>(Ty));
126 case Type::StructTyID:
127 case Type::ArrayTyID:
128 case Type::VectorTyID:
129 return ConstantAggregateZero::get(Ty);
130 default:
131 // Function, Label, or Opaque type?
Craig Topper50bee422012-02-05 22:14:15 +0000132 llvm_unreachable("Cannot create a null constant of that type!");
Owen Andersona7235ea2009-07-31 20:28:14 +0000133 }
134}
135
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000136Constant *Constant::getIntegerValue(Type *Ty, const APInt &V) {
137 Type *ScalarTy = Ty->getScalarType();
Dan Gohman43ee5f72009-08-03 22:07:33 +0000138
139 // Create the base integer constant.
140 Constant *C = ConstantInt::get(Ty->getContext(), V);
141
142 // Convert an integer to a pointer, if necessary.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000143 if (PointerType *PTy = dyn_cast<PointerType>(ScalarTy))
Dan Gohman43ee5f72009-08-03 22:07:33 +0000144 C = ConstantExpr::getIntToPtr(C, PTy);
145
146 // Broadcast a scalar to a vector, if necessary.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000147 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
Chris Lattner3c2c9542012-01-25 05:19:54 +0000148 C = ConstantVector::getSplat(VTy->getNumElements(), C);
Dan Gohman43ee5f72009-08-03 22:07:33 +0000149
150 return C;
151}
152
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000153Constant *Constant::getAllOnesValue(Type *Ty) {
154 if (IntegerType *ITy = dyn_cast<IntegerType>(Ty))
Owen Andersona7235ea2009-07-31 20:28:14 +0000155 return ConstantInt::get(Ty->getContext(),
156 APInt::getAllOnesValue(ITy->getBitWidth()));
Nadav Rotem093399c2011-02-17 21:22:27 +0000157
158 if (Ty->isFloatingPointTy()) {
159 APFloat FL = APFloat::getAllOnesValue(Ty->getPrimitiveSizeInBits(),
160 !Ty->isPPC_FP128Ty());
161 return ConstantFP::get(Ty->getContext(), FL);
162 }
163
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000164 VectorType *VTy = cast<VectorType>(Ty);
Chris Lattner3c2c9542012-01-25 05:19:54 +0000165 return ConstantVector::getSplat(VTy->getNumElements(),
166 getAllOnesValue(VTy->getElementType()));
Owen Andersona7235ea2009-07-31 20:28:14 +0000167}
168
Chris Lattner3d5ed222012-01-25 06:16:32 +0000169/// getAggregateElement - For aggregates (struct/array/vector) return the
170/// constant that corresponds to the specified element if possible, or null if
171/// not. This can return null if the element index is a ConstantExpr, or if
172/// 'this' is a constant expr.
173Constant *Constant::getAggregateElement(unsigned Elt) const {
174 if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(this))
175 return Elt < CS->getNumOperands() ? CS->getOperand(Elt) : 0;
Galina Kistanovaa46517e2012-07-13 01:25:27 +0000176
Chris Lattner3d5ed222012-01-25 06:16:32 +0000177 if (const ConstantArray *CA = dyn_cast<ConstantArray>(this))
178 return Elt < CA->getNumOperands() ? CA->getOperand(Elt) : 0;
Galina Kistanovaa46517e2012-07-13 01:25:27 +0000179
Chris Lattner3d5ed222012-01-25 06:16:32 +0000180 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
181 return Elt < CV->getNumOperands() ? CV->getOperand(Elt) : 0;
Galina Kistanovaa46517e2012-07-13 01:25:27 +0000182
Chris Lattner3d5ed222012-01-25 06:16:32 +0000183 if (const ConstantAggregateZero *CAZ =dyn_cast<ConstantAggregateZero>(this))
184 return CAZ->getElementValue(Elt);
Galina Kistanovaa46517e2012-07-13 01:25:27 +0000185
Chris Lattner3d5ed222012-01-25 06:16:32 +0000186 if (const UndefValue *UV = dyn_cast<UndefValue>(this))
187 return UV->getElementValue(Elt);
Galina Kistanovaa46517e2012-07-13 01:25:27 +0000188
Chris Lattner230cdab2012-01-26 00:42:34 +0000189 if (const ConstantDataSequential *CDS =dyn_cast<ConstantDataSequential>(this))
Chris Lattner18c7f802012-02-05 02:29:43 +0000190 return Elt < CDS->getNumElements() ? CDS->getElementAsConstant(Elt) : 0;
Chris Lattner3d5ed222012-01-25 06:16:32 +0000191 return 0;
192}
193
194Constant *Constant::getAggregateElement(Constant *Elt) const {
195 assert(isa<IntegerType>(Elt->getType()) && "Index must be an integer");
196 if (ConstantInt *CI = dyn_cast<ConstantInt>(Elt))
197 return getAggregateElement(CI->getZExtValue());
198 return 0;
199}
200
201
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000202void Constant::destroyConstantImpl() {
203 // When a Constant is destroyed, there may be lingering
Chris Lattnerf5ec48d2001-10-13 06:57:33 +0000204 // references to the constant by other constants in the constant pool. These
Misha Brukmanef6a6a62003-08-21 22:14:26 +0000205 // constants are implicitly dependent on the module that is being deleted,
Chris Lattnerf5ec48d2001-10-13 06:57:33 +0000206 // but they don't know that. Because we only find out when the CPV is
207 // deleted, we must now notify all of our users (that should only be
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000208 // Constants) that they are, in fact, invalid now and should be deleted.
Chris Lattnerf5ec48d2001-10-13 06:57:33 +0000209 //
210 while (!use_empty()) {
211 Value *V = use_back();
212#ifndef NDEBUG // Only in -g mode...
Chris Lattner37f077a2009-08-23 04:02:03 +0000213 if (!isa<Constant>(V)) {
David Greened2e63b72010-01-05 01:29:19 +0000214 dbgs() << "While deleting: " << *this
Chris Lattner37f077a2009-08-23 04:02:03 +0000215 << "\n\nUse still stuck around after Def is destroyed: "
216 << *V << "\n\n";
217 }
Chris Lattnerf5ec48d2001-10-13 06:57:33 +0000218#endif
Vikram S. Adve345e0cf2002-07-14 23:13:17 +0000219 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
Chris Lattner230cdab2012-01-26 00:42:34 +0000220 cast<Constant>(V)->destroyConstant();
Chris Lattnerf5ec48d2001-10-13 06:57:33 +0000221
222 // The constant should remove itself from our use list...
Vikram S. Adve345e0cf2002-07-14 23:13:17 +0000223 assert((use_empty() || use_back() != V) && "Constant not removed!");
Chris Lattnerf5ec48d2001-10-13 06:57:33 +0000224 }
225
226 // Value has no outstanding references it is safe to delete it now...
227 delete this;
Chris Lattner1d87bcf2001-10-01 20:11:19 +0000228}
Chris Lattner00950542001-06-06 20:29:01 +0000229
Chris Lattner35b89fa2006-10-20 00:27:06 +0000230/// canTrap - Return true if evaluation of this constant could trap. This is
231/// true for things like constant expressions that could divide by zero.
232bool Constant::canTrap() const {
233 assert(getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
234 // The only thing that could possibly trap are constant exprs.
235 const ConstantExpr *CE = dyn_cast<ConstantExpr>(this);
236 if (!CE) return false;
Galina Kistanovaa46517e2012-07-13 01:25:27 +0000237
238 // ConstantExpr traps if any operands can trap.
Chris Lattner35b89fa2006-10-20 00:27:06 +0000239 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
Galina Kistanovaa46517e2012-07-13 01:25:27 +0000240 if (CE->getOperand(i)->canTrap())
Chris Lattner35b89fa2006-10-20 00:27:06 +0000241 return true;
242
243 // Otherwise, only specific operations can trap.
244 switch (CE->getOpcode()) {
245 default:
246 return false;
Reid Spencer1628cec2006-10-26 06:15:43 +0000247 case Instruction::UDiv:
248 case Instruction::SDiv:
249 case Instruction::FDiv:
Reid Spencer0a783f72006-11-02 01:53:59 +0000250 case Instruction::URem:
251 case Instruction::SRem:
252 case Instruction::FRem:
Chris Lattner35b89fa2006-10-20 00:27:06 +0000253 // Div and rem can trap if the RHS is not known to be non-zero.
Chris Lattner0eeb9132009-10-28 05:14:34 +0000254 if (!isa<ConstantInt>(CE->getOperand(1)) ||CE->getOperand(1)->isNullValue())
Chris Lattner35b89fa2006-10-20 00:27:06 +0000255 return true;
256 return false;
257 }
258}
259
Hans Wennborg18398582012-11-15 11:40:00 +0000260/// isThreadDependent - Return true if the value can vary between threads.
261bool Constant::isThreadDependent() const {
262 SmallPtrSet<const Constant*, 64> Visited;
263 SmallVector<const Constant*, 64> WorkList;
264 WorkList.push_back(this);
265 Visited.insert(this);
266
267 while (!WorkList.empty()) {
268 const Constant *C = WorkList.pop_back_val();
269
270 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
271 if (GV->isThreadLocal())
272 return true;
273 }
274
275 for (unsigned I = 0, E = C->getNumOperands(); I != E; ++I) {
Hans Wennborgfbeb9562012-11-16 10:33:25 +0000276 const Constant *D = dyn_cast<Constant>(C->getOperand(I));
277 if (!D)
278 continue;
Hans Wennborg18398582012-11-15 11:40:00 +0000279 if (Visited.insert(D))
280 WorkList.push_back(D);
281 }
282 }
283
284 return false;
285}
286
Chris Lattner4a7642e2009-11-01 18:11:50 +0000287/// isConstantUsed - Return true if the constant has users other than constant
288/// exprs and other dangling things.
289bool Constant::isConstantUsed() const {
Gabor Greif60ad7812010-03-25 23:06:16 +0000290 for (const_use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
Chris Lattner4a7642e2009-11-01 18:11:50 +0000291 const Constant *UC = dyn_cast<Constant>(*UI);
292 if (UC == 0 || isa<GlobalValue>(UC))
293 return true;
Galina Kistanovaa46517e2012-07-13 01:25:27 +0000294
Chris Lattner4a7642e2009-11-01 18:11:50 +0000295 if (UC->isConstantUsed())
296 return true;
297 }
298 return false;
299}
300
301
Chris Lattner7cf12c72009-07-22 00:05:44 +0000302
303/// getRelocationInfo - This method classifies the entry according to
304/// whether or not it may generate a relocation entry. This must be
305/// conservative, so if it might codegen to a relocatable entry, it should say
306/// so. The return values are:
307///
Chris Lattner083a1e02009-07-24 03:27:21 +0000308/// NoRelocation: This constant pool entry is guaranteed to never have a
309/// relocation applied to it (because it holds a simple constant like
310/// '4').
311/// LocalRelocation: This entry has relocations, but the entries are
312/// guaranteed to be resolvable by the static linker, so the dynamic
313/// linker will never see them.
314/// GlobalRelocations: This entry may have arbitrary relocations.
Chris Lattner7cf12c72009-07-22 00:05:44 +0000315///
Chandler Carruthc2c50cd2013-01-02 09:10:48 +0000316/// FIXME: This really should not be in IR.
Chris Lattner083a1e02009-07-24 03:27:21 +0000317Constant::PossibleRelocationsTy Constant::getRelocationInfo() const {
318 if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
Chris Lattner7cf12c72009-07-22 00:05:44 +0000319 if (GV->hasLocalLinkage() || GV->hasHiddenVisibility())
Chris Lattner083a1e02009-07-24 03:27:21 +0000320 return LocalRelocation; // Local to this file/library.
321 return GlobalRelocations; // Global reference.
Anton Korobeynikovab267a22009-03-29 17:13:18 +0000322 }
Chris Lattner7cf12c72009-07-22 00:05:44 +0000323
Chris Lattner5d81bef2009-10-28 04:12:16 +0000324 if (const BlockAddress *BA = dyn_cast<BlockAddress>(this))
325 return BA->getFunction()->getRelocationInfo();
326
Chris Lattner5099b312010-01-03 18:09:40 +0000327 // While raw uses of blockaddress need to be relocated, differences between
328 // two of them don't when they are for labels in the same function. This is a
329 // common idiom when creating a table for the indirect goto extension, so we
330 // handle it efficiently here.
331 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(this))
332 if (CE->getOpcode() == Instruction::Sub) {
333 ConstantExpr *LHS = dyn_cast<ConstantExpr>(CE->getOperand(0));
334 ConstantExpr *RHS = dyn_cast<ConstantExpr>(CE->getOperand(1));
335 if (LHS && RHS &&
336 LHS->getOpcode() == Instruction::PtrToInt &&
337 RHS->getOpcode() == Instruction::PtrToInt &&
338 isa<BlockAddress>(LHS->getOperand(0)) &&
339 isa<BlockAddress>(RHS->getOperand(0)) &&
340 cast<BlockAddress>(LHS->getOperand(0))->getFunction() ==
341 cast<BlockAddress>(RHS->getOperand(0))->getFunction())
342 return NoRelocation;
343 }
Galina Kistanovaa46517e2012-07-13 01:25:27 +0000344
Chris Lattner083a1e02009-07-24 03:27:21 +0000345 PossibleRelocationsTy Result = NoRelocation;
Evan Chengafe15812007-03-08 00:59:12 +0000346 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
Chris Lattner0eeb9132009-10-28 05:14:34 +0000347 Result = std::max(Result,
348 cast<Constant>(getOperand(i))->getRelocationInfo());
Galina Kistanovaa46517e2012-07-13 01:25:27 +0000349
Chris Lattner7cf12c72009-07-22 00:05:44 +0000350 return Result;
Evan Chengafe15812007-03-08 00:59:12 +0000351}
352
Chris Lattner13fb0db2011-02-18 04:41:42 +0000353/// removeDeadUsersOfConstant - If the specified constantexpr is dead, remove
354/// it. This involves recursively eliminating any dead users of the
355/// constantexpr.
356static bool removeDeadUsersOfConstant(const Constant *C) {
357 if (isa<GlobalValue>(C)) return false; // Cannot remove this
Galina Kistanovaa46517e2012-07-13 01:25:27 +0000358
Chris Lattner13fb0db2011-02-18 04:41:42 +0000359 while (!C->use_empty()) {
360 const Constant *User = dyn_cast<Constant>(C->use_back());
361 if (!User) return false; // Non-constant usage;
362 if (!removeDeadUsersOfConstant(User))
363 return false; // Constant wasn't dead
364 }
Galina Kistanovaa46517e2012-07-13 01:25:27 +0000365
Chris Lattner13fb0db2011-02-18 04:41:42 +0000366 const_cast<Constant*>(C)->destroyConstant();
367 return true;
368}
369
370
371/// removeDeadConstantUsers - If there are any dead constant users dangling
372/// off of this constant, remove them. This method is useful for clients
373/// that want to check to see if a global is unused, but don't want to deal
374/// with potentially dead constants hanging off of the globals.
375void Constant::removeDeadConstantUsers() const {
376 Value::const_use_iterator I = use_begin(), E = use_end();
377 Value::const_use_iterator LastNonDeadUser = E;
378 while (I != E) {
379 const Constant *User = dyn_cast<Constant>(*I);
380 if (User == 0) {
381 LastNonDeadUser = I;
382 ++I;
383 continue;
384 }
Galina Kistanovaa46517e2012-07-13 01:25:27 +0000385
Chris Lattner13fb0db2011-02-18 04:41:42 +0000386 if (!removeDeadUsersOfConstant(User)) {
387 // If the constant wasn't dead, remember that this was the last live use
388 // and move on to the next constant.
389 LastNonDeadUser = I;
390 ++I;
391 continue;
392 }
Galina Kistanovaa46517e2012-07-13 01:25:27 +0000393
Chris Lattner13fb0db2011-02-18 04:41:42 +0000394 // If the constant was dead, then the iterator is invalidated.
395 if (LastNonDeadUser == E) {
396 I = use_begin();
397 if (I == E) break;
398 } else {
399 I = LastNonDeadUser;
400 ++I;
401 }
402 }
403}
404
405
Chris Lattner86381442008-07-10 00:28:11 +0000406
Chris Lattner00950542001-06-06 20:29:01 +0000407//===----------------------------------------------------------------------===//
Chris Lattner6b6f6ba2007-02-20 06:39:57 +0000408// ConstantInt
Chris Lattner00950542001-06-06 20:29:01 +0000409//===----------------------------------------------------------------------===//
410
David Blaikie2d24e2a2011-12-20 02:50:00 +0000411void ConstantInt::anchor() { }
412
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000413ConstantInt::ConstantInt(IntegerType *Ty, const APInt& V)
Chris Lattnereb41bdd2007-02-20 05:55:46 +0000414 : Constant(Ty, ConstantIntVal, 0, 0), Val(V) {
Reid Spencer532d0ce2007-02-26 23:54:03 +0000415 assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
Chris Lattner00950542001-06-06 20:29:01 +0000416}
417
Nick Lewyckyd01f50f2011-03-06 03:36:19 +0000418ConstantInt *ConstantInt::getTrue(LLVMContext &Context) {
Owen Anderson5defacc2009-07-31 17:39:07 +0000419 LLVMContextImpl *pImpl = Context.pImpl;
Benjamin Kramerf601d6d2010-11-20 18:43:35 +0000420 if (!pImpl->TheTrueVal)
421 pImpl->TheTrueVal = ConstantInt::get(Type::getInt1Ty(Context), 1);
422 return pImpl->TheTrueVal;
Owen Anderson5defacc2009-07-31 17:39:07 +0000423}
424
Nick Lewyckyd01f50f2011-03-06 03:36:19 +0000425ConstantInt *ConstantInt::getFalse(LLVMContext &Context) {
Owen Anderson5defacc2009-07-31 17:39:07 +0000426 LLVMContextImpl *pImpl = Context.pImpl;
Benjamin Kramerf601d6d2010-11-20 18:43:35 +0000427 if (!pImpl->TheFalseVal)
428 pImpl->TheFalseVal = ConstantInt::get(Type::getInt1Ty(Context), 0);
429 return pImpl->TheFalseVal;
Owen Anderson5defacc2009-07-31 17:39:07 +0000430}
431
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000432Constant *ConstantInt::getTrue(Type *Ty) {
433 VectorType *VTy = dyn_cast<VectorType>(Ty);
Nick Lewyckyd01f50f2011-03-06 03:36:19 +0000434 if (!VTy) {
435 assert(Ty->isIntegerTy(1) && "True must be i1 or vector of i1.");
436 return ConstantInt::getTrue(Ty->getContext());
437 }
438 assert(VTy->getElementType()->isIntegerTy(1) &&
439 "True must be vector of i1 or i1.");
Chris Lattner3c2c9542012-01-25 05:19:54 +0000440 return ConstantVector::getSplat(VTy->getNumElements(),
441 ConstantInt::getTrue(Ty->getContext()));
Nick Lewyckyd01f50f2011-03-06 03:36:19 +0000442}
443
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000444Constant *ConstantInt::getFalse(Type *Ty) {
445 VectorType *VTy = dyn_cast<VectorType>(Ty);
Nick Lewyckyd01f50f2011-03-06 03:36:19 +0000446 if (!VTy) {
447 assert(Ty->isIntegerTy(1) && "False must be i1 or vector of i1.");
448 return ConstantInt::getFalse(Ty->getContext());
449 }
450 assert(VTy->getElementType()->isIntegerTy(1) &&
451 "False must be vector of i1 or i1.");
Chris Lattner3c2c9542012-01-25 05:19:54 +0000452 return ConstantVector::getSplat(VTy->getNumElements(),
453 ConstantInt::getFalse(Ty->getContext()));
Nick Lewyckyd01f50f2011-03-06 03:36:19 +0000454}
455
Owen Anderson5defacc2009-07-31 17:39:07 +0000456
Owen Andersoneed707b2009-07-24 23:12:02 +0000457// Get a ConstantInt from an APInt. Note that the value stored in the DenseMap
458// as the key, is a DenseMapAPIntKeyInfo::KeyTy which has provided the
459// operator== and operator!= to ensure that the DenseMap doesn't attempt to
460// compare APInt's of different widths, which would violate an APInt class
461// invariant which generates an assertion.
Nick Lewyckyd01f50f2011-03-06 03:36:19 +0000462ConstantInt *ConstantInt::get(LLVMContext &Context, const APInt &V) {
Owen Andersoneed707b2009-07-24 23:12:02 +0000463 // Get the corresponding integer type for the bit width of the value.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000464 IntegerType *ITy = IntegerType::get(Context, V.getBitWidth());
Owen Andersoneed707b2009-07-24 23:12:02 +0000465 // get an existing value or the insertion position
466 DenseMapAPIntKeyInfo::KeyTy Key(V, ITy);
Owen Andersoneed707b2009-07-24 23:12:02 +0000467 ConstantInt *&Slot = Context.pImpl->IntConstants[Key];
Owen Anderson59d5aac2009-10-19 20:11:52 +0000468 if (!Slot) Slot = new ConstantInt(ITy, V);
469 return Slot;
Owen Andersoneed707b2009-07-24 23:12:02 +0000470}
471
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000472Constant *ConstantInt::get(Type *Ty, uint64_t V, bool isSigned) {
Nick Lewyckyd01f50f2011-03-06 03:36:19 +0000473 Constant *C = get(cast<IntegerType>(Ty->getScalarType()), V, isSigned);
Owen Andersoneed707b2009-07-24 23:12:02 +0000474
475 // For vectors, broadcast the value.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000476 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
Chris Lattner3c2c9542012-01-25 05:19:54 +0000477 return ConstantVector::getSplat(VTy->getNumElements(), C);
Owen Andersoneed707b2009-07-24 23:12:02 +0000478
479 return C;
480}
481
Chris Lattnera78fa8c2012-01-27 03:08:05 +0000482ConstantInt *ConstantInt::get(IntegerType *Ty, uint64_t V,
Owen Andersoneed707b2009-07-24 23:12:02 +0000483 bool isSigned) {
484 return get(Ty->getContext(), APInt(Ty->getBitWidth(), V, isSigned));
485}
486
Chris Lattnera78fa8c2012-01-27 03:08:05 +0000487ConstantInt *ConstantInt::getSigned(IntegerType *Ty, int64_t V) {
Owen Andersoneed707b2009-07-24 23:12:02 +0000488 return get(Ty, V, true);
489}
490
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000491Constant *ConstantInt::getSigned(Type *Ty, int64_t V) {
Owen Andersoneed707b2009-07-24 23:12:02 +0000492 return get(Ty, V, true);
493}
494
Chris Lattnera78fa8c2012-01-27 03:08:05 +0000495Constant *ConstantInt::get(Type *Ty, const APInt& V) {
Owen Andersoneed707b2009-07-24 23:12:02 +0000496 ConstantInt *C = get(Ty->getContext(), V);
497 assert(C->getType() == Ty->getScalarType() &&
498 "ConstantInt type doesn't match the type implied by its value!");
499
500 // For vectors, broadcast the value.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000501 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
Chris Lattner3c2c9542012-01-25 05:19:54 +0000502 return ConstantVector::getSplat(VTy->getNumElements(), C);
Owen Andersoneed707b2009-07-24 23:12:02 +0000503
504 return C;
505}
506
Chris Lattnera78fa8c2012-01-27 03:08:05 +0000507ConstantInt *ConstantInt::get(IntegerType* Ty, StringRef Str,
Erick Tryzelaar0e81f662009-08-16 23:36:33 +0000508 uint8_t radix) {
509 return get(Ty->getContext(), APInt(Ty->getBitWidth(), Str, radix));
510}
511
Chris Lattner6b6f6ba2007-02-20 06:39:57 +0000512//===----------------------------------------------------------------------===//
Chris Lattner9b4ee0c2007-02-20 07:17:17 +0000513// ConstantFP
Chris Lattner6b6f6ba2007-02-20 06:39:57 +0000514//===----------------------------------------------------------------------===//
515
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000516static const fltSemantics *TypeToFloatSemantics(Type *Ty) {
Dan Gohmance163392011-12-17 00:04:22 +0000517 if (Ty->isHalfTy())
518 return &APFloat::IEEEhalf;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000519 if (Ty->isFloatTy())
Rafael Espindola87d1f472009-07-15 17:40:42 +0000520 return &APFloat::IEEEsingle;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000521 if (Ty->isDoubleTy())
Rafael Espindola87d1f472009-07-15 17:40:42 +0000522 return &APFloat::IEEEdouble;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000523 if (Ty->isX86_FP80Ty())
Rafael Espindola87d1f472009-07-15 17:40:42 +0000524 return &APFloat::x87DoubleExtended;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000525 else if (Ty->isFP128Ty())
Rafael Espindola87d1f472009-07-15 17:40:42 +0000526 return &APFloat::IEEEquad;
Galina Kistanovaa46517e2012-07-13 01:25:27 +0000527
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000528 assert(Ty->isPPC_FP128Ty() && "Unknown FP format");
Rafael Espindola87d1f472009-07-15 17:40:42 +0000529 return &APFloat::PPCDoubleDouble;
530}
531
David Blaikie2d24e2a2011-12-20 02:50:00 +0000532void ConstantFP::anchor() { }
533
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000534/// get() - This returns a constant fp for the specified value in the
535/// specified type. This should only be used for simple constant values like
536/// 2.0/1.0 etc, that are known-valid both as double and as the target format.
Chris Lattnera78fa8c2012-01-27 03:08:05 +0000537Constant *ConstantFP::get(Type *Ty, double V) {
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000538 LLVMContext &Context = Ty->getContext();
Galina Kistanovaa46517e2012-07-13 01:25:27 +0000539
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000540 APFloat FV(V);
541 bool ignored;
542 FV.convert(*TypeToFloatSemantics(Ty->getScalarType()),
543 APFloat::rmNearestTiesToEven, &ignored);
544 Constant *C = get(Context, FV);
545
546 // For vectors, broadcast the value.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000547 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
Chris Lattner3c2c9542012-01-25 05:19:54 +0000548 return ConstantVector::getSplat(VTy->getNumElements(), C);
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000549
550 return C;
551}
552
Erick Tryzelaar0e81f662009-08-16 23:36:33 +0000553
Chris Lattnera78fa8c2012-01-27 03:08:05 +0000554Constant *ConstantFP::get(Type *Ty, StringRef Str) {
Erick Tryzelaar0e81f662009-08-16 23:36:33 +0000555 LLVMContext &Context = Ty->getContext();
556
557 APFloat FV(*TypeToFloatSemantics(Ty->getScalarType()), Str);
558 Constant *C = get(Context, FV);
559
560 // For vectors, broadcast the value.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000561 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
Chris Lattner3c2c9542012-01-25 05:19:54 +0000562 return ConstantVector::getSplat(VTy->getNumElements(), C);
Erick Tryzelaar0e81f662009-08-16 23:36:33 +0000563
564 return C;
565}
566
567
Chris Lattner3c2c9542012-01-25 05:19:54 +0000568ConstantFP *ConstantFP::getNegativeZero(Type *Ty) {
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000569 LLVMContext &Context = Ty->getContext();
Chris Lattner3c2c9542012-01-25 05:19:54 +0000570 APFloat apf = cast<ConstantFP>(Constant::getNullValue(Ty))->getValueAPF();
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000571 apf.changeSign();
572 return get(Context, apf);
573}
574
575
Chris Lattner3c2c9542012-01-25 05:19:54 +0000576Constant *ConstantFP::getZeroValueForNegation(Type *Ty) {
577 Type *ScalarTy = Ty->getScalarType();
578 if (ScalarTy->isFloatingPointTy()) {
579 Constant *C = getNegativeZero(ScalarTy);
580 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
581 return ConstantVector::getSplat(VTy->getNumElements(), C);
582 return C;
583 }
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000584
Owen Andersona7235ea2009-07-31 20:28:14 +0000585 return Constant::getNullValue(Ty);
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000586}
587
588
589// ConstantFP accessors.
590ConstantFP* ConstantFP::get(LLVMContext &Context, const APFloat& V) {
591 DenseMapAPFloatKeyInfo::KeyTy Key(V);
Galina Kistanovaa46517e2012-07-13 01:25:27 +0000592
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000593 LLVMContextImpl* pImpl = Context.pImpl;
Galina Kistanovaa46517e2012-07-13 01:25:27 +0000594
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000595 ConstantFP *&Slot = pImpl->FPConstants[Key];
Galina Kistanovaa46517e2012-07-13 01:25:27 +0000596
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000597 if (!Slot) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000598 Type *Ty;
Dan Gohmance163392011-12-17 00:04:22 +0000599 if (&V.getSemantics() == &APFloat::IEEEhalf)
600 Ty = Type::getHalfTy(Context);
601 else if (&V.getSemantics() == &APFloat::IEEEsingle)
Owen Anderson59d5aac2009-10-19 20:11:52 +0000602 Ty = Type::getFloatTy(Context);
603 else if (&V.getSemantics() == &APFloat::IEEEdouble)
604 Ty = Type::getDoubleTy(Context);
605 else if (&V.getSemantics() == &APFloat::x87DoubleExtended)
606 Ty = Type::getX86_FP80Ty(Context);
607 else if (&V.getSemantics() == &APFloat::IEEEquad)
608 Ty = Type::getFP128Ty(Context);
609 else {
610 assert(&V.getSemantics() == &APFloat::PPCDoubleDouble &&
611 "Unknown FP format");
612 Ty = Type::getPPC_FP128Ty(Context);
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000613 }
Owen Anderson59d5aac2009-10-19 20:11:52 +0000614 Slot = new ConstantFP(Ty, V);
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000615 }
Galina Kistanovaa46517e2012-07-13 01:25:27 +0000616
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000617 return Slot;
618}
619
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000620ConstantFP *ConstantFP::getInfinity(Type *Ty, bool Negative) {
Dan Gohmanf344f7f2009-09-25 23:00:48 +0000621 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty);
622 return ConstantFP::get(Ty->getContext(),
623 APFloat::getInf(Semantics, Negative));
624}
625
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000626ConstantFP::ConstantFP(Type *Ty, const APFloat& V)
Dale Johannesenf04afdb2007-08-30 00:23:21 +0000627 : Constant(Ty, ConstantFPVal, 0, 0), Val(V) {
Chris Lattner288e78f2008-04-09 06:38:30 +0000628 assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
629 "FP type Mismatch");
Chris Lattner00950542001-06-06 20:29:01 +0000630}
631
Chris Lattner032c6eb2011-07-15 06:14:08 +0000632bool ConstantFP::isExactlyValue(const APFloat &V) const {
Dale Johannesenf04afdb2007-08-30 00:23:21 +0000633 return Val.bitwiseIsEqual(V);
Chris Lattner9b4ee0c2007-02-20 07:17:17 +0000634}
635
Chris Lattner9b4ee0c2007-02-20 07:17:17 +0000636//===----------------------------------------------------------------------===//
Chris Lattnerff2b7f32012-01-24 05:42:11 +0000637// ConstantAggregateZero Implementation
638//===----------------------------------------------------------------------===//
639
640/// getSequentialElement - If this CAZ has array or vector type, return a zero
641/// with the right element type.
Chris Lattner3d5ed222012-01-25 06:16:32 +0000642Constant *ConstantAggregateZero::getSequentialElement() const {
Chris Lattner230cdab2012-01-26 00:42:34 +0000643 return Constant::getNullValue(getType()->getSequentialElementType());
Chris Lattnerff2b7f32012-01-24 05:42:11 +0000644}
645
646/// getStructElement - If this CAZ has struct type, return a zero with the
647/// right element type for the specified element.
Chris Lattner3d5ed222012-01-25 06:16:32 +0000648Constant *ConstantAggregateZero::getStructElement(unsigned Elt) const {
Chris Lattner230cdab2012-01-26 00:42:34 +0000649 return Constant::getNullValue(getType()->getStructElementType(Elt));
Chris Lattnerff2b7f32012-01-24 05:42:11 +0000650}
651
652/// getElementValue - Return a zero of the right value for the specified GEP
653/// index if we can, otherwise return null (e.g. if C is a ConstantExpr).
Chris Lattner3d5ed222012-01-25 06:16:32 +0000654Constant *ConstantAggregateZero::getElementValue(Constant *C) const {
Chris Lattnerff2b7f32012-01-24 05:42:11 +0000655 if (isa<SequentialType>(getType()))
656 return getSequentialElement();
657 return getStructElement(cast<ConstantInt>(C)->getZExtValue());
658}
659
Chris Lattnerdf390282012-01-24 07:54:10 +0000660/// getElementValue - Return a zero of the right value for the specified GEP
661/// index.
Chris Lattner3d5ed222012-01-25 06:16:32 +0000662Constant *ConstantAggregateZero::getElementValue(unsigned Idx) const {
Chris Lattnerdf390282012-01-24 07:54:10 +0000663 if (isa<SequentialType>(getType()))
664 return getSequentialElement();
665 return getStructElement(Idx);
666}
667
668
Chris Lattnerff2b7f32012-01-24 05:42:11 +0000669//===----------------------------------------------------------------------===//
670// UndefValue Implementation
671//===----------------------------------------------------------------------===//
672
673/// getSequentialElement - If this undef has array or vector type, return an
674/// undef with the right element type.
Chris Lattner3d5ed222012-01-25 06:16:32 +0000675UndefValue *UndefValue::getSequentialElement() const {
Chris Lattner230cdab2012-01-26 00:42:34 +0000676 return UndefValue::get(getType()->getSequentialElementType());
Chris Lattnerff2b7f32012-01-24 05:42:11 +0000677}
678
679/// getStructElement - If this undef has struct type, return a zero with the
680/// right element type for the specified element.
Chris Lattner3d5ed222012-01-25 06:16:32 +0000681UndefValue *UndefValue::getStructElement(unsigned Elt) const {
Chris Lattner230cdab2012-01-26 00:42:34 +0000682 return UndefValue::get(getType()->getStructElementType(Elt));
Chris Lattnerff2b7f32012-01-24 05:42:11 +0000683}
684
685/// getElementValue - Return an undef of the right value for the specified GEP
686/// index if we can, otherwise return null (e.g. if C is a ConstantExpr).
Chris Lattner3d5ed222012-01-25 06:16:32 +0000687UndefValue *UndefValue::getElementValue(Constant *C) const {
Chris Lattnerff2b7f32012-01-24 05:42:11 +0000688 if (isa<SequentialType>(getType()))
689 return getSequentialElement();
690 return getStructElement(cast<ConstantInt>(C)->getZExtValue());
691}
692
Chris Lattnerdf390282012-01-24 07:54:10 +0000693/// getElementValue - Return an undef of the right value for the specified GEP
694/// index.
Chris Lattner3d5ed222012-01-25 06:16:32 +0000695UndefValue *UndefValue::getElementValue(unsigned Idx) const {
Chris Lattnerdf390282012-01-24 07:54:10 +0000696 if (isa<SequentialType>(getType()))
697 return getSequentialElement();
698 return getStructElement(Idx);
699}
700
701
Chris Lattnerff2b7f32012-01-24 05:42:11 +0000702
703//===----------------------------------------------------------------------===//
Chris Lattner9b4ee0c2007-02-20 07:17:17 +0000704// ConstantXXX Classes
705//===----------------------------------------------------------------------===//
706
Chris Lattner18c7f802012-02-05 02:29:43 +0000707template <typename ItTy, typename EltTy>
708static bool rangeOnlyContains(ItTy Start, ItTy End, EltTy Elt) {
709 for (; Start != End; ++Start)
710 if (*Start != Elt)
711 return false;
712 return true;
713}
Chris Lattner9b4ee0c2007-02-20 07:17:17 +0000714
Jay Foad166579e2011-07-25 10:14:44 +0000715ConstantArray::ConstantArray(ArrayType *T, ArrayRef<Constant *> V)
Gabor Greifefe65362008-05-10 08:32:32 +0000716 : Constant(T, ConstantArrayVal,
717 OperandTraits<ConstantArray>::op_end(this) - V.size(),
718 V.size()) {
Alkis Evlogimenose0de1d62004-09-15 02:32:15 +0000719 assert(V.size() == T->getNumElements() &&
720 "Invalid initializer vector for constant array");
Jay Foad166579e2011-07-25 10:14:44 +0000721 for (unsigned i = 0, e = V.size(); i != e; ++i)
722 assert(V[i]->getType() == T->getElementType() &&
Alkis Evlogimenoscad90ad2004-09-10 04:16:59 +0000723 "Initializer for array element doesn't match array element type!");
Jay Foad166579e2011-07-25 10:14:44 +0000724 std::copy(V.begin(), V.end(), op_begin());
Chris Lattner00950542001-06-06 20:29:01 +0000725}
726
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000727Constant *ConstantArray::get(ArrayType *Ty, ArrayRef<Constant*> V) {
Chris Lattner18c7f802012-02-05 02:29:43 +0000728 // Empty arrays are canonicalized to ConstantAggregateZero.
729 if (V.empty())
730 return ConstantAggregateZero::get(Ty);
731
Jeffrey Yasskin1fb613c2009-09-30 21:08:08 +0000732 for (unsigned i = 0, e = V.size(); i != e; ++i) {
733 assert(V[i]->getType() == Ty->getElementType() &&
734 "Wrong type in array element initializer");
735 }
Owen Anderson1fd70962009-07-28 18:32:17 +0000736 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
Galina Kistanovaa46517e2012-07-13 01:25:27 +0000737
Chris Lattner18c7f802012-02-05 02:29:43 +0000738 // If this is an all-zero array, return a ConstantAggregateZero object. If
739 // all undef, return an UndefValue, if "all simple", then return a
740 // ConstantDataArray.
741 Constant *C = V[0];
742 if (isa<UndefValue>(C) && rangeOnlyContains(V.begin(), V.end(), C))
743 return UndefValue::get(Ty);
Chris Lattnere150e2d2012-01-26 02:31:22 +0000744
Chris Lattner18c7f802012-02-05 02:29:43 +0000745 if (C->isNullValue() && rangeOnlyContains(V.begin(), V.end(), C))
746 return ConstantAggregateZero::get(Ty);
747
748 // Check to see if all of the elements are ConstantFP or ConstantInt and if
749 // the element type is compatible with ConstantDataVector. If so, use it.
750 if (ConstantDataSequential::isElementTypeCompatible(C->getType())) {
751 // We speculatively build the elements here even if it turns out that there
752 // is a constantexpr or something else weird in the array, since it is so
753 // uncommon for that to happen.
754 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
755 if (CI->getType()->isIntegerTy(8)) {
756 SmallVector<uint8_t, 16> Elts;
757 for (unsigned i = 0, e = V.size(); i != e; ++i)
758 if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
759 Elts.push_back(CI->getZExtValue());
760 else
761 break;
762 if (Elts.size() == V.size())
763 return ConstantDataArray::get(C->getContext(), Elts);
764 } else if (CI->getType()->isIntegerTy(16)) {
765 SmallVector<uint16_t, 16> Elts;
766 for (unsigned i = 0, e = V.size(); i != e; ++i)
767 if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
768 Elts.push_back(CI->getZExtValue());
769 else
770 break;
771 if (Elts.size() == V.size())
772 return ConstantDataArray::get(C->getContext(), Elts);
773 } else if (CI->getType()->isIntegerTy(32)) {
774 SmallVector<uint32_t, 16> Elts;
775 for (unsigned i = 0, e = V.size(); i != e; ++i)
776 if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
777 Elts.push_back(CI->getZExtValue());
778 else
779 break;
780 if (Elts.size() == V.size())
781 return ConstantDataArray::get(C->getContext(), Elts);
782 } else if (CI->getType()->isIntegerTy(64)) {
783 SmallVector<uint64_t, 16> Elts;
784 for (unsigned i = 0, e = V.size(); i != e; ++i)
785 if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
786 Elts.push_back(CI->getZExtValue());
787 else
788 break;
789 if (Elts.size() == V.size())
790 return ConstantDataArray::get(C->getContext(), Elts);
791 }
792 }
Galina Kistanovaa46517e2012-07-13 01:25:27 +0000793
Chris Lattner18c7f802012-02-05 02:29:43 +0000794 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
795 if (CFP->getType()->isFloatTy()) {
796 SmallVector<float, 16> Elts;
797 for (unsigned i = 0, e = V.size(); i != e; ++i)
798 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V[i]))
799 Elts.push_back(CFP->getValueAPF().convertToFloat());
800 else
801 break;
802 if (Elts.size() == V.size())
803 return ConstantDataArray::get(C->getContext(), Elts);
804 } else if (CFP->getType()->isDoubleTy()) {
805 SmallVector<double, 16> Elts;
806 for (unsigned i = 0, e = V.size(); i != e; ++i)
807 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V[i]))
808 Elts.push_back(CFP->getValueAPF().convertToDouble());
809 else
810 break;
811 if (Elts.size() == V.size())
812 return ConstantDataArray::get(C->getContext(), Elts);
813 }
814 }
Owen Anderson1fd70962009-07-28 18:32:17 +0000815 }
Chris Lattnere150e2d2012-01-26 02:31:22 +0000816
Chris Lattner18c7f802012-02-05 02:29:43 +0000817 // Otherwise, we really do want to create a ConstantArray.
Chris Lattnere150e2d2012-01-26 02:31:22 +0000818 return pImpl->ArrayConstants.getOrCreate(Ty, V);
Owen Anderson1fd70962009-07-28 18:32:17 +0000819}
820
Chris Lattnerb065b062011-06-20 04:01:31 +0000821/// getTypeForElements - Return an anonymous struct type to use for a constant
822/// with the specified set of elements. The list must not be empty.
823StructType *ConstantStruct::getTypeForElements(LLVMContext &Context,
824 ArrayRef<Constant*> V,
825 bool Packed) {
Bill Wendlinga7a3f042012-02-07 01:27:51 +0000826 unsigned VecSize = V.size();
827 SmallVector<Type*, 16> EltTypes(VecSize);
828 for (unsigned i = 0; i != VecSize; ++i)
829 EltTypes[i] = V[i]->getType();
Galina Kistanovaa46517e2012-07-13 01:25:27 +0000830
Chris Lattnerb065b062011-06-20 04:01:31 +0000831 return StructType::get(Context, EltTypes, Packed);
832}
833
834
835StructType *ConstantStruct::getTypeForElements(ArrayRef<Constant*> V,
836 bool Packed) {
837 assert(!V.empty() &&
838 "ConstantStruct::getTypeForElements cannot be called on empty list");
839 return getTypeForElements(V[0]->getContext(), V, Packed);
840}
841
842
Jay Foad166579e2011-07-25 10:14:44 +0000843ConstantStruct::ConstantStruct(StructType *T, ArrayRef<Constant *> V)
Gabor Greifefe65362008-05-10 08:32:32 +0000844 : Constant(T, ConstantStructVal,
845 OperandTraits<ConstantStruct>::op_end(this) - V.size(),
846 V.size()) {
Chris Lattnerf4ef8db2011-08-07 04:18:48 +0000847 assert(V.size() == T->getNumElements() &&
Vikram S. Adve345e0cf2002-07-14 23:13:17 +0000848 "Invalid initializer vector for constant structure");
Jay Foad166579e2011-07-25 10:14:44 +0000849 for (unsigned i = 0, e = V.size(); i != e; ++i)
850 assert((T->isOpaque() || V[i]->getType() == T->getElementType(i)) &&
Chris Lattnerb8438892003-06-02 17:42:47 +0000851 "Initializer for struct element doesn't match struct element type!");
Jay Foad166579e2011-07-25 10:14:44 +0000852 std::copy(V.begin(), V.end(), op_begin());
Chris Lattner00950542001-06-06 20:29:01 +0000853}
854
Owen Anderson8fa33382009-07-27 22:29:26 +0000855// ConstantStruct accessors.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000856Constant *ConstantStruct::get(StructType *ST, ArrayRef<Constant*> V) {
Chris Lattner1afcace2011-07-09 17:41:24 +0000857 assert((ST->isOpaque() || ST->getNumElements() == V.size()) &&
858 "Incorrect # elements specified to ConstantStruct::get");
Chris Lattnere150e2d2012-01-26 02:31:22 +0000859
860 // Create a ConstantAggregateZero value if all elements are zeros.
861 bool isZero = true;
862 bool isUndef = false;
863
864 if (!V.empty()) {
865 isUndef = isa<UndefValue>(V[0]);
866 isZero = V[0]->isNullValue();
867 if (isUndef || isZero) {
868 for (unsigned i = 0, e = V.size(); i != e; ++i) {
869 if (!V[i]->isNullValue())
870 isZero = false;
871 if (!isa<UndefValue>(V[i]))
872 isUndef = false;
873 }
874 }
Galina Kistanovaa46517e2012-07-13 01:25:27 +0000875 }
Chris Lattnere150e2d2012-01-26 02:31:22 +0000876 if (isZero)
877 return ConstantAggregateZero::get(ST);
878 if (isUndef)
879 return UndefValue::get(ST);
Galina Kistanovaa46517e2012-07-13 01:25:27 +0000880
Chris Lattnere150e2d2012-01-26 02:31:22 +0000881 return ST->getContext().pImpl->StructConstants.getOrCreate(ST, V);
Owen Anderson8fa33382009-07-27 22:29:26 +0000882}
883
Chris Lattnerf4ef8db2011-08-07 04:18:48 +0000884Constant *ConstantStruct::get(StructType *T, ...) {
Talin41ee4e52011-02-28 23:53:27 +0000885 va_list ap;
Chris Lattnerb065b062011-06-20 04:01:31 +0000886 SmallVector<Constant*, 8> Values;
887 va_start(ap, T);
888 while (Constant *Val = va_arg(ap, llvm::Constant*))
Talin41ee4e52011-02-28 23:53:27 +0000889 Values.push_back(Val);
Talinbdcd7662011-03-01 18:00:49 +0000890 va_end(ap);
Chris Lattnerb065b062011-06-20 04:01:31 +0000891 return get(T, Values);
Talin41ee4e52011-02-28 23:53:27 +0000892}
893
Jay Foad166579e2011-07-25 10:14:44 +0000894ConstantVector::ConstantVector(VectorType *T, ArrayRef<Constant *> V)
Gabor Greifefe65362008-05-10 08:32:32 +0000895 : Constant(T, ConstantVectorVal,
896 OperandTraits<ConstantVector>::op_end(this) - V.size(),
897 V.size()) {
Jay Foad166579e2011-07-25 10:14:44 +0000898 for (size_t i = 0, e = V.size(); i != e; i++)
899 assert(V[i]->getType() == T->getElementType() &&
Dan Gohmanfa73ea22007-05-24 14:36:04 +0000900 "Initializer for vector element doesn't match vector element type!");
Jay Foad166579e2011-07-25 10:14:44 +0000901 std::copy(V.begin(), V.end(), op_begin());
Brian Gaeke715c90b2004-08-20 06:00:58 +0000902}
903
Owen Andersonaf7ec972009-07-28 21:19:26 +0000904// ConstantVector accessors.
Jay Foada0c13842011-06-22 09:10:19 +0000905Constant *ConstantVector::get(ArrayRef<Constant*> V) {
Jay Foad9afc5272011-01-27 14:44:55 +0000906 assert(!V.empty() && "Vectors can't be empty");
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000907 VectorType *T = VectorType::get(V.front()->getType(), V.size());
Chris Lattner2ca5c862011-02-15 00:14:00 +0000908 LLVMContextImpl *pImpl = T->getContext().pImpl;
Jay Foad9afc5272011-01-27 14:44:55 +0000909
Chris Lattner2ca5c862011-02-15 00:14:00 +0000910 // If this is an all-undef or all-zero vector, return a
Owen Andersonaf7ec972009-07-28 21:19:26 +0000911 // ConstantAggregateZero or UndefValue.
912 Constant *C = V[0];
913 bool isZero = C->isNullValue();
914 bool isUndef = isa<UndefValue>(C);
915
916 if (isZero || isUndef) {
917 for (unsigned i = 1, e = V.size(); i != e; ++i)
918 if (V[i] != C) {
919 isZero = isUndef = false;
920 break;
921 }
922 }
Galina Kistanovaa46517e2012-07-13 01:25:27 +0000923
Owen Andersonaf7ec972009-07-28 21:19:26 +0000924 if (isZero)
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000925 return ConstantAggregateZero::get(T);
Owen Andersonaf7ec972009-07-28 21:19:26 +0000926 if (isUndef)
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000927 return UndefValue::get(T);
Galina Kistanovaa46517e2012-07-13 01:25:27 +0000928
Chris Lattner36c744f2012-01-30 06:21:21 +0000929 // Check to see if all of the elements are ConstantFP or ConstantInt and if
930 // the element type is compatible with ConstantDataVector. If so, use it.
Chris Lattner18c7f802012-02-05 02:29:43 +0000931 if (ConstantDataSequential::isElementTypeCompatible(C->getType())) {
Chris Lattner36c744f2012-01-30 06:21:21 +0000932 // We speculatively build the elements here even if it turns out that there
933 // is a constantexpr or something else weird in the array, since it is so
934 // uncommon for that to happen.
935 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
936 if (CI->getType()->isIntegerTy(8)) {
937 SmallVector<uint8_t, 16> Elts;
938 for (unsigned i = 0, e = V.size(); i != e; ++i)
939 if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
940 Elts.push_back(CI->getZExtValue());
941 else
942 break;
943 if (Elts.size() == V.size())
944 return ConstantDataVector::get(C->getContext(), Elts);
945 } else if (CI->getType()->isIntegerTy(16)) {
946 SmallVector<uint16_t, 16> Elts;
947 for (unsigned i = 0, e = V.size(); i != e; ++i)
948 if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
949 Elts.push_back(CI->getZExtValue());
950 else
951 break;
952 if (Elts.size() == V.size())
953 return ConstantDataVector::get(C->getContext(), Elts);
954 } else if (CI->getType()->isIntegerTy(32)) {
955 SmallVector<uint32_t, 16> Elts;
956 for (unsigned i = 0, e = V.size(); i != e; ++i)
957 if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
958 Elts.push_back(CI->getZExtValue());
959 else
960 break;
961 if (Elts.size() == V.size())
962 return ConstantDataVector::get(C->getContext(), Elts);
963 } else if (CI->getType()->isIntegerTy(64)) {
964 SmallVector<uint64_t, 16> Elts;
965 for (unsigned i = 0, e = V.size(); i != e; ++i)
966 if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
967 Elts.push_back(CI->getZExtValue());
968 else
969 break;
970 if (Elts.size() == V.size())
971 return ConstantDataVector::get(C->getContext(), Elts);
972 }
973 }
Galina Kistanovaa46517e2012-07-13 01:25:27 +0000974
Chris Lattner36c744f2012-01-30 06:21:21 +0000975 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
976 if (CFP->getType()->isFloatTy()) {
977 SmallVector<float, 16> Elts;
978 for (unsigned i = 0, e = V.size(); i != e; ++i)
979 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V[i]))
980 Elts.push_back(CFP->getValueAPF().convertToFloat());
981 else
982 break;
983 if (Elts.size() == V.size())
984 return ConstantDataVector::get(C->getContext(), Elts);
985 } else if (CFP->getType()->isDoubleTy()) {
986 SmallVector<double, 16> Elts;
987 for (unsigned i = 0, e = V.size(); i != e; ++i)
988 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V[i]))
989 Elts.push_back(CFP->getValueAPF().convertToDouble());
990 else
991 break;
992 if (Elts.size() == V.size())
993 return ConstantDataVector::get(C->getContext(), Elts);
994 }
995 }
996 }
Galina Kistanovaa46517e2012-07-13 01:25:27 +0000997
Chris Lattner36c744f2012-01-30 06:21:21 +0000998 // Otherwise, the element type isn't compatible with ConstantDataVector, or
999 // the operand list constants a ConstantExpr or something else strange.
Owen Andersonaf7ec972009-07-28 21:19:26 +00001000 return pImpl->VectorConstants.getOrCreate(T, V);
1001}
1002
Chris Lattner3c2c9542012-01-25 05:19:54 +00001003Constant *ConstantVector::getSplat(unsigned NumElts, Constant *V) {
Chris Lattner36c744f2012-01-30 06:21:21 +00001004 // If this splat is compatible with ConstantDataVector, use it instead of
1005 // ConstantVector.
1006 if ((isa<ConstantFP>(V) || isa<ConstantInt>(V)) &&
1007 ConstantDataSequential::isElementTypeCompatible(V->getType()))
1008 return ConstantDataVector::getSplat(NumElts, V);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001009
Chris Lattner3c2c9542012-01-25 05:19:54 +00001010 SmallVector<Constant*, 32> Elts(NumElts, V);
1011 return get(Elts);
1012}
1013
1014
Reid Spencer3da59db2006-11-27 01:05:10 +00001015// Utility function for determining if a ConstantExpr is a CastOp or not. This
1016// can't be inline because we don't want to #include Instruction.h into
1017// Constant.h
1018bool ConstantExpr::isCast() const {
1019 return Instruction::isCast(getOpcode());
1020}
1021
Reid Spencer077d0eb2006-12-04 05:19:50 +00001022bool ConstantExpr::isCompare() const {
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00001023 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
Reid Spencer077d0eb2006-12-04 05:19:50 +00001024}
1025
Dan Gohmane6992f72009-09-10 23:37:55 +00001026bool ConstantExpr::isGEPWithNoNotionalOverIndexing() const {
1027 if (getOpcode() != Instruction::GetElementPtr) return false;
1028
1029 gep_type_iterator GEPI = gep_type_begin(this), E = gep_type_end(this);
Oscar Fuentesee56c422010-08-02 06:00:15 +00001030 User::const_op_iterator OI = llvm::next(this->op_begin());
Dan Gohmane6992f72009-09-10 23:37:55 +00001031
1032 // Skip the first index, as it has no static limit.
1033 ++GEPI;
1034 ++OI;
1035
1036 // The remaining indices must be compile-time known integers within the
1037 // bounds of the corresponding notional static array types.
1038 for (; GEPI != E; ++GEPI, ++OI) {
1039 ConstantInt *CI = dyn_cast<ConstantInt>(*OI);
1040 if (!CI) return false;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001041 if (ArrayType *ATy = dyn_cast<ArrayType>(*GEPI))
Dan Gohmane6992f72009-09-10 23:37:55 +00001042 if (CI->getValue().getActiveBits() > 64 ||
1043 CI->getZExtValue() >= ATy->getNumElements())
1044 return false;
1045 }
1046
1047 // All the indices checked out.
1048 return true;
1049}
1050
Dan Gohman81a0c0b2008-05-31 00:58:22 +00001051bool ConstantExpr::hasIndices() const {
1052 return getOpcode() == Instruction::ExtractValue ||
1053 getOpcode() == Instruction::InsertValue;
1054}
1055
Jay Foadd30aa5a2011-04-13 15:22:40 +00001056ArrayRef<unsigned> ConstantExpr::getIndices() const {
Dan Gohman81a0c0b2008-05-31 00:58:22 +00001057 if (const ExtractValueConstantExpr *EVCE =
1058 dyn_cast<ExtractValueConstantExpr>(this))
1059 return EVCE->Indices;
Dan Gohman1a203572008-06-23 16:39:44 +00001060
1061 return cast<InsertValueConstantExpr>(this)->Indices;
Dan Gohman81a0c0b2008-05-31 00:58:22 +00001062}
1063
Reid Spencer728b6db2006-12-03 05:48:19 +00001064unsigned ConstantExpr::getPredicate() const {
Chris Lattner3e194732011-07-17 06:01:30 +00001065 assert(isCompare());
Chris Lattnerb7daa842007-10-18 16:26:24 +00001066 return ((const CompareConstantExpr*)this)->predicate;
Reid Spencer728b6db2006-12-03 05:48:19 +00001067}
Chris Lattnerf4ba6c72001-10-03 06:12:09 +00001068
Chris Lattner1fe8f6b2006-07-14 19:37:40 +00001069/// getWithOperandReplaced - Return a constant expression identical to this
1070/// one, but with the specified operand set to the specified value.
Reid Spencer3da59db2006-11-27 01:05:10 +00001071Constant *
1072ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
Chris Lattner1fe8f6b2006-07-14 19:37:40 +00001073 assert(Op->getType() == getOperand(OpNo)->getType() &&
1074 "Replacing operand with value of different type!");
Chris Lattnerb88a7fb2006-07-14 22:20:01 +00001075 if (getOperand(OpNo) == Op)
1076 return const_cast<ConstantExpr*>(this);
Chris Lattner1a8def62012-01-26 20:37:11 +00001077
1078 SmallVector<Constant*, 8> NewOps;
1079 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1080 NewOps.push_back(i == OpNo ? Op : getOperand(i));
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001081
Chris Lattner1a8def62012-01-26 20:37:11 +00001082 return getWithOperands(NewOps);
Chris Lattnerb88a7fb2006-07-14 22:20:01 +00001083}
1084
1085/// getWithOperands - This returns the current constant expression with the
Chris Lattner1afcace2011-07-09 17:41:24 +00001086/// operands replaced with the specified values. The specified array must
1087/// have the same number of operands as our current one.
Chris Lattnerb88a7fb2006-07-14 22:20:01 +00001088Constant *ConstantExpr::
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001089getWithOperands(ArrayRef<Constant*> Ops, Type *Ty) const {
Jay Foadb81e4572011-04-13 13:46:01 +00001090 assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
Chris Lattner1afcace2011-07-09 17:41:24 +00001091 bool AnyChange = Ty != getType();
1092 for (unsigned i = 0; i != Ops.size(); ++i)
Chris Lattnerb88a7fb2006-07-14 22:20:01 +00001093 AnyChange |= Ops[i] != getOperand(i);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001094
Chris Lattnerb88a7fb2006-07-14 22:20:01 +00001095 if (!AnyChange) // No operands changed, return self.
1096 return const_cast<ConstantExpr*>(this);
1097
1098 switch (getOpcode()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001099 case Instruction::Trunc:
1100 case Instruction::ZExt:
1101 case Instruction::SExt:
1102 case Instruction::FPTrunc:
1103 case Instruction::FPExt:
1104 case Instruction::UIToFP:
1105 case Instruction::SIToFP:
1106 case Instruction::FPToUI:
1107 case Instruction::FPToSI:
1108 case Instruction::PtrToInt:
1109 case Instruction::IntToPtr:
1110 case Instruction::BitCast:
Chris Lattner1afcace2011-07-09 17:41:24 +00001111 return ConstantExpr::getCast(getOpcode(), Ops[0], Ty);
Chris Lattnerb88a7fb2006-07-14 22:20:01 +00001112 case Instruction::Select:
1113 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
1114 case Instruction::InsertElement:
1115 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
1116 case Instruction::ExtractElement:
1117 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
Chris Lattner1a8def62012-01-26 20:37:11 +00001118 case Instruction::InsertValue:
1119 return ConstantExpr::getInsertValue(Ops[0], Ops[1], getIndices());
1120 case Instruction::ExtractValue:
1121 return ConstantExpr::getExtractValue(Ops[0], getIndices());
Chris Lattnerb88a7fb2006-07-14 22:20:01 +00001122 case Instruction::ShuffleVector:
1123 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
Chris Lattnerf9021ff2007-02-19 20:01:23 +00001124 case Instruction::GetElementPtr:
Chris Lattner1a8def62012-01-26 20:37:11 +00001125 return ConstantExpr::getGetElementPtr(Ops[0], Ops.slice(1),
1126 cast<GEPOperator>(this)->isInBounds());
Reid Spencere4d87aa2006-12-23 06:05:41 +00001127 case Instruction::ICmp:
1128 case Instruction::FCmp:
1129 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
Chris Lattnerb88a7fb2006-07-14 22:20:01 +00001130 default:
1131 assert(getNumOperands() == 2 && "Must be binary operator?");
Chris Lattnercafe9bb2009-12-29 02:14:09 +00001132 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1], SubclassOptionalData);
Chris Lattner1fe8f6b2006-07-14 19:37:40 +00001133 }
1134}
1135
Chris Lattner00950542001-06-06 20:29:01 +00001136
1137//===----------------------------------------------------------------------===//
Chris Lattner00950542001-06-06 20:29:01 +00001138// isValueValidForType implementations
1139
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001140bool ConstantInt::isValueValidForType(Type *Ty, uint64_t Val) {
Chris Lattner230cdab2012-01-26 00:42:34 +00001141 unsigned NumBits = Ty->getIntegerBitWidth(); // assert okay
1142 if (Ty->isIntegerTy(1))
Reid Spencera54b7cb2007-01-12 07:05:14 +00001143 return Val == 0 || Val == 1;
Reid Spencer554cec62007-02-05 23:47:56 +00001144 if (NumBits >= 64)
Reid Spencera54b7cb2007-01-12 07:05:14 +00001145 return true; // always true, has to fit in largest type
1146 uint64_t Max = (1ll << NumBits) - 1;
1147 return Val <= Max;
Reid Spencer9b11d512006-12-19 01:28:19 +00001148}
1149
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001150bool ConstantInt::isValueValidForType(Type *Ty, int64_t Val) {
Chris Lattner230cdab2012-01-26 00:42:34 +00001151 unsigned NumBits = Ty->getIntegerBitWidth();
1152 if (Ty->isIntegerTy(1))
Reid Spencerc1030572007-01-19 21:13:56 +00001153 return Val == 0 || Val == 1 || Val == -1;
Reid Spencer554cec62007-02-05 23:47:56 +00001154 if (NumBits >= 64)
Reid Spencera54b7cb2007-01-12 07:05:14 +00001155 return true; // always true, has to fit in largest type
1156 int64_t Min = -(1ll << (NumBits-1));
1157 int64_t Max = (1ll << (NumBits-1)) - 1;
1158 return (Val >= Min && Val <= Max);
Chris Lattner00950542001-06-06 20:29:01 +00001159}
1160
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001161bool ConstantFP::isValueValidForType(Type *Ty, const APFloat& Val) {
Dale Johannesenf04afdb2007-08-30 00:23:21 +00001162 // convert modifies in place, so make a copy.
1163 APFloat Val2 = APFloat(Val);
Dale Johannesen23a98552008-10-09 23:00:39 +00001164 bool losesInfo;
Chris Lattnerf70c22b2004-06-17 18:19:28 +00001165 switch (Ty->getTypeID()) {
Chris Lattner00950542001-06-06 20:29:01 +00001166 default:
1167 return false; // These can't be represented as floating point!
1168
Dale Johannesenf04afdb2007-08-30 00:23:21 +00001169 // FIXME rounding mode needs to be more flexible
Dan Gohmance163392011-12-17 00:04:22 +00001170 case Type::HalfTyID: {
1171 if (&Val2.getSemantics() == &APFloat::IEEEhalf)
1172 return true;
1173 Val2.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven, &losesInfo);
1174 return !losesInfo;
1175 }
Dale Johannesen23a98552008-10-09 23:00:39 +00001176 case Type::FloatTyID: {
1177 if (&Val2.getSemantics() == &APFloat::IEEEsingle)
1178 return true;
1179 Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &losesInfo);
1180 return !losesInfo;
1181 }
1182 case Type::DoubleTyID: {
Dan Gohmance163392011-12-17 00:04:22 +00001183 if (&Val2.getSemantics() == &APFloat::IEEEhalf ||
1184 &Val2.getSemantics() == &APFloat::IEEEsingle ||
Dale Johannesen23a98552008-10-09 23:00:39 +00001185 &Val2.getSemantics() == &APFloat::IEEEdouble)
1186 return true;
1187 Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &losesInfo);
1188 return !losesInfo;
1189 }
Dale Johannesenebbc95d2007-08-09 22:51:36 +00001190 case Type::X86_FP80TyID:
Dan Gohmance163392011-12-17 00:04:22 +00001191 return &Val2.getSemantics() == &APFloat::IEEEhalf ||
1192 &Val2.getSemantics() == &APFloat::IEEEsingle ||
Dale Johannesen9d5f4562007-09-12 03:30:33 +00001193 &Val2.getSemantics() == &APFloat::IEEEdouble ||
1194 &Val2.getSemantics() == &APFloat::x87DoubleExtended;
Dale Johannesenebbc95d2007-08-09 22:51:36 +00001195 case Type::FP128TyID:
Dan Gohmance163392011-12-17 00:04:22 +00001196 return &Val2.getSemantics() == &APFloat::IEEEhalf ||
1197 &Val2.getSemantics() == &APFloat::IEEEsingle ||
Dale Johannesen9d5f4562007-09-12 03:30:33 +00001198 &Val2.getSemantics() == &APFloat::IEEEdouble ||
1199 &Val2.getSemantics() == &APFloat::IEEEquad;
Dale Johannesena471c2e2007-10-11 18:07:22 +00001200 case Type::PPC_FP128TyID:
Dan Gohmance163392011-12-17 00:04:22 +00001201 return &Val2.getSemantics() == &APFloat::IEEEhalf ||
1202 &Val2.getSemantics() == &APFloat::IEEEsingle ||
Dale Johannesena471c2e2007-10-11 18:07:22 +00001203 &Val2.getSemantics() == &APFloat::IEEEdouble ||
1204 &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
Chris Lattner00950542001-06-06 20:29:01 +00001205 }
Chris Lattnerd74ea2b2006-05-24 17:04:05 +00001206}
Chris Lattner37bf6302001-07-20 19:16:02 +00001207
Chris Lattnerff2b7f32012-01-24 05:42:11 +00001208
Chris Lattner531daef2001-09-07 16:46:31 +00001209//===----------------------------------------------------------------------===//
Chris Lattner531daef2001-09-07 16:46:31 +00001210// Factory Function Implementation
1211
Chris Lattner9df0fb42012-01-23 15:20:12 +00001212ConstantAggregateZero *ConstantAggregateZero::get(Type *Ty) {
Chris Lattner61c70e92010-08-28 04:09:24 +00001213 assert((Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()) &&
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001214 "Cannot create an aggregate zero of non-aggregate type!");
1215
Chris Lattner9df0fb42012-01-23 15:20:12 +00001216 ConstantAggregateZero *&Entry = Ty->getContext().pImpl->CAZConstants[Ty];
1217 if (Entry == 0)
1218 Entry = new ConstantAggregateZero(Ty);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001219
Chris Lattner9df0fb42012-01-23 15:20:12 +00001220 return Entry;
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001221}
1222
Chris Lattnerff2b7f32012-01-24 05:42:11 +00001223/// destroyConstant - Remove the constant from the constant table.
Dan Gohman0f8b53f2009-03-03 02:55:14 +00001224///
Owen Anderson04fb7c32009-06-20 00:24:58 +00001225void ConstantAggregateZero::destroyConstant() {
Chris Lattner9df0fb42012-01-23 15:20:12 +00001226 getContext().pImpl->CAZConstants.erase(getType());
Chris Lattner40bbeb52004-02-15 05:53:04 +00001227 destroyConstantImpl();
1228}
1229
Dan Gohman0f8b53f2009-03-03 02:55:14 +00001230/// destroyConstant - Remove the constant from the constant table...
1231///
Owen Anderson04fb7c32009-06-20 00:24:58 +00001232void ConstantArray::destroyConstant() {
Chris Lattner1afcace2011-07-09 17:41:24 +00001233 getType()->getContext().pImpl->ArrayConstants.remove(this);
Chris Lattner02ec5ed2003-05-23 20:03:32 +00001234 destroyConstantImpl();
1235}
1236
Chris Lattner93aeea32002-08-26 17:53:56 +00001237
Chris Lattnere9bb2df2001-12-03 22:26:30 +00001238//---- ConstantStruct::get() implementation...
Chris Lattner531daef2001-09-07 16:46:31 +00001239//
Chris Lattnered468e372003-10-05 00:17:43 +00001240
Chris Lattnerf5ec48d2001-10-13 06:57:33 +00001241// destroyConstant - Remove the constant from the constant table...
Chris Lattner6a57baa2001-10-03 15:39:36 +00001242//
Owen Anderson04fb7c32009-06-20 00:24:58 +00001243void ConstantStruct::destroyConstant() {
Chris Lattner1afcace2011-07-09 17:41:24 +00001244 getType()->getContext().pImpl->StructConstants.remove(this);
Chris Lattnerf5ec48d2001-10-13 06:57:33 +00001245 destroyConstantImpl();
1246}
Chris Lattner6a57baa2001-10-03 15:39:36 +00001247
Brian Gaeke715c90b2004-08-20 06:00:58 +00001248// destroyConstant - Remove the constant from the constant table...
1249//
Owen Anderson04fb7c32009-06-20 00:24:58 +00001250void ConstantVector::destroyConstant() {
Chris Lattner1afcace2011-07-09 17:41:24 +00001251 getType()->getContext().pImpl->VectorConstants.remove(this);
Brian Gaeke715c90b2004-08-20 06:00:58 +00001252 destroyConstantImpl();
1253}
1254
Duncan Sands2333e292012-11-13 12:59:33 +00001255/// getSplatValue - If this is a splat vector constant, meaning that all of
1256/// the elements have the same value, return that value. Otherwise return 0.
1257Constant *Constant::getSplatValue() const {
1258 assert(this->getType()->isVectorTy() && "Only valid for vectors!");
1259 if (isa<ConstantAggregateZero>(this))
1260 return getNullValue(this->getType()->getVectorElementType());
1261 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
1262 return CV->getSplatValue();
1263 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
1264 return CV->getSplatValue();
1265 return 0;
1266}
1267
Dan Gohman3b7cf0a2007-10-17 17:51:30 +00001268/// getSplatValue - If this is a splat constant, where all of the
1269/// elements have the same value, return that value. Otherwise return null.
Duncan Sands7681c6d2011-02-01 08:39:12 +00001270Constant *ConstantVector::getSplatValue() const {
Dan Gohman3b7cf0a2007-10-17 17:51:30 +00001271 // Check out first element.
1272 Constant *Elt = getOperand(0);
1273 // Then make sure all remaining elements point to the same value.
1274 for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
Chris Lattner3e194732011-07-17 06:01:30 +00001275 if (getOperand(I) != Elt)
1276 return 0;
Dan Gohman3b7cf0a2007-10-17 17:51:30 +00001277 return Elt;
1278}
1279
Duncan Sands2333e292012-11-13 12:59:33 +00001280/// If C is a constant integer then return its value, otherwise C must be a
1281/// vector of constant integers, all equal, and the common value is returned.
1282const APInt &Constant::getUniqueInteger() const {
1283 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
1284 return CI->getValue();
1285 assert(this->getSplatValue() && "Doesn't contain a unique integer!");
1286 const Constant *C = this->getAggregateElement(0U);
1287 assert(C && isa<ConstantInt>(C) && "Not a vector of numbers!");
1288 return cast<ConstantInt>(C)->getValue();
1289}
1290
1291
Chris Lattner2ee11ec2009-10-28 00:01:44 +00001292//---- ConstantPointerNull::get() implementation.
Chris Lattnerf5ec48d2001-10-13 06:57:33 +00001293//
Chris Lattner02ec5ed2003-05-23 20:03:32 +00001294
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001295ConstantPointerNull *ConstantPointerNull::get(PointerType *Ty) {
Chris Lattner9df0fb42012-01-23 15:20:12 +00001296 ConstantPointerNull *&Entry = Ty->getContext().pImpl->CPNConstants[Ty];
1297 if (Entry == 0)
1298 Entry = new ConstantPointerNull(Ty);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001299
Chris Lattner9df0fb42012-01-23 15:20:12 +00001300 return Entry;
Chris Lattner6a57baa2001-10-03 15:39:36 +00001301}
1302
Chris Lattner41661fd2002-08-18 00:40:04 +00001303// destroyConstant - Remove the constant from the constant table...
1304//
Owen Anderson04fb7c32009-06-20 00:24:58 +00001305void ConstantPointerNull::destroyConstant() {
Chris Lattner9df0fb42012-01-23 15:20:12 +00001306 getContext().pImpl->CPNConstants.erase(getType());
1307 // Free the constant and any dangling references to it.
Chris Lattner41661fd2002-08-18 00:40:04 +00001308 destroyConstantImpl();
1309}
1310
1311
Chris Lattner2ee11ec2009-10-28 00:01:44 +00001312//---- UndefValue::get() implementation.
Chris Lattnerb9f18592004-10-16 18:07:16 +00001313//
1314
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001315UndefValue *UndefValue::get(Type *Ty) {
Chris Lattner9df0fb42012-01-23 15:20:12 +00001316 UndefValue *&Entry = Ty->getContext().pImpl->UVConstants[Ty];
1317 if (Entry == 0)
1318 Entry = new UndefValue(Ty);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001319
Chris Lattner9df0fb42012-01-23 15:20:12 +00001320 return Entry;
Chris Lattnerb9f18592004-10-16 18:07:16 +00001321}
1322
1323// destroyConstant - Remove the constant from the constant table.
1324//
Owen Anderson04fb7c32009-06-20 00:24:58 +00001325void UndefValue::destroyConstant() {
Chris Lattner9df0fb42012-01-23 15:20:12 +00001326 // Free the constant and any dangling references to it.
1327 getContext().pImpl->UVConstants.erase(getType());
Chris Lattnerb9f18592004-10-16 18:07:16 +00001328 destroyConstantImpl();
1329}
1330
Chris Lattner2ee11ec2009-10-28 00:01:44 +00001331//---- BlockAddress::get() implementation.
1332//
1333
1334BlockAddress *BlockAddress::get(BasicBlock *BB) {
1335 assert(BB->getParent() != 0 && "Block must have a parent");
1336 return get(BB->getParent(), BB);
1337}
1338
1339BlockAddress *BlockAddress::get(Function *F, BasicBlock *BB) {
1340 BlockAddress *&BA =
1341 F->getContext().pImpl->BlockAddresses[std::make_pair(F, BB)];
1342 if (BA == 0)
1343 BA = new BlockAddress(F, BB);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001344
Chris Lattner2ee11ec2009-10-28 00:01:44 +00001345 assert(BA->getFunction() == F && "Basic block moved between functions");
1346 return BA;
1347}
1348
1349BlockAddress::BlockAddress(Function *F, BasicBlock *BB)
1350: Constant(Type::getInt8PtrTy(F->getContext()), Value::BlockAddressVal,
1351 &Op<0>(), 2) {
Chris Lattnerd0ec2352009-11-01 03:03:03 +00001352 setOperand(0, F);
1353 setOperand(1, BB);
Chris Lattnercdfc9402009-11-01 01:27:45 +00001354 BB->AdjustBlockAddressRefCount(1);
Chris Lattner2ee11ec2009-10-28 00:01:44 +00001355}
1356
1357
1358// destroyConstant - Remove the constant from the constant table.
1359//
1360void BlockAddress::destroyConstant() {
Chris Lattner1afcace2011-07-09 17:41:24 +00001361 getFunction()->getType()->getContext().pImpl
Chris Lattner2ee11ec2009-10-28 00:01:44 +00001362 ->BlockAddresses.erase(std::make_pair(getFunction(), getBasicBlock()));
Chris Lattnercdfc9402009-11-01 01:27:45 +00001363 getBasicBlock()->AdjustBlockAddressRefCount(-1);
Chris Lattner2ee11ec2009-10-28 00:01:44 +00001364 destroyConstantImpl();
1365}
1366
1367void BlockAddress::replaceUsesOfWithOnConstant(Value *From, Value *To, Use *U) {
1368 // This could be replacing either the Basic Block or the Function. In either
1369 // case, we have to remove the map entry.
1370 Function *NewF = getFunction();
1371 BasicBlock *NewBB = getBasicBlock();
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001372
Chris Lattner2ee11ec2009-10-28 00:01:44 +00001373 if (U == &Op<0>())
1374 NewF = cast<Function>(To);
1375 else
1376 NewBB = cast<BasicBlock>(To);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001377
Chris Lattner2ee11ec2009-10-28 00:01:44 +00001378 // See if the 'new' entry already exists, if not, just update this in place
1379 // and return early.
1380 BlockAddress *&NewBA =
1381 getContext().pImpl->BlockAddresses[std::make_pair(NewF, NewBB)];
1382 if (NewBA == 0) {
Chris Lattnerd0ec2352009-11-01 03:03:03 +00001383 getBasicBlock()->AdjustBlockAddressRefCount(-1);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001384
Chris Lattner2ee11ec2009-10-28 00:01:44 +00001385 // Remove the old entry, this can't cause the map to rehash (just a
1386 // tombstone will get added).
1387 getContext().pImpl->BlockAddresses.erase(std::make_pair(getFunction(),
1388 getBasicBlock()));
1389 NewBA = this;
Chris Lattnerd0ec2352009-11-01 03:03:03 +00001390 setOperand(0, NewF);
1391 setOperand(1, NewBB);
1392 getBasicBlock()->AdjustBlockAddressRefCount(1);
Chris Lattner2ee11ec2009-10-28 00:01:44 +00001393 return;
1394 }
1395
1396 // Otherwise, I do need to replace this with an existing value.
1397 assert(NewBA != this && "I didn't contain From!");
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001398
Chris Lattner2ee11ec2009-10-28 00:01:44 +00001399 // Everyone using this now uses the replacement.
Chris Lattner678f9e02011-07-15 06:18:52 +00001400 replaceAllUsesWith(NewBA);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001401
Chris Lattner2ee11ec2009-10-28 00:01:44 +00001402 destroyConstant();
1403}
1404
1405//---- ConstantExpr::get() implementations.
Vikram S. Adve345e0cf2002-07-14 23:13:17 +00001406//
Reid Spencer79e21d32006-12-31 05:26:44 +00001407
Reid Spencer3da59db2006-11-27 01:05:10 +00001408/// This is a utility function to handle folding of casts and lookup of the
Duncan Sands66a1a052008-03-30 19:38:55 +00001409/// cast in the ExprConstants map. It is used by the various get* methods below.
Reid Spencer3da59db2006-11-27 01:05:10 +00001410static inline Constant *getFoldedCast(
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001411 Instruction::CastOps opc, Constant *C, Type *Ty) {
Chris Lattner9eacf8a2003-10-07 22:19:19 +00001412 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
Reid Spencer3da59db2006-11-27 01:05:10 +00001413 // Fold a few common cases
Chris Lattnerb29d5962010-02-01 20:48:08 +00001414 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
Reid Spencer3da59db2006-11-27 01:05:10 +00001415 return FC;
Chris Lattnerd628f6a2003-04-17 19:24:48 +00001416
Owen Andersond03eecd2009-08-04 20:25:11 +00001417 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
1418
Vikram S. Adved0b1bb02002-07-15 18:19:33 +00001419 // Look up the constant in the table first to ensure uniqueness
Chris Lattner9bc02a42003-05-13 21:37:02 +00001420 std::vector<Constant*> argVec(1, C);
Reid Spencer077d0eb2006-12-04 05:19:50 +00001421 ExprMapKeyType Key(opc, argVec);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001422
Owen Andersond03eecd2009-08-04 20:25:11 +00001423 return pImpl->ExprConstants.getOrCreate(Ty, Key);
Vikram S. Adve345e0cf2002-07-14 23:13:17 +00001424}
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001425
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001426Constant *ConstantExpr::getCast(unsigned oc, Constant *C, Type *Ty) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001427 Instruction::CastOps opc = Instruction::CastOps(oc);
1428 assert(Instruction::isCast(opc) && "opcode out of range");
1429 assert(C && Ty && "Null arguments to getCast");
Chris Lattner0b68a002010-01-26 21:51:43 +00001430 assert(CastInst::castIsValid(opc, C, Ty) && "Invalid constantexpr cast!");
Reid Spencer3da59db2006-11-27 01:05:10 +00001431
1432 switch (opc) {
Chris Lattner0b68a002010-01-26 21:51:43 +00001433 default:
1434 llvm_unreachable("Invalid cast opcode");
Chris Lattner0b68a002010-01-26 21:51:43 +00001435 case Instruction::Trunc: return getTrunc(C, Ty);
1436 case Instruction::ZExt: return getZExt(C, Ty);
1437 case Instruction::SExt: return getSExt(C, Ty);
1438 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
1439 case Instruction::FPExt: return getFPExtend(C, Ty);
1440 case Instruction::UIToFP: return getUIToFP(C, Ty);
1441 case Instruction::SIToFP: return getSIToFP(C, Ty);
1442 case Instruction::FPToUI: return getFPToUI(C, Ty);
1443 case Instruction::FPToSI: return getFPToSI(C, Ty);
1444 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1445 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1446 case Instruction::BitCast: return getBitCast(C, Ty);
Chris Lattnerf5ac6c22005-01-01 15:59:57 +00001447 }
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001448}
Reid Spencer7858b332006-12-05 19:14:13 +00001449
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001450Constant *ConstantExpr::getZExtOrBitCast(Constant *C, Type *Ty) {
Dan Gohman6de29f82009-06-15 22:12:54 +00001451 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
Dan Gohman3b490632010-04-12 22:12:29 +00001452 return getBitCast(C, Ty);
1453 return getZExt(C, Ty);
Reid Spencer848414e2006-12-04 20:17:56 +00001454}
1455
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001456Constant *ConstantExpr::getSExtOrBitCast(Constant *C, Type *Ty) {
Dan Gohman6de29f82009-06-15 22:12:54 +00001457 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
Dan Gohman3b490632010-04-12 22:12:29 +00001458 return getBitCast(C, Ty);
1459 return getSExt(C, Ty);
Reid Spencer848414e2006-12-04 20:17:56 +00001460}
1461
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001462Constant *ConstantExpr::getTruncOrBitCast(Constant *C, Type *Ty) {
Dan Gohman6de29f82009-06-15 22:12:54 +00001463 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
Dan Gohman3b490632010-04-12 22:12:29 +00001464 return getBitCast(C, Ty);
1465 return getTrunc(C, Ty);
Reid Spencer848414e2006-12-04 20:17:56 +00001466}
1467
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001468Constant *ConstantExpr::getPointerCast(Constant *S, Type *Ty) {
Evgeniy Stepanov655578f2013-01-16 14:41:46 +00001469 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
1470 assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
1471 "Invalid cast");
Reid Spencerc0459fb2006-12-05 03:25:26 +00001472
Evgeniy Stepanov655578f2013-01-16 14:41:46 +00001473 if (Ty->isIntOrIntVectorTy())
Dan Gohman3b490632010-04-12 22:12:29 +00001474 return getPtrToInt(S, Ty);
1475 return getBitCast(S, Ty);
Reid Spencerc0459fb2006-12-05 03:25:26 +00001476}
1477
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001478Constant *ConstantExpr::getIntegerCast(Constant *C, Type *Ty,
Reid Spencer84f3eab2006-12-12 00:51:07 +00001479 bool isSigned) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001480 assert(C->getType()->isIntOrIntVectorTy() &&
1481 Ty->isIntOrIntVectorTy() && "Invalid cast");
Dan Gohman6de29f82009-06-15 22:12:54 +00001482 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1483 unsigned DstBits = Ty->getScalarSizeInBits();
Reid Spencer84f3eab2006-12-12 00:51:07 +00001484 Instruction::CastOps opcode =
1485 (SrcBits == DstBits ? Instruction::BitCast :
1486 (SrcBits > DstBits ? Instruction::Trunc :
1487 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1488 return getCast(opcode, C, Ty);
1489}
1490
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001491Constant *ConstantExpr::getFPCast(Constant *C, Type *Ty) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001492 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
Reid Spencer84f3eab2006-12-12 00:51:07 +00001493 "Invalid cast");
Dan Gohman6de29f82009-06-15 22:12:54 +00001494 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1495 unsigned DstBits = Ty->getScalarSizeInBits();
Reid Spencerf25212a2006-12-12 05:38:50 +00001496 if (SrcBits == DstBits)
1497 return C; // Avoid a useless cast
Reid Spencer84f3eab2006-12-12 00:51:07 +00001498 Instruction::CastOps opcode =
Jay Foad9afc5272011-01-27 14:44:55 +00001499 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
Reid Spencer84f3eab2006-12-12 00:51:07 +00001500 return getCast(opcode, C, Ty);
1501}
1502
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001503Constant *ConstantExpr::getTrunc(Constant *C, Type *Ty) {
Dan Gohman6de29f82009-06-15 22:12:54 +00001504#ifndef NDEBUG
1505 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1506 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1507#endif
1508 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001509 assert(C->getType()->isIntOrIntVectorTy() && "Trunc operand must be integer");
1510 assert(Ty->isIntOrIntVectorTy() && "Trunc produces only integral");
Dan Gohman6de29f82009-06-15 22:12:54 +00001511 assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
Reid Spencer3da59db2006-11-27 01:05:10 +00001512 "SrcTy must be larger than DestTy for Trunc!");
1513
Owen Anderson04fb7c32009-06-20 00:24:58 +00001514 return getFoldedCast(Instruction::Trunc, C, Ty);
Reid Spencer3da59db2006-11-27 01:05:10 +00001515}
1516
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001517Constant *ConstantExpr::getSExt(Constant *C, Type *Ty) {
Dan Gohman6de29f82009-06-15 22:12:54 +00001518#ifndef NDEBUG
1519 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1520 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1521#endif
1522 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001523 assert(C->getType()->isIntOrIntVectorTy() && "SExt operand must be integral");
1524 assert(Ty->isIntOrIntVectorTy() && "SExt produces only integer");
Dan Gohman6de29f82009-06-15 22:12:54 +00001525 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
Reid Spencer3da59db2006-11-27 01:05:10 +00001526 "SrcTy must be smaller than DestTy for SExt!");
1527
Owen Anderson04fb7c32009-06-20 00:24:58 +00001528 return getFoldedCast(Instruction::SExt, C, Ty);
Chris Lattnerd144f422004-04-04 23:20:30 +00001529}
1530
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001531Constant *ConstantExpr::getZExt(Constant *C, Type *Ty) {
Dan Gohman6de29f82009-06-15 22:12:54 +00001532#ifndef NDEBUG
1533 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1534 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1535#endif
1536 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001537 assert(C->getType()->isIntOrIntVectorTy() && "ZEXt operand must be integral");
1538 assert(Ty->isIntOrIntVectorTy() && "ZExt produces only integer");
Dan Gohman6de29f82009-06-15 22:12:54 +00001539 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
Reid Spencer3da59db2006-11-27 01:05:10 +00001540 "SrcTy must be smaller than DestTy for ZExt!");
1541
Owen Anderson04fb7c32009-06-20 00:24:58 +00001542 return getFoldedCast(Instruction::ZExt, C, Ty);
Reid Spencer3da59db2006-11-27 01:05:10 +00001543}
1544
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001545Constant *ConstantExpr::getFPTrunc(Constant *C, Type *Ty) {
Dan Gohman6de29f82009-06-15 22:12:54 +00001546#ifndef NDEBUG
1547 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1548 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1549#endif
1550 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001551 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00001552 C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
Reid Spencer3da59db2006-11-27 01:05:10 +00001553 "This is an illegal floating point truncation!");
Owen Anderson04fb7c32009-06-20 00:24:58 +00001554 return getFoldedCast(Instruction::FPTrunc, C, Ty);
Reid Spencer3da59db2006-11-27 01:05:10 +00001555}
1556
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001557Constant *ConstantExpr::getFPExtend(Constant *C, Type *Ty) {
Dan Gohman6de29f82009-06-15 22:12:54 +00001558#ifndef NDEBUG
1559 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1560 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1561#endif
1562 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001563 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00001564 C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
Reid Spencer3da59db2006-11-27 01:05:10 +00001565 "This is an illegal floating point extension!");
Owen Anderson04fb7c32009-06-20 00:24:58 +00001566 return getFoldedCast(Instruction::FPExt, C, Ty);
Reid Spencer3da59db2006-11-27 01:05:10 +00001567}
1568
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001569Constant *ConstantExpr::getUIToFP(Constant *C, Type *Ty) {
Devang Patelb6dc9352008-11-03 23:20:04 +00001570#ifndef NDEBUG
Nate Begemanb348d182007-11-17 03:58:34 +00001571 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1572 bool toVec = Ty->getTypeID() == Type::VectorTyID;
Devang Patelb6dc9352008-11-03 23:20:04 +00001573#endif
Nate Begemanb348d182007-11-17 03:58:34 +00001574 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001575 assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
Nate Begemanb348d182007-11-17 03:58:34 +00001576 "This is an illegal uint to floating point cast!");
Owen Anderson04fb7c32009-06-20 00:24:58 +00001577 return getFoldedCast(Instruction::UIToFP, C, Ty);
Reid Spencer3da59db2006-11-27 01:05:10 +00001578}
1579
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001580Constant *ConstantExpr::getSIToFP(Constant *C, Type *Ty) {
Devang Patelb6dc9352008-11-03 23:20:04 +00001581#ifndef NDEBUG
Nate Begemanb348d182007-11-17 03:58:34 +00001582 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1583 bool toVec = Ty->getTypeID() == Type::VectorTyID;
Devang Patelb6dc9352008-11-03 23:20:04 +00001584#endif
Nate Begemanb348d182007-11-17 03:58:34 +00001585 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001586 assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
Reid Spencer3da59db2006-11-27 01:05:10 +00001587 "This is an illegal sint to floating point cast!");
Owen Anderson04fb7c32009-06-20 00:24:58 +00001588 return getFoldedCast(Instruction::SIToFP, C, Ty);
Reid Spencer3da59db2006-11-27 01:05:10 +00001589}
1590
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001591Constant *ConstantExpr::getFPToUI(Constant *C, Type *Ty) {
Devang Patelb6dc9352008-11-03 23:20:04 +00001592#ifndef NDEBUG
Nate Begemanb348d182007-11-17 03:58:34 +00001593 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1594 bool toVec = Ty->getTypeID() == Type::VectorTyID;
Devang Patelb6dc9352008-11-03 23:20:04 +00001595#endif
Nate Begemanb348d182007-11-17 03:58:34 +00001596 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001597 assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
Nate Begemanb348d182007-11-17 03:58:34 +00001598 "This is an illegal floating point to uint cast!");
Owen Anderson04fb7c32009-06-20 00:24:58 +00001599 return getFoldedCast(Instruction::FPToUI, C, Ty);
Reid Spencer3da59db2006-11-27 01:05:10 +00001600}
1601
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001602Constant *ConstantExpr::getFPToSI(Constant *C, Type *Ty) {
Devang Patelb6dc9352008-11-03 23:20:04 +00001603#ifndef NDEBUG
Nate Begemanb348d182007-11-17 03:58:34 +00001604 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1605 bool toVec = Ty->getTypeID() == Type::VectorTyID;
Devang Patelb6dc9352008-11-03 23:20:04 +00001606#endif
Nate Begemanb348d182007-11-17 03:58:34 +00001607 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001608 assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
Nate Begemanb348d182007-11-17 03:58:34 +00001609 "This is an illegal floating point to sint cast!");
Owen Anderson04fb7c32009-06-20 00:24:58 +00001610 return getFoldedCast(Instruction::FPToSI, C, Ty);
Reid Spencer3da59db2006-11-27 01:05:10 +00001611}
1612
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001613Constant *ConstantExpr::getPtrToInt(Constant *C, Type *DstTy) {
Nadav Rotem16087692011-12-05 06:29:09 +00001614 assert(C->getType()->getScalarType()->isPointerTy() &&
1615 "PtrToInt source must be pointer or pointer vector");
1616 assert(DstTy->getScalarType()->isIntegerTy() &&
1617 "PtrToInt destination must be integer or integer vector");
Chris Lattneraf7b4fb2012-01-25 01:32:59 +00001618 assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
Nick Lewycky1486ae62012-01-25 03:20:12 +00001619 if (isa<VectorType>(C->getType()))
Chris Lattner230cdab2012-01-26 00:42:34 +00001620 assert(C->getType()->getVectorNumElements()==DstTy->getVectorNumElements()&&
Chris Lattneraf7b4fb2012-01-25 01:32:59 +00001621 "Invalid cast between a different number of vector elements");
Owen Anderson04fb7c32009-06-20 00:24:58 +00001622 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00001623}
1624
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001625Constant *ConstantExpr::getIntToPtr(Constant *C, Type *DstTy) {
Nadav Rotem16087692011-12-05 06:29:09 +00001626 assert(C->getType()->getScalarType()->isIntegerTy() &&
1627 "IntToPtr source must be integer or integer vector");
1628 assert(DstTy->getScalarType()->isPointerTy() &&
1629 "IntToPtr destination must be a pointer or pointer vector");
Chris Lattneraf7b4fb2012-01-25 01:32:59 +00001630 assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
Nick Lewycky1486ae62012-01-25 03:20:12 +00001631 if (isa<VectorType>(C->getType()))
Chris Lattner230cdab2012-01-26 00:42:34 +00001632 assert(C->getType()->getVectorNumElements()==DstTy->getVectorNumElements()&&
Chris Lattneraf7b4fb2012-01-25 01:32:59 +00001633 "Invalid cast between a different number of vector elements");
Owen Anderson04fb7c32009-06-20 00:24:58 +00001634 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00001635}
1636
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001637Constant *ConstantExpr::getBitCast(Constant *C, Type *DstTy) {
Chris Lattner0b68a002010-01-26 21:51:43 +00001638 assert(CastInst::castIsValid(Instruction::BitCast, C, DstTy) &&
1639 "Invalid constantexpr bitcast!");
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001640
Chris Lattner8c7f24a2009-03-21 06:55:54 +00001641 // It is common to ask for a bitcast of a value to its own type, handle this
1642 // speedily.
1643 if (C->getType() == DstTy) return C;
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001644
Owen Anderson04fb7c32009-06-20 00:24:58 +00001645 return getFoldedCast(Instruction::BitCast, C, DstTy);
Chris Lattnerd144f422004-04-04 23:20:30 +00001646}
1647
Chris Lattnereaf79802011-07-09 18:23:52 +00001648Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2,
1649 unsigned Flags) {
1650 // Check the operands for consistency first.
Reid Spencer0a783f72006-11-02 01:53:59 +00001651 assert(Opcode >= Instruction::BinaryOpsBegin &&
1652 Opcode < Instruction::BinaryOpsEnd &&
Chris Lattnerf31f5832003-05-21 17:49:25 +00001653 "Invalid opcode in binary constant expression");
1654 assert(C1->getType() == C2->getType() &&
1655 "Operand types in binary constant expression should match");
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001656
Chris Lattner91b362b2004-08-17 17:28:46 +00001657#ifndef NDEBUG
1658 switch (Opcode) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001659 case Instruction::Add:
Reid Spencer0a783f72006-11-02 01:53:59 +00001660 case Instruction::Sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001661 case Instruction::Mul:
Chris Lattner91b362b2004-08-17 17:28:46 +00001662 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001663 assert(C1->getType()->isIntOrIntVectorTy() &&
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001664 "Tried to create an integer operation on a non-integer type!");
1665 break;
1666 case Instruction::FAdd:
1667 case Instruction::FSub:
1668 case Instruction::FMul:
1669 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001670 assert(C1->getType()->isFPOrFPVectorTy() &&
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001671 "Tried to create a floating-point operation on a "
1672 "non-floating-point type!");
Chris Lattner91b362b2004-08-17 17:28:46 +00001673 break;
Reid Spencer1628cec2006-10-26 06:15:43 +00001674 case Instruction::UDiv:
1675 case Instruction::SDiv:
1676 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001677 assert(C1->getType()->isIntOrIntVectorTy() &&
Reid Spencer1628cec2006-10-26 06:15:43 +00001678 "Tried to create an arithmetic operation on a non-arithmetic type!");
1679 break;
1680 case Instruction::FDiv:
1681 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001682 assert(C1->getType()->isFPOrFPVectorTy() &&
Dan Gohmanf57478f2009-06-15 22:25:12 +00001683 "Tried to create an arithmetic operation on a non-arithmetic type!");
Reid Spencer1628cec2006-10-26 06:15:43 +00001684 break;
Reid Spencer0a783f72006-11-02 01:53:59 +00001685 case Instruction::URem:
1686 case Instruction::SRem:
1687 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001688 assert(C1->getType()->isIntOrIntVectorTy() &&
Reid Spencer0a783f72006-11-02 01:53:59 +00001689 "Tried to create an arithmetic operation on a non-arithmetic type!");
1690 break;
1691 case Instruction::FRem:
1692 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001693 assert(C1->getType()->isFPOrFPVectorTy() &&
Dan Gohmanf57478f2009-06-15 22:25:12 +00001694 "Tried to create an arithmetic operation on a non-arithmetic type!");
Reid Spencer0a783f72006-11-02 01:53:59 +00001695 break;
Chris Lattner91b362b2004-08-17 17:28:46 +00001696 case Instruction::And:
1697 case Instruction::Or:
1698 case Instruction::Xor:
1699 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001700 assert(C1->getType()->isIntOrIntVectorTy() &&
Misha Brukman1bae2912005-01-27 06:46:38 +00001701 "Tried to create a logical operation on a non-integral type!");
Chris Lattner91b362b2004-08-17 17:28:46 +00001702 break;
Chris Lattner91b362b2004-08-17 17:28:46 +00001703 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00001704 case Instruction::LShr:
1705 case Instruction::AShr:
Reid Spencer832254e2007-02-02 02:16:23 +00001706 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001707 assert(C1->getType()->isIntOrIntVectorTy() &&
Chris Lattner91b362b2004-08-17 17:28:46 +00001708 "Tried to create a shift operation on a non-integer type!");
1709 break;
1710 default:
1711 break;
1712 }
1713#endif
1714
Chris Lattnereaf79802011-07-09 18:23:52 +00001715 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1716 return FC; // Fold a few common cases.
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001717
Chris Lattnereaf79802011-07-09 18:23:52 +00001718 std::vector<Constant*> argVec(1, C1);
1719 argVec.push_back(C2);
1720 ExprMapKeyType Key(Opcode, argVec, 0, Flags);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001721
Chris Lattnereaf79802011-07-09 18:23:52 +00001722 LLVMContextImpl *pImpl = C1->getContext().pImpl;
1723 return pImpl->ExprConstants.getOrCreate(C1->getType(), Key);
Reid Spencer67263fe2006-12-04 21:35:24 +00001724}
1725
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001726Constant *ConstantExpr::getSizeOf(Type* Ty) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00001727 // sizeof is implemented as: (i64) gep (Ty*)null, 1
1728 // Note that a non-inbounds gep is used, as null isn't within any object.
Owen Anderson1d0be152009-08-13 21:58:54 +00001729 Constant *GEPIdx = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001730 Constant *GEP = getGetElementPtr(
Jay Foaddab3d292011-07-21 14:31:17 +00001731 Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx);
Dan Gohman3b490632010-04-12 22:12:29 +00001732 return getPtrToInt(GEP,
1733 Type::getInt64Ty(Ty->getContext()));
Owen Andersonbaf3c402009-07-29 18:55:55 +00001734}
1735
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001736Constant *ConstantExpr::getAlignOf(Type* Ty) {
Dan Gohman0f5efe52010-01-28 02:15:55 +00001737 // alignof is implemented as: (i64) gep ({i1,Ty}*)null, 0, 1
Dan Gohmane2574d32009-08-11 17:57:01 +00001738 // Note that a non-inbounds gep is used, as null isn't within any object.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001739 Type *AligningTy =
Chris Lattnerb2318662011-06-18 22:48:56 +00001740 StructType::get(Type::getInt1Ty(Ty->getContext()), Ty, NULL);
Micah Villmowb8bce922012-10-24 17:25:11 +00001741 Constant *NullPtr = Constant::getNullValue(AligningTy->getPointerTo());
Dan Gohman06ed3e72010-01-28 02:43:22 +00001742 Constant *Zero = ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0);
Owen Anderson1d0be152009-08-13 21:58:54 +00001743 Constant *One = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001744 Constant *Indices[2] = { Zero, One };
Jay Foaddab3d292011-07-21 14:31:17 +00001745 Constant *GEP = getGetElementPtr(NullPtr, Indices);
Dan Gohman3b490632010-04-12 22:12:29 +00001746 return getPtrToInt(GEP,
1747 Type::getInt64Ty(Ty->getContext()));
Owen Andersonbaf3c402009-07-29 18:55:55 +00001748}
1749
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001750Constant *ConstantExpr::getOffsetOf(StructType* STy, unsigned FieldNo) {
Dan Gohman2544a1d2010-02-01 16:37:38 +00001751 return getOffsetOf(STy, ConstantInt::get(Type::getInt32Ty(STy->getContext()),
1752 FieldNo));
1753}
1754
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001755Constant *ConstantExpr::getOffsetOf(Type* Ty, Constant *FieldNo) {
Dan Gohman3778f212009-08-16 21:26:11 +00001756 // offsetof is implemented as: (i64) gep (Ty*)null, 0, FieldNo
1757 // Note that a non-inbounds gep is used, as null isn't within any object.
1758 Constant *GEPIdx[] = {
Dan Gohman2544a1d2010-02-01 16:37:38 +00001759 ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0),
1760 FieldNo
Dan Gohman3778f212009-08-16 21:26:11 +00001761 };
1762 Constant *GEP = getGetElementPtr(
Jay Foaddab3d292011-07-21 14:31:17 +00001763 Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx);
Dan Gohman3b490632010-04-12 22:12:29 +00001764 return getPtrToInt(GEP,
1765 Type::getInt64Ty(Ty->getContext()));
Dan Gohman3778f212009-08-16 21:26:11 +00001766}
Owen Andersonbaf3c402009-07-29 18:55:55 +00001767
Chris Lattnereaf79802011-07-09 18:23:52 +00001768Constant *ConstantExpr::getCompare(unsigned short Predicate,
1769 Constant *C1, Constant *C2) {
Reid Spencer67263fe2006-12-04 21:35:24 +00001770 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001771
Chris Lattnereaf79802011-07-09 18:23:52 +00001772 switch (Predicate) {
1773 default: llvm_unreachable("Invalid CmpInst predicate");
1774 case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
1775 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
1776 case CmpInst::FCMP_ONE: case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
1777 case CmpInst::FCMP_UEQ: case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
1778 case CmpInst::FCMP_ULT: case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
1779 case CmpInst::FCMP_TRUE:
1780 return getFCmp(Predicate, C1, C2);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001781
Chris Lattnereaf79802011-07-09 18:23:52 +00001782 case CmpInst::ICMP_EQ: case CmpInst::ICMP_NE: case CmpInst::ICMP_UGT:
1783 case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
1784 case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
1785 case CmpInst::ICMP_SLE:
1786 return getICmp(Predicate, C1, C2);
1787 }
Chris Lattnerc3d12f02004-08-04 18:50:09 +00001788}
1789
Chris Lattnereaf79802011-07-09 18:23:52 +00001790Constant *ConstantExpr::getSelect(Constant *C, Constant *V1, Constant *V2) {
Chris Lattner9ace0cd2008-12-29 00:16:12 +00001791 assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
Chris Lattner08a45cc2004-03-12 05:54:04 +00001792
Chris Lattnereaf79802011-07-09 18:23:52 +00001793 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1794 return SC; // Fold common cases
Chris Lattner08a45cc2004-03-12 05:54:04 +00001795
1796 std::vector<Constant*> argVec(3, C);
1797 argVec[1] = V1;
1798 argVec[2] = V2;
Reid Spencer077d0eb2006-12-04 05:19:50 +00001799 ExprMapKeyType Key(Instruction::Select, argVec);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001800
Chris Lattnereaf79802011-07-09 18:23:52 +00001801 LLVMContextImpl *pImpl = C->getContext().pImpl;
1802 return pImpl->ExprConstants.getOrCreate(V1->getType(), Key);
Chris Lattner08a45cc2004-03-12 05:54:04 +00001803}
1804
Jay Foaddab3d292011-07-21 14:31:17 +00001805Constant *ConstantExpr::getGetElementPtr(Constant *C, ArrayRef<Value *> Idxs,
1806 bool InBounds) {
Duncan Sands2333e292012-11-13 12:59:33 +00001807 assert(C->getType()->isPtrOrPtrVectorTy() &&
1808 "Non-pointer type for constant GetElementPtr expression");
1809
Jay Foaddab3d292011-07-21 14:31:17 +00001810 if (Constant *FC = ConstantFoldGetElementPtr(C, InBounds, Idxs))
Chris Lattner1f78d512011-02-11 05:34:33 +00001811 return FC; // Fold a few common cases.
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001812
Chris Lattnereaf79802011-07-09 18:23:52 +00001813 // Get the result type of the getelementptr!
Jay Foada9203102011-07-25 09:48:08 +00001814 Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), Idxs);
Chris Lattnereaf79802011-07-09 18:23:52 +00001815 assert(Ty && "GEP indices invalid!");
Chris Lattner230cdab2012-01-26 00:42:34 +00001816 unsigned AS = C->getType()->getPointerAddressSpace();
Chris Lattnereaf79802011-07-09 18:23:52 +00001817 Type *ReqTy = Ty->getPointerTo(AS);
Duncan Sands2333e292012-11-13 12:59:33 +00001818 if (VectorType *VecTy = dyn_cast<VectorType>(C->getType()))
1819 ReqTy = VectorType::get(ReqTy, VecTy->getNumElements());
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001820
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001821 // Look up the constant in the table first to ensure uniqueness
1822 std::vector<Constant*> ArgVec;
Jay Foaddab3d292011-07-21 14:31:17 +00001823 ArgVec.reserve(1 + Idxs.size());
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001824 ArgVec.push_back(C);
Duncan Sands2333e292012-11-13 12:59:33 +00001825 for (unsigned i = 0, e = Idxs.size(); i != e; ++i) {
1826 assert(Idxs[i]->getType()->isVectorTy() == ReqTy->isVectorTy() &&
1827 "getelementptr index type missmatch");
1828 assert((!Idxs[i]->getType()->isVectorTy() ||
1829 ReqTy->getVectorNumElements() ==
1830 Idxs[i]->getType()->getVectorNumElements()) &&
1831 "getelementptr index type missmatch");
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001832 ArgVec.push_back(cast<Constant>(Idxs[i]));
Duncan Sands2333e292012-11-13 12:59:33 +00001833 }
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001834 const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec, 0,
Chris Lattner1f78d512011-02-11 05:34:33 +00001835 InBounds ? GEPOperator::IsInBounds : 0);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001836
Chris Lattnereaf79802011-07-09 18:23:52 +00001837 LLVMContextImpl *pImpl = C->getContext().pImpl;
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001838 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1839}
1840
Reid Spencer077d0eb2006-12-04 05:19:50 +00001841Constant *
Nick Lewycky401f3252010-01-21 07:03:21 +00001842ConstantExpr::getICmp(unsigned short pred, Constant *LHS, Constant *RHS) {
Reid Spencer077d0eb2006-12-04 05:19:50 +00001843 assert(LHS->getType() == RHS->getType());
1844 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
1845 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
1846
Chris Lattnerb29d5962010-02-01 20:48:08 +00001847 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
Reid Spencer077d0eb2006-12-04 05:19:50 +00001848 return FC; // Fold a few common cases...
1849
1850 // Look up the constant in the table first to ensure uniqueness
1851 std::vector<Constant*> ArgVec;
1852 ArgVec.push_back(LHS);
1853 ArgVec.push_back(RHS);
Reid Spencer4fa021a2006-12-24 18:42:29 +00001854 // Get the key type with both the opcode and predicate
Reid Spencer077d0eb2006-12-04 05:19:50 +00001855 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
Owen Anderson31c36f02009-06-17 20:10:08 +00001856
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001857 Type *ResultTy = Type::getInt1Ty(LHS->getContext());
1858 if (VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
Nick Lewycky401f3252010-01-21 07:03:21 +00001859 ResultTy = VectorType::get(ResultTy, VT->getNumElements());
1860
Owen Andersond03eecd2009-08-04 20:25:11 +00001861 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
Nick Lewycky401f3252010-01-21 07:03:21 +00001862 return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
Reid Spencer077d0eb2006-12-04 05:19:50 +00001863}
1864
1865Constant *
Nick Lewycky401f3252010-01-21 07:03:21 +00001866ConstantExpr::getFCmp(unsigned short pred, Constant *LHS, Constant *RHS) {
Reid Spencer077d0eb2006-12-04 05:19:50 +00001867 assert(LHS->getType() == RHS->getType());
1868 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
1869
Chris Lattnerb29d5962010-02-01 20:48:08 +00001870 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
Reid Spencer077d0eb2006-12-04 05:19:50 +00001871 return FC; // Fold a few common cases...
1872
1873 // Look up the constant in the table first to ensure uniqueness
1874 std::vector<Constant*> ArgVec;
1875 ArgVec.push_back(LHS);
1876 ArgVec.push_back(RHS);
Reid Spencer4fa021a2006-12-24 18:42:29 +00001877 // Get the key type with both the opcode and predicate
Reid Spencer077d0eb2006-12-04 05:19:50 +00001878 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
Nick Lewycky401f3252010-01-21 07:03:21 +00001879
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001880 Type *ResultTy = Type::getInt1Ty(LHS->getContext());
1881 if (VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
Nick Lewycky401f3252010-01-21 07:03:21 +00001882 ResultTy = VectorType::get(ResultTy, VT->getNumElements());
1883
Owen Andersond03eecd2009-08-04 20:25:11 +00001884 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
Nick Lewycky401f3252010-01-21 07:03:21 +00001885 return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
Reid Spencer077d0eb2006-12-04 05:19:50 +00001886}
1887
Robert Bocchinob52ee7f2006-01-10 19:05:34 +00001888Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
Duncan Sands1df98592010-02-16 11:11:14 +00001889 assert(Val->getType()->isVectorTy() &&
Reid Spencerac9dcb92007-02-15 03:39:18 +00001890 "Tried to create extractelement operation on non-vector type!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001891 assert(Idx->getType()->isIntegerTy(32) &&
Reid Spencer3d10b0b2007-01-26 07:37:34 +00001892 "Extractelement index must be i32 type!");
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001893
Chris Lattnereaf79802011-07-09 18:23:52 +00001894 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
Chris Lattner83738a22009-12-30 20:25:09 +00001895 return FC; // Fold a few common cases.
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001896
Robert Bocchinoc152f9c2006-01-17 20:07:22 +00001897 // Look up the constant in the table first to ensure uniqueness
1898 std::vector<Constant*> ArgVec(1, Val);
Robert Bocchinoc152f9c2006-01-17 20:07:22 +00001899 ArgVec.push_back(Idx);
Chris Lattnereaf79802011-07-09 18:23:52 +00001900 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001901
Chris Lattnereaf79802011-07-09 18:23:52 +00001902 LLVMContextImpl *pImpl = Val->getContext().pImpl;
Chris Lattner230cdab2012-01-26 00:42:34 +00001903 Type *ReqTy = Val->getType()->getVectorElementType();
Owen Andersond03eecd2009-08-04 20:25:11 +00001904 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
Robert Bocchinoc152f9c2006-01-17 20:07:22 +00001905}
1906
1907Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
1908 Constant *Idx) {
Duncan Sands1df98592010-02-16 11:11:14 +00001909 assert(Val->getType()->isVectorTy() &&
Reid Spencerac9dcb92007-02-15 03:39:18 +00001910 "Tried to create insertelement operation on non-vector type!");
Chris Lattner230cdab2012-01-26 00:42:34 +00001911 assert(Elt->getType() == Val->getType()->getVectorElementType() &&
1912 "Insertelement types must match!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001913 assert(Idx->getType()->isIntegerTy(32) &&
Reid Spencer3d10b0b2007-01-26 07:37:34 +00001914 "Insertelement index must be i32 type!");
Robert Bocchinoc152f9c2006-01-17 20:07:22 +00001915
Chris Lattnereaf79802011-07-09 18:23:52 +00001916 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
1917 return FC; // Fold a few common cases.
Chris Lattner00f10232006-04-08 01:18:18 +00001918 // Look up the constant in the table first to ensure uniqueness
Chris Lattnereaf79802011-07-09 18:23:52 +00001919 std::vector<Constant*> ArgVec(1, Val);
1920 ArgVec.push_back(Elt);
1921 ArgVec.push_back(Idx);
1922 const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001923
Chris Lattnereaf79802011-07-09 18:23:52 +00001924 LLVMContextImpl *pImpl = Val->getContext().pImpl;
1925 return pImpl->ExprConstants.getOrCreate(Val->getType(), Key);
Chris Lattner00f10232006-04-08 01:18:18 +00001926}
1927
1928Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
1929 Constant *Mask) {
1930 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
1931 "Invalid shuffle vector constant expr operands!");
Nate Begeman0f123cf2009-02-12 21:28:33 +00001932
Chris Lattnereaf79802011-07-09 18:23:52 +00001933 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
1934 return FC; // Fold a few common cases.
1935
Chris Lattner230cdab2012-01-26 00:42:34 +00001936 unsigned NElts = Mask->getType()->getVectorNumElements();
1937 Type *EltTy = V1->getType()->getVectorElementType();
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001938 Type *ShufTy = VectorType::get(EltTy, NElts);
Chris Lattnereaf79802011-07-09 18:23:52 +00001939
1940 // Look up the constant in the table first to ensure uniqueness
1941 std::vector<Constant*> ArgVec(1, V1);
1942 ArgVec.push_back(V2);
1943 ArgVec.push_back(Mask);
1944 const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001945
Chris Lattnereaf79802011-07-09 18:23:52 +00001946 LLVMContextImpl *pImpl = ShufTy->getContext().pImpl;
1947 return pImpl->ExprConstants.getOrCreate(ShufTy, Key);
Chris Lattner00f10232006-04-08 01:18:18 +00001948}
1949
Chris Lattnereaf79802011-07-09 18:23:52 +00001950Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
Jay Foadfc6d3a42011-07-13 10:26:04 +00001951 ArrayRef<unsigned> Idxs) {
1952 assert(ExtractValueInst::getIndexedType(Agg->getType(),
1953 Idxs) == Val->getType() &&
Dan Gohman041e2eb2008-05-15 19:50:34 +00001954 "insertvalue indices invalid!");
Dan Gohmane4569942008-05-23 00:36:11 +00001955 assert(Agg->getType()->isFirstClassType() &&
Chris Lattner4e47aad2011-07-12 05:26:21 +00001956 "Non-first-class type for constant insertvalue expression");
Jay Foadfc6d3a42011-07-13 10:26:04 +00001957 Constant *FC = ConstantFoldInsertValueInstruction(Agg, Val, Idxs);
Chris Lattner4e47aad2011-07-12 05:26:21 +00001958 assert(FC && "insertvalue constant expr couldn't be folded!");
Dan Gohmane0891602008-07-21 23:30:30 +00001959 return FC;
Dan Gohman041e2eb2008-05-15 19:50:34 +00001960}
1961
Chris Lattnereaf79802011-07-09 18:23:52 +00001962Constant *ConstantExpr::getExtractValue(Constant *Agg,
Jay Foadfc6d3a42011-07-13 10:26:04 +00001963 ArrayRef<unsigned> Idxs) {
Dan Gohmane4569942008-05-23 00:36:11 +00001964 assert(Agg->getType()->isFirstClassType() &&
Chris Lattnereaf79802011-07-09 18:23:52 +00001965 "Tried to create extractelement operation on non-first-class type!");
Dan Gohman041e2eb2008-05-15 19:50:34 +00001966
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001967 Type *ReqTy = ExtractValueInst::getIndexedType(Agg->getType(), Idxs);
Chandler Carruthdc770fc2011-07-10 09:45:35 +00001968 (void)ReqTy;
Chris Lattnereaf79802011-07-09 18:23:52 +00001969 assert(ReqTy && "extractvalue indices invalid!");
Galina Kistanovaa46517e2012-07-13 01:25:27 +00001970
Dan Gohmane4569942008-05-23 00:36:11 +00001971 assert(Agg->getType()->isFirstClassType() &&
1972 "Non-first-class type for constant extractvalue expression");
Jay Foadfc6d3a42011-07-13 10:26:04 +00001973 Constant *FC = ConstantFoldExtractValueInstruction(Agg, Idxs);
Dan Gohmane0891602008-07-21 23:30:30 +00001974 assert(FC && "ExtractValue constant expr couldn't be folded!");
1975 return FC;
Dan Gohman041e2eb2008-05-15 19:50:34 +00001976}
1977
Chris Lattner81baf142011-02-10 07:01:55 +00001978Constant *ConstantExpr::getNeg(Constant *C, bool HasNUW, bool HasNSW) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001979 assert(C->getType()->isIntOrIntVectorTy() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00001980 "Cannot NEG a nonintegral value!");
Chris Lattner81baf142011-02-10 07:01:55 +00001981 return getSub(ConstantFP::getZeroValueForNegation(C->getType()),
1982 C, HasNUW, HasNSW);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001983}
1984
Chris Lattnerf067d582011-02-07 16:40:21 +00001985Constant *ConstantExpr::getFNeg(Constant *C) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001986 assert(C->getType()->isFPOrFPVectorTy() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00001987 "Cannot FNEG a non-floating-point value!");
Chris Lattner81baf142011-02-10 07:01:55 +00001988 return getFSub(ConstantFP::getZeroValueForNegation(C->getType()), C);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001989}
1990
Chris Lattnerf067d582011-02-07 16:40:21 +00001991Constant *ConstantExpr::getNot(Constant *C) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001992 assert(C->getType()->isIntOrIntVectorTy() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00001993 "Cannot NOT a nonintegral value!");
Owen Andersona7235ea2009-07-31 20:28:14 +00001994 return get(Instruction::Xor, C, Constant::getAllOnesValue(C->getType()));
Owen Andersonbaf3c402009-07-29 18:55:55 +00001995}
1996
Chris Lattner81baf142011-02-10 07:01:55 +00001997Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2,
1998 bool HasNUW, bool HasNSW) {
1999 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2000 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2001 return get(Instruction::Add, C1, C2, Flags);
Owen Andersonbaf3c402009-07-29 18:55:55 +00002002}
2003
Chris Lattnerf067d582011-02-07 16:40:21 +00002004Constant *ConstantExpr::getFAdd(Constant *C1, Constant *C2) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002005 return get(Instruction::FAdd, C1, C2);
2006}
2007
Chris Lattner81baf142011-02-10 07:01:55 +00002008Constant *ConstantExpr::getSub(Constant *C1, Constant *C2,
2009 bool HasNUW, bool HasNSW) {
2010 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2011 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2012 return get(Instruction::Sub, C1, C2, Flags);
Owen Andersonbaf3c402009-07-29 18:55:55 +00002013}
2014
Chris Lattnerf067d582011-02-07 16:40:21 +00002015Constant *ConstantExpr::getFSub(Constant *C1, Constant *C2) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002016 return get(Instruction::FSub, C1, C2);
2017}
2018
Chris Lattner81baf142011-02-10 07:01:55 +00002019Constant *ConstantExpr::getMul(Constant *C1, Constant *C2,
2020 bool HasNUW, bool HasNSW) {
2021 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2022 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2023 return get(Instruction::Mul, C1, C2, Flags);
Owen Andersonbaf3c402009-07-29 18:55:55 +00002024}
2025
Chris Lattnerf067d582011-02-07 16:40:21 +00002026Constant *ConstantExpr::getFMul(Constant *C1, Constant *C2) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002027 return get(Instruction::FMul, C1, C2);
2028}
2029
Chris Lattner74f5c5a2011-02-09 16:43:07 +00002030Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2, bool isExact) {
2031 return get(Instruction::UDiv, C1, C2,
2032 isExact ? PossiblyExactOperator::IsExact : 0);
Owen Andersonbaf3c402009-07-29 18:55:55 +00002033}
2034
Chris Lattner74f5c5a2011-02-09 16:43:07 +00002035Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2, bool isExact) {
2036 return get(Instruction::SDiv, C1, C2,
2037 isExact ? PossiblyExactOperator::IsExact : 0);
Owen Andersonbaf3c402009-07-29 18:55:55 +00002038}
2039
Chris Lattnerf067d582011-02-07 16:40:21 +00002040Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002041 return get(Instruction::FDiv, C1, C2);
2042}
2043
Chris Lattnerf067d582011-02-07 16:40:21 +00002044Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002045 return get(Instruction::URem, C1, C2);
2046}
2047
Chris Lattnerf067d582011-02-07 16:40:21 +00002048Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002049 return get(Instruction::SRem, C1, C2);
2050}
2051
Chris Lattnerf067d582011-02-07 16:40:21 +00002052Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002053 return get(Instruction::FRem, C1, C2);
2054}
2055
Chris Lattnerf067d582011-02-07 16:40:21 +00002056Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002057 return get(Instruction::And, C1, C2);
2058}
2059
Chris Lattnerf067d582011-02-07 16:40:21 +00002060Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002061 return get(Instruction::Or, C1, C2);
2062}
2063
Chris Lattnerf067d582011-02-07 16:40:21 +00002064Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002065 return get(Instruction::Xor, C1, C2);
2066}
2067
Chris Lattner81baf142011-02-10 07:01:55 +00002068Constant *ConstantExpr::getShl(Constant *C1, Constant *C2,
2069 bool HasNUW, bool HasNSW) {
2070 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2071 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2072 return get(Instruction::Shl, C1, C2, Flags);
Owen Andersonbaf3c402009-07-29 18:55:55 +00002073}
2074
Chris Lattner74f5c5a2011-02-09 16:43:07 +00002075Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2, bool isExact) {
2076 return get(Instruction::LShr, C1, C2,
2077 isExact ? PossiblyExactOperator::IsExact : 0);
Owen Andersonbaf3c402009-07-29 18:55:55 +00002078}
2079
Chris Lattner74f5c5a2011-02-09 16:43:07 +00002080Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2, bool isExact) {
2081 return get(Instruction::AShr, C1, C2,
2082 isExact ? PossiblyExactOperator::IsExact : 0);
Owen Andersonbaf3c402009-07-29 18:55:55 +00002083}
2084
Duncan Sandsc038a782012-06-12 14:33:56 +00002085/// getBinOpIdentity - Return the identity for the given binary operation,
2086/// i.e. a constant C such that X op C = X and C op X = X for every X. It
Duncan Sandsee5a0942012-06-13 09:42:13 +00002087/// returns null if the operator doesn't have an identity.
Duncan Sandsc038a782012-06-12 14:33:56 +00002088Constant *ConstantExpr::getBinOpIdentity(unsigned Opcode, Type *Ty) {
2089 switch (Opcode) {
2090 default:
Duncan Sandsee5a0942012-06-13 09:42:13 +00002091 // Doesn't have an identity.
2092 return 0;
2093
Duncan Sandsc038a782012-06-12 14:33:56 +00002094 case Instruction::Add:
2095 case Instruction::Or:
2096 case Instruction::Xor:
2097 return Constant::getNullValue(Ty);
2098
2099 case Instruction::Mul:
2100 return ConstantInt::get(Ty, 1);
2101
2102 case Instruction::And:
2103 return Constant::getAllOnesValue(Ty);
2104 }
2105}
2106
Duncan Sandsee5a0942012-06-13 09:42:13 +00002107/// getBinOpAbsorber - Return the absorbing element for the given binary
2108/// operation, i.e. a constant C such that X op C = C and C op X = C for
2109/// every X. For example, this returns zero for integer multiplication.
2110/// It returns null if the operator doesn't have an absorbing element.
2111Constant *ConstantExpr::getBinOpAbsorber(unsigned Opcode, Type *Ty) {
2112 switch (Opcode) {
2113 default:
2114 // Doesn't have an absorber.
2115 return 0;
2116
2117 case Instruction::Or:
2118 return Constant::getAllOnesValue(Ty);
2119
2120 case Instruction::And:
2121 case Instruction::Mul:
2122 return Constant::getNullValue(Ty);
2123 }
2124}
2125
Vikram S. Adved0b1bb02002-07-15 18:19:33 +00002126// destroyConstant - Remove the constant from the constant table...
2127//
Owen Anderson04fb7c32009-06-20 00:24:58 +00002128void ConstantExpr::destroyConstant() {
Chris Lattner1afcace2011-07-09 17:41:24 +00002129 getType()->getContext().pImpl->ExprConstants.remove(this);
Vikram S. Adved0b1bb02002-07-15 18:19:33 +00002130 destroyConstantImpl();
Vikram S. Adve345e0cf2002-07-14 23:13:17 +00002131}
2132
Chris Lattnerc188eeb2002-07-30 18:54:25 +00002133const char *ConstantExpr::getOpcodeName() const {
2134 return Instruction::getOpcodeName(getOpcode());
Vikram S. Adve345e0cf2002-07-14 23:13:17 +00002135}
Reid Spencer1c9c8e62004-07-17 23:48:33 +00002136
Chris Lattner04e3b1e2010-03-30 20:48:48 +00002137
2138
2139GetElementPtrConstantExpr::
Chris Lattnera7c69882012-01-26 20:40:56 +00002140GetElementPtrConstantExpr(Constant *C, ArrayRef<Constant*> IdxList,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002141 Type *DestTy)
Chris Lattner04e3b1e2010-03-30 20:48:48 +00002142 : ConstantExpr(DestTy, Instruction::GetElementPtr,
2143 OperandTraits<GetElementPtrConstantExpr>::op_end(this)
2144 - (IdxList.size()+1), IdxList.size()+1) {
2145 OperandList[0] = C;
2146 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
2147 OperandList[i+1] = IdxList[i];
2148}
2149
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002150//===----------------------------------------------------------------------===//
2151// ConstantData* implementations
2152
2153void ConstantDataArray::anchor() {}
2154void ConstantDataVector::anchor() {}
2155
Chris Lattner45bb5c52012-01-24 04:43:41 +00002156/// getElementType - Return the element type of the array/vector.
2157Type *ConstantDataSequential::getElementType() const {
2158 return getType()->getElementType();
2159}
2160
Chris Lattner9e631da2012-01-24 09:31:43 +00002161StringRef ConstantDataSequential::getRawDataValues() const {
Chris Lattner1ee0ecf2012-01-24 13:41:11 +00002162 return StringRef(DataElements, getNumElements()*getElementByteSize());
Chris Lattner9e631da2012-01-24 09:31:43 +00002163}
2164
Chris Lattnerff2b7f32012-01-24 05:42:11 +00002165/// isElementTypeCompatible - Return true if a ConstantDataSequential can be
2166/// formed with a vector or array of the specified element type.
2167/// ConstantDataArray only works with normal float and int types that are
2168/// stored densely in memory, not with things like i42 or x86_f80.
2169bool ConstantDataSequential::isElementTypeCompatible(const Type *Ty) {
Chris Lattner45bb5c52012-01-24 04:43:41 +00002170 if (Ty->isFloatTy() || Ty->isDoubleTy()) return true;
2171 if (const IntegerType *IT = dyn_cast<IntegerType>(Ty)) {
2172 switch (IT->getBitWidth()) {
2173 case 8:
2174 case 16:
2175 case 32:
2176 case 64:
2177 return true;
2178 default: break;
2179 }
2180 }
2181 return false;
2182}
2183
Chris Lattner1ee0ecf2012-01-24 13:41:11 +00002184/// getNumElements - Return the number of elements in the array or vector.
2185unsigned ConstantDataSequential::getNumElements() const {
Chris Lattneraf7b4fb2012-01-25 01:32:59 +00002186 if (ArrayType *AT = dyn_cast<ArrayType>(getType()))
2187 return AT->getNumElements();
Chris Lattner230cdab2012-01-26 00:42:34 +00002188 return getType()->getVectorNumElements();
Chris Lattner1ee0ecf2012-01-24 13:41:11 +00002189}
2190
2191
Chris Lattner45bb5c52012-01-24 04:43:41 +00002192/// getElementByteSize - Return the size in bytes of the elements in the data.
2193uint64_t ConstantDataSequential::getElementByteSize() const {
2194 return getElementType()->getPrimitiveSizeInBits()/8;
2195}
2196
2197/// getElementPointer - Return the start of the specified element.
2198const char *ConstantDataSequential::getElementPointer(unsigned Elt) const {
Chris Lattner1ee0ecf2012-01-24 13:41:11 +00002199 assert(Elt < getNumElements() && "Invalid Elt");
Chris Lattner45bb5c52012-01-24 04:43:41 +00002200 return DataElements+Elt*getElementByteSize();
2201}
2202
2203
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002204/// isAllZeros - return true if the array is empty or all zeros.
2205static bool isAllZeros(StringRef Arr) {
2206 for (StringRef::iterator I = Arr.begin(), E = Arr.end(); I != E; ++I)
2207 if (*I != 0)
2208 return false;
2209 return true;
2210}
Chris Lattnerff2b7f32012-01-24 05:42:11 +00002211
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002212/// getImpl - This is the underlying implementation of all of the
2213/// ConstantDataSequential::get methods. They all thunk down to here, providing
Chris Lattner8cf27ef2012-01-30 18:19:30 +00002214/// the correct element type. We take the bytes in as a StringRef because
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002215/// we *want* an underlying "char*" to avoid TBAA type punning violations.
2216Constant *ConstantDataSequential::getImpl(StringRef Elements, Type *Ty) {
Chris Lattner230cdab2012-01-26 00:42:34 +00002217 assert(isElementTypeCompatible(Ty->getSequentialElementType()));
Chris Lattner29cc6cb2012-01-24 14:17:05 +00002218 // If the elements are all zero or there are no elements, return a CAZ, which
2219 // is more dense and canonical.
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002220 if (isAllZeros(Elements))
2221 return ConstantAggregateZero::get(Ty);
2222
2223 // Do a lookup to see if we have already formed one of these.
2224 StringMap<ConstantDataSequential*>::MapEntryTy &Slot =
2225 Ty->getContext().pImpl->CDSConstants.GetOrCreateValue(Elements);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002226
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002227 // The bucket can point to a linked list of different CDS's that have the same
2228 // body but different types. For example, 0,0,0,1 could be a 4 element array
2229 // of i8, or a 1-element array of i32. They'll both end up in the same
2230 /// StringMap bucket, linked up by their Next pointers. Walk the list.
2231 ConstantDataSequential **Entry = &Slot.getValue();
2232 for (ConstantDataSequential *Node = *Entry; Node != 0;
2233 Entry = &Node->Next, Node = *Entry)
2234 if (Node->getType() == Ty)
2235 return Node;
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002236
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002237 // Okay, we didn't get a hit. Create a node of the right class, link it in,
2238 // and return it.
2239 if (isa<ArrayType>(Ty))
2240 return *Entry = new ConstantDataArray(Ty, Slot.getKeyData());
2241
2242 assert(isa<VectorType>(Ty));
2243 return *Entry = new ConstantDataVector(Ty, Slot.getKeyData());
2244}
2245
2246void ConstantDataSequential::destroyConstant() {
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002247 // Remove the constant from the StringMap.
2248 StringMap<ConstantDataSequential*> &CDSConstants =
2249 getType()->getContext().pImpl->CDSConstants;
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002250
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002251 StringMap<ConstantDataSequential*>::iterator Slot =
Chris Lattner9e631da2012-01-24 09:31:43 +00002252 CDSConstants.find(getRawDataValues());
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002253
2254 assert(Slot != CDSConstants.end() && "CDS not found in uniquing table");
2255
2256 ConstantDataSequential **Entry = &Slot->getValue();
2257
2258 // Remove the entry from the hash table.
2259 if ((*Entry)->Next == 0) {
2260 // If there is only one value in the bucket (common case) it must be this
2261 // entry, and removing the entry should remove the bucket completely.
2262 assert((*Entry) == this && "Hash mismatch in ConstantDataSequential");
2263 getContext().pImpl->CDSConstants.erase(Slot);
2264 } else {
2265 // Otherwise, there are multiple entries linked off the bucket, unlink the
2266 // node we care about but keep the bucket around.
2267 for (ConstantDataSequential *Node = *Entry; ;
2268 Entry = &Node->Next, Node = *Entry) {
2269 assert(Node && "Didn't find entry in its uniquing hash table!");
2270 // If we found our entry, unlink it from the list and we're done.
2271 if (Node == this) {
2272 *Entry = Node->Next;
2273 break;
2274 }
2275 }
2276 }
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002277
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002278 // If we were part of a list, make sure that we don't delete the list that is
2279 // still owned by the uniquing map.
2280 Next = 0;
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002281
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002282 // Finally, actually delete it.
2283 destroyConstantImpl();
2284}
2285
2286/// get() constructors - Return a constant with array type with an element
2287/// count and element type matching the ArrayRef passed in. Note that this
2288/// can return a ConstantAggregateZero object.
Chris Lattner32100602012-01-24 14:04:40 +00002289Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint8_t> Elts) {
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002290 Type *Ty = ArrayType::get(Type::getInt8Ty(Context), Elts.size());
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002291 const char *Data = reinterpret_cast<const char *>(Elts.data());
2292 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*1), Ty);
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002293}
Chris Lattner32100602012-01-24 14:04:40 +00002294Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint16_t> Elts){
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002295 Type *Ty = ArrayType::get(Type::getInt16Ty(Context), Elts.size());
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002296 const char *Data = reinterpret_cast<const char *>(Elts.data());
2297 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*2), Ty);
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002298}
Chris Lattner32100602012-01-24 14:04:40 +00002299Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint32_t> Elts){
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002300 Type *Ty = ArrayType::get(Type::getInt32Ty(Context), Elts.size());
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002301 const char *Data = reinterpret_cast<const char *>(Elts.data());
2302 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*4), Ty);
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002303}
Chris Lattner32100602012-01-24 14:04:40 +00002304Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint64_t> Elts){
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002305 Type *Ty = ArrayType::get(Type::getInt64Ty(Context), Elts.size());
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002306 const char *Data = reinterpret_cast<const char *>(Elts.data());
2307 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*8), Ty);
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002308}
Chris Lattner32100602012-01-24 14:04:40 +00002309Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<float> Elts) {
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002310 Type *Ty = ArrayType::get(Type::getFloatTy(Context), Elts.size());
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002311 const char *Data = reinterpret_cast<const char *>(Elts.data());
2312 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*4), Ty);
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002313}
Chris Lattner32100602012-01-24 14:04:40 +00002314Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<double> Elts) {
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002315 Type *Ty = ArrayType::get(Type::getDoubleTy(Context), Elts.size());
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002316 const char *Data = reinterpret_cast<const char *>(Elts.data());
2317 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*8), Ty);
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002318}
2319
Chris Lattner32100602012-01-24 14:04:40 +00002320/// getString - This method constructs a CDS and initializes it with a text
2321/// string. The default behavior (AddNull==true) causes a null terminator to
2322/// be placed at the end of the array (increasing the length of the string by
2323/// one more than the StringRef would normally indicate. Pass AddNull=false
2324/// to disable this behavior.
2325Constant *ConstantDataArray::getString(LLVMContext &Context,
2326 StringRef Str, bool AddNull) {
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002327 if (!AddNull) {
2328 const uint8_t *Data = reinterpret_cast<const uint8_t *>(Str.data());
2329 return get(Context, ArrayRef<uint8_t>(const_cast<uint8_t *>(Data),
2330 Str.size()));
2331 }
2332
Chris Lattner32100602012-01-24 14:04:40 +00002333 SmallVector<uint8_t, 64> ElementVals;
2334 ElementVals.append(Str.begin(), Str.end());
2335 ElementVals.push_back(0);
2336 return get(Context, ElementVals);
2337}
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002338
2339/// get() constructors - Return a constant with vector type with an element
2340/// count and element type matching the ArrayRef passed in. Note that this
2341/// can return a ConstantAggregateZero object.
Chris Lattner32100602012-01-24 14:04:40 +00002342Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint8_t> Elts){
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002343 Type *Ty = VectorType::get(Type::getInt8Ty(Context), Elts.size());
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002344 const char *Data = reinterpret_cast<const char *>(Elts.data());
2345 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*1), Ty);
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002346}
Chris Lattner32100602012-01-24 14:04:40 +00002347Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint16_t> Elts){
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002348 Type *Ty = VectorType::get(Type::getInt16Ty(Context), Elts.size());
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002349 const char *Data = reinterpret_cast<const char *>(Elts.data());
2350 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*2), Ty);
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002351}
Chris Lattner32100602012-01-24 14:04:40 +00002352Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint32_t> Elts){
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002353 Type *Ty = VectorType::get(Type::getInt32Ty(Context), Elts.size());
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002354 const char *Data = reinterpret_cast<const char *>(Elts.data());
2355 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*4), Ty);
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002356}
Chris Lattner32100602012-01-24 14:04:40 +00002357Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint64_t> Elts){
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002358 Type *Ty = VectorType::get(Type::getInt64Ty(Context), Elts.size());
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002359 const char *Data = reinterpret_cast<const char *>(Elts.data());
2360 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*8), Ty);
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002361}
Chris Lattner32100602012-01-24 14:04:40 +00002362Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<float> Elts) {
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002363 Type *Ty = VectorType::get(Type::getFloatTy(Context), Elts.size());
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002364 const char *Data = reinterpret_cast<const char *>(Elts.data());
2365 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*4), Ty);
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002366}
Chris Lattner32100602012-01-24 14:04:40 +00002367Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<double> Elts) {
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002368 Type *Ty = VectorType::get(Type::getDoubleTy(Context), Elts.size());
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002369 const char *Data = reinterpret_cast<const char *>(Elts.data());
2370 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*8), Ty);
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002371}
2372
Chris Lattner3c2c9542012-01-25 05:19:54 +00002373Constant *ConstantDataVector::getSplat(unsigned NumElts, Constant *V) {
2374 assert(isElementTypeCompatible(V->getType()) &&
2375 "Element type not compatible with ConstantData");
2376 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
2377 if (CI->getType()->isIntegerTy(8)) {
2378 SmallVector<uint8_t, 16> Elts(NumElts, CI->getZExtValue());
2379 return get(V->getContext(), Elts);
2380 }
2381 if (CI->getType()->isIntegerTy(16)) {
2382 SmallVector<uint16_t, 16> Elts(NumElts, CI->getZExtValue());
2383 return get(V->getContext(), Elts);
2384 }
2385 if (CI->getType()->isIntegerTy(32)) {
2386 SmallVector<uint32_t, 16> Elts(NumElts, CI->getZExtValue());
2387 return get(V->getContext(), Elts);
2388 }
2389 assert(CI->getType()->isIntegerTy(64) && "Unsupported ConstantData type");
2390 SmallVector<uint64_t, 16> Elts(NumElts, CI->getZExtValue());
2391 return get(V->getContext(), Elts);
2392 }
2393
Chris Lattner36c744f2012-01-30 06:21:21 +00002394 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
2395 if (CFP->getType()->isFloatTy()) {
2396 SmallVector<float, 16> Elts(NumElts, CFP->getValueAPF().convertToFloat());
2397 return get(V->getContext(), Elts);
2398 }
2399 if (CFP->getType()->isDoubleTy()) {
2400 SmallVector<double, 16> Elts(NumElts,
2401 CFP->getValueAPF().convertToDouble());
2402 return get(V->getContext(), Elts);
2403 }
Chris Lattner3c2c9542012-01-25 05:19:54 +00002404 }
Chris Lattner36c744f2012-01-30 06:21:21 +00002405 return ConstantVector::getSplat(NumElts, V);
Chris Lattner3c2c9542012-01-25 05:19:54 +00002406}
2407
2408
Chris Lattner45bb5c52012-01-24 04:43:41 +00002409/// getElementAsInteger - If this is a sequential container of integers (of
2410/// any size), return the specified element in the low bits of a uint64_t.
2411uint64_t ConstantDataSequential::getElementAsInteger(unsigned Elt) const {
2412 assert(isa<IntegerType>(getElementType()) &&
2413 "Accessor can only be used when element is an integer");
2414 const char *EltPtr = getElementPointer(Elt);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002415
Chris Lattner45bb5c52012-01-24 04:43:41 +00002416 // The data is stored in host byte order, make sure to cast back to the right
2417 // type to load with the right endianness.
Chris Lattner230cdab2012-01-26 00:42:34 +00002418 switch (getElementType()->getIntegerBitWidth()) {
Craig Topper50bee422012-02-05 22:14:15 +00002419 default: llvm_unreachable("Invalid bitwidth for CDS");
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002420 case 8:
2421 return *const_cast<uint8_t *>(reinterpret_cast<const uint8_t *>(EltPtr));
2422 case 16:
2423 return *const_cast<uint16_t *>(reinterpret_cast<const uint16_t *>(EltPtr));
2424 case 32:
2425 return *const_cast<uint32_t *>(reinterpret_cast<const uint32_t *>(EltPtr));
2426 case 64:
2427 return *const_cast<uint64_t *>(reinterpret_cast<const uint64_t *>(EltPtr));
Chris Lattner45bb5c52012-01-24 04:43:41 +00002428 }
2429}
2430
2431/// getElementAsAPFloat - If this is a sequential container of floating point
2432/// type, return the specified element as an APFloat.
2433APFloat ConstantDataSequential::getElementAsAPFloat(unsigned Elt) const {
2434 const char *EltPtr = getElementPointer(Elt);
2435
2436 switch (getElementType()->getTypeID()) {
Nick Lewycky1486ae62012-01-25 03:20:12 +00002437 default:
Craig Topper50bee422012-02-05 22:14:15 +00002438 llvm_unreachable("Accessor can only be used when element is float/double!");
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002439 case Type::FloatTyID: {
2440 const float *FloatPrt = reinterpret_cast<const float *>(EltPtr);
2441 return APFloat(*const_cast<float *>(FloatPrt));
2442 }
2443 case Type::DoubleTyID: {
2444 const double *DoublePtr = reinterpret_cast<const double *>(EltPtr);
2445 return APFloat(*const_cast<double *>(DoublePtr));
2446 }
Chris Lattner45bb5c52012-01-24 04:43:41 +00002447 }
2448}
2449
2450/// getElementAsFloat - If this is an sequential container of floats, return
2451/// the specified element as a float.
2452float ConstantDataSequential::getElementAsFloat(unsigned Elt) const {
2453 assert(getElementType()->isFloatTy() &&
2454 "Accessor can only be used when element is a 'float'");
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002455 const float *EltPtr = reinterpret_cast<const float *>(getElementPointer(Elt));
2456 return *const_cast<float *>(EltPtr);
Chris Lattner45bb5c52012-01-24 04:43:41 +00002457}
2458
2459/// getElementAsDouble - If this is an sequential container of doubles, return
2460/// the specified element as a float.
2461double ConstantDataSequential::getElementAsDouble(unsigned Elt) const {
2462 assert(getElementType()->isDoubleTy() &&
2463 "Accessor can only be used when element is a 'float'");
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002464 const double *EltPtr =
2465 reinterpret_cast<const double *>(getElementPointer(Elt));
2466 return *const_cast<double *>(EltPtr);
Chris Lattner45bb5c52012-01-24 04:43:41 +00002467}
2468
2469/// getElementAsConstant - Return a Constant for a specified index's element.
2470/// Note that this has to compute a new constant to return, so it isn't as
2471/// efficient as getElementAsInteger/Float/Double.
2472Constant *ConstantDataSequential::getElementAsConstant(unsigned Elt) const {
2473 if (getElementType()->isFloatTy() || getElementType()->isDoubleTy())
2474 return ConstantFP::get(getContext(), getElementAsAPFloat(Elt));
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002475
Chris Lattner45bb5c52012-01-24 04:43:41 +00002476 return ConstantInt::get(getElementType(), getElementAsInteger(Elt));
2477}
2478
Chris Lattner62339072012-01-24 09:01:07 +00002479/// isString - This method returns true if this is an array of i8.
2480bool ConstantDataSequential::isString() const {
2481 return isa<ArrayType>(getType()) && getElementType()->isIntegerTy(8);
2482}
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002483
Chris Lattner62339072012-01-24 09:01:07 +00002484/// isCString - This method returns true if the array "isString", ends with a
2485/// nul byte, and does not contains any other nul bytes.
2486bool ConstantDataSequential::isCString() const {
2487 if (!isString())
2488 return false;
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002489
Chris Lattner62339072012-01-24 09:01:07 +00002490 StringRef Str = getAsString();
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002491
Chris Lattner62339072012-01-24 09:01:07 +00002492 // The last value must be nul.
2493 if (Str.back() != 0) return false;
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002494
Chris Lattner62339072012-01-24 09:01:07 +00002495 // Other elements must be non-nul.
2496 return Str.drop_back().find(0) == StringRef::npos;
2497}
Chris Lattner27dd9cf2012-01-23 22:57:10 +00002498
Chris Lattnere150e2d2012-01-26 02:31:22 +00002499/// getSplatValue - If this is a splat constant, meaning that all of the
2500/// elements have the same value, return that value. Otherwise return NULL.
2501Constant *ConstantDataVector::getSplatValue() const {
2502 const char *Base = getRawDataValues().data();
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002503
Chris Lattnere150e2d2012-01-26 02:31:22 +00002504 // Compare elements 1+ to the 0'th element.
2505 unsigned EltSize = getElementByteSize();
2506 for (unsigned i = 1, e = getNumElements(); i != e; ++i)
2507 if (memcmp(Base, Base+i*EltSize, EltSize))
2508 return 0;
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002509
Chris Lattnere150e2d2012-01-26 02:31:22 +00002510 // If they're all the same, return the 0th one as a representative.
2511 return getElementAsConstant(0);
2512}
Chris Lattner04e3b1e2010-03-30 20:48:48 +00002513
Chris Lattner5cbade92005-10-03 21:58:36 +00002514//===----------------------------------------------------------------------===//
2515// replaceUsesOfWithOnConstant implementations
2516
Chris Lattner54984052007-08-21 00:55:23 +00002517/// replaceUsesOfWithOnConstant - Update this constant array to change uses of
2518/// 'From' to be uses of 'To'. This must update the uniquing data structures
2519/// etc.
2520///
2521/// Note that we intentionally replace all uses of From with To here. Consider
2522/// a large array that uses 'From' 1000 times. By handling this case all here,
2523/// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
2524/// single invocation handles all 1000 uses. Handling them one at a time would
2525/// work, but would be really slow because it would have to unique each updated
2526/// array instance.
Chris Lattner2ee11ec2009-10-28 00:01:44 +00002527///
Chris Lattner5cbade92005-10-03 21:58:36 +00002528void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
Chris Lattnerd0ff1ad2005-10-04 18:13:04 +00002529 Use *U) {
Owen Anderson1fd70962009-07-28 18:32:17 +00002530 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2531 Constant *ToC = cast<Constant>(To);
2532
Chris Lattner1afcace2011-07-09 17:41:24 +00002533 LLVMContextImpl *pImpl = getType()->getContext().pImpl;
Owen Anderson1fd70962009-07-28 18:32:17 +00002534
Talin2cb395e2012-02-05 20:54:10 +00002535 SmallVector<Constant*, 8> Values;
2536 LLVMContextImpl::ArrayConstantsTy::LookupKey Lookup;
2537 Lookup.first = cast<ArrayType>(getType());
Owen Anderson1fd70962009-07-28 18:32:17 +00002538 Values.reserve(getNumOperands()); // Build replacement array.
2539
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002540 // Fill values with the modified operands of the constant array. Also,
Owen Anderson1fd70962009-07-28 18:32:17 +00002541 // compute whether this turns into an all-zeros array.
Owen Anderson1fd70962009-07-28 18:32:17 +00002542 unsigned NumUpdated = 0;
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002543
Chris Lattnere150e2d2012-01-26 02:31:22 +00002544 // Keep track of whether all the values in the array are "ToC".
2545 bool AllSame = true;
2546 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2547 Constant *Val = cast<Constant>(O->get());
2548 if (Val == From) {
2549 Val = ToC;
2550 ++NumUpdated;
Owen Anderson1fd70962009-07-28 18:32:17 +00002551 }
Chris Lattnere150e2d2012-01-26 02:31:22 +00002552 Values.push_back(Val);
Talin2cb395e2012-02-05 20:54:10 +00002553 AllSame &= Val == ToC;
Owen Anderson1fd70962009-07-28 18:32:17 +00002554 }
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002555
Owen Anderson1fd70962009-07-28 18:32:17 +00002556 Constant *Replacement = 0;
Chris Lattnere150e2d2012-01-26 02:31:22 +00002557 if (AllSame && ToC->isNullValue()) {
Chris Lattner1afcace2011-07-09 17:41:24 +00002558 Replacement = ConstantAggregateZero::get(getType());
Chris Lattnere150e2d2012-01-26 02:31:22 +00002559 } else if (AllSame && isa<UndefValue>(ToC)) {
2560 Replacement = UndefValue::get(getType());
Owen Anderson1fd70962009-07-28 18:32:17 +00002561 } else {
2562 // Check to see if we have this array type already.
Talin2cb395e2012-02-05 20:54:10 +00002563 Lookup.second = makeArrayRef(Values);
Owen Anderson1fd70962009-07-28 18:32:17 +00002564 LLVMContextImpl::ArrayConstantsTy::MapTy::iterator I =
Talin2cb395e2012-02-05 20:54:10 +00002565 pImpl->ArrayConstants.find(Lookup);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002566
Talin2cb395e2012-02-05 20:54:10 +00002567 if (I != pImpl->ArrayConstants.map_end()) {
2568 Replacement = I->first;
Owen Anderson1fd70962009-07-28 18:32:17 +00002569 } else {
2570 // Okay, the new shape doesn't exist in the system yet. Instead of
2571 // creating a new constant array, inserting it, replaceallusesof'ing the
2572 // old with the new, then deleting the old... just update the current one
2573 // in place!
Talin2cb395e2012-02-05 20:54:10 +00002574 pImpl->ArrayConstants.remove(this);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002575
Owen Anderson1fd70962009-07-28 18:32:17 +00002576 // Update to the new value. Optimize for the case when we have a single
2577 // operand that we're changing, but handle bulk updates efficiently.
2578 if (NumUpdated == 1) {
2579 unsigned OperandToUpdate = U - OperandList;
2580 assert(getOperand(OperandToUpdate) == From &&
2581 "ReplaceAllUsesWith broken!");
2582 setOperand(OperandToUpdate, ToC);
2583 } else {
2584 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2585 if (getOperand(i) == From)
2586 setOperand(i, ToC);
2587 }
Talin2cb395e2012-02-05 20:54:10 +00002588 pImpl->ArrayConstants.insert(this);
Owen Anderson1fd70962009-07-28 18:32:17 +00002589 return;
2590 }
2591 }
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002592
Chris Lattnercea141f2005-10-03 22:51:37 +00002593 // Otherwise, I do need to replace this with an existing value.
Chris Lattner5cbade92005-10-03 21:58:36 +00002594 assert(Replacement != this && "I didn't contain From!");
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002595
Chris Lattnerd0ff1ad2005-10-04 18:13:04 +00002596 // Everyone using this now uses the replacement.
Chris Lattner678f9e02011-07-15 06:18:52 +00002597 replaceAllUsesWith(Replacement);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002598
Chris Lattner5cbade92005-10-03 21:58:36 +00002599 // Delete the old constant!
2600 destroyConstant();
2601}
2602
2603void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
Chris Lattnerd0ff1ad2005-10-04 18:13:04 +00002604 Use *U) {
Owen Anderson8fa33382009-07-27 22:29:26 +00002605 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2606 Constant *ToC = cast<Constant>(To);
2607
2608 unsigned OperandToUpdate = U-OperandList;
2609 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
2610
Talin2cb395e2012-02-05 20:54:10 +00002611 SmallVector<Constant*, 8> Values;
2612 LLVMContextImpl::StructConstantsTy::LookupKey Lookup;
2613 Lookup.first = cast<StructType>(getType());
Owen Anderson8fa33382009-07-27 22:29:26 +00002614 Values.reserve(getNumOperands()); // Build replacement struct.
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002615
2616 // Fill values with the modified operands of the constant struct. Also,
Owen Anderson8fa33382009-07-27 22:29:26 +00002617 // compute whether this turns into an all-zeros struct.
2618 bool isAllZeros = false;
Chris Lattnere150e2d2012-01-26 02:31:22 +00002619 bool isAllUndef = false;
2620 if (ToC->isNullValue()) {
Owen Anderson8fa33382009-07-27 22:29:26 +00002621 isAllZeros = true;
2622 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2623 Constant *Val = cast<Constant>(O->get());
2624 Values.push_back(Val);
2625 if (isAllZeros) isAllZeros = Val->isNullValue();
2626 }
Chris Lattnere150e2d2012-01-26 02:31:22 +00002627 } else if (isa<UndefValue>(ToC)) {
2628 isAllUndef = true;
2629 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2630 Constant *Val = cast<Constant>(O->get());
2631 Values.push_back(Val);
2632 if (isAllUndef) isAllUndef = isa<UndefValue>(Val);
2633 }
2634 } else {
2635 for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O)
2636 Values.push_back(cast<Constant>(O->get()));
Owen Anderson8fa33382009-07-27 22:29:26 +00002637 }
2638 Values[OperandToUpdate] = ToC;
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002639
Chris Lattner1afcace2011-07-09 17:41:24 +00002640 LLVMContextImpl *pImpl = getContext().pImpl;
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002641
Owen Anderson8fa33382009-07-27 22:29:26 +00002642 Constant *Replacement = 0;
2643 if (isAllZeros) {
Chris Lattner1afcace2011-07-09 17:41:24 +00002644 Replacement = ConstantAggregateZero::get(getType());
Chris Lattnere150e2d2012-01-26 02:31:22 +00002645 } else if (isAllUndef) {
2646 Replacement = UndefValue::get(getType());
Owen Anderson8fa33382009-07-27 22:29:26 +00002647 } else {
Chris Lattner93604b62010-07-17 06:13:52 +00002648 // Check to see if we have this struct type already.
Talin2cb395e2012-02-05 20:54:10 +00002649 Lookup.second = makeArrayRef(Values);
Owen Anderson8fa33382009-07-27 22:29:26 +00002650 LLVMContextImpl::StructConstantsTy::MapTy::iterator I =
Talin2cb395e2012-02-05 20:54:10 +00002651 pImpl->StructConstants.find(Lookup);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002652
Talin2cb395e2012-02-05 20:54:10 +00002653 if (I != pImpl->StructConstants.map_end()) {
2654 Replacement = I->first;
Owen Anderson8fa33382009-07-27 22:29:26 +00002655 } else {
2656 // Okay, the new shape doesn't exist in the system yet. Instead of
2657 // creating a new constant struct, inserting it, replaceallusesof'ing the
2658 // old with the new, then deleting the old... just update the current one
2659 // in place!
Talin2cb395e2012-02-05 20:54:10 +00002660 pImpl->StructConstants.remove(this);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002661
Owen Anderson8fa33382009-07-27 22:29:26 +00002662 // Update to the new value.
2663 setOperand(OperandToUpdate, ToC);
Talin2cb395e2012-02-05 20:54:10 +00002664 pImpl->StructConstants.insert(this);
Owen Anderson8fa33382009-07-27 22:29:26 +00002665 return;
2666 }
2667 }
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002668
Owen Anderson8fa33382009-07-27 22:29:26 +00002669 assert(Replacement != this && "I didn't contain From!");
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002670
Chris Lattnerd0ff1ad2005-10-04 18:13:04 +00002671 // Everyone using this now uses the replacement.
Chris Lattner678f9e02011-07-15 06:18:52 +00002672 replaceAllUsesWith(Replacement);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002673
Chris Lattner5cbade92005-10-03 21:58:36 +00002674 // Delete the old constant!
2675 destroyConstant();
2676}
2677
Reid Spencer9d6565a2007-02-15 02:26:10 +00002678void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
Chris Lattnerd0ff1ad2005-10-04 18:13:04 +00002679 Use *U) {
Chris Lattner5cbade92005-10-03 21:58:36 +00002680 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002681
Chris Lattnera7c69882012-01-26 20:40:56 +00002682 SmallVector<Constant*, 8> Values;
Chris Lattner5cbade92005-10-03 21:58:36 +00002683 Values.reserve(getNumOperands()); // Build replacement array...
2684 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2685 Constant *Val = getOperand(i);
2686 if (Val == From) Val = cast<Constant>(To);
2687 Values.push_back(Val);
2688 }
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002689
Jay Foada0c13842011-06-22 09:10:19 +00002690 Constant *Replacement = get(Values);
Chris Lattner5cbade92005-10-03 21:58:36 +00002691 assert(Replacement != this && "I didn't contain From!");
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002692
Chris Lattnerd0ff1ad2005-10-04 18:13:04 +00002693 // Everyone using this now uses the replacement.
Chris Lattner678f9e02011-07-15 06:18:52 +00002694 replaceAllUsesWith(Replacement);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002695
Chris Lattner5cbade92005-10-03 21:58:36 +00002696 // Delete the old constant!
2697 destroyConstant();
2698}
2699
2700void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
Chris Lattnerd0ff1ad2005-10-04 18:13:04 +00002701 Use *U) {
Chris Lattner5cbade92005-10-03 21:58:36 +00002702 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2703 Constant *To = cast<Constant>(ToV);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002704
Chris Lattner1a8def62012-01-26 20:37:11 +00002705 SmallVector<Constant*, 8> NewOps;
2706 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2707 Constant *Op = getOperand(i);
2708 NewOps.push_back(Op == From ? To : Op);
Chris Lattner5cbade92005-10-03 21:58:36 +00002709 }
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002710
Chris Lattner1a8def62012-01-26 20:37:11 +00002711 Constant *Replacement = getWithOperands(NewOps);
Chris Lattner5cbade92005-10-03 21:58:36 +00002712 assert(Replacement != this && "I didn't contain From!");
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002713
Chris Lattnerd0ff1ad2005-10-04 18:13:04 +00002714 // Everyone using this now uses the replacement.
Chris Lattner678f9e02011-07-15 06:18:52 +00002715 replaceAllUsesWith(Replacement);
Galina Kistanovaa46517e2012-07-13 01:25:27 +00002716
Chris Lattner5cbade92005-10-03 21:58:36 +00002717 // Delete the old constant!
2718 destroyConstant();
Matthijs Kooijman10b9de62008-07-03 07:46:41 +00002719}
James Molloyb9478c22012-11-17 17:56:30 +00002720
2721Instruction *ConstantExpr::getAsInstruction() {
2722 SmallVector<Value*,4> ValueOperands;
2723 for (op_iterator I = op_begin(), E = op_end(); I != E; ++I)
2724 ValueOperands.push_back(cast<Value>(I));
2725
2726 ArrayRef<Value*> Ops(ValueOperands);
2727
2728 switch (getOpcode()) {
2729 case Instruction::Trunc:
2730 case Instruction::ZExt:
2731 case Instruction::SExt:
2732 case Instruction::FPTrunc:
2733 case Instruction::FPExt:
2734 case Instruction::UIToFP:
2735 case Instruction::SIToFP:
2736 case Instruction::FPToUI:
2737 case Instruction::FPToSI:
2738 case Instruction::PtrToInt:
2739 case Instruction::IntToPtr:
2740 case Instruction::BitCast:
2741 return CastInst::Create((Instruction::CastOps)getOpcode(),
2742 Ops[0], getType());
2743 case Instruction::Select:
2744 return SelectInst::Create(Ops[0], Ops[1], Ops[2]);
2745 case Instruction::InsertElement:
2746 return InsertElementInst::Create(Ops[0], Ops[1], Ops[2]);
2747 case Instruction::ExtractElement:
2748 return ExtractElementInst::Create(Ops[0], Ops[1]);
2749 case Instruction::InsertValue:
2750 return InsertValueInst::Create(Ops[0], Ops[1], getIndices());
2751 case Instruction::ExtractValue:
2752 return ExtractValueInst::Create(Ops[0], getIndices());
2753 case Instruction::ShuffleVector:
2754 return new ShuffleVectorInst(Ops[0], Ops[1], Ops[2]);
2755
2756 case Instruction::GetElementPtr:
2757 if (cast<GEPOperator>(this)->isInBounds())
2758 return GetElementPtrInst::CreateInBounds(Ops[0], Ops.slice(1));
2759 else
2760 return GetElementPtrInst::Create(Ops[0], Ops.slice(1));
2761
2762 case Instruction::ICmp:
2763 case Instruction::FCmp:
2764 return CmpInst::Create((Instruction::OtherOps)getOpcode(),
2765 getPredicate(), Ops[0], Ops[1]);
2766
2767 default:
2768 assert(getNumOperands() == 2 && "Must be binary operator?");
2769 BinaryOperator *BO =
2770 BinaryOperator::Create((Instruction::BinaryOps)getOpcode(),
2771 Ops[0], Ops[1]);
2772 if (isa<OverflowingBinaryOperator>(BO)) {
2773 BO->setHasNoUnsignedWrap(SubclassOptionalData &
2774 OverflowingBinaryOperator::NoUnsignedWrap);
2775 BO->setHasNoSignedWrap(SubclassOptionalData &
2776 OverflowingBinaryOperator::NoSignedWrap);
2777 }
2778 if (isa<PossiblyExactOperator>(BO))
2779 BO->setIsExact(SubclassOptionalData & PossiblyExactOperator::IsExact);
2780 return BO;
2781 }
2782}