blob: 945af7acc9f6324b44ee0fbfbe1a237ff6eff44b [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
Chris Lattner31bcdb82002-04-28 19:55:58 +000014#include "llvm/Constants.h"
Chris Lattner37f077a2009-08-23 04:02:03 +000015#include "LLVMContextImpl.h"
Chris Lattner92f6fea2007-02-27 03:05:06 +000016#include "ConstantFold.h"
Chris Lattner00950542001-06-06 20:29:01 +000017#include "llvm/DerivedTypes.h"
Reid Spencer1c9c8e62004-07-17 23:48:33 +000018#include "llvm/GlobalValue.h"
Misha Brukman47b14a42004-07-29 17:30:56 +000019#include "llvm/Instructions.h"
Chris Lattnerf5ec48d2001-10-13 06:57:33 +000020#include "llvm/Module.h"
Dan Gohman5a206ee2009-07-18 01:49:22 +000021#include "llvm/Operator.h"
Nick Lewycky21cc4462009-04-04 07:22:01 +000022#include "llvm/ADT/FoldingSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000023#include "llvm/ADT/StringExtras.h"
Nick Lewycky21cc4462009-04-04 07:22:01 +000024#include "llvm/ADT/StringMap.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000025#include "llvm/Support/Compiler.h"
Bill Wendling2e3def12006-11-17 08:03:48 +000026#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000027#include "llvm/Support/ErrorHandling.h"
Chris Lattner8a94bf12006-09-28 00:35:06 +000028#include "llvm/Support/ManagedStatic.h"
Bill Wendling2e3def12006-11-17 08:03:48 +000029#include "llvm/Support/MathExtras.h"
Chris Lattner37f077a2009-08-23 04:02:03 +000030#include "llvm/Support/raw_ostream.h"
Dan Gohmane6992f72009-09-10 23:37:55 +000031#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner6b6f6ba2007-02-20 06:39:57 +000032#include "llvm/ADT/DenseMap.h"
Chris Lattnerf9021ff2007-02-19 20:01:23 +000033#include "llvm/ADT/SmallVector.h"
Chris Lattner1afcace2011-07-09 17:41:24 +000034#include "llvm/ADT/STLExtras.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
Owen Andersona7235ea2009-07-31 20:28:14 +000043// Constructor to create a '0' constant of arbitrary type...
Chris Lattner38211762009-10-30 22:33:29 +000044Constant *Constant::getNullValue(const Type *Ty) {
Owen Andersona7235ea2009-07-31 20:28:14 +000045 switch (Ty->getTypeID()) {
46 case Type::IntegerTyID:
47 return ConstantInt::get(Ty, 0);
48 case Type::FloatTyID:
Benjamin Kramer98383962010-12-04 14:22:24 +000049 return ConstantFP::get(Ty->getContext(),
50 APFloat::getZero(APFloat::IEEEsingle));
Owen Andersona7235ea2009-07-31 20:28:14 +000051 case Type::DoubleTyID:
Benjamin Kramer98383962010-12-04 14:22:24 +000052 return ConstantFP::get(Ty->getContext(),
53 APFloat::getZero(APFloat::IEEEdouble));
Owen Andersona7235ea2009-07-31 20:28:14 +000054 case Type::X86_FP80TyID:
Benjamin Kramer98383962010-12-04 14:22:24 +000055 return ConstantFP::get(Ty->getContext(),
56 APFloat::getZero(APFloat::x87DoubleExtended));
Owen Andersona7235ea2009-07-31 20:28:14 +000057 case Type::FP128TyID:
58 return ConstantFP::get(Ty->getContext(),
Benjamin Kramer98383962010-12-04 14:22:24 +000059 APFloat::getZero(APFloat::IEEEquad));
Owen Andersona7235ea2009-07-31 20:28:14 +000060 case Type::PPC_FP128TyID:
Benjamin Kramer98383962010-12-04 14:22:24 +000061 return ConstantFP::get(Ty->getContext(),
Benjamin Kramer299ee182010-12-04 14:43:08 +000062 APFloat(APInt::getNullValue(128)));
Owen Andersona7235ea2009-07-31 20:28:14 +000063 case Type::PointerTyID:
64 return ConstantPointerNull::get(cast<PointerType>(Ty));
65 case Type::StructTyID:
66 case Type::ArrayTyID:
67 case Type::VectorTyID:
68 return ConstantAggregateZero::get(Ty);
69 default:
70 // Function, Label, or Opaque type?
71 assert(!"Cannot create a null constant of that type!");
72 return 0;
73 }
74}
75
Chris Lattnerf067d582011-02-07 16:40:21 +000076Constant *Constant::getIntegerValue(const Type *Ty, const APInt &V) {
Dan Gohman43ee5f72009-08-03 22:07:33 +000077 const Type *ScalarTy = Ty->getScalarType();
78
79 // Create the base integer constant.
80 Constant *C = ConstantInt::get(Ty->getContext(), V);
81
82 // Convert an integer to a pointer, if necessary.
83 if (const PointerType *PTy = dyn_cast<PointerType>(ScalarTy))
84 C = ConstantExpr::getIntToPtr(C, PTy);
85
86 // Broadcast a scalar to a vector, if necessary.
87 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
88 C = ConstantVector::get(std::vector<Constant *>(VTy->getNumElements(), C));
89
90 return C;
91}
92
Chris Lattnerf067d582011-02-07 16:40:21 +000093Constant *Constant::getAllOnesValue(const Type *Ty) {
Chris Lattner38211762009-10-30 22:33:29 +000094 if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty))
Owen Andersona7235ea2009-07-31 20:28:14 +000095 return ConstantInt::get(Ty->getContext(),
96 APInt::getAllOnesValue(ITy->getBitWidth()));
Nadav Rotem093399c2011-02-17 21:22:27 +000097
98 if (Ty->isFloatingPointTy()) {
99 APFloat FL = APFloat::getAllOnesValue(Ty->getPrimitiveSizeInBits(),
100 !Ty->isPPC_FP128Ty());
101 return ConstantFP::get(Ty->getContext(), FL);
102 }
103
Chris Lattner2ca5c862011-02-15 00:14:00 +0000104 SmallVector<Constant*, 16> Elts;
Chris Lattner38211762009-10-30 22:33:29 +0000105 const VectorType *VTy = cast<VectorType>(Ty);
Owen Andersona7235ea2009-07-31 20:28:14 +0000106 Elts.resize(VTy->getNumElements(), getAllOnesValue(VTy->getElementType()));
107 assert(Elts[0] && "Not a vector integer type!");
108 return cast<ConstantVector>(ConstantVector::get(Elts));
109}
110
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000111void Constant::destroyConstantImpl() {
112 // When a Constant is destroyed, there may be lingering
Chris Lattnerf5ec48d2001-10-13 06:57:33 +0000113 // references to the constant by other constants in the constant pool. These
Misha Brukmanef6a6a62003-08-21 22:14:26 +0000114 // constants are implicitly dependent on the module that is being deleted,
Chris Lattnerf5ec48d2001-10-13 06:57:33 +0000115 // but they don't know that. Because we only find out when the CPV is
116 // deleted, we must now notify all of our users (that should only be
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000117 // Constants) that they are, in fact, invalid now and should be deleted.
Chris Lattnerf5ec48d2001-10-13 06:57:33 +0000118 //
119 while (!use_empty()) {
120 Value *V = use_back();
121#ifndef NDEBUG // Only in -g mode...
Chris Lattner37f077a2009-08-23 04:02:03 +0000122 if (!isa<Constant>(V)) {
David Greened2e63b72010-01-05 01:29:19 +0000123 dbgs() << "While deleting: " << *this
Chris Lattner37f077a2009-08-23 04:02:03 +0000124 << "\n\nUse still stuck around after Def is destroyed: "
125 << *V << "\n\n";
126 }
Chris Lattnerf5ec48d2001-10-13 06:57:33 +0000127#endif
Vikram S. Adve345e0cf2002-07-14 23:13:17 +0000128 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
Reid Spencer1c9c8e62004-07-17 23:48:33 +0000129 Constant *CV = cast<Constant>(V);
130 CV->destroyConstant();
Chris Lattnerf5ec48d2001-10-13 06:57:33 +0000131
132 // The constant should remove itself from our use list...
Vikram S. Adve345e0cf2002-07-14 23:13:17 +0000133 assert((use_empty() || use_back() != V) && "Constant not removed!");
Chris Lattnerf5ec48d2001-10-13 06:57:33 +0000134 }
135
136 // Value has no outstanding references it is safe to delete it now...
137 delete this;
Chris Lattner1d87bcf2001-10-01 20:11:19 +0000138}
Chris Lattner00950542001-06-06 20:29:01 +0000139
Chris Lattner35b89fa2006-10-20 00:27:06 +0000140/// canTrap - Return true if evaluation of this constant could trap. This is
141/// true for things like constant expressions that could divide by zero.
142bool Constant::canTrap() const {
143 assert(getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
144 // The only thing that could possibly trap are constant exprs.
145 const ConstantExpr *CE = dyn_cast<ConstantExpr>(this);
146 if (!CE) return false;
147
148 // ConstantExpr traps if any operands can trap.
149 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
Chris Lattner0eeb9132009-10-28 05:14:34 +0000150 if (CE->getOperand(i)->canTrap())
Chris Lattner35b89fa2006-10-20 00:27:06 +0000151 return true;
152
153 // Otherwise, only specific operations can trap.
154 switch (CE->getOpcode()) {
155 default:
156 return false;
Reid Spencer1628cec2006-10-26 06:15:43 +0000157 case Instruction::UDiv:
158 case Instruction::SDiv:
159 case Instruction::FDiv:
Reid Spencer0a783f72006-11-02 01:53:59 +0000160 case Instruction::URem:
161 case Instruction::SRem:
162 case Instruction::FRem:
Chris Lattner35b89fa2006-10-20 00:27:06 +0000163 // Div and rem can trap if the RHS is not known to be non-zero.
Chris Lattner0eeb9132009-10-28 05:14:34 +0000164 if (!isa<ConstantInt>(CE->getOperand(1)) ||CE->getOperand(1)->isNullValue())
Chris Lattner35b89fa2006-10-20 00:27:06 +0000165 return true;
166 return false;
167 }
168}
169
Chris Lattner4a7642e2009-11-01 18:11:50 +0000170/// isConstantUsed - Return true if the constant has users other than constant
171/// exprs and other dangling things.
172bool Constant::isConstantUsed() const {
Gabor Greif60ad7812010-03-25 23:06:16 +0000173 for (const_use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
Chris Lattner4a7642e2009-11-01 18:11:50 +0000174 const Constant *UC = dyn_cast<Constant>(*UI);
175 if (UC == 0 || isa<GlobalValue>(UC))
176 return true;
177
178 if (UC->isConstantUsed())
179 return true;
180 }
181 return false;
182}
183
184
Chris Lattner7cf12c72009-07-22 00:05:44 +0000185
186/// getRelocationInfo - This method classifies the entry according to
187/// whether or not it may generate a relocation entry. This must be
188/// conservative, so if it might codegen to a relocatable entry, it should say
189/// so. The return values are:
190///
Chris Lattner083a1e02009-07-24 03:27:21 +0000191/// NoRelocation: This constant pool entry is guaranteed to never have a
192/// relocation applied to it (because it holds a simple constant like
193/// '4').
194/// LocalRelocation: This entry has relocations, but the entries are
195/// guaranteed to be resolvable by the static linker, so the dynamic
196/// linker will never see them.
197/// GlobalRelocations: This entry may have arbitrary relocations.
Chris Lattner7cf12c72009-07-22 00:05:44 +0000198///
199/// FIXME: This really should not be in VMCore.
Chris Lattner083a1e02009-07-24 03:27:21 +0000200Constant::PossibleRelocationsTy Constant::getRelocationInfo() const {
201 if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
Chris Lattner7cf12c72009-07-22 00:05:44 +0000202 if (GV->hasLocalLinkage() || GV->hasHiddenVisibility())
Chris Lattner083a1e02009-07-24 03:27:21 +0000203 return LocalRelocation; // Local to this file/library.
204 return GlobalRelocations; // Global reference.
Anton Korobeynikovab267a22009-03-29 17:13:18 +0000205 }
Chris Lattner7cf12c72009-07-22 00:05:44 +0000206
Chris Lattner5d81bef2009-10-28 04:12:16 +0000207 if (const BlockAddress *BA = dyn_cast<BlockAddress>(this))
208 return BA->getFunction()->getRelocationInfo();
209
Chris Lattner5099b312010-01-03 18:09:40 +0000210 // While raw uses of blockaddress need to be relocated, differences between
211 // two of them don't when they are for labels in the same function. This is a
212 // common idiom when creating a table for the indirect goto extension, so we
213 // handle it efficiently here.
214 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(this))
215 if (CE->getOpcode() == Instruction::Sub) {
216 ConstantExpr *LHS = dyn_cast<ConstantExpr>(CE->getOperand(0));
217 ConstantExpr *RHS = dyn_cast<ConstantExpr>(CE->getOperand(1));
218 if (LHS && RHS &&
219 LHS->getOpcode() == Instruction::PtrToInt &&
220 RHS->getOpcode() == Instruction::PtrToInt &&
221 isa<BlockAddress>(LHS->getOperand(0)) &&
222 isa<BlockAddress>(RHS->getOperand(0)) &&
223 cast<BlockAddress>(LHS->getOperand(0))->getFunction() ==
224 cast<BlockAddress>(RHS->getOperand(0))->getFunction())
225 return NoRelocation;
226 }
227
Chris Lattner083a1e02009-07-24 03:27:21 +0000228 PossibleRelocationsTy Result = NoRelocation;
Evan Chengafe15812007-03-08 00:59:12 +0000229 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
Chris Lattner0eeb9132009-10-28 05:14:34 +0000230 Result = std::max(Result,
231 cast<Constant>(getOperand(i))->getRelocationInfo());
Chris Lattner7cf12c72009-07-22 00:05:44 +0000232
233 return Result;
Evan Chengafe15812007-03-08 00:59:12 +0000234}
235
Chris Lattner7cf12c72009-07-22 00:05:44 +0000236
Chris Lattner86381442008-07-10 00:28:11 +0000237/// getVectorElements - This method, which is only valid on constant of vector
238/// type, returns the elements of the vector in the specified smallvector.
Chris Lattner071aade2008-07-14 05:10:41 +0000239/// This handles breaking down a vector undef into undef elements, etc. For
240/// constant exprs and other cases we can't handle, we return an empty vector.
Chris Lattnerb29d5962010-02-01 20:48:08 +0000241void Constant::getVectorElements(SmallVectorImpl<Constant*> &Elts) const {
Duncan Sands1df98592010-02-16 11:11:14 +0000242 assert(getType()->isVectorTy() && "Not a vector constant!");
Chris Lattner86381442008-07-10 00:28:11 +0000243
244 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this)) {
245 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i)
246 Elts.push_back(CV->getOperand(i));
247 return;
248 }
249
250 const VectorType *VT = cast<VectorType>(getType());
251 if (isa<ConstantAggregateZero>(this)) {
252 Elts.assign(VT->getNumElements(),
Owen Andersona7235ea2009-07-31 20:28:14 +0000253 Constant::getNullValue(VT->getElementType()));
Chris Lattner86381442008-07-10 00:28:11 +0000254 return;
255 }
256
Chris Lattner071aade2008-07-14 05:10:41 +0000257 if (isa<UndefValue>(this)) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000258 Elts.assign(VT->getNumElements(), UndefValue::get(VT->getElementType()));
Chris Lattner071aade2008-07-14 05:10:41 +0000259 return;
260 }
261
262 // Unknown type, must be constant expr etc.
Chris Lattner86381442008-07-10 00:28:11 +0000263}
264
265
Chris Lattner13fb0db2011-02-18 04:41:42 +0000266/// removeDeadUsersOfConstant - If the specified constantexpr is dead, remove
267/// it. This involves recursively eliminating any dead users of the
268/// constantexpr.
269static bool removeDeadUsersOfConstant(const Constant *C) {
270 if (isa<GlobalValue>(C)) return false; // Cannot remove this
271
272 while (!C->use_empty()) {
273 const Constant *User = dyn_cast<Constant>(C->use_back());
274 if (!User) return false; // Non-constant usage;
275 if (!removeDeadUsersOfConstant(User))
276 return false; // Constant wasn't dead
277 }
278
279 const_cast<Constant*>(C)->destroyConstant();
280 return true;
281}
282
283
284/// removeDeadConstantUsers - If there are any dead constant users dangling
285/// off of this constant, remove them. This method is useful for clients
286/// that want to check to see if a global is unused, but don't want to deal
287/// with potentially dead constants hanging off of the globals.
288void Constant::removeDeadConstantUsers() const {
289 Value::const_use_iterator I = use_begin(), E = use_end();
290 Value::const_use_iterator LastNonDeadUser = E;
291 while (I != E) {
292 const Constant *User = dyn_cast<Constant>(*I);
293 if (User == 0) {
294 LastNonDeadUser = I;
295 ++I;
296 continue;
297 }
298
299 if (!removeDeadUsersOfConstant(User)) {
300 // If the constant wasn't dead, remember that this was the last live use
301 // and move on to the next constant.
302 LastNonDeadUser = I;
303 ++I;
304 continue;
305 }
306
307 // If the constant was dead, then the iterator is invalidated.
308 if (LastNonDeadUser == E) {
309 I = use_begin();
310 if (I == E) break;
311 } else {
312 I = LastNonDeadUser;
313 ++I;
314 }
315 }
316}
317
318
Chris Lattner86381442008-07-10 00:28:11 +0000319
Chris Lattner00950542001-06-06 20:29:01 +0000320//===----------------------------------------------------------------------===//
Chris Lattner6b6f6ba2007-02-20 06:39:57 +0000321// ConstantInt
Chris Lattner00950542001-06-06 20:29:01 +0000322//===----------------------------------------------------------------------===//
323
Reid Spencer532d0ce2007-02-26 23:54:03 +0000324ConstantInt::ConstantInt(const IntegerType *Ty, const APInt& V)
Chris Lattnereb41bdd2007-02-20 05:55:46 +0000325 : Constant(Ty, ConstantIntVal, 0, 0), Val(V) {
Reid Spencer532d0ce2007-02-26 23:54:03 +0000326 assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
Chris Lattner00950542001-06-06 20:29:01 +0000327}
328
Nick Lewyckyd01f50f2011-03-06 03:36:19 +0000329ConstantInt *ConstantInt::getTrue(LLVMContext &Context) {
Owen Anderson5defacc2009-07-31 17:39:07 +0000330 LLVMContextImpl *pImpl = Context.pImpl;
Benjamin Kramerf601d6d2010-11-20 18:43:35 +0000331 if (!pImpl->TheTrueVal)
332 pImpl->TheTrueVal = ConstantInt::get(Type::getInt1Ty(Context), 1);
333 return pImpl->TheTrueVal;
Owen Anderson5defacc2009-07-31 17:39:07 +0000334}
335
Nick Lewyckyd01f50f2011-03-06 03:36:19 +0000336ConstantInt *ConstantInt::getFalse(LLVMContext &Context) {
Owen Anderson5defacc2009-07-31 17:39:07 +0000337 LLVMContextImpl *pImpl = Context.pImpl;
Benjamin Kramerf601d6d2010-11-20 18:43:35 +0000338 if (!pImpl->TheFalseVal)
339 pImpl->TheFalseVal = ConstantInt::get(Type::getInt1Ty(Context), 0);
340 return pImpl->TheFalseVal;
Owen Anderson5defacc2009-07-31 17:39:07 +0000341}
342
Nick Lewyckyd01f50f2011-03-06 03:36:19 +0000343Constant *ConstantInt::getTrue(const Type *Ty) {
344 const VectorType *VTy = dyn_cast<VectorType>(Ty);
345 if (!VTy) {
346 assert(Ty->isIntegerTy(1) && "True must be i1 or vector of i1.");
347 return ConstantInt::getTrue(Ty->getContext());
348 }
349 assert(VTy->getElementType()->isIntegerTy(1) &&
350 "True must be vector of i1 or i1.");
351 SmallVector<Constant*, 16> Splat(VTy->getNumElements(),
352 ConstantInt::getTrue(Ty->getContext()));
353 return ConstantVector::get(Splat);
354}
355
356Constant *ConstantInt::getFalse(const Type *Ty) {
357 const VectorType *VTy = dyn_cast<VectorType>(Ty);
358 if (!VTy) {
359 assert(Ty->isIntegerTy(1) && "False must be i1 or vector of i1.");
360 return ConstantInt::getFalse(Ty->getContext());
361 }
362 assert(VTy->getElementType()->isIntegerTy(1) &&
363 "False must be vector of i1 or i1.");
364 SmallVector<Constant*, 16> Splat(VTy->getNumElements(),
365 ConstantInt::getFalse(Ty->getContext()));
366 return ConstantVector::get(Splat);
367}
368
Owen Anderson5defacc2009-07-31 17:39:07 +0000369
Owen Andersoneed707b2009-07-24 23:12:02 +0000370// Get a ConstantInt from an APInt. Note that the value stored in the DenseMap
371// as the key, is a DenseMapAPIntKeyInfo::KeyTy which has provided the
372// operator== and operator!= to ensure that the DenseMap doesn't attempt to
373// compare APInt's of different widths, which would violate an APInt class
374// invariant which generates an assertion.
Nick Lewyckyd01f50f2011-03-06 03:36:19 +0000375ConstantInt *ConstantInt::get(LLVMContext &Context, const APInt &V) {
Owen Andersoneed707b2009-07-24 23:12:02 +0000376 // Get the corresponding integer type for the bit width of the value.
Owen Anderson1d0be152009-08-13 21:58:54 +0000377 const IntegerType *ITy = IntegerType::get(Context, V.getBitWidth());
Owen Andersoneed707b2009-07-24 23:12:02 +0000378 // get an existing value or the insertion position
379 DenseMapAPIntKeyInfo::KeyTy Key(V, ITy);
Owen Andersoneed707b2009-07-24 23:12:02 +0000380 ConstantInt *&Slot = Context.pImpl->IntConstants[Key];
Owen Anderson59d5aac2009-10-19 20:11:52 +0000381 if (!Slot) Slot = new ConstantInt(ITy, V);
382 return Slot;
Owen Andersoneed707b2009-07-24 23:12:02 +0000383}
384
Nick Lewyckyd01f50f2011-03-06 03:36:19 +0000385Constant *ConstantInt::get(const Type *Ty, uint64_t V, bool isSigned) {
386 Constant *C = get(cast<IntegerType>(Ty->getScalarType()), V, isSigned);
Owen Andersoneed707b2009-07-24 23:12:02 +0000387
388 // For vectors, broadcast the value.
389 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
Chris Lattner2ca5c862011-02-15 00:14:00 +0000390 return ConstantVector::get(SmallVector<Constant*,
391 16>(VTy->getNumElements(), C));
Owen Andersoneed707b2009-07-24 23:12:02 +0000392
393 return C;
394}
395
396ConstantInt* ConstantInt::get(const IntegerType* Ty, uint64_t V,
397 bool isSigned) {
398 return get(Ty->getContext(), APInt(Ty->getBitWidth(), V, isSigned));
399}
400
401ConstantInt* ConstantInt::getSigned(const IntegerType* Ty, int64_t V) {
402 return get(Ty, V, true);
403}
404
405Constant *ConstantInt::getSigned(const Type *Ty, int64_t V) {
406 return get(Ty, V, true);
407}
408
Chris Lattnerf067d582011-02-07 16:40:21 +0000409Constant *ConstantInt::get(const Type* Ty, const APInt& V) {
Owen Andersoneed707b2009-07-24 23:12:02 +0000410 ConstantInt *C = get(Ty->getContext(), V);
411 assert(C->getType() == Ty->getScalarType() &&
412 "ConstantInt type doesn't match the type implied by its value!");
413
414 // For vectors, broadcast the value.
415 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
Owen Andersonaf7ec972009-07-28 21:19:26 +0000416 return ConstantVector::get(
Chris Lattner2ca5c862011-02-15 00:14:00 +0000417 SmallVector<Constant *, 16>(VTy->getNumElements(), C));
Owen Andersoneed707b2009-07-24 23:12:02 +0000418
419 return C;
420}
421
Daniel Dunbar2928c832009-11-06 10:58:06 +0000422ConstantInt* ConstantInt::get(const IntegerType* Ty, StringRef Str,
Erick Tryzelaar0e81f662009-08-16 23:36:33 +0000423 uint8_t radix) {
424 return get(Ty->getContext(), APInt(Ty->getBitWidth(), Str, radix));
425}
426
Chris Lattner6b6f6ba2007-02-20 06:39:57 +0000427//===----------------------------------------------------------------------===//
Chris Lattner9b4ee0c2007-02-20 07:17:17 +0000428// ConstantFP
Chris Lattner6b6f6ba2007-02-20 06:39:57 +0000429//===----------------------------------------------------------------------===//
430
Rafael Espindola87d1f472009-07-15 17:40:42 +0000431static const fltSemantics *TypeToFloatSemantics(const Type *Ty) {
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000432 if (Ty->isFloatTy())
Rafael Espindola87d1f472009-07-15 17:40:42 +0000433 return &APFloat::IEEEsingle;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000434 if (Ty->isDoubleTy())
Rafael Espindola87d1f472009-07-15 17:40:42 +0000435 return &APFloat::IEEEdouble;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000436 if (Ty->isX86_FP80Ty())
Rafael Espindola87d1f472009-07-15 17:40:42 +0000437 return &APFloat::x87DoubleExtended;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000438 else if (Ty->isFP128Ty())
Rafael Espindola87d1f472009-07-15 17:40:42 +0000439 return &APFloat::IEEEquad;
440
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000441 assert(Ty->isPPC_FP128Ty() && "Unknown FP format");
Rafael Espindola87d1f472009-07-15 17:40:42 +0000442 return &APFloat::PPCDoubleDouble;
443}
444
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000445/// get() - This returns a constant fp for the specified value in the
446/// specified type. This should only be used for simple constant values like
447/// 2.0/1.0 etc, that are known-valid both as double and as the target format.
Chris Lattnerf067d582011-02-07 16:40:21 +0000448Constant *ConstantFP::get(const Type* Ty, double V) {
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000449 LLVMContext &Context = Ty->getContext();
450
451 APFloat FV(V);
452 bool ignored;
453 FV.convert(*TypeToFloatSemantics(Ty->getScalarType()),
454 APFloat::rmNearestTiesToEven, &ignored);
455 Constant *C = get(Context, FV);
456
457 // For vectors, broadcast the value.
458 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
Owen Andersonaf7ec972009-07-28 21:19:26 +0000459 return ConstantVector::get(
Chris Lattner2ca5c862011-02-15 00:14:00 +0000460 SmallVector<Constant *, 16>(VTy->getNumElements(), C));
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000461
462 return C;
463}
464
Erick Tryzelaar0e81f662009-08-16 23:36:33 +0000465
Chris Lattnerf067d582011-02-07 16:40:21 +0000466Constant *ConstantFP::get(const Type* Ty, StringRef Str) {
Erick Tryzelaar0e81f662009-08-16 23:36:33 +0000467 LLVMContext &Context = Ty->getContext();
468
469 APFloat FV(*TypeToFloatSemantics(Ty->getScalarType()), Str);
470 Constant *C = get(Context, FV);
471
472 // For vectors, broadcast the value.
473 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
474 return ConstantVector::get(
Chris Lattner2ca5c862011-02-15 00:14:00 +0000475 SmallVector<Constant *, 16>(VTy->getNumElements(), C));
Erick Tryzelaar0e81f662009-08-16 23:36:33 +0000476
477 return C;
478}
479
480
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000481ConstantFP* ConstantFP::getNegativeZero(const Type* Ty) {
482 LLVMContext &Context = Ty->getContext();
Owen Andersona7235ea2009-07-31 20:28:14 +0000483 APFloat apf = cast <ConstantFP>(Constant::getNullValue(Ty))->getValueAPF();
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000484 apf.changeSign();
485 return get(Context, apf);
486}
487
488
Chris Lattnerf067d582011-02-07 16:40:21 +0000489Constant *ConstantFP::getZeroValueForNegation(const Type* Ty) {
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000490 if (const VectorType *PTy = dyn_cast<VectorType>(Ty))
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000491 if (PTy->getElementType()->isFloatingPointTy()) {
Chris Lattner2ca5c862011-02-15 00:14:00 +0000492 SmallVector<Constant*, 16> zeros(PTy->getNumElements(),
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000493 getNegativeZero(PTy->getElementType()));
Chris Lattner2ca5c862011-02-15 00:14:00 +0000494 return ConstantVector::get(zeros);
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000495 }
496
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000497 if (Ty->isFloatingPointTy())
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000498 return getNegativeZero(Ty);
499
Owen Andersona7235ea2009-07-31 20:28:14 +0000500 return Constant::getNullValue(Ty);
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000501}
502
503
504// ConstantFP accessors.
505ConstantFP* ConstantFP::get(LLVMContext &Context, const APFloat& V) {
506 DenseMapAPFloatKeyInfo::KeyTy Key(V);
507
508 LLVMContextImpl* pImpl = Context.pImpl;
509
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000510 ConstantFP *&Slot = pImpl->FPConstants[Key];
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000511
512 if (!Slot) {
Owen Anderson59d5aac2009-10-19 20:11:52 +0000513 const Type *Ty;
514 if (&V.getSemantics() == &APFloat::IEEEsingle)
515 Ty = Type::getFloatTy(Context);
516 else if (&V.getSemantics() == &APFloat::IEEEdouble)
517 Ty = Type::getDoubleTy(Context);
518 else if (&V.getSemantics() == &APFloat::x87DoubleExtended)
519 Ty = Type::getX86_FP80Ty(Context);
520 else if (&V.getSemantics() == &APFloat::IEEEquad)
521 Ty = Type::getFP128Ty(Context);
522 else {
523 assert(&V.getSemantics() == &APFloat::PPCDoubleDouble &&
524 "Unknown FP format");
525 Ty = Type::getPPC_FP128Ty(Context);
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000526 }
Owen Anderson59d5aac2009-10-19 20:11:52 +0000527 Slot = new ConstantFP(Ty, V);
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000528 }
529
530 return Slot;
531}
532
Dan Gohmana23643d2009-09-25 23:40:21 +0000533ConstantFP *ConstantFP::getInfinity(const Type *Ty, bool Negative) {
Dan Gohmanf344f7f2009-09-25 23:00:48 +0000534 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty);
535 return ConstantFP::get(Ty->getContext(),
536 APFloat::getInf(Semantics, Negative));
537}
538
Dale Johannesenf04afdb2007-08-30 00:23:21 +0000539ConstantFP::ConstantFP(const Type *Ty, const APFloat& V)
540 : Constant(Ty, ConstantFPVal, 0, 0), Val(V) {
Chris Lattner288e78f2008-04-09 06:38:30 +0000541 assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
542 "FP type Mismatch");
Chris Lattner00950542001-06-06 20:29:01 +0000543}
544
Chris Lattner9b4ee0c2007-02-20 07:17:17 +0000545bool ConstantFP::isNullValue() const {
Dale Johannesen343e7702007-08-24 00:56:33 +0000546 return Val.isZero() && !Val.isNegative();
Chris Lattner9b4ee0c2007-02-20 07:17:17 +0000547}
548
Dale Johannesenf04afdb2007-08-30 00:23:21 +0000549bool ConstantFP::isExactlyValue(const APFloat& V) const {
550 return Val.bitwiseIsEqual(V);
Chris Lattner9b4ee0c2007-02-20 07:17:17 +0000551}
552
Chris Lattner9b4ee0c2007-02-20 07:17:17 +0000553//===----------------------------------------------------------------------===//
554// ConstantXXX Classes
555//===----------------------------------------------------------------------===//
556
557
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000558ConstantArray::ConstantArray(const ArrayType *T,
Chris Lattnere4671472005-01-29 00:34:39 +0000559 const std::vector<Constant*> &V)
Gabor Greifefe65362008-05-10 08:32:32 +0000560 : Constant(T, ConstantArrayVal,
561 OperandTraits<ConstantArray>::op_end(this) - V.size(),
562 V.size()) {
Alkis Evlogimenose0de1d62004-09-15 02:32:15 +0000563 assert(V.size() == T->getNumElements() &&
564 "Invalid initializer vector for constant array");
Chris Lattnere4671472005-01-29 00:34:39 +0000565 Use *OL = OperandList;
Chris Lattnerdfdd6c52005-10-03 21:56:24 +0000566 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
567 I != E; ++I, ++OL) {
Chris Lattner71abaab2005-10-07 05:23:36 +0000568 Constant *C = *I;
Nick Lewyckyb13105f2009-10-03 19:30:43 +0000569 assert(C->getType() == T->getElementType() &&
Alkis Evlogimenoscad90ad2004-09-10 04:16:59 +0000570 "Initializer for array element doesn't match array element type!");
Gabor Greif6c80c382008-05-26 21:33:52 +0000571 *OL = C;
Chris Lattner00950542001-06-06 20:29:01 +0000572 }
573}
574
Jay Foad26701082011-06-22 09:24:39 +0000575Constant *ConstantArray::get(const ArrayType *Ty, ArrayRef<Constant*> V) {
Jeffrey Yasskin1fb613c2009-09-30 21:08:08 +0000576 for (unsigned i = 0, e = V.size(); i != e; ++i) {
577 assert(V[i]->getType() == Ty->getElementType() &&
578 "Wrong type in array element initializer");
579 }
Owen Anderson1fd70962009-07-28 18:32:17 +0000580 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
581 // If this is an all-zero array, return a ConstantAggregateZero object
582 if (!V.empty()) {
583 Constant *C = V[0];
Chris Lattner83738a22009-12-30 20:25:09 +0000584 if (!C->isNullValue())
Owen Anderson1fd70962009-07-28 18:32:17 +0000585 return pImpl->ArrayConstants.getOrCreate(Ty, V);
Chris Lattner83738a22009-12-30 20:25:09 +0000586
Owen Anderson1fd70962009-07-28 18:32:17 +0000587 for (unsigned i = 1, e = V.size(); i != e; ++i)
Chris Lattner83738a22009-12-30 20:25:09 +0000588 if (V[i] != C)
Owen Anderson1fd70962009-07-28 18:32:17 +0000589 return pImpl->ArrayConstants.getOrCreate(Ty, V);
Owen Anderson1fd70962009-07-28 18:32:17 +0000590 }
591
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000592 return ConstantAggregateZero::get(Ty);
Owen Anderson1fd70962009-07-28 18:32:17 +0000593}
594
Owen Anderson1fd70962009-07-28 18:32:17 +0000595/// ConstantArray::get(const string&) - Return an array that is initialized to
596/// contain the specified string. If length is zero then a null terminator is
597/// added to the specified string so that it may be used in a natural way.
598/// Otherwise, the length parameter specifies how much of the string to use
599/// and it won't be null terminated.
600///
Chris Lattnerf067d582011-02-07 16:40:21 +0000601Constant *ConstantArray::get(LLVMContext &Context, StringRef Str,
Owen Anderson1d0be152009-08-13 21:58:54 +0000602 bool AddNull) {
Owen Anderson1fd70962009-07-28 18:32:17 +0000603 std::vector<Constant*> ElementVals;
Benjamin Kramerad2b04c2010-08-01 11:43:26 +0000604 ElementVals.reserve(Str.size() + size_t(AddNull));
Owen Anderson1fd70962009-07-28 18:32:17 +0000605 for (unsigned i = 0; i < Str.size(); ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +0000606 ElementVals.push_back(ConstantInt::get(Type::getInt8Ty(Context), Str[i]));
Owen Anderson1fd70962009-07-28 18:32:17 +0000607
608 // Add a null terminator to the string...
609 if (AddNull) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000610 ElementVals.push_back(ConstantInt::get(Type::getInt8Ty(Context), 0));
Owen Anderson1fd70962009-07-28 18:32:17 +0000611 }
612
Owen Anderson1d0be152009-08-13 21:58:54 +0000613 ArrayType *ATy = ArrayType::get(Type::getInt8Ty(Context), ElementVals.size());
Owen Anderson1fd70962009-07-28 18:32:17 +0000614 return get(ATy, ElementVals);
615}
616
Chris Lattnerb065b062011-06-20 04:01:31 +0000617/// getTypeForElements - Return an anonymous struct type to use for a constant
618/// with the specified set of elements. The list must not be empty.
619StructType *ConstantStruct::getTypeForElements(LLVMContext &Context,
620 ArrayRef<Constant*> V,
621 bool Packed) {
Jay Foad5fdd6c82011-07-12 14:06:48 +0000622 SmallVector<Type*, 16> EltTypes;
Chris Lattnerb065b062011-06-20 04:01:31 +0000623 for (unsigned i = 0, e = V.size(); i != e; ++i)
624 EltTypes.push_back(V[i]->getType());
625
626 return StructType::get(Context, EltTypes, Packed);
627}
628
629
630StructType *ConstantStruct::getTypeForElements(ArrayRef<Constant*> V,
631 bool Packed) {
632 assert(!V.empty() &&
633 "ConstantStruct::getTypeForElements cannot be called on empty list");
634 return getTypeForElements(V[0]->getContext(), V, Packed);
635}
636
637
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000638ConstantStruct::ConstantStruct(const StructType *T,
Chris Lattnere4671472005-01-29 00:34:39 +0000639 const std::vector<Constant*> &V)
Gabor Greifefe65362008-05-10 08:32:32 +0000640 : Constant(T, ConstantStructVal,
641 OperandTraits<ConstantStruct>::op_end(this) - V.size(),
642 V.size()) {
Chris Lattner1afcace2011-07-09 17:41:24 +0000643 assert((T->isOpaque() || V.size() == T->getNumElements()) &&
Vikram S. Adve345e0cf2002-07-14 23:13:17 +0000644 "Invalid initializer vector for constant structure");
Chris Lattnere4671472005-01-29 00:34:39 +0000645 Use *OL = OperandList;
Chris Lattnerdfdd6c52005-10-03 21:56:24 +0000646 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
647 I != E; ++I, ++OL) {
Chris Lattner71abaab2005-10-07 05:23:36 +0000648 Constant *C = *I;
Chris Lattner1afcace2011-07-09 17:41:24 +0000649 assert((T->isOpaque() || C->getType() == T->getElementType(I-V.begin())) &&
Chris Lattnerb8438892003-06-02 17:42:47 +0000650 "Initializer for struct element doesn't match struct element type!");
Gabor Greif6c80c382008-05-26 21:33:52 +0000651 *OL = C;
Chris Lattner00950542001-06-06 20:29:01 +0000652 }
653}
654
Owen Anderson8fa33382009-07-27 22:29:26 +0000655// ConstantStruct accessors.
Chris Lattnerb065b062011-06-20 04:01:31 +0000656Constant *ConstantStruct::get(const StructType *ST, ArrayRef<Constant*> V) {
Chris Lattnerb065b062011-06-20 04:01:31 +0000657 // Create a ConstantAggregateZero value if all elements are zeros.
Owen Anderson8fa33382009-07-27 22:29:26 +0000658 for (unsigned i = 0, e = V.size(); i != e; ++i)
Jay Foad0df445b2011-06-22 08:55:11 +0000659 if (!V[i]->isNullValue())
660 return ST->getContext().pImpl->StructConstants.getOrCreate(ST, V);
Owen Anderson8fa33382009-07-27 22:29:26 +0000661
Chris Lattner1afcace2011-07-09 17:41:24 +0000662 assert((ST->isOpaque() || ST->getNumElements() == V.size()) &&
663 "Incorrect # elements specified to ConstantStruct::get");
Chris Lattnerb065b062011-06-20 04:01:31 +0000664 return ConstantAggregateZero::get(ST);
Owen Anderson8fa33382009-07-27 22:29:26 +0000665}
666
Chris Lattnerb065b062011-06-20 04:01:31 +0000667Constant* ConstantStruct::get(const StructType *T, ...) {
Talin41ee4e52011-02-28 23:53:27 +0000668 va_list ap;
Chris Lattnerb065b062011-06-20 04:01:31 +0000669 SmallVector<Constant*, 8> Values;
670 va_start(ap, T);
671 while (Constant *Val = va_arg(ap, llvm::Constant*))
Talin41ee4e52011-02-28 23:53:27 +0000672 Values.push_back(Val);
Talinbdcd7662011-03-01 18:00:49 +0000673 va_end(ap);
Chris Lattnerb065b062011-06-20 04:01:31 +0000674 return get(T, Values);
Talin41ee4e52011-02-28 23:53:27 +0000675}
676
Reid Spencer9d6565a2007-02-15 02:26:10 +0000677ConstantVector::ConstantVector(const VectorType *T,
Chris Lattnere4671472005-01-29 00:34:39 +0000678 const std::vector<Constant*> &V)
Gabor Greifefe65362008-05-10 08:32:32 +0000679 : Constant(T, ConstantVectorVal,
680 OperandTraits<ConstantVector>::op_end(this) - V.size(),
681 V.size()) {
Chris Lattnere4671472005-01-29 00:34:39 +0000682 Use *OL = OperandList;
Jay Foad9afc5272011-01-27 14:44:55 +0000683 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
684 I != E; ++I, ++OL) {
685 Constant *C = *I;
686 assert(C->getType() == T->getElementType() &&
Dan Gohmanfa73ea22007-05-24 14:36:04 +0000687 "Initializer for vector element doesn't match vector element type!");
Gabor Greif6c80c382008-05-26 21:33:52 +0000688 *OL = C;
Brian Gaeke715c90b2004-08-20 06:00:58 +0000689 }
690}
691
Owen Andersonaf7ec972009-07-28 21:19:26 +0000692// ConstantVector accessors.
Jay Foada0c13842011-06-22 09:10:19 +0000693Constant *ConstantVector::get(ArrayRef<Constant*> V) {
Jay Foad9afc5272011-01-27 14:44:55 +0000694 assert(!V.empty() && "Vectors can't be empty");
Jay Foada0c13842011-06-22 09:10:19 +0000695 const VectorType *T = VectorType::get(V.front()->getType(), V.size());
Chris Lattner2ca5c862011-02-15 00:14:00 +0000696 LLVMContextImpl *pImpl = T->getContext().pImpl;
Jay Foad9afc5272011-01-27 14:44:55 +0000697
Chris Lattner2ca5c862011-02-15 00:14:00 +0000698 // If this is an all-undef or all-zero vector, return a
Owen Andersonaf7ec972009-07-28 21:19:26 +0000699 // ConstantAggregateZero or UndefValue.
700 Constant *C = V[0];
701 bool isZero = C->isNullValue();
702 bool isUndef = isa<UndefValue>(C);
703
704 if (isZero || isUndef) {
705 for (unsigned i = 1, e = V.size(); i != e; ++i)
706 if (V[i] != C) {
707 isZero = isUndef = false;
708 break;
709 }
710 }
711
712 if (isZero)
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000713 return ConstantAggregateZero::get(T);
Owen Andersonaf7ec972009-07-28 21:19:26 +0000714 if (isUndef)
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000715 return UndefValue::get(T);
Owen Andersonaf7ec972009-07-28 21:19:26 +0000716
Owen Andersonaf7ec972009-07-28 21:19:26 +0000717 return pImpl->VectorConstants.getOrCreate(T, V);
718}
719
Reid Spencer3da59db2006-11-27 01:05:10 +0000720// Utility function for determining if a ConstantExpr is a CastOp or not. This
721// can't be inline because we don't want to #include Instruction.h into
722// Constant.h
723bool ConstantExpr::isCast() const {
724 return Instruction::isCast(getOpcode());
725}
726
Reid Spencer077d0eb2006-12-04 05:19:50 +0000727bool ConstantExpr::isCompare() const {
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +0000728 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
Reid Spencer077d0eb2006-12-04 05:19:50 +0000729}
730
Dan Gohmane6992f72009-09-10 23:37:55 +0000731bool ConstantExpr::isGEPWithNoNotionalOverIndexing() const {
732 if (getOpcode() != Instruction::GetElementPtr) return false;
733
734 gep_type_iterator GEPI = gep_type_begin(this), E = gep_type_end(this);
Oscar Fuentesee56c422010-08-02 06:00:15 +0000735 User::const_op_iterator OI = llvm::next(this->op_begin());
Dan Gohmane6992f72009-09-10 23:37:55 +0000736
737 // Skip the first index, as it has no static limit.
738 ++GEPI;
739 ++OI;
740
741 // The remaining indices must be compile-time known integers within the
742 // bounds of the corresponding notional static array types.
743 for (; GEPI != E; ++GEPI, ++OI) {
744 ConstantInt *CI = dyn_cast<ConstantInt>(*OI);
745 if (!CI) return false;
746 if (const ArrayType *ATy = dyn_cast<ArrayType>(*GEPI))
747 if (CI->getValue().getActiveBits() > 64 ||
748 CI->getZExtValue() >= ATy->getNumElements())
749 return false;
750 }
751
752 // All the indices checked out.
753 return true;
754}
755
Dan Gohman81a0c0b2008-05-31 00:58:22 +0000756bool ConstantExpr::hasIndices() const {
757 return getOpcode() == Instruction::ExtractValue ||
758 getOpcode() == Instruction::InsertValue;
759}
760
Jay Foadd30aa5a2011-04-13 15:22:40 +0000761ArrayRef<unsigned> ConstantExpr::getIndices() const {
Dan Gohman81a0c0b2008-05-31 00:58:22 +0000762 if (const ExtractValueConstantExpr *EVCE =
763 dyn_cast<ExtractValueConstantExpr>(this))
764 return EVCE->Indices;
Dan Gohman1a203572008-06-23 16:39:44 +0000765
766 return cast<InsertValueConstantExpr>(this)->Indices;
Dan Gohman81a0c0b2008-05-31 00:58:22 +0000767}
768
Reid Spencer728b6db2006-12-03 05:48:19 +0000769unsigned ConstantExpr::getPredicate() const {
Nate Begemanac80ade2008-05-12 19:01:56 +0000770 assert(getOpcode() == Instruction::FCmp ||
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +0000771 getOpcode() == Instruction::ICmp);
Chris Lattnerb7daa842007-10-18 16:26:24 +0000772 return ((const CompareConstantExpr*)this)->predicate;
Reid Spencer728b6db2006-12-03 05:48:19 +0000773}
Chris Lattnerf4ba6c72001-10-03 06:12:09 +0000774
Chris Lattner1fe8f6b2006-07-14 19:37:40 +0000775/// getWithOperandReplaced - Return a constant expression identical to this
776/// one, but with the specified operand set to the specified value.
Reid Spencer3da59db2006-11-27 01:05:10 +0000777Constant *
778ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
Chris Lattner1fe8f6b2006-07-14 19:37:40 +0000779 assert(OpNo < getNumOperands() && "Operand num is out of range!");
780 assert(Op->getType() == getOperand(OpNo)->getType() &&
781 "Replacing operand with value of different type!");
Chris Lattnerb88a7fb2006-07-14 22:20:01 +0000782 if (getOperand(OpNo) == Op)
783 return const_cast<ConstantExpr*>(this);
Chris Lattner1fe8f6b2006-07-14 19:37:40 +0000784
Chris Lattnerb88a7fb2006-07-14 22:20:01 +0000785 Constant *Op0, *Op1, *Op2;
Chris Lattner1fe8f6b2006-07-14 19:37:40 +0000786 switch (getOpcode()) {
Reid Spencer3da59db2006-11-27 01:05:10 +0000787 case Instruction::Trunc:
788 case Instruction::ZExt:
789 case Instruction::SExt:
790 case Instruction::FPTrunc:
791 case Instruction::FPExt:
792 case Instruction::UIToFP:
793 case Instruction::SIToFP:
794 case Instruction::FPToUI:
795 case Instruction::FPToSI:
796 case Instruction::PtrToInt:
797 case Instruction::IntToPtr:
798 case Instruction::BitCast:
799 return ConstantExpr::getCast(getOpcode(), Op, getType());
Chris Lattnerb88a7fb2006-07-14 22:20:01 +0000800 case Instruction::Select:
801 Op0 = (OpNo == 0) ? Op : getOperand(0);
802 Op1 = (OpNo == 1) ? Op : getOperand(1);
803 Op2 = (OpNo == 2) ? Op : getOperand(2);
804 return ConstantExpr::getSelect(Op0, Op1, Op2);
805 case Instruction::InsertElement:
806 Op0 = (OpNo == 0) ? Op : getOperand(0);
807 Op1 = (OpNo == 1) ? Op : getOperand(1);
808 Op2 = (OpNo == 2) ? Op : getOperand(2);
809 return ConstantExpr::getInsertElement(Op0, Op1, Op2);
810 case Instruction::ExtractElement:
811 Op0 = (OpNo == 0) ? Op : getOperand(0);
812 Op1 = (OpNo == 1) ? Op : getOperand(1);
813 return ConstantExpr::getExtractElement(Op0, Op1);
814 case Instruction::ShuffleVector:
815 Op0 = (OpNo == 0) ? Op : getOperand(0);
816 Op1 = (OpNo == 1) ? Op : getOperand(1);
817 Op2 = (OpNo == 2) ? Op : getOperand(2);
818 return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Chris Lattner1fe8f6b2006-07-14 19:37:40 +0000819 case Instruction::GetElementPtr: {
Chris Lattnerf9021ff2007-02-19 20:01:23 +0000820 SmallVector<Constant*, 8> Ops;
Dan Gohman041e2eb2008-05-15 19:50:34 +0000821 Ops.resize(getNumOperands()-1);
Chris Lattner1fe8f6b2006-07-14 19:37:40 +0000822 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
Dan Gohman041e2eb2008-05-15 19:50:34 +0000823 Ops[i-1] = getOperand(i);
Chris Lattner1fe8f6b2006-07-14 19:37:40 +0000824 if (OpNo == 0)
Dan Gohmanf8dbee72009-09-07 23:54:19 +0000825 return cast<GEPOperator>(this)->isInBounds() ?
826 ConstantExpr::getInBoundsGetElementPtr(Op, &Ops[0], Ops.size()) :
827 ConstantExpr::getGetElementPtr(Op, &Ops[0], Ops.size());
Chris Lattner1fe8f6b2006-07-14 19:37:40 +0000828 Ops[OpNo-1] = Op;
Dan Gohmanf8dbee72009-09-07 23:54:19 +0000829 return cast<GEPOperator>(this)->isInBounds() ?
Chris Lattnercafe9bb2009-12-29 02:14:09 +0000830 ConstantExpr::getInBoundsGetElementPtr(getOperand(0), &Ops[0],Ops.size()):
Dan Gohmanf8dbee72009-09-07 23:54:19 +0000831 ConstantExpr::getGetElementPtr(getOperand(0), &Ops[0], Ops.size());
Chris Lattner1fe8f6b2006-07-14 19:37:40 +0000832 }
Chris Lattner1fe8f6b2006-07-14 19:37:40 +0000833 default:
834 assert(getNumOperands() == 2 && "Must be binary operator?");
Chris Lattnerb88a7fb2006-07-14 22:20:01 +0000835 Op0 = (OpNo == 0) ? Op : getOperand(0);
836 Op1 = (OpNo == 1) ? Op : getOperand(1);
Chris Lattnercafe9bb2009-12-29 02:14:09 +0000837 return ConstantExpr::get(getOpcode(), Op0, Op1, SubclassOptionalData);
Chris Lattnerb88a7fb2006-07-14 22:20:01 +0000838 }
839}
840
841/// getWithOperands - This returns the current constant expression with the
Chris Lattner1afcace2011-07-09 17:41:24 +0000842/// operands replaced with the specified values. The specified array must
843/// have the same number of operands as our current one.
Chris Lattnerb88a7fb2006-07-14 22:20:01 +0000844Constant *ConstantExpr::
Chris Lattner1afcace2011-07-09 17:41:24 +0000845getWithOperands(ArrayRef<Constant*> Ops, const Type *Ty) const {
Jay Foadb81e4572011-04-13 13:46:01 +0000846 assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
Chris Lattner1afcace2011-07-09 17:41:24 +0000847 bool AnyChange = Ty != getType();
848 for (unsigned i = 0; i != Ops.size(); ++i)
Chris Lattnerb88a7fb2006-07-14 22:20:01 +0000849 AnyChange |= Ops[i] != getOperand(i);
Chris Lattner1afcace2011-07-09 17:41:24 +0000850
Chris Lattnerb88a7fb2006-07-14 22:20:01 +0000851 if (!AnyChange) // No operands changed, return self.
852 return const_cast<ConstantExpr*>(this);
853
854 switch (getOpcode()) {
Reid Spencer3da59db2006-11-27 01:05:10 +0000855 case Instruction::Trunc:
856 case Instruction::ZExt:
857 case Instruction::SExt:
858 case Instruction::FPTrunc:
859 case Instruction::FPExt:
860 case Instruction::UIToFP:
861 case Instruction::SIToFP:
862 case Instruction::FPToUI:
863 case Instruction::FPToSI:
864 case Instruction::PtrToInt:
865 case Instruction::IntToPtr:
866 case Instruction::BitCast:
Chris Lattner1afcace2011-07-09 17:41:24 +0000867 return ConstantExpr::getCast(getOpcode(), Ops[0], Ty);
Chris Lattnerb88a7fb2006-07-14 22:20:01 +0000868 case Instruction::Select:
869 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
870 case Instruction::InsertElement:
871 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
872 case Instruction::ExtractElement:
873 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
874 case Instruction::ShuffleVector:
875 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
Chris Lattnerf9021ff2007-02-19 20:01:23 +0000876 case Instruction::GetElementPtr:
Dan Gohmanf8dbee72009-09-07 23:54:19 +0000877 return cast<GEPOperator>(this)->isInBounds() ?
Jay Foadb81e4572011-04-13 13:46:01 +0000878 ConstantExpr::getInBoundsGetElementPtr(Ops[0], &Ops[1], Ops.size()-1) :
879 ConstantExpr::getGetElementPtr(Ops[0], &Ops[1], Ops.size()-1);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000880 case Instruction::ICmp:
881 case Instruction::FCmp:
882 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
Chris Lattnerb88a7fb2006-07-14 22:20:01 +0000883 default:
884 assert(getNumOperands() == 2 && "Must be binary operator?");
Chris Lattnercafe9bb2009-12-29 02:14:09 +0000885 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1], SubclassOptionalData);
Chris Lattner1fe8f6b2006-07-14 19:37:40 +0000886 }
887}
888
Chris Lattner00950542001-06-06 20:29:01 +0000889
890//===----------------------------------------------------------------------===//
Chris Lattner00950542001-06-06 20:29:01 +0000891// isValueValidForType implementations
892
Reid Spencer9b11d512006-12-19 01:28:19 +0000893bool ConstantInt::isValueValidForType(const Type *Ty, uint64_t Val) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000894 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
Owen Anderson1d0be152009-08-13 21:58:54 +0000895 if (Ty == Type::getInt1Ty(Ty->getContext()))
Reid Spencera54b7cb2007-01-12 07:05:14 +0000896 return Val == 0 || Val == 1;
Reid Spencer554cec62007-02-05 23:47:56 +0000897 if (NumBits >= 64)
Reid Spencera54b7cb2007-01-12 07:05:14 +0000898 return true; // always true, has to fit in largest type
899 uint64_t Max = (1ll << NumBits) - 1;
900 return Val <= Max;
Reid Spencer9b11d512006-12-19 01:28:19 +0000901}
902
Reid Spencerb83eb642006-10-20 07:07:24 +0000903bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000904 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
Owen Anderson1d0be152009-08-13 21:58:54 +0000905 if (Ty == Type::getInt1Ty(Ty->getContext()))
Reid Spencerc1030572007-01-19 21:13:56 +0000906 return Val == 0 || Val == 1 || Val == -1;
Reid Spencer554cec62007-02-05 23:47:56 +0000907 if (NumBits >= 64)
Reid Spencera54b7cb2007-01-12 07:05:14 +0000908 return true; // always true, has to fit in largest type
909 int64_t Min = -(1ll << (NumBits-1));
910 int64_t Max = (1ll << (NumBits-1)) - 1;
911 return (Val >= Min && Val <= Max);
Chris Lattner00950542001-06-06 20:29:01 +0000912}
913
Dale Johannesenf04afdb2007-08-30 00:23:21 +0000914bool ConstantFP::isValueValidForType(const Type *Ty, const APFloat& Val) {
915 // convert modifies in place, so make a copy.
916 APFloat Val2 = APFloat(Val);
Dale Johannesen23a98552008-10-09 23:00:39 +0000917 bool losesInfo;
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000918 switch (Ty->getTypeID()) {
Chris Lattner00950542001-06-06 20:29:01 +0000919 default:
920 return false; // These can't be represented as floating point!
921
Dale Johannesenf04afdb2007-08-30 00:23:21 +0000922 // FIXME rounding mode needs to be more flexible
Dale Johannesen23a98552008-10-09 23:00:39 +0000923 case Type::FloatTyID: {
924 if (&Val2.getSemantics() == &APFloat::IEEEsingle)
925 return true;
926 Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &losesInfo);
927 return !losesInfo;
928 }
929 case Type::DoubleTyID: {
930 if (&Val2.getSemantics() == &APFloat::IEEEsingle ||
931 &Val2.getSemantics() == &APFloat::IEEEdouble)
932 return true;
933 Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &losesInfo);
934 return !losesInfo;
935 }
Dale Johannesenebbc95d2007-08-09 22:51:36 +0000936 case Type::X86_FP80TyID:
Dale Johannesen9d5f4562007-09-12 03:30:33 +0000937 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
938 &Val2.getSemantics() == &APFloat::IEEEdouble ||
939 &Val2.getSemantics() == &APFloat::x87DoubleExtended;
Dale Johannesenebbc95d2007-08-09 22:51:36 +0000940 case Type::FP128TyID:
Dale Johannesen9d5f4562007-09-12 03:30:33 +0000941 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
942 &Val2.getSemantics() == &APFloat::IEEEdouble ||
943 &Val2.getSemantics() == &APFloat::IEEEquad;
Dale Johannesena471c2e2007-10-11 18:07:22 +0000944 case Type::PPC_FP128TyID:
945 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
946 &Val2.getSemantics() == &APFloat::IEEEdouble ||
947 &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
Chris Lattner00950542001-06-06 20:29:01 +0000948 }
Chris Lattnerd74ea2b2006-05-24 17:04:05 +0000949}
Chris Lattner37bf6302001-07-20 19:16:02 +0000950
Chris Lattner531daef2001-09-07 16:46:31 +0000951//===----------------------------------------------------------------------===//
Chris Lattner531daef2001-09-07 16:46:31 +0000952// Factory Function Implementation
953
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000954ConstantAggregateZero* ConstantAggregateZero::get(const Type* Ty) {
Chris Lattner61c70e92010-08-28 04:09:24 +0000955 assert((Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()) &&
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000956 "Cannot create an aggregate zero of non-aggregate type!");
957
958 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000959 return pImpl->AggZeroConstants.getOrCreate(Ty, 0);
960}
961
Dan Gohman0f8b53f2009-03-03 02:55:14 +0000962/// destroyConstant - Remove the constant from the constant table...
963///
Owen Anderson04fb7c32009-06-20 00:24:58 +0000964void ConstantAggregateZero::destroyConstant() {
Chris Lattner1afcace2011-07-09 17:41:24 +0000965 getType()->getContext().pImpl->AggZeroConstants.remove(this);
Chris Lattner40bbeb52004-02-15 05:53:04 +0000966 destroyConstantImpl();
967}
968
Dan Gohman0f8b53f2009-03-03 02:55:14 +0000969/// destroyConstant - Remove the constant from the constant table...
970///
Owen Anderson04fb7c32009-06-20 00:24:58 +0000971void ConstantArray::destroyConstant() {
Chris Lattner1afcace2011-07-09 17:41:24 +0000972 getType()->getContext().pImpl->ArrayConstants.remove(this);
Chris Lattner02ec5ed2003-05-23 20:03:32 +0000973 destroyConstantImpl();
974}
975
Reid Spencer3d10b0b2007-01-26 07:37:34 +0000976/// isString - This method returns true if the array is an array of i8, and
977/// if the elements of the array are all ConstantInt's.
Chris Lattner13cfdea2004-01-14 17:06:38 +0000978bool ConstantArray::isString() const {
Reid Spencer3d10b0b2007-01-26 07:37:34 +0000979 // Check the element type for i8...
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000980 if (!getType()->getElementType()->isIntegerTy(8))
Chris Lattner13cfdea2004-01-14 17:06:38 +0000981 return false;
982 // Check the elements to make sure they are all integers, not constant
983 // expressions.
984 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
985 if (!isa<ConstantInt>(getOperand(i)))
986 return false;
987 return true;
988}
989
Evan Cheng22c70302006-10-26 19:15:05 +0000990/// isCString - This method returns true if the array is a string (see
Dan Gohman0f8b53f2009-03-03 02:55:14 +0000991/// isString) and it ends in a null byte \\0 and does not contains any other
Evan Cheng22c70302006-10-26 19:15:05 +0000992/// null bytes except its terminator.
Owen Anderson1ca29d32009-07-13 21:27:19 +0000993bool ConstantArray::isCString() const {
Reid Spencer3d10b0b2007-01-26 07:37:34 +0000994 // Check the element type for i8...
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000995 if (!getType()->getElementType()->isIntegerTy(8))
Evan Chengabf63452006-10-26 21:48:03 +0000996 return false;
Owen Anderson1ca29d32009-07-13 21:27:19 +0000997
Evan Chengabf63452006-10-26 21:48:03 +0000998 // Last element must be a null.
Owen Anderson1ca29d32009-07-13 21:27:19 +0000999 if (!getOperand(getNumOperands()-1)->isNullValue())
Evan Chengabf63452006-10-26 21:48:03 +00001000 return false;
1001 // Other elements must be non-null integers.
1002 for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
1003 if (!isa<ConstantInt>(getOperand(i)))
Evan Cheng22c70302006-10-26 19:15:05 +00001004 return false;
Owen Anderson1ca29d32009-07-13 21:27:19 +00001005 if (getOperand(i)->isNullValue())
Evan Chengabf63452006-10-26 21:48:03 +00001006 return false;
1007 }
Evan Cheng22c70302006-10-26 19:15:05 +00001008 return true;
1009}
1010
1011
Jay Foad4f910542011-06-28 08:24:19 +00001012/// convertToString - Helper function for getAsString() and getAsCString().
1013static std::string convertToString(const User *U, unsigned len)
1014{
1015 std::string Result;
1016 Result.reserve(len);
1017 for (unsigned i = 0; i != len; ++i)
1018 Result.push_back((char)cast<ConstantInt>(U->getOperand(i))->getZExtValue());
1019 return Result;
1020}
1021
1022/// getAsString - If this array is isString(), then this method converts the
1023/// array to an std::string and returns it. Otherwise, it asserts out.
Dan Gohman0f8b53f2009-03-03 02:55:14 +00001024///
Chris Lattner93aeea32002-08-26 17:53:56 +00001025std::string ConstantArray::getAsString() const {
Chris Lattner13cfdea2004-01-14 17:06:38 +00001026 assert(isString() && "Not a string!");
Jay Foad4f910542011-06-28 08:24:19 +00001027 return convertToString(this, getNumOperands());
1028}
1029
1030
1031/// getAsCString - If this array is isCString(), then this method converts the
1032/// array (without the trailing null byte) to an std::string and returns it.
1033/// Otherwise, it asserts out.
1034///
1035std::string ConstantArray::getAsCString() const {
1036 assert(isCString() && "Not a string!");
1037 return convertToString(this, getNumOperands() - 1);
Chris Lattner93aeea32002-08-26 17:53:56 +00001038}
1039
1040
Chris Lattnere9bb2df2001-12-03 22:26:30 +00001041//---- ConstantStruct::get() implementation...
Chris Lattner531daef2001-09-07 16:46:31 +00001042//
Chris Lattnered468e372003-10-05 00:17:43 +00001043
Chris Lattner31f84992003-11-21 20:23:48 +00001044namespace llvm {
Misha Brukmanfd939082005-04-21 23:48:37 +00001045
Chris Lattner531daef2001-09-07 16:46:31 +00001046}
Chris Lattner6a57baa2001-10-03 15:39:36 +00001047
Chris Lattnerf5ec48d2001-10-13 06:57:33 +00001048// destroyConstant - Remove the constant from the constant table...
Chris Lattner6a57baa2001-10-03 15:39:36 +00001049//
Owen Anderson04fb7c32009-06-20 00:24:58 +00001050void ConstantStruct::destroyConstant() {
Chris Lattner1afcace2011-07-09 17:41:24 +00001051 getType()->getContext().pImpl->StructConstants.remove(this);
Chris Lattnerf5ec48d2001-10-13 06:57:33 +00001052 destroyConstantImpl();
1053}
Chris Lattner6a57baa2001-10-03 15:39:36 +00001054
Brian Gaeke715c90b2004-08-20 06:00:58 +00001055// destroyConstant - Remove the constant from the constant table...
1056//
Owen Anderson04fb7c32009-06-20 00:24:58 +00001057void ConstantVector::destroyConstant() {
Chris Lattner1afcace2011-07-09 17:41:24 +00001058 getType()->getContext().pImpl->VectorConstants.remove(this);
Brian Gaeke715c90b2004-08-20 06:00:58 +00001059 destroyConstantImpl();
1060}
1061
Dan Gohmanfa73ea22007-05-24 14:36:04 +00001062/// This function will return true iff every element in this vector constant
Jim Laskeyfa301822007-01-12 22:39:14 +00001063/// is set to all ones.
1064/// @returns true iff this constant's emements are all set to all ones.
1065/// @brief Determine if the value is all ones.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001066bool ConstantVector::isAllOnesValue() const {
Jim Laskeyfa301822007-01-12 22:39:14 +00001067 // Check out first element.
1068 const Constant *Elt = getOperand(0);
1069 const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1070 if (!CI || !CI->isAllOnesValue()) return false;
1071 // Then make sure all remaining elements point to the same value.
1072 for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
1073 if (getOperand(I) != Elt) return false;
1074 }
1075 return true;
1076}
1077
Dan Gohman3b7cf0a2007-10-17 17:51:30 +00001078/// getSplatValue - If this is a splat constant, where all of the
1079/// elements have the same value, return that value. Otherwise return null.
Duncan Sands7681c6d2011-02-01 08:39:12 +00001080Constant *ConstantVector::getSplatValue() const {
Dan Gohman3b7cf0a2007-10-17 17:51:30 +00001081 // Check out first element.
1082 Constant *Elt = getOperand(0);
1083 // Then make sure all remaining elements point to the same value.
1084 for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
1085 if (getOperand(I) != Elt) return 0;
1086 return Elt;
1087}
1088
Chris Lattner2ee11ec2009-10-28 00:01:44 +00001089//---- ConstantPointerNull::get() implementation.
Chris Lattnerf5ec48d2001-10-13 06:57:33 +00001090//
Chris Lattner02ec5ed2003-05-23 20:03:32 +00001091
Owen Anderson04fb7c32009-06-20 00:24:58 +00001092ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
Owen Anderson7e3142b2009-07-31 22:45:43 +00001093 return Ty->getContext().pImpl->NullPtrConstants.getOrCreate(Ty, 0);
Chris Lattner6a57baa2001-10-03 15:39:36 +00001094}
1095
Chris Lattner41661fd2002-08-18 00:40:04 +00001096// destroyConstant - Remove the constant from the constant table...
1097//
Owen Anderson04fb7c32009-06-20 00:24:58 +00001098void ConstantPointerNull::destroyConstant() {
Chris Lattner1afcace2011-07-09 17:41:24 +00001099 getType()->getContext().pImpl->NullPtrConstants.remove(this);
Chris Lattner41661fd2002-08-18 00:40:04 +00001100 destroyConstantImpl();
1101}
1102
1103
Chris Lattner2ee11ec2009-10-28 00:01:44 +00001104//---- UndefValue::get() implementation.
Chris Lattnerb9f18592004-10-16 18:07:16 +00001105//
1106
Owen Anderson04fb7c32009-06-20 00:24:58 +00001107UndefValue *UndefValue::get(const Type *Ty) {
Owen Anderson7e3142b2009-07-31 22:45:43 +00001108 return Ty->getContext().pImpl->UndefValueConstants.getOrCreate(Ty, 0);
Chris Lattnerb9f18592004-10-16 18:07:16 +00001109}
1110
1111// destroyConstant - Remove the constant from the constant table.
1112//
Owen Anderson04fb7c32009-06-20 00:24:58 +00001113void UndefValue::destroyConstant() {
Chris Lattner1afcace2011-07-09 17:41:24 +00001114 getType()->getContext().pImpl->UndefValueConstants.remove(this);
Chris Lattnerb9f18592004-10-16 18:07:16 +00001115 destroyConstantImpl();
1116}
1117
Chris Lattner2ee11ec2009-10-28 00:01:44 +00001118//---- BlockAddress::get() implementation.
1119//
1120
1121BlockAddress *BlockAddress::get(BasicBlock *BB) {
1122 assert(BB->getParent() != 0 && "Block must have a parent");
1123 return get(BB->getParent(), BB);
1124}
1125
1126BlockAddress *BlockAddress::get(Function *F, BasicBlock *BB) {
1127 BlockAddress *&BA =
1128 F->getContext().pImpl->BlockAddresses[std::make_pair(F, BB)];
1129 if (BA == 0)
1130 BA = new BlockAddress(F, BB);
1131
1132 assert(BA->getFunction() == F && "Basic block moved between functions");
1133 return BA;
1134}
1135
1136BlockAddress::BlockAddress(Function *F, BasicBlock *BB)
1137: Constant(Type::getInt8PtrTy(F->getContext()), Value::BlockAddressVal,
1138 &Op<0>(), 2) {
Chris Lattnerd0ec2352009-11-01 03:03:03 +00001139 setOperand(0, F);
1140 setOperand(1, BB);
Chris Lattnercdfc9402009-11-01 01:27:45 +00001141 BB->AdjustBlockAddressRefCount(1);
Chris Lattner2ee11ec2009-10-28 00:01:44 +00001142}
1143
1144
1145// destroyConstant - Remove the constant from the constant table.
1146//
1147void BlockAddress::destroyConstant() {
Chris Lattner1afcace2011-07-09 17:41:24 +00001148 getFunction()->getType()->getContext().pImpl
Chris Lattner2ee11ec2009-10-28 00:01:44 +00001149 ->BlockAddresses.erase(std::make_pair(getFunction(), getBasicBlock()));
Chris Lattnercdfc9402009-11-01 01:27:45 +00001150 getBasicBlock()->AdjustBlockAddressRefCount(-1);
Chris Lattner2ee11ec2009-10-28 00:01:44 +00001151 destroyConstantImpl();
1152}
1153
1154void BlockAddress::replaceUsesOfWithOnConstant(Value *From, Value *To, Use *U) {
1155 // This could be replacing either the Basic Block or the Function. In either
1156 // case, we have to remove the map entry.
1157 Function *NewF = getFunction();
1158 BasicBlock *NewBB = getBasicBlock();
1159
1160 if (U == &Op<0>())
1161 NewF = cast<Function>(To);
1162 else
1163 NewBB = cast<BasicBlock>(To);
1164
1165 // See if the 'new' entry already exists, if not, just update this in place
1166 // and return early.
1167 BlockAddress *&NewBA =
1168 getContext().pImpl->BlockAddresses[std::make_pair(NewF, NewBB)];
1169 if (NewBA == 0) {
Chris Lattnerd0ec2352009-11-01 03:03:03 +00001170 getBasicBlock()->AdjustBlockAddressRefCount(-1);
1171
Chris Lattner2ee11ec2009-10-28 00:01:44 +00001172 // Remove the old entry, this can't cause the map to rehash (just a
1173 // tombstone will get added).
1174 getContext().pImpl->BlockAddresses.erase(std::make_pair(getFunction(),
1175 getBasicBlock()));
1176 NewBA = this;
Chris Lattnerd0ec2352009-11-01 03:03:03 +00001177 setOperand(0, NewF);
1178 setOperand(1, NewBB);
1179 getBasicBlock()->AdjustBlockAddressRefCount(1);
Chris Lattner2ee11ec2009-10-28 00:01:44 +00001180 return;
1181 }
1182
1183 // Otherwise, I do need to replace this with an existing value.
1184 assert(NewBA != this && "I didn't contain From!");
1185
1186 // Everyone using this now uses the replacement.
1187 uncheckedReplaceAllUsesWith(NewBA);
1188
1189 destroyConstant();
1190}
1191
1192//---- ConstantExpr::get() implementations.
Vikram S. Adve345e0cf2002-07-14 23:13:17 +00001193//
Reid Spencer79e21d32006-12-31 05:26:44 +00001194
Reid Spencer3da59db2006-11-27 01:05:10 +00001195/// This is a utility function to handle folding of casts and lookup of the
Duncan Sands66a1a052008-03-30 19:38:55 +00001196/// cast in the ExprConstants map. It is used by the various get* methods below.
Reid Spencer3da59db2006-11-27 01:05:10 +00001197static inline Constant *getFoldedCast(
Owen Anderson04fb7c32009-06-20 00:24:58 +00001198 Instruction::CastOps opc, Constant *C, const Type *Ty) {
Chris Lattner9eacf8a2003-10-07 22:19:19 +00001199 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
Reid Spencer3da59db2006-11-27 01:05:10 +00001200 // Fold a few common cases
Chris Lattnerb29d5962010-02-01 20:48:08 +00001201 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
Reid Spencer3da59db2006-11-27 01:05:10 +00001202 return FC;
Chris Lattnerd628f6a2003-04-17 19:24:48 +00001203
Owen Andersond03eecd2009-08-04 20:25:11 +00001204 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
1205
Vikram S. Adved0b1bb02002-07-15 18:19:33 +00001206 // Look up the constant in the table first to ensure uniqueness
Chris Lattner9bc02a42003-05-13 21:37:02 +00001207 std::vector<Constant*> argVec(1, C);
Reid Spencer077d0eb2006-12-04 05:19:50 +00001208 ExprMapKeyType Key(opc, argVec);
Owen Anderson3e456ab2009-06-17 18:40:29 +00001209
Owen Andersond03eecd2009-08-04 20:25:11 +00001210 return pImpl->ExprConstants.getOrCreate(Ty, Key);
Vikram S. Adve345e0cf2002-07-14 23:13:17 +00001211}
Reid Spencer7858b332006-12-05 19:14:13 +00001212
Owen Anderson04fb7c32009-06-20 00:24:58 +00001213Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001214 Instruction::CastOps opc = Instruction::CastOps(oc);
1215 assert(Instruction::isCast(opc) && "opcode out of range");
1216 assert(C && Ty && "Null arguments to getCast");
Chris Lattner0b68a002010-01-26 21:51:43 +00001217 assert(CastInst::castIsValid(opc, C, Ty) && "Invalid constantexpr cast!");
Reid Spencer3da59db2006-11-27 01:05:10 +00001218
1219 switch (opc) {
Chris Lattner0b68a002010-01-26 21:51:43 +00001220 default:
1221 llvm_unreachable("Invalid cast opcode");
1222 break;
1223 case Instruction::Trunc: return getTrunc(C, Ty);
1224 case Instruction::ZExt: return getZExt(C, Ty);
1225 case Instruction::SExt: return getSExt(C, Ty);
1226 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
1227 case Instruction::FPExt: return getFPExtend(C, Ty);
1228 case Instruction::UIToFP: return getUIToFP(C, Ty);
1229 case Instruction::SIToFP: return getSIToFP(C, Ty);
1230 case Instruction::FPToUI: return getFPToUI(C, Ty);
1231 case Instruction::FPToSI: return getFPToSI(C, Ty);
1232 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1233 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1234 case Instruction::BitCast: return getBitCast(C, Ty);
Chris Lattnerf5ac6c22005-01-01 15:59:57 +00001235 }
Reid Spencer3da59db2006-11-27 01:05:10 +00001236 return 0;
Reid Spencer7858b332006-12-05 19:14:13 +00001237}
1238
Reid Spencer848414e2006-12-04 20:17:56 +00001239Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
Dan Gohman6de29f82009-06-15 22:12:54 +00001240 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
Dan Gohman3b490632010-04-12 22:12:29 +00001241 return getBitCast(C, Ty);
1242 return getZExt(C, Ty);
Reid Spencer848414e2006-12-04 20:17:56 +00001243}
1244
Owen Anderson04fb7c32009-06-20 00:24:58 +00001245Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
Dan Gohman6de29f82009-06-15 22:12:54 +00001246 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
Dan Gohman3b490632010-04-12 22:12:29 +00001247 return getBitCast(C, Ty);
1248 return getSExt(C, Ty);
Reid Spencer848414e2006-12-04 20:17:56 +00001249}
1250
1251Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
Dan Gohman6de29f82009-06-15 22:12:54 +00001252 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
Dan Gohman3b490632010-04-12 22:12:29 +00001253 return getBitCast(C, Ty);
1254 return getTrunc(C, Ty);
Reid Spencer848414e2006-12-04 20:17:56 +00001255}
1256
Owen Anderson04fb7c32009-06-20 00:24:58 +00001257Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
Duncan Sands1df98592010-02-16 11:11:14 +00001258 assert(S->getType()->isPointerTy() && "Invalid cast");
1259 assert((Ty->isIntegerTy() || Ty->isPointerTy()) && "Invalid cast");
Reid Spencerc0459fb2006-12-05 03:25:26 +00001260
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001261 if (Ty->isIntegerTy())
Dan Gohman3b490632010-04-12 22:12:29 +00001262 return getPtrToInt(S, Ty);
1263 return getBitCast(S, Ty);
Reid Spencerc0459fb2006-12-05 03:25:26 +00001264}
1265
Reid Spencer84f3eab2006-12-12 00:51:07 +00001266Constant *ConstantExpr::getIntegerCast(Constant *C, const Type *Ty,
1267 bool isSigned) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001268 assert(C->getType()->isIntOrIntVectorTy() &&
1269 Ty->isIntOrIntVectorTy() && "Invalid cast");
Dan Gohman6de29f82009-06-15 22:12:54 +00001270 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1271 unsigned DstBits = Ty->getScalarSizeInBits();
Reid Spencer84f3eab2006-12-12 00:51:07 +00001272 Instruction::CastOps opcode =
1273 (SrcBits == DstBits ? Instruction::BitCast :
1274 (SrcBits > DstBits ? Instruction::Trunc :
1275 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1276 return getCast(opcode, C, Ty);
1277}
1278
1279Constant *ConstantExpr::getFPCast(Constant *C, const Type *Ty) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001280 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
Reid Spencer84f3eab2006-12-12 00:51:07 +00001281 "Invalid cast");
Dan Gohman6de29f82009-06-15 22:12:54 +00001282 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1283 unsigned DstBits = Ty->getScalarSizeInBits();
Reid Spencerf25212a2006-12-12 05:38:50 +00001284 if (SrcBits == DstBits)
1285 return C; // Avoid a useless cast
Reid Spencer84f3eab2006-12-12 00:51:07 +00001286 Instruction::CastOps opcode =
Jay Foad9afc5272011-01-27 14:44:55 +00001287 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
Reid Spencer84f3eab2006-12-12 00:51:07 +00001288 return getCast(opcode, C, Ty);
1289}
1290
Owen Anderson04fb7c32009-06-20 00:24:58 +00001291Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
Dan Gohman6de29f82009-06-15 22:12:54 +00001292#ifndef NDEBUG
1293 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1294 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1295#endif
1296 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001297 assert(C->getType()->isIntOrIntVectorTy() && "Trunc operand must be integer");
1298 assert(Ty->isIntOrIntVectorTy() && "Trunc produces only integral");
Dan Gohman6de29f82009-06-15 22:12:54 +00001299 assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
Reid Spencer3da59db2006-11-27 01:05:10 +00001300 "SrcTy must be larger than DestTy for Trunc!");
1301
Owen Anderson04fb7c32009-06-20 00:24:58 +00001302 return getFoldedCast(Instruction::Trunc, C, Ty);
Reid Spencer3da59db2006-11-27 01:05:10 +00001303}
1304
Owen Anderson04fb7c32009-06-20 00:24:58 +00001305Constant *ConstantExpr::getSExt(Constant *C, const Type *Ty) {
Dan Gohman6de29f82009-06-15 22:12:54 +00001306#ifndef NDEBUG
1307 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1308 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1309#endif
1310 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001311 assert(C->getType()->isIntOrIntVectorTy() && "SExt operand must be integral");
1312 assert(Ty->isIntOrIntVectorTy() && "SExt produces only integer");
Dan Gohman6de29f82009-06-15 22:12:54 +00001313 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
Reid Spencer3da59db2006-11-27 01:05:10 +00001314 "SrcTy must be smaller than DestTy for SExt!");
1315
Owen Anderson04fb7c32009-06-20 00:24:58 +00001316 return getFoldedCast(Instruction::SExt, C, Ty);
Chris Lattnerd144f422004-04-04 23:20:30 +00001317}
1318
Owen Anderson04fb7c32009-06-20 00:24:58 +00001319Constant *ConstantExpr::getZExt(Constant *C, const Type *Ty) {
Dan Gohman6de29f82009-06-15 22:12:54 +00001320#ifndef NDEBUG
1321 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1322 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1323#endif
1324 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001325 assert(C->getType()->isIntOrIntVectorTy() && "ZEXt operand must be integral");
1326 assert(Ty->isIntOrIntVectorTy() && "ZExt produces only integer");
Dan Gohman6de29f82009-06-15 22:12:54 +00001327 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
Reid Spencer3da59db2006-11-27 01:05:10 +00001328 "SrcTy must be smaller than DestTy for ZExt!");
1329
Owen Anderson04fb7c32009-06-20 00:24:58 +00001330 return getFoldedCast(Instruction::ZExt, C, Ty);
Reid Spencer3da59db2006-11-27 01:05:10 +00001331}
1332
Owen Anderson04fb7c32009-06-20 00:24:58 +00001333Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
Dan Gohman6de29f82009-06-15 22:12:54 +00001334#ifndef NDEBUG
1335 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1336 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1337#endif
1338 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001339 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00001340 C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
Reid Spencer3da59db2006-11-27 01:05:10 +00001341 "This is an illegal floating point truncation!");
Owen Anderson04fb7c32009-06-20 00:24:58 +00001342 return getFoldedCast(Instruction::FPTrunc, C, Ty);
Reid Spencer3da59db2006-11-27 01:05:10 +00001343}
1344
Owen Anderson04fb7c32009-06-20 00:24:58 +00001345Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
Dan Gohman6de29f82009-06-15 22:12:54 +00001346#ifndef NDEBUG
1347 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1348 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1349#endif
1350 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001351 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00001352 C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
Reid Spencer3da59db2006-11-27 01:05:10 +00001353 "This is an illegal floating point extension!");
Owen Anderson04fb7c32009-06-20 00:24:58 +00001354 return getFoldedCast(Instruction::FPExt, C, Ty);
Reid Spencer3da59db2006-11-27 01:05:10 +00001355}
1356
Owen Anderson04fb7c32009-06-20 00:24:58 +00001357Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
Devang Patelb6dc9352008-11-03 23:20:04 +00001358#ifndef NDEBUG
Nate Begemanb348d182007-11-17 03:58:34 +00001359 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1360 bool toVec = Ty->getTypeID() == Type::VectorTyID;
Devang Patelb6dc9352008-11-03 23:20:04 +00001361#endif
Nate Begemanb348d182007-11-17 03:58:34 +00001362 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001363 assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
Nate Begemanb348d182007-11-17 03:58:34 +00001364 "This is an illegal uint to floating point cast!");
Owen Anderson04fb7c32009-06-20 00:24:58 +00001365 return getFoldedCast(Instruction::UIToFP, C, Ty);
Reid Spencer3da59db2006-11-27 01:05:10 +00001366}
1367
Owen Anderson04fb7c32009-06-20 00:24:58 +00001368Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
Devang Patelb6dc9352008-11-03 23:20:04 +00001369#ifndef NDEBUG
Nate Begemanb348d182007-11-17 03:58:34 +00001370 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1371 bool toVec = Ty->getTypeID() == Type::VectorTyID;
Devang Patelb6dc9352008-11-03 23:20:04 +00001372#endif
Nate Begemanb348d182007-11-17 03:58:34 +00001373 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001374 assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
Reid Spencer3da59db2006-11-27 01:05:10 +00001375 "This is an illegal sint to floating point cast!");
Owen Anderson04fb7c32009-06-20 00:24:58 +00001376 return getFoldedCast(Instruction::SIToFP, C, Ty);
Reid Spencer3da59db2006-11-27 01:05:10 +00001377}
1378
Owen Anderson04fb7c32009-06-20 00:24:58 +00001379Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
Devang Patelb6dc9352008-11-03 23:20:04 +00001380#ifndef NDEBUG
Nate Begemanb348d182007-11-17 03:58:34 +00001381 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1382 bool toVec = Ty->getTypeID() == Type::VectorTyID;
Devang Patelb6dc9352008-11-03 23:20:04 +00001383#endif
Nate Begemanb348d182007-11-17 03:58:34 +00001384 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001385 assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
Nate Begemanb348d182007-11-17 03:58:34 +00001386 "This is an illegal floating point to uint cast!");
Owen Anderson04fb7c32009-06-20 00:24:58 +00001387 return getFoldedCast(Instruction::FPToUI, C, Ty);
Reid Spencer3da59db2006-11-27 01:05:10 +00001388}
1389
Owen Anderson04fb7c32009-06-20 00:24:58 +00001390Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
Devang Patelb6dc9352008-11-03 23:20:04 +00001391#ifndef NDEBUG
Nate Begemanb348d182007-11-17 03:58:34 +00001392 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1393 bool toVec = Ty->getTypeID() == Type::VectorTyID;
Devang Patelb6dc9352008-11-03 23:20:04 +00001394#endif
Nate Begemanb348d182007-11-17 03:58:34 +00001395 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001396 assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
Nate Begemanb348d182007-11-17 03:58:34 +00001397 "This is an illegal floating point to sint cast!");
Owen Anderson04fb7c32009-06-20 00:24:58 +00001398 return getFoldedCast(Instruction::FPToSI, C, Ty);
Reid Spencer3da59db2006-11-27 01:05:10 +00001399}
1400
Owen Anderson04fb7c32009-06-20 00:24:58 +00001401Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
Duncan Sands1df98592010-02-16 11:11:14 +00001402 assert(C->getType()->isPointerTy() && "PtrToInt source must be pointer");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001403 assert(DstTy->isIntegerTy() && "PtrToInt destination must be integral");
Owen Anderson04fb7c32009-06-20 00:24:58 +00001404 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00001405}
1406
Owen Anderson04fb7c32009-06-20 00:24:58 +00001407Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001408 assert(C->getType()->isIntegerTy() && "IntToPtr source must be integral");
Duncan Sands1df98592010-02-16 11:11:14 +00001409 assert(DstTy->isPointerTy() && "IntToPtr destination must be a pointer");
Owen Anderson04fb7c32009-06-20 00:24:58 +00001410 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00001411}
1412
Owen Anderson04fb7c32009-06-20 00:24:58 +00001413Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
Chris Lattner0b68a002010-01-26 21:51:43 +00001414 assert(CastInst::castIsValid(Instruction::BitCast, C, DstTy) &&
1415 "Invalid constantexpr bitcast!");
Chris Lattner8c7f24a2009-03-21 06:55:54 +00001416
1417 // It is common to ask for a bitcast of a value to its own type, handle this
1418 // speedily.
1419 if (C->getType() == DstTy) return C;
1420
Owen Anderson04fb7c32009-06-20 00:24:58 +00001421 return getFoldedCast(Instruction::BitCast, C, DstTy);
Chris Lattnerd144f422004-04-04 23:20:30 +00001422}
1423
Chris Lattnereaf79802011-07-09 18:23:52 +00001424Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2,
1425 unsigned Flags) {
1426 // Check the operands for consistency first.
Reid Spencer0a783f72006-11-02 01:53:59 +00001427 assert(Opcode >= Instruction::BinaryOpsBegin &&
1428 Opcode < Instruction::BinaryOpsEnd &&
Chris Lattnerf31f5832003-05-21 17:49:25 +00001429 "Invalid opcode in binary constant expression");
1430 assert(C1->getType() == C2->getType() &&
1431 "Operand types in binary constant expression should match");
Owen Anderson31c36f02009-06-17 20:10:08 +00001432
Chris Lattner91b362b2004-08-17 17:28:46 +00001433#ifndef NDEBUG
1434 switch (Opcode) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001435 case Instruction::Add:
Reid Spencer0a783f72006-11-02 01:53:59 +00001436 case Instruction::Sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001437 case Instruction::Mul:
Chris Lattner91b362b2004-08-17 17:28:46 +00001438 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001439 assert(C1->getType()->isIntOrIntVectorTy() &&
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001440 "Tried to create an integer operation on a non-integer type!");
1441 break;
1442 case Instruction::FAdd:
1443 case Instruction::FSub:
1444 case Instruction::FMul:
1445 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001446 assert(C1->getType()->isFPOrFPVectorTy() &&
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001447 "Tried to create a floating-point operation on a "
1448 "non-floating-point type!");
Chris Lattner91b362b2004-08-17 17:28:46 +00001449 break;
Reid Spencer1628cec2006-10-26 06:15:43 +00001450 case Instruction::UDiv:
1451 case Instruction::SDiv:
1452 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001453 assert(C1->getType()->isIntOrIntVectorTy() &&
Reid Spencer1628cec2006-10-26 06:15:43 +00001454 "Tried to create an arithmetic operation on a non-arithmetic type!");
1455 break;
1456 case Instruction::FDiv:
1457 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001458 assert(C1->getType()->isFPOrFPVectorTy() &&
Dan Gohmanf57478f2009-06-15 22:25:12 +00001459 "Tried to create an arithmetic operation on a non-arithmetic type!");
Reid Spencer1628cec2006-10-26 06:15:43 +00001460 break;
Reid Spencer0a783f72006-11-02 01:53:59 +00001461 case Instruction::URem:
1462 case Instruction::SRem:
1463 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001464 assert(C1->getType()->isIntOrIntVectorTy() &&
Reid Spencer0a783f72006-11-02 01:53:59 +00001465 "Tried to create an arithmetic operation on a non-arithmetic type!");
1466 break;
1467 case Instruction::FRem:
1468 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001469 assert(C1->getType()->isFPOrFPVectorTy() &&
Dan Gohmanf57478f2009-06-15 22:25:12 +00001470 "Tried to create an arithmetic operation on a non-arithmetic type!");
Reid Spencer0a783f72006-11-02 01:53:59 +00001471 break;
Chris Lattner91b362b2004-08-17 17:28:46 +00001472 case Instruction::And:
1473 case Instruction::Or:
1474 case Instruction::Xor:
1475 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001476 assert(C1->getType()->isIntOrIntVectorTy() &&
Misha Brukman1bae2912005-01-27 06:46:38 +00001477 "Tried to create a logical operation on a non-integral type!");
Chris Lattner91b362b2004-08-17 17:28:46 +00001478 break;
Chris Lattner91b362b2004-08-17 17:28:46 +00001479 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00001480 case Instruction::LShr:
1481 case Instruction::AShr:
Reid Spencer832254e2007-02-02 02:16:23 +00001482 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001483 assert(C1->getType()->isIntOrIntVectorTy() &&
Chris Lattner91b362b2004-08-17 17:28:46 +00001484 "Tried to create a shift operation on a non-integer type!");
1485 break;
1486 default:
1487 break;
1488 }
1489#endif
1490
Chris Lattnereaf79802011-07-09 18:23:52 +00001491 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1492 return FC; // Fold a few common cases.
1493
1494 std::vector<Constant*> argVec(1, C1);
1495 argVec.push_back(C2);
1496 ExprMapKeyType Key(Opcode, argVec, 0, Flags);
1497
1498 LLVMContextImpl *pImpl = C1->getContext().pImpl;
1499 return pImpl->ExprConstants.getOrCreate(C1->getType(), Key);
Reid Spencer67263fe2006-12-04 21:35:24 +00001500}
1501
Chris Lattnerf067d582011-02-07 16:40:21 +00001502Constant *ConstantExpr::getSizeOf(const Type* Ty) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00001503 // sizeof is implemented as: (i64) gep (Ty*)null, 1
1504 // Note that a non-inbounds gep is used, as null isn't within any object.
Owen Anderson1d0be152009-08-13 21:58:54 +00001505 Constant *GEPIdx = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001506 Constant *GEP = getGetElementPtr(
Owen Andersona7235ea2009-07-31 20:28:14 +00001507 Constant::getNullValue(PointerType::getUnqual(Ty)), &GEPIdx, 1);
Dan Gohman3b490632010-04-12 22:12:29 +00001508 return getPtrToInt(GEP,
1509 Type::getInt64Ty(Ty->getContext()));
Owen Andersonbaf3c402009-07-29 18:55:55 +00001510}
1511
Chris Lattnerf067d582011-02-07 16:40:21 +00001512Constant *ConstantExpr::getAlignOf(const Type* Ty) {
Dan Gohman0f5efe52010-01-28 02:15:55 +00001513 // alignof is implemented as: (i64) gep ({i1,Ty}*)null, 0, 1
Dan Gohmane2574d32009-08-11 17:57:01 +00001514 // Note that a non-inbounds gep is used, as null isn't within any object.
Chris Lattnerb2318662011-06-18 22:48:56 +00001515 const Type *AligningTy =
1516 StructType::get(Type::getInt1Ty(Ty->getContext()), Ty, NULL);
Owen Andersona7235ea2009-07-31 20:28:14 +00001517 Constant *NullPtr = Constant::getNullValue(AligningTy->getPointerTo());
Dan Gohman06ed3e72010-01-28 02:43:22 +00001518 Constant *Zero = ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0);
Owen Anderson1d0be152009-08-13 21:58:54 +00001519 Constant *One = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001520 Constant *Indices[2] = { Zero, One };
1521 Constant *GEP = getGetElementPtr(NullPtr, Indices, 2);
Dan Gohman3b490632010-04-12 22:12:29 +00001522 return getPtrToInt(GEP,
1523 Type::getInt64Ty(Ty->getContext()));
Owen Andersonbaf3c402009-07-29 18:55:55 +00001524}
1525
Chris Lattnerf067d582011-02-07 16:40:21 +00001526Constant *ConstantExpr::getOffsetOf(const StructType* STy, unsigned FieldNo) {
Dan Gohman2544a1d2010-02-01 16:37:38 +00001527 return getOffsetOf(STy, ConstantInt::get(Type::getInt32Ty(STy->getContext()),
1528 FieldNo));
1529}
1530
Chris Lattnerf067d582011-02-07 16:40:21 +00001531Constant *ConstantExpr::getOffsetOf(const Type* Ty, Constant *FieldNo) {
Dan Gohman3778f212009-08-16 21:26:11 +00001532 // offsetof is implemented as: (i64) gep (Ty*)null, 0, FieldNo
1533 // Note that a non-inbounds gep is used, as null isn't within any object.
1534 Constant *GEPIdx[] = {
Dan Gohman2544a1d2010-02-01 16:37:38 +00001535 ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0),
1536 FieldNo
Dan Gohman3778f212009-08-16 21:26:11 +00001537 };
1538 Constant *GEP = getGetElementPtr(
Dan Gohman2544a1d2010-02-01 16:37:38 +00001539 Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx, 2);
Dan Gohman3b490632010-04-12 22:12:29 +00001540 return getPtrToInt(GEP,
1541 Type::getInt64Ty(Ty->getContext()));
Dan Gohman3778f212009-08-16 21:26:11 +00001542}
Owen Andersonbaf3c402009-07-29 18:55:55 +00001543
Chris Lattnereaf79802011-07-09 18:23:52 +00001544Constant *ConstantExpr::getCompare(unsigned short Predicate,
1545 Constant *C1, Constant *C2) {
Reid Spencer67263fe2006-12-04 21:35:24 +00001546 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Chris Lattnereaf79802011-07-09 18:23:52 +00001547
1548 switch (Predicate) {
1549 default: llvm_unreachable("Invalid CmpInst predicate");
1550 case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
1551 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
1552 case CmpInst::FCMP_ONE: case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
1553 case CmpInst::FCMP_UEQ: case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
1554 case CmpInst::FCMP_ULT: case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
1555 case CmpInst::FCMP_TRUE:
1556 return getFCmp(Predicate, C1, C2);
1557
1558 case CmpInst::ICMP_EQ: case CmpInst::ICMP_NE: case CmpInst::ICMP_UGT:
1559 case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
1560 case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
1561 case CmpInst::ICMP_SLE:
1562 return getICmp(Predicate, C1, C2);
1563 }
Chris Lattnerc3d12f02004-08-04 18:50:09 +00001564}
1565
Chris Lattnereaf79802011-07-09 18:23:52 +00001566Constant *ConstantExpr::getSelect(Constant *C, Constant *V1, Constant *V2) {
Chris Lattner9ace0cd2008-12-29 00:16:12 +00001567 assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
Chris Lattner08a45cc2004-03-12 05:54:04 +00001568
Chris Lattnereaf79802011-07-09 18:23:52 +00001569 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1570 return SC; // Fold common cases
Chris Lattner08a45cc2004-03-12 05:54:04 +00001571
1572 std::vector<Constant*> argVec(3, C);
1573 argVec[1] = V1;
1574 argVec[2] = V2;
Reid Spencer077d0eb2006-12-04 05:19:50 +00001575 ExprMapKeyType Key(Instruction::Select, argVec);
Owen Anderson31c36f02009-06-17 20:10:08 +00001576
Chris Lattnereaf79802011-07-09 18:23:52 +00001577 LLVMContextImpl *pImpl = C->getContext().pImpl;
1578 return pImpl->ExprConstants.getOrCreate(V1->getType(), Key);
Chris Lattner08a45cc2004-03-12 05:54:04 +00001579}
1580
Chris Lattnereaf79802011-07-09 18:23:52 +00001581Constant *ConstantExpr::getGetElementPtr(Constant *C, Value* const *Idxs,
1582 unsigned NumIdx, bool InBounds) {
Chris Lattner1f78d512011-02-11 05:34:33 +00001583 if (Constant *FC = ConstantFoldGetElementPtr(C, InBounds, Idxs, NumIdx))
1584 return FC; // Fold a few common cases.
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001585
Chris Lattnereaf79802011-07-09 18:23:52 +00001586 // Get the result type of the getelementptr!
1587 const Type *Ty =
1588 GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx);
1589 assert(Ty && "GEP indices invalid!");
1590 unsigned AS = cast<PointerType>(C->getType())->getAddressSpace();
1591 Type *ReqTy = Ty->getPointerTo(AS);
1592
Duncan Sands1df98592010-02-16 11:11:14 +00001593 assert(C->getType()->isPointerTy() &&
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001594 "Non-pointer type for constant GetElementPtr expression");
1595 // Look up the constant in the table first to ensure uniqueness
1596 std::vector<Constant*> ArgVec;
1597 ArgVec.reserve(NumIdx+1);
1598 ArgVec.push_back(C);
1599 for (unsigned i = 0; i != NumIdx; ++i)
1600 ArgVec.push_back(cast<Constant>(Idxs[i]));
1601 const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec, 0,
Chris Lattner1f78d512011-02-11 05:34:33 +00001602 InBounds ? GEPOperator::IsInBounds : 0);
Chris Lattnereaf79802011-07-09 18:23:52 +00001603
1604 LLVMContextImpl *pImpl = C->getContext().pImpl;
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001605 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1606}
1607
Reid Spencer077d0eb2006-12-04 05:19:50 +00001608Constant *
Nick Lewycky401f3252010-01-21 07:03:21 +00001609ConstantExpr::getICmp(unsigned short pred, Constant *LHS, Constant *RHS) {
Reid Spencer077d0eb2006-12-04 05:19:50 +00001610 assert(LHS->getType() == RHS->getType());
1611 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
1612 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
1613
Chris Lattnerb29d5962010-02-01 20:48:08 +00001614 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
Reid Spencer077d0eb2006-12-04 05:19:50 +00001615 return FC; // Fold a few common cases...
1616
1617 // Look up the constant in the table first to ensure uniqueness
1618 std::vector<Constant*> ArgVec;
1619 ArgVec.push_back(LHS);
1620 ArgVec.push_back(RHS);
Reid Spencer4fa021a2006-12-24 18:42:29 +00001621 // Get the key type with both the opcode and predicate
Reid Spencer077d0eb2006-12-04 05:19:50 +00001622 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
Owen Anderson31c36f02009-06-17 20:10:08 +00001623
Nick Lewycky401f3252010-01-21 07:03:21 +00001624 const Type *ResultTy = Type::getInt1Ty(LHS->getContext());
1625 if (const VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
1626 ResultTy = VectorType::get(ResultTy, VT->getNumElements());
1627
Owen Andersond03eecd2009-08-04 20:25:11 +00001628 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
Nick Lewycky401f3252010-01-21 07:03:21 +00001629 return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
Reid Spencer077d0eb2006-12-04 05:19:50 +00001630}
1631
1632Constant *
Nick Lewycky401f3252010-01-21 07:03:21 +00001633ConstantExpr::getFCmp(unsigned short pred, Constant *LHS, Constant *RHS) {
Reid Spencer077d0eb2006-12-04 05:19:50 +00001634 assert(LHS->getType() == RHS->getType());
1635 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
1636
Chris Lattnerb29d5962010-02-01 20:48:08 +00001637 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
Reid Spencer077d0eb2006-12-04 05:19:50 +00001638 return FC; // Fold a few common cases...
1639
1640 // Look up the constant in the table first to ensure uniqueness
1641 std::vector<Constant*> ArgVec;
1642 ArgVec.push_back(LHS);
1643 ArgVec.push_back(RHS);
Reid Spencer4fa021a2006-12-24 18:42:29 +00001644 // Get the key type with both the opcode and predicate
Reid Spencer077d0eb2006-12-04 05:19:50 +00001645 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
Nick Lewycky401f3252010-01-21 07:03:21 +00001646
1647 const Type *ResultTy = Type::getInt1Ty(LHS->getContext());
1648 if (const VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
1649 ResultTy = VectorType::get(ResultTy, VT->getNumElements());
1650
Owen Andersond03eecd2009-08-04 20:25:11 +00001651 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
Nick Lewycky401f3252010-01-21 07:03:21 +00001652 return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
Reid Spencer077d0eb2006-12-04 05:19:50 +00001653}
1654
Robert Bocchinob52ee7f2006-01-10 19:05:34 +00001655Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
Duncan Sands1df98592010-02-16 11:11:14 +00001656 assert(Val->getType()->isVectorTy() &&
Reid Spencerac9dcb92007-02-15 03:39:18 +00001657 "Tried to create extractelement operation on non-vector type!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001658 assert(Idx->getType()->isIntegerTy(32) &&
Reid Spencer3d10b0b2007-01-26 07:37:34 +00001659 "Extractelement index must be i32 type!");
Chris Lattnereaf79802011-07-09 18:23:52 +00001660
1661 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
Chris Lattner83738a22009-12-30 20:25:09 +00001662 return FC; // Fold a few common cases.
Chris Lattnereaf79802011-07-09 18:23:52 +00001663
Robert Bocchinoc152f9c2006-01-17 20:07:22 +00001664 // Look up the constant in the table first to ensure uniqueness
1665 std::vector<Constant*> ArgVec(1, Val);
Robert Bocchinoc152f9c2006-01-17 20:07:22 +00001666 ArgVec.push_back(Idx);
Chris Lattnereaf79802011-07-09 18:23:52 +00001667 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
Owen Anderson31c36f02009-06-17 20:10:08 +00001668
Chris Lattnereaf79802011-07-09 18:23:52 +00001669 LLVMContextImpl *pImpl = Val->getContext().pImpl;
1670 Type *ReqTy = cast<VectorType>(Val->getType())->getElementType();
Owen Andersond03eecd2009-08-04 20:25:11 +00001671 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
Robert Bocchinoc152f9c2006-01-17 20:07:22 +00001672}
1673
1674Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
1675 Constant *Idx) {
Duncan Sands1df98592010-02-16 11:11:14 +00001676 assert(Val->getType()->isVectorTy() &&
Reid Spencerac9dcb92007-02-15 03:39:18 +00001677 "Tried to create insertelement operation on non-vector type!");
Reid Spencer9d6565a2007-02-15 02:26:10 +00001678 assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType()
Robert Bocchinoc152f9c2006-01-17 20:07:22 +00001679 && "Insertelement types must match!");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001680 assert(Idx->getType()->isIntegerTy(32) &&
Reid Spencer3d10b0b2007-01-26 07:37:34 +00001681 "Insertelement index must be i32 type!");
Robert Bocchinoc152f9c2006-01-17 20:07:22 +00001682
Chris Lattnereaf79802011-07-09 18:23:52 +00001683 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
1684 return FC; // Fold a few common cases.
Chris Lattner00f10232006-04-08 01:18:18 +00001685 // Look up the constant in the table first to ensure uniqueness
Chris Lattnereaf79802011-07-09 18:23:52 +00001686 std::vector<Constant*> ArgVec(1, Val);
1687 ArgVec.push_back(Elt);
1688 ArgVec.push_back(Idx);
1689 const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
Owen Anderson31c36f02009-06-17 20:10:08 +00001690
Chris Lattnereaf79802011-07-09 18:23:52 +00001691 LLVMContextImpl *pImpl = Val->getContext().pImpl;
1692 return pImpl->ExprConstants.getOrCreate(Val->getType(), Key);
Chris Lattner00f10232006-04-08 01:18:18 +00001693}
1694
1695Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
1696 Constant *Mask) {
1697 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
1698 "Invalid shuffle vector constant expr operands!");
Nate Begeman0f123cf2009-02-12 21:28:33 +00001699
Chris Lattnereaf79802011-07-09 18:23:52 +00001700 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
1701 return FC; // Fold a few common cases.
1702
Nate Begeman0f123cf2009-02-12 21:28:33 +00001703 unsigned NElts = cast<VectorType>(Mask->getType())->getNumElements();
1704 const Type *EltTy = cast<VectorType>(V1->getType())->getElementType();
1705 const Type *ShufTy = VectorType::get(EltTy, NElts);
Chris Lattnereaf79802011-07-09 18:23:52 +00001706
1707 // Look up the constant in the table first to ensure uniqueness
1708 std::vector<Constant*> ArgVec(1, V1);
1709 ArgVec.push_back(V2);
1710 ArgVec.push_back(Mask);
1711 const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
1712
1713 LLVMContextImpl *pImpl = ShufTy->getContext().pImpl;
1714 return pImpl->ExprConstants.getOrCreate(ShufTy, Key);
Chris Lattner00f10232006-04-08 01:18:18 +00001715}
1716
Chris Lattnereaf79802011-07-09 18:23:52 +00001717Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
1718 const unsigned *Idxs, unsigned NumIdx) {
Dan Gohman041e2eb2008-05-15 19:50:34 +00001719 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
1720 Idxs+NumIdx) == Val->getType() &&
1721 "insertvalue indices invalid!");
Dan Gohmane4569942008-05-23 00:36:11 +00001722 assert(Agg->getType()->isFirstClassType() &&
Chris Lattner4e47aad2011-07-12 05:26:21 +00001723 "Non-first-class type for constant insertvalue expression");
Chris Lattnerb29d5962010-02-01 20:48:08 +00001724 Constant *FC = ConstantFoldInsertValueInstruction(Agg, Val, Idxs, NumIdx);
Chris Lattner4e47aad2011-07-12 05:26:21 +00001725 assert(FC && "insertvalue constant expr couldn't be folded!");
Dan Gohmane0891602008-07-21 23:30:30 +00001726 return FC;
Dan Gohman041e2eb2008-05-15 19:50:34 +00001727}
1728
Chris Lattnereaf79802011-07-09 18:23:52 +00001729Constant *ConstantExpr::getExtractValue(Constant *Agg,
1730 const unsigned *Idxs, unsigned NumIdx) {
Dan Gohmane4569942008-05-23 00:36:11 +00001731 assert(Agg->getType()->isFirstClassType() &&
Chris Lattnereaf79802011-07-09 18:23:52 +00001732 "Tried to create extractelement operation on non-first-class type!");
Dan Gohman041e2eb2008-05-15 19:50:34 +00001733
Chris Lattnereaf79802011-07-09 18:23:52 +00001734 const Type *ReqTy =
1735 ExtractValueInst::getIndexedType(Agg->getType(), Idxs, Idxs+NumIdx);
Chandler Carruthdc770fc2011-07-10 09:45:35 +00001736 (void)ReqTy;
Chris Lattnereaf79802011-07-09 18:23:52 +00001737 assert(ReqTy && "extractvalue indices invalid!");
1738
Dan Gohmane4569942008-05-23 00:36:11 +00001739 assert(Agg->getType()->isFirstClassType() &&
1740 "Non-first-class type for constant extractvalue expression");
Chris Lattnerb29d5962010-02-01 20:48:08 +00001741 Constant *FC = ConstantFoldExtractValueInstruction(Agg, Idxs, NumIdx);
Dan Gohmane0891602008-07-21 23:30:30 +00001742 assert(FC && "ExtractValue constant expr couldn't be folded!");
1743 return FC;
Dan Gohman041e2eb2008-05-15 19:50:34 +00001744}
1745
Chris Lattner81baf142011-02-10 07:01:55 +00001746Constant *ConstantExpr::getNeg(Constant *C, bool HasNUW, bool HasNSW) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001747 assert(C->getType()->isIntOrIntVectorTy() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00001748 "Cannot NEG a nonintegral value!");
Chris Lattner81baf142011-02-10 07:01:55 +00001749 return getSub(ConstantFP::getZeroValueForNegation(C->getType()),
1750 C, HasNUW, HasNSW);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001751}
1752
Chris Lattnerf067d582011-02-07 16:40:21 +00001753Constant *ConstantExpr::getFNeg(Constant *C) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001754 assert(C->getType()->isFPOrFPVectorTy() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00001755 "Cannot FNEG a non-floating-point value!");
Chris Lattner81baf142011-02-10 07:01:55 +00001756 return getFSub(ConstantFP::getZeroValueForNegation(C->getType()), C);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001757}
1758
Chris Lattnerf067d582011-02-07 16:40:21 +00001759Constant *ConstantExpr::getNot(Constant *C) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001760 assert(C->getType()->isIntOrIntVectorTy() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00001761 "Cannot NOT a nonintegral value!");
Owen Andersona7235ea2009-07-31 20:28:14 +00001762 return get(Instruction::Xor, C, Constant::getAllOnesValue(C->getType()));
Owen Andersonbaf3c402009-07-29 18:55:55 +00001763}
1764
Chris Lattner81baf142011-02-10 07:01:55 +00001765Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2,
1766 bool HasNUW, bool HasNSW) {
1767 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
1768 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
1769 return get(Instruction::Add, C1, C2, Flags);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001770}
1771
Chris Lattnerf067d582011-02-07 16:40:21 +00001772Constant *ConstantExpr::getFAdd(Constant *C1, Constant *C2) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00001773 return get(Instruction::FAdd, C1, C2);
1774}
1775
Chris Lattner81baf142011-02-10 07:01:55 +00001776Constant *ConstantExpr::getSub(Constant *C1, Constant *C2,
1777 bool HasNUW, bool HasNSW) {
1778 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
1779 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
1780 return get(Instruction::Sub, C1, C2, Flags);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001781}
1782
Chris Lattnerf067d582011-02-07 16:40:21 +00001783Constant *ConstantExpr::getFSub(Constant *C1, Constant *C2) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00001784 return get(Instruction::FSub, C1, C2);
1785}
1786
Chris Lattner81baf142011-02-10 07:01:55 +00001787Constant *ConstantExpr::getMul(Constant *C1, Constant *C2,
1788 bool HasNUW, bool HasNSW) {
1789 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
1790 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
1791 return get(Instruction::Mul, C1, C2, Flags);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001792}
1793
Chris Lattnerf067d582011-02-07 16:40:21 +00001794Constant *ConstantExpr::getFMul(Constant *C1, Constant *C2) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00001795 return get(Instruction::FMul, C1, C2);
1796}
1797
Chris Lattner74f5c5a2011-02-09 16:43:07 +00001798Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2, bool isExact) {
1799 return get(Instruction::UDiv, C1, C2,
1800 isExact ? PossiblyExactOperator::IsExact : 0);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001801}
1802
Chris Lattner74f5c5a2011-02-09 16:43:07 +00001803Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2, bool isExact) {
1804 return get(Instruction::SDiv, C1, C2,
1805 isExact ? PossiblyExactOperator::IsExact : 0);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001806}
1807
Chris Lattnerf067d582011-02-07 16:40:21 +00001808Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00001809 return get(Instruction::FDiv, C1, C2);
1810}
1811
Chris Lattnerf067d582011-02-07 16:40:21 +00001812Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00001813 return get(Instruction::URem, C1, C2);
1814}
1815
Chris Lattnerf067d582011-02-07 16:40:21 +00001816Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00001817 return get(Instruction::SRem, C1, C2);
1818}
1819
Chris Lattnerf067d582011-02-07 16:40:21 +00001820Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00001821 return get(Instruction::FRem, C1, C2);
1822}
1823
Chris Lattnerf067d582011-02-07 16:40:21 +00001824Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00001825 return get(Instruction::And, C1, C2);
1826}
1827
Chris Lattnerf067d582011-02-07 16:40:21 +00001828Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00001829 return get(Instruction::Or, C1, C2);
1830}
1831
Chris Lattnerf067d582011-02-07 16:40:21 +00001832Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00001833 return get(Instruction::Xor, C1, C2);
1834}
1835
Chris Lattner81baf142011-02-10 07:01:55 +00001836Constant *ConstantExpr::getShl(Constant *C1, Constant *C2,
1837 bool HasNUW, bool HasNSW) {
1838 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
1839 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
1840 return get(Instruction::Shl, C1, C2, Flags);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001841}
1842
Chris Lattner74f5c5a2011-02-09 16:43:07 +00001843Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2, bool isExact) {
1844 return get(Instruction::LShr, C1, C2,
1845 isExact ? PossiblyExactOperator::IsExact : 0);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001846}
1847
Chris Lattner74f5c5a2011-02-09 16:43:07 +00001848Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2, bool isExact) {
1849 return get(Instruction::AShr, C1, C2,
1850 isExact ? PossiblyExactOperator::IsExact : 0);
Owen Andersonbaf3c402009-07-29 18:55:55 +00001851}
1852
Vikram S. Adved0b1bb02002-07-15 18:19:33 +00001853// destroyConstant - Remove the constant from the constant table...
1854//
Owen Anderson04fb7c32009-06-20 00:24:58 +00001855void ConstantExpr::destroyConstant() {
Chris Lattner1afcace2011-07-09 17:41:24 +00001856 getType()->getContext().pImpl->ExprConstants.remove(this);
Vikram S. Adved0b1bb02002-07-15 18:19:33 +00001857 destroyConstantImpl();
Vikram S. Adve345e0cf2002-07-14 23:13:17 +00001858}
1859
Chris Lattnerc188eeb2002-07-30 18:54:25 +00001860const char *ConstantExpr::getOpcodeName() const {
1861 return Instruction::getOpcodeName(getOpcode());
Vikram S. Adve345e0cf2002-07-14 23:13:17 +00001862}
Reid Spencer1c9c8e62004-07-17 23:48:33 +00001863
Chris Lattner04e3b1e2010-03-30 20:48:48 +00001864
1865
1866GetElementPtrConstantExpr::
1867GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
1868 const Type *DestTy)
1869 : ConstantExpr(DestTy, Instruction::GetElementPtr,
1870 OperandTraits<GetElementPtrConstantExpr>::op_end(this)
1871 - (IdxList.size()+1), IdxList.size()+1) {
1872 OperandList[0] = C;
1873 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
1874 OperandList[i+1] = IdxList[i];
1875}
1876
1877
Chris Lattner5cbade92005-10-03 21:58:36 +00001878//===----------------------------------------------------------------------===//
1879// replaceUsesOfWithOnConstant implementations
1880
Chris Lattner54984052007-08-21 00:55:23 +00001881/// replaceUsesOfWithOnConstant - Update this constant array to change uses of
1882/// 'From' to be uses of 'To'. This must update the uniquing data structures
1883/// etc.
1884///
1885/// Note that we intentionally replace all uses of From with To here. Consider
1886/// a large array that uses 'From' 1000 times. By handling this case all here,
1887/// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
1888/// single invocation handles all 1000 uses. Handling them one at a time would
1889/// work, but would be really slow because it would have to unique each updated
1890/// array instance.
Chris Lattner2ee11ec2009-10-28 00:01:44 +00001891///
Chris Lattner5cbade92005-10-03 21:58:36 +00001892void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
Chris Lattnerd0ff1ad2005-10-04 18:13:04 +00001893 Use *U) {
Owen Anderson1fd70962009-07-28 18:32:17 +00001894 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1895 Constant *ToC = cast<Constant>(To);
1896
Chris Lattner1afcace2011-07-09 17:41:24 +00001897 LLVMContextImpl *pImpl = getType()->getContext().pImpl;
Owen Anderson1fd70962009-07-28 18:32:17 +00001898
Dan Gohmane3394d42009-09-15 15:58:07 +00001899 std::pair<LLVMContextImpl::ArrayConstantsTy::MapKey, ConstantArray*> Lookup;
Chris Lattner1afcace2011-07-09 17:41:24 +00001900 Lookup.first.first = cast<ArrayType>(getType());
Owen Anderson1fd70962009-07-28 18:32:17 +00001901 Lookup.second = this;
1902
1903 std::vector<Constant*> &Values = Lookup.first.second;
1904 Values.reserve(getNumOperands()); // Build replacement array.
1905
1906 // Fill values with the modified operands of the constant array. Also,
1907 // compute whether this turns into an all-zeros array.
1908 bool isAllZeros = false;
1909 unsigned NumUpdated = 0;
1910 if (!ToC->isNullValue()) {
1911 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1912 Constant *Val = cast<Constant>(O->get());
1913 if (Val == From) {
1914 Val = ToC;
1915 ++NumUpdated;
1916 }
1917 Values.push_back(Val);
1918 }
1919 } else {
1920 isAllZeros = true;
1921 for (Use *O = OperandList, *E = OperandList+getNumOperands();O != E; ++O) {
1922 Constant *Val = cast<Constant>(O->get());
1923 if (Val == From) {
1924 Val = ToC;
1925 ++NumUpdated;
1926 }
1927 Values.push_back(Val);
1928 if (isAllZeros) isAllZeros = Val->isNullValue();
1929 }
1930 }
1931
1932 Constant *Replacement = 0;
1933 if (isAllZeros) {
Chris Lattner1afcace2011-07-09 17:41:24 +00001934 Replacement = ConstantAggregateZero::get(getType());
Owen Anderson1fd70962009-07-28 18:32:17 +00001935 } else {
1936 // Check to see if we have this array type already.
Owen Anderson1fd70962009-07-28 18:32:17 +00001937 bool Exists;
1938 LLVMContextImpl::ArrayConstantsTy::MapTy::iterator I =
1939 pImpl->ArrayConstants.InsertOrGetItem(Lookup, Exists);
1940
1941 if (Exists) {
Devang Patel5f4ac842009-09-03 01:39:20 +00001942 Replacement = I->second;
Owen Anderson1fd70962009-07-28 18:32:17 +00001943 } else {
1944 // Okay, the new shape doesn't exist in the system yet. Instead of
1945 // creating a new constant array, inserting it, replaceallusesof'ing the
1946 // old with the new, then deleting the old... just update the current one
1947 // in place!
1948 pImpl->ArrayConstants.MoveConstantToNewSlot(this, I);
1949
1950 // Update to the new value. Optimize for the case when we have a single
1951 // operand that we're changing, but handle bulk updates efficiently.
1952 if (NumUpdated == 1) {
1953 unsigned OperandToUpdate = U - OperandList;
1954 assert(getOperand(OperandToUpdate) == From &&
1955 "ReplaceAllUsesWith broken!");
1956 setOperand(OperandToUpdate, ToC);
1957 } else {
1958 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1959 if (getOperand(i) == From)
1960 setOperand(i, ToC);
1961 }
1962 return;
1963 }
1964 }
Chris Lattnercea141f2005-10-03 22:51:37 +00001965
1966 // Otherwise, I do need to replace this with an existing value.
Chris Lattner5cbade92005-10-03 21:58:36 +00001967 assert(Replacement != this && "I didn't contain From!");
1968
Chris Lattnerd0ff1ad2005-10-04 18:13:04 +00001969 // Everyone using this now uses the replacement.
1970 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattner5cbade92005-10-03 21:58:36 +00001971
1972 // Delete the old constant!
1973 destroyConstant();
1974}
1975
1976void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
Chris Lattnerd0ff1ad2005-10-04 18:13:04 +00001977 Use *U) {
Owen Anderson8fa33382009-07-27 22:29:26 +00001978 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1979 Constant *ToC = cast<Constant>(To);
1980
1981 unsigned OperandToUpdate = U-OperandList;
1982 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
1983
Dan Gohmane3394d42009-09-15 15:58:07 +00001984 std::pair<LLVMContextImpl::StructConstantsTy::MapKey, ConstantStruct*> Lookup;
Chris Lattner1afcace2011-07-09 17:41:24 +00001985 Lookup.first.first = cast<StructType>(getType());
Owen Anderson8fa33382009-07-27 22:29:26 +00001986 Lookup.second = this;
1987 std::vector<Constant*> &Values = Lookup.first.second;
1988 Values.reserve(getNumOperands()); // Build replacement struct.
1989
1990
1991 // Fill values with the modified operands of the constant struct. Also,
1992 // compute whether this turns into an all-zeros struct.
1993 bool isAllZeros = false;
1994 if (!ToC->isNullValue()) {
1995 for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O)
1996 Values.push_back(cast<Constant>(O->get()));
1997 } else {
1998 isAllZeros = true;
1999 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2000 Constant *Val = cast<Constant>(O->get());
2001 Values.push_back(Val);
2002 if (isAllZeros) isAllZeros = Val->isNullValue();
2003 }
2004 }
2005 Values[OperandToUpdate] = ToC;
2006
Chris Lattner1afcace2011-07-09 17:41:24 +00002007 LLVMContextImpl *pImpl = getContext().pImpl;
Owen Anderson8fa33382009-07-27 22:29:26 +00002008
2009 Constant *Replacement = 0;
2010 if (isAllZeros) {
Chris Lattner1afcace2011-07-09 17:41:24 +00002011 Replacement = ConstantAggregateZero::get(getType());
Owen Anderson8fa33382009-07-27 22:29:26 +00002012 } else {
Chris Lattner93604b62010-07-17 06:13:52 +00002013 // Check to see if we have this struct type already.
Owen Anderson8fa33382009-07-27 22:29:26 +00002014 bool Exists;
2015 LLVMContextImpl::StructConstantsTy::MapTy::iterator I =
2016 pImpl->StructConstants.InsertOrGetItem(Lookup, Exists);
2017
2018 if (Exists) {
Devang Patel5f4ac842009-09-03 01:39:20 +00002019 Replacement = I->second;
Owen Anderson8fa33382009-07-27 22:29:26 +00002020 } else {
2021 // Okay, the new shape doesn't exist in the system yet. Instead of
2022 // creating a new constant struct, inserting it, replaceallusesof'ing the
2023 // old with the new, then deleting the old... just update the current one
2024 // in place!
2025 pImpl->StructConstants.MoveConstantToNewSlot(this, I);
2026
2027 // Update to the new value.
2028 setOperand(OperandToUpdate, ToC);
2029 return;
2030 }
2031 }
2032
2033 assert(Replacement != this && "I didn't contain From!");
Chris Lattner5cbade92005-10-03 21:58:36 +00002034
Chris Lattnerd0ff1ad2005-10-04 18:13:04 +00002035 // Everyone using this now uses the replacement.
2036 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattner5cbade92005-10-03 21:58:36 +00002037
2038 // Delete the old constant!
2039 destroyConstant();
2040}
2041
Reid Spencer9d6565a2007-02-15 02:26:10 +00002042void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
Chris Lattnerd0ff1ad2005-10-04 18:13:04 +00002043 Use *U) {
Chris Lattner5cbade92005-10-03 21:58:36 +00002044 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2045
2046 std::vector<Constant*> Values;
2047 Values.reserve(getNumOperands()); // Build replacement array...
2048 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2049 Constant *Val = getOperand(i);
2050 if (Val == From) Val = cast<Constant>(To);
2051 Values.push_back(Val);
2052 }
2053
Jay Foada0c13842011-06-22 09:10:19 +00002054 Constant *Replacement = get(Values);
Chris Lattner5cbade92005-10-03 21:58:36 +00002055 assert(Replacement != this && "I didn't contain From!");
2056
Chris Lattnerd0ff1ad2005-10-04 18:13:04 +00002057 // Everyone using this now uses the replacement.
2058 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattner5cbade92005-10-03 21:58:36 +00002059
2060 // Delete the old constant!
2061 destroyConstant();
2062}
2063
2064void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
Chris Lattnerd0ff1ad2005-10-04 18:13:04 +00002065 Use *U) {
Chris Lattner5cbade92005-10-03 21:58:36 +00002066 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2067 Constant *To = cast<Constant>(ToV);
2068
2069 Constant *Replacement = 0;
2070 if (getOpcode() == Instruction::GetElementPtr) {
Chris Lattnerf9021ff2007-02-19 20:01:23 +00002071 SmallVector<Constant*, 8> Indices;
Chris Lattner5cbade92005-10-03 21:58:36 +00002072 Constant *Pointer = getOperand(0);
2073 Indices.reserve(getNumOperands()-1);
2074 if (Pointer == From) Pointer = To;
2075
2076 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2077 Constant *Val = getOperand(i);
2078 if (Val == From) Val = To;
2079 Indices.push_back(Val);
2080 }
Chris Lattnerf9021ff2007-02-19 20:01:23 +00002081 Replacement = ConstantExpr::getGetElementPtr(Pointer,
Chris Lattner33a8f332011-02-11 05:37:21 +00002082 &Indices[0], Indices.size(),
2083 cast<GEPOperator>(this)->isInBounds());
Dan Gohman041e2eb2008-05-15 19:50:34 +00002084 } else if (getOpcode() == Instruction::ExtractValue) {
Dan Gohman041e2eb2008-05-15 19:50:34 +00002085 Constant *Agg = getOperand(0);
Dan Gohman041e2eb2008-05-15 19:50:34 +00002086 if (Agg == From) Agg = To;
2087
Jay Foadd30aa5a2011-04-13 15:22:40 +00002088 ArrayRef<unsigned> Indices = getIndices();
Dan Gohman041e2eb2008-05-15 19:50:34 +00002089 Replacement = ConstantExpr::getExtractValue(Agg,
2090 &Indices[0], Indices.size());
2091 } else if (getOpcode() == Instruction::InsertValue) {
Dan Gohman041e2eb2008-05-15 19:50:34 +00002092 Constant *Agg = getOperand(0);
2093 Constant *Val = getOperand(1);
Dan Gohman041e2eb2008-05-15 19:50:34 +00002094 if (Agg == From) Agg = To;
2095 if (Val == From) Val = To;
2096
Jay Foadd30aa5a2011-04-13 15:22:40 +00002097 ArrayRef<unsigned> Indices = getIndices();
Dan Gohman041e2eb2008-05-15 19:50:34 +00002098 Replacement = ConstantExpr::getInsertValue(Agg, Val,
2099 &Indices[0], Indices.size());
Reid Spencer3da59db2006-11-27 01:05:10 +00002100 } else if (isCast()) {
Chris Lattner5cbade92005-10-03 21:58:36 +00002101 assert(getOperand(0) == From && "Cast only has one use!");
Chris Lattner1afcace2011-07-09 17:41:24 +00002102 Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
Chris Lattner5cbade92005-10-03 21:58:36 +00002103 } else if (getOpcode() == Instruction::Select) {
2104 Constant *C1 = getOperand(0);
2105 Constant *C2 = getOperand(1);
2106 Constant *C3 = getOperand(2);
2107 if (C1 == From) C1 = To;
2108 if (C2 == From) C2 = To;
2109 if (C3 == From) C3 = To;
2110 Replacement = ConstantExpr::getSelect(C1, C2, C3);
Robert Bocchinob52ee7f2006-01-10 19:05:34 +00002111 } else if (getOpcode() == Instruction::ExtractElement) {
2112 Constant *C1 = getOperand(0);
2113 Constant *C2 = getOperand(1);
2114 if (C1 == From) C1 = To;
2115 if (C2 == From) C2 = To;
2116 Replacement = ConstantExpr::getExtractElement(C1, C2);
Chris Lattner42b55802006-04-08 05:09:48 +00002117 } else if (getOpcode() == Instruction::InsertElement) {
2118 Constant *C1 = getOperand(0);
2119 Constant *C2 = getOperand(1);
2120 Constant *C3 = getOperand(1);
2121 if (C1 == From) C1 = To;
2122 if (C2 == From) C2 = To;
2123 if (C3 == From) C3 = To;
2124 Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2125 } else if (getOpcode() == Instruction::ShuffleVector) {
2126 Constant *C1 = getOperand(0);
2127 Constant *C2 = getOperand(1);
2128 Constant *C3 = getOperand(2);
2129 if (C1 == From) C1 = To;
2130 if (C2 == From) C2 = To;
2131 if (C3 == From) C3 = To;
2132 Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
Reid Spencer077d0eb2006-12-04 05:19:50 +00002133 } else if (isCompare()) {
2134 Constant *C1 = getOperand(0);
2135 Constant *C2 = getOperand(1);
2136 if (C1 == From) C1 = To;
2137 if (C2 == From) C2 = To;
2138 if (getOpcode() == Instruction::ICmp)
2139 Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
Chris Lattnerbbedb0e2008-07-14 05:17:31 +00002140 else {
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +00002141 assert(getOpcode() == Instruction::FCmp);
2142 Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
Chris Lattnerbbedb0e2008-07-14 05:17:31 +00002143 }
Chris Lattner5cbade92005-10-03 21:58:36 +00002144 } else if (getNumOperands() == 2) {
2145 Constant *C1 = getOperand(0);
2146 Constant *C2 = getOperand(1);
2147 if (C1 == From) C1 = To;
2148 if (C2 == From) C2 = To;
Chris Lattnercafe9bb2009-12-29 02:14:09 +00002149 Replacement = ConstantExpr::get(getOpcode(), C1, C2, SubclassOptionalData);
Chris Lattner5cbade92005-10-03 21:58:36 +00002150 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00002151 llvm_unreachable("Unknown ConstantExpr type!");
Chris Lattner5cbade92005-10-03 21:58:36 +00002152 return;
2153 }
2154
2155 assert(Replacement != this && "I didn't contain From!");
2156
Chris Lattnerd0ff1ad2005-10-04 18:13:04 +00002157 // Everyone using this now uses the replacement.
2158 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattner5cbade92005-10-03 21:58:36 +00002159
2160 // Delete the old constant!
2161 destroyConstant();
Matthijs Kooijman10b9de62008-07-03 07:46:41 +00002162}