blob: 78d24ef5f50617074fbd564cde7508faac0fa077 [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 Lattnere9bb2df2001-12-03 22:26:30 +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 Lattner92f6fea2007-02-27 03:05:06 +000015#include "ConstantFold.h"
Chris Lattner00950542001-06-06 20:29:01 +000016#include "llvm/DerivedTypes.h"
Reid Spencer1c9c8e62004-07-17 23:48:33 +000017#include "llvm/GlobalValue.h"
Misha Brukman47b14a42004-07-29 17:30:56 +000018#include "llvm/Instructions.h"
Chris Lattnerf5ec48d2001-10-13 06:57:33 +000019#include "llvm/Module.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000020#include "llvm/ADT/StringExtras.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000021#include "llvm/Support/Compiler.h"
Bill Wendling2e3def12006-11-17 08:03:48 +000022#include "llvm/Support/Debug.h"
Chris Lattner8a94bf12006-09-28 00:35:06 +000023#include "llvm/Support/ManagedStatic.h"
Bill Wendling2e3def12006-11-17 08:03:48 +000024#include "llvm/Support/MathExtras.h"
Chris Lattner6b6f6ba2007-02-20 06:39:57 +000025#include "llvm/ADT/DenseMap.h"
Chris Lattnerf9021ff2007-02-19 20:01:23 +000026#include "llvm/ADT/SmallVector.h"
Chris Lattner00950542001-06-06 20:29:01 +000027#include <algorithm>
Reid Spenceref9b9a72007-02-05 20:47:22 +000028#include <map>
Chris Lattner31f84992003-11-21 20:23:48 +000029using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000030
Chris Lattner00950542001-06-06 20:29:01 +000031//===----------------------------------------------------------------------===//
Chris Lattnere9bb2df2001-12-03 22:26:30 +000032// Constant Class
Chris Lattner00950542001-06-06 20:29:01 +000033//===----------------------------------------------------------------------===//
34
Chris Lattnere9bb2df2001-12-03 22:26:30 +000035void Constant::destroyConstantImpl() {
36 // When a Constant is destroyed, there may be lingering
Chris Lattnerf5ec48d2001-10-13 06:57:33 +000037 // references to the constant by other constants in the constant pool. These
Misha Brukmanef6a6a62003-08-21 22:14:26 +000038 // constants are implicitly dependent on the module that is being deleted,
Chris Lattnerf5ec48d2001-10-13 06:57:33 +000039 // but they don't know that. Because we only find out when the CPV is
40 // deleted, we must now notify all of our users (that should only be
Chris Lattnere9bb2df2001-12-03 22:26:30 +000041 // Constants) that they are, in fact, invalid now and should be deleted.
Chris Lattnerf5ec48d2001-10-13 06:57:33 +000042 //
43 while (!use_empty()) {
44 Value *V = use_back();
45#ifndef NDEBUG // Only in -g mode...
Chris Lattner6183b922002-07-18 00:14:50 +000046 if (!isa<Constant>(V))
Bill Wendling2e3def12006-11-17 08:03:48 +000047 DOUT << "While deleting: " << *this
48 << "\n\nUse still stuck around after Def is destroyed: "
49 << *V << "\n\n";
Chris Lattnerf5ec48d2001-10-13 06:57:33 +000050#endif
Vikram S. Adve345e0cf2002-07-14 23:13:17 +000051 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
Reid Spencer1c9c8e62004-07-17 23:48:33 +000052 Constant *CV = cast<Constant>(V);
53 CV->destroyConstant();
Chris Lattnerf5ec48d2001-10-13 06:57:33 +000054
55 // The constant should remove itself from our use list...
Vikram S. Adve345e0cf2002-07-14 23:13:17 +000056 assert((use_empty() || use_back() != V) && "Constant not removed!");
Chris Lattnerf5ec48d2001-10-13 06:57:33 +000057 }
58
59 // Value has no outstanding references it is safe to delete it now...
60 delete this;
Chris Lattner1d87bcf2001-10-01 20:11:19 +000061}
Chris Lattner00950542001-06-06 20:29:01 +000062
Chris Lattner35b89fa2006-10-20 00:27:06 +000063/// canTrap - Return true if evaluation of this constant could trap. This is
64/// true for things like constant expressions that could divide by zero.
65bool Constant::canTrap() const {
66 assert(getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
67 // The only thing that could possibly trap are constant exprs.
68 const ConstantExpr *CE = dyn_cast<ConstantExpr>(this);
69 if (!CE) return false;
70
71 // ConstantExpr traps if any operands can trap.
72 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
73 if (getOperand(i)->canTrap())
74 return true;
75
76 // Otherwise, only specific operations can trap.
77 switch (CE->getOpcode()) {
78 default:
79 return false;
Reid Spencer1628cec2006-10-26 06:15:43 +000080 case Instruction::UDiv:
81 case Instruction::SDiv:
82 case Instruction::FDiv:
Reid Spencer0a783f72006-11-02 01:53:59 +000083 case Instruction::URem:
84 case Instruction::SRem:
85 case Instruction::FRem:
Chris Lattner35b89fa2006-10-20 00:27:06 +000086 // Div and rem can trap if the RHS is not known to be non-zero.
87 if (!isa<ConstantInt>(getOperand(1)) || getOperand(1)->isNullValue())
88 return true;
89 return false;
90 }
91}
92
Evan Chengafe15812007-03-08 00:59:12 +000093/// ContaintsRelocations - Return true if the constant value contains
94/// relocations which cannot be resolved at compile time.
95bool Constant::ContainsRelocations() const {
96 if (isa<GlobalValue>(this))
97 return true;
98 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
99 if (getOperand(i)->ContainsRelocations())
100 return true;
101 return false;
102}
103
Chris Lattner9fb96412002-08-13 17:50:20 +0000104// Static constructor to create a '0' constant of arbitrary type...
105Constant *Constant::getNullValue(const Type *Ty) {
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +0000106 static uint64_t zero[2] = {0, 0};
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000107 switch (Ty->getTypeID()) {
Chris Lattnere0e76962007-02-20 05:46:39 +0000108 case Type::IntegerTyID:
109 return ConstantInt::get(Ty, 0);
110 case Type::FloatTyID:
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +0000111 return ConstantFP::get(Ty, APFloat(APInt(32, 0)));
Chris Lattnere0e76962007-02-20 05:46:39 +0000112 case Type::DoubleTyID:
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +0000113 return ConstantFP::get(Ty, APFloat(APInt(64, 0)));
Dale Johannesenebbc95d2007-08-09 22:51:36 +0000114 case Type::X86_FP80TyID:
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +0000115 return ConstantFP::get(Ty, APFloat(APInt(80, 2, zero)));
Dale Johannesenebbc95d2007-08-09 22:51:36 +0000116 case Type::FP128TyID:
Dale Johannesena471c2e2007-10-11 18:07:22 +0000117 return ConstantFP::get(Ty, APFloat(APInt(128, 2, zero), true));
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +0000118 case Type::PPC_FP128TyID:
119 return ConstantFP::get(Ty, APFloat(APInt(128, 2, zero)));
Misha Brukmanfd939082005-04-21 23:48:37 +0000120 case Type::PointerTyID:
Chris Lattner9fb96412002-08-13 17:50:20 +0000121 return ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattner40bbeb52004-02-15 05:53:04 +0000122 case Type::StructTyID:
123 case Type::ArrayTyID:
Reid Spencer9d6565a2007-02-15 02:26:10 +0000124 case Type::VectorTyID:
Chris Lattner40bbeb52004-02-15 05:53:04 +0000125 return ConstantAggregateZero::get(Ty);
Chris Lattner9fb96412002-08-13 17:50:20 +0000126 default:
Reid Spencer57f6efc2004-07-04 11:51:24 +0000127 // Function, Label, or Opaque type?
128 assert(!"Cannot create a null constant of that type!");
Chris Lattner9fb96412002-08-13 17:50:20 +0000129 return 0;
130 }
131}
132
Chris Lattnercef4b532007-06-15 06:10:53 +0000133Constant *Constant::getAllOnesValue(const Type *Ty) {
134 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty))
135 return ConstantInt::get(APInt::getAllOnesValue(ITy->getBitWidth()));
136 return ConstantVector::getAllOnesValue(cast<VectorType>(Ty));
137}
Chris Lattner9fb96412002-08-13 17:50:20 +0000138
139// Static constructor to create an integral constant with all bits set
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000140ConstantInt *ConstantInt::getAllOnesValue(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000141 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty))
Reid Spencer0050c732007-03-01 19:30:34 +0000142 return ConstantInt::get(APInt::getAllOnesValue(ITy->getBitWidth()));
Reid Spencera54b7cb2007-01-12 07:05:14 +0000143 return 0;
Chris Lattner9fb96412002-08-13 17:50:20 +0000144}
145
Dan Gohmanfa73ea22007-05-24 14:36:04 +0000146/// @returns the value for a vector integer constant of the given type that
Chris Lattner58513aa2007-01-04 01:49:26 +0000147/// has all its bits set to true.
148/// @brief Get the all ones value
Reid Spencer9d6565a2007-02-15 02:26:10 +0000149ConstantVector *ConstantVector::getAllOnesValue(const VectorType *Ty) {
Chris Lattner58513aa2007-01-04 01:49:26 +0000150 std::vector<Constant*> Elts;
151 Elts.resize(Ty->getNumElements(),
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000152 ConstantInt::getAllOnesValue(Ty->getElementType()));
Dan Gohmanfa73ea22007-05-24 14:36:04 +0000153 assert(Elts[0] && "Not a vector integer type!");
Reid Spencer9d6565a2007-02-15 02:26:10 +0000154 return cast<ConstantVector>(ConstantVector::get(Elts));
Chris Lattner58513aa2007-01-04 01:49:26 +0000155}
156
157
Chris Lattner00950542001-06-06 20:29:01 +0000158//===----------------------------------------------------------------------===//
Chris Lattner6b6f6ba2007-02-20 06:39:57 +0000159// ConstantInt
Chris Lattner00950542001-06-06 20:29:01 +0000160//===----------------------------------------------------------------------===//
161
Reid Spencer532d0ce2007-02-26 23:54:03 +0000162ConstantInt::ConstantInt(const IntegerType *Ty, const APInt& V)
Chris Lattnereb41bdd2007-02-20 05:55:46 +0000163 : Constant(Ty, ConstantIntVal, 0, 0), Val(V) {
Reid Spencer532d0ce2007-02-26 23:54:03 +0000164 assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
Chris Lattner00950542001-06-06 20:29:01 +0000165}
166
Chris Lattner6b6f6ba2007-02-20 06:39:57 +0000167ConstantInt *ConstantInt::TheTrueVal = 0;
168ConstantInt *ConstantInt::TheFalseVal = 0;
169
170namespace llvm {
171 void CleanupTrueFalse(void *) {
172 ConstantInt::ResetTrueFalse();
173 }
174}
175
176static ManagedCleanup<llvm::CleanupTrueFalse> TrueFalseCleanup;
177
178ConstantInt *ConstantInt::CreateTrueFalseVals(bool WhichOne) {
179 assert(TheTrueVal == 0 && TheFalseVal == 0);
180 TheTrueVal = get(Type::Int1Ty, 1);
181 TheFalseVal = get(Type::Int1Ty, 0);
182
183 // Ensure that llvm_shutdown nulls out TheTrueVal/TheFalseVal.
184 TrueFalseCleanup.Register();
185
186 return WhichOne ? TheTrueVal : TheFalseVal;
187}
188
189
Chris Lattner6b6f6ba2007-02-20 06:39:57 +0000190namespace {
Reid Spencer532d0ce2007-02-26 23:54:03 +0000191 struct DenseMapAPIntKeyInfo {
192 struct KeyTy {
193 APInt val;
194 const Type* type;
195 KeyTy(const APInt& V, const Type* Ty) : val(V), type(Ty) {}
196 KeyTy(const KeyTy& that) : val(that.val), type(that.type) {}
197 bool operator==(const KeyTy& that) const {
198 return type == that.type && this->val == that.val;
199 }
200 bool operator!=(const KeyTy& that) const {
201 return !this->operator==(that);
202 }
203 };
204 static inline KeyTy getEmptyKey() { return KeyTy(APInt(1,0), 0); }
205 static inline KeyTy getTombstoneKey() { return KeyTy(APInt(1,1), 0); }
Chris Lattner6b6f6ba2007-02-20 06:39:57 +0000206 static unsigned getHashValue(const KeyTy &Key) {
Chris Lattner76c1b972007-09-17 18:34:04 +0000207 return DenseMapInfo<void*>::getHashValue(Key.type) ^
Reid Spencer532d0ce2007-02-26 23:54:03 +0000208 Key.val.getHashValue();
Chris Lattner6b6f6ba2007-02-20 06:39:57 +0000209 }
Chris Lattner76c1b972007-09-17 18:34:04 +0000210 static bool isEqual(const KeyTy &LHS, const KeyTy &RHS) {
211 return LHS == RHS;
212 }
Dale Johannesen343e7702007-08-24 00:56:33 +0000213 static bool isPod() { return false; }
Chris Lattner6b6f6ba2007-02-20 06:39:57 +0000214 };
215}
216
217
Reid Spencer532d0ce2007-02-26 23:54:03 +0000218typedef DenseMap<DenseMapAPIntKeyInfo::KeyTy, ConstantInt*,
219 DenseMapAPIntKeyInfo> IntMapTy;
Chris Lattner6b6f6ba2007-02-20 06:39:57 +0000220static ManagedStatic<IntMapTy> IntConstants;
221
Reid Spencer7fc44c82007-03-19 20:39:08 +0000222ConstantInt *ConstantInt::get(const Type *Ty, uint64_t V, bool isSigned) {
Chris Lattner6b6f6ba2007-02-20 06:39:57 +0000223 const IntegerType *ITy = cast<IntegerType>(Ty);
Reid Spencer7fc44c82007-03-19 20:39:08 +0000224 return get(APInt(ITy->getBitWidth(), V, isSigned));
Reid Spencer532d0ce2007-02-26 23:54:03 +0000225}
226
Reid Spencer0050c732007-03-01 19:30:34 +0000227// Get a ConstantInt from an APInt. Note that the value stored in the DenseMap
Dan Gohmanb3f5cfc2008-02-07 02:30:40 +0000228// as the key, is a DenseMapAPIntKeyInfo::KeyTy which has provided the
Reid Spencer532d0ce2007-02-26 23:54:03 +0000229// operator== and operator!= to ensure that the DenseMap doesn't attempt to
230// compare APInt's of different widths, which would violate an APInt class
231// invariant which generates an assertion.
Reid Spencer0050c732007-03-01 19:30:34 +0000232ConstantInt *ConstantInt::get(const APInt& V) {
233 // Get the corresponding integer type for the bit width of the value.
234 const IntegerType *ITy = IntegerType::get(V.getBitWidth());
Reid Spencer532d0ce2007-02-26 23:54:03 +0000235 // get an existing value or the insertion position
Reid Spencer0050c732007-03-01 19:30:34 +0000236 DenseMapAPIntKeyInfo::KeyTy Key(V, ITy);
Reid Spencer532d0ce2007-02-26 23:54:03 +0000237 ConstantInt *&Slot = (*IntConstants)[Key];
238 // if it exists, return it.
239 if (Slot)
240 return Slot;
241 // otherwise create a new one, insert it, and return it.
Chris Lattner6b6f6ba2007-02-20 06:39:57 +0000242 return Slot = new ConstantInt(ITy, V);
243}
244
245//===----------------------------------------------------------------------===//
Chris Lattner9b4ee0c2007-02-20 07:17:17 +0000246// ConstantFP
Chris Lattner6b6f6ba2007-02-20 06:39:57 +0000247//===----------------------------------------------------------------------===//
248
Dale Johannesenf04afdb2007-08-30 00:23:21 +0000249ConstantFP::ConstantFP(const Type *Ty, const APFloat& V)
250 : Constant(Ty, ConstantFPVal, 0, 0), Val(V) {
251 // temporary
252 if (Ty==Type::FloatTy)
253 assert(&V.getSemantics()==&APFloat::IEEEsingle);
Dale Johannesen9d5f4562007-09-12 03:30:33 +0000254 else if (Ty==Type::DoubleTy)
Dale Johannesenf04afdb2007-08-30 00:23:21 +0000255 assert(&V.getSemantics()==&APFloat::IEEEdouble);
Dale Johannesen9d5f4562007-09-12 03:30:33 +0000256 else if (Ty==Type::X86_FP80Ty)
257 assert(&V.getSemantics()==&APFloat::x87DoubleExtended);
258 else if (Ty==Type::FP128Ty)
259 assert(&V.getSemantics()==&APFloat::IEEEquad);
Dale Johannesena471c2e2007-10-11 18:07:22 +0000260 else if (Ty==Type::PPC_FP128Ty)
261 assert(&V.getSemantics()==&APFloat::PPCDoubleDouble);
Dale Johannesen9d5f4562007-09-12 03:30:33 +0000262 else
263 assert(0);
Chris Lattner00950542001-06-06 20:29:01 +0000264}
265
Chris Lattner9b4ee0c2007-02-20 07:17:17 +0000266bool ConstantFP::isNullValue() const {
Dale Johannesen343e7702007-08-24 00:56:33 +0000267 return Val.isZero() && !Val.isNegative();
Chris Lattner9b4ee0c2007-02-20 07:17:17 +0000268}
269
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +0000270ConstantFP *ConstantFP::getNegativeZero(const Type *Ty) {
271 APFloat apf = cast <ConstantFP>(Constant::getNullValue(Ty))->getValueAPF();
272 apf.changeSign();
273 return ConstantFP::get(Ty, apf);
274}
275
Dale Johannesenf04afdb2007-08-30 00:23:21 +0000276bool ConstantFP::isExactlyValue(const APFloat& V) const {
277 return Val.bitwiseIsEqual(V);
Chris Lattner9b4ee0c2007-02-20 07:17:17 +0000278}
279
Chris Lattner9b4ee0c2007-02-20 07:17:17 +0000280namespace {
Dale Johannesen343e7702007-08-24 00:56:33 +0000281 struct DenseMapAPFloatKeyInfo {
Dale Johannesen12595d72007-08-24 22:09:56 +0000282 struct KeyTy {
283 APFloat val;
284 KeyTy(const APFloat& V) : val(V){}
285 KeyTy(const KeyTy& that) : val(that.val) {}
286 bool operator==(const KeyTy& that) const {
287 return this->val.bitwiseIsEqual(that.val);
288 }
289 bool operator!=(const KeyTy& that) const {
290 return !this->operator==(that);
291 }
292 };
293 static inline KeyTy getEmptyKey() {
294 return KeyTy(APFloat(APFloat::Bogus,1));
Reid Spencer532d0ce2007-02-26 23:54:03 +0000295 }
Dale Johannesen12595d72007-08-24 22:09:56 +0000296 static inline KeyTy getTombstoneKey() {
297 return KeyTy(APFloat(APFloat::Bogus,2));
Chris Lattner9b4ee0c2007-02-20 07:17:17 +0000298 }
Dale Johannesen12595d72007-08-24 22:09:56 +0000299 static unsigned getHashValue(const KeyTy &Key) {
300 return Key.val.getHashValue();
Dale Johannesen343e7702007-08-24 00:56:33 +0000301 }
Chris Lattner76c1b972007-09-17 18:34:04 +0000302 static bool isEqual(const KeyTy &LHS, const KeyTy &RHS) {
303 return LHS == RHS;
304 }
Dale Johannesen343e7702007-08-24 00:56:33 +0000305 static bool isPod() { return false; }
Chris Lattner9b4ee0c2007-02-20 07:17:17 +0000306 };
307}
308
309//---- ConstantFP::get() implementation...
310//
Dale Johannesen12595d72007-08-24 22:09:56 +0000311typedef DenseMap<DenseMapAPFloatKeyInfo::KeyTy, ConstantFP*,
Dale Johannesen343e7702007-08-24 00:56:33 +0000312 DenseMapAPFloatKeyInfo> FPMapTy;
Chris Lattner9b4ee0c2007-02-20 07:17:17 +0000313
Dale Johannesen343e7702007-08-24 00:56:33 +0000314static ManagedStatic<FPMapTy> FPConstants;
Chris Lattner9b4ee0c2007-02-20 07:17:17 +0000315
Dale Johannesenf04afdb2007-08-30 00:23:21 +0000316ConstantFP *ConstantFP::get(const Type *Ty, const APFloat& V) {
317 // temporary
318 if (Ty==Type::FloatTy)
319 assert(&V.getSemantics()==&APFloat::IEEEsingle);
Dale Johannesen9d5f4562007-09-12 03:30:33 +0000320 else if (Ty==Type::DoubleTy)
Dale Johannesenf04afdb2007-08-30 00:23:21 +0000321 assert(&V.getSemantics()==&APFloat::IEEEdouble);
Dale Johannesen9d5f4562007-09-12 03:30:33 +0000322 else if (Ty==Type::X86_FP80Ty)
323 assert(&V.getSemantics()==&APFloat::x87DoubleExtended);
324 else if (Ty==Type::FP128Ty)
325 assert(&V.getSemantics()==&APFloat::IEEEquad);
Dale Johannesena471c2e2007-10-11 18:07:22 +0000326 else if (Ty==Type::PPC_FP128Ty)
327 assert(&V.getSemantics()==&APFloat::PPCDoubleDouble);
Dale Johannesen9d5f4562007-09-12 03:30:33 +0000328 else
329 assert(0);
Dale Johannesenf04afdb2007-08-30 00:23:21 +0000330
331 DenseMapAPFloatKeyInfo::KeyTy Key(V);
332 ConstantFP *&Slot = (*FPConstants)[Key];
333 if (Slot) return Slot;
334 return Slot = new ConstantFP(Ty, V);
335}
Chris Lattner9b4ee0c2007-02-20 07:17:17 +0000336
337//===----------------------------------------------------------------------===//
338// ConstantXXX Classes
339//===----------------------------------------------------------------------===//
340
341
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000342ConstantArray::ConstantArray(const ArrayType *T,
Chris Lattnere4671472005-01-29 00:34:39 +0000343 const std::vector<Constant*> &V)
Chris Lattnerdf0ef1d2005-09-27 06:09:08 +0000344 : Constant(T, ConstantArrayVal, new Use[V.size()], V.size()) {
Alkis Evlogimenose0de1d62004-09-15 02:32:15 +0000345 assert(V.size() == T->getNumElements() &&
346 "Invalid initializer vector for constant array");
Chris Lattnere4671472005-01-29 00:34:39 +0000347 Use *OL = OperandList;
Chris Lattnerdfdd6c52005-10-03 21:56:24 +0000348 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
349 I != E; ++I, ++OL) {
Chris Lattner71abaab2005-10-07 05:23:36 +0000350 Constant *C = *I;
351 assert((C->getType() == T->getElementType() ||
Alkis Evlogimenoscad90ad2004-09-10 04:16:59 +0000352 (T->isAbstract() &&
Chris Lattner71abaab2005-10-07 05:23:36 +0000353 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
Alkis Evlogimenoscad90ad2004-09-10 04:16:59 +0000354 "Initializer for array element doesn't match array element type!");
Chris Lattner71abaab2005-10-07 05:23:36 +0000355 OL->init(C, this);
Chris Lattner00950542001-06-06 20:29:01 +0000356 }
357}
358
Gordon Henriksenafba8fe2007-12-10 02:14:30 +0000359ConstantArray::~ConstantArray() {
360 delete [] OperandList;
Chris Lattnere4671472005-01-29 00:34:39 +0000361}
362
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000363ConstantStruct::ConstantStruct(const StructType *T,
Chris Lattnere4671472005-01-29 00:34:39 +0000364 const std::vector<Constant*> &V)
Chris Lattnerdf0ef1d2005-09-27 06:09:08 +0000365 : Constant(T, ConstantStructVal, new Use[V.size()], V.size()) {
Chris Lattnerd21cd802004-02-09 04:37:31 +0000366 assert(V.size() == T->getNumElements() &&
Vikram S. Adve345e0cf2002-07-14 23:13:17 +0000367 "Invalid initializer vector for constant structure");
Chris Lattnere4671472005-01-29 00:34:39 +0000368 Use *OL = OperandList;
Chris Lattnerdfdd6c52005-10-03 21:56:24 +0000369 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
370 I != E; ++I, ++OL) {
Chris Lattner71abaab2005-10-07 05:23:36 +0000371 Constant *C = *I;
372 assert((C->getType() == T->getElementType(I-V.begin()) ||
Chris Lattnerdfdd6c52005-10-03 21:56:24 +0000373 ((T->getElementType(I-V.begin())->isAbstract() ||
Chris Lattner71abaab2005-10-07 05:23:36 +0000374 C->getType()->isAbstract()) &&
Chris Lattnerdfdd6c52005-10-03 21:56:24 +0000375 T->getElementType(I-V.begin())->getTypeID() ==
Chris Lattner71abaab2005-10-07 05:23:36 +0000376 C->getType()->getTypeID())) &&
Chris Lattnerb8438892003-06-02 17:42:47 +0000377 "Initializer for struct element doesn't match struct element type!");
Chris Lattner71abaab2005-10-07 05:23:36 +0000378 OL->init(C, this);
Chris Lattner00950542001-06-06 20:29:01 +0000379 }
380}
381
Gordon Henriksenafba8fe2007-12-10 02:14:30 +0000382ConstantStruct::~ConstantStruct() {
383 delete [] OperandList;
Chris Lattnere4671472005-01-29 00:34:39 +0000384}
385
386
Reid Spencer9d6565a2007-02-15 02:26:10 +0000387ConstantVector::ConstantVector(const VectorType *T,
Chris Lattnere4671472005-01-29 00:34:39 +0000388 const std::vector<Constant*> &V)
Reid Spencer9d6565a2007-02-15 02:26:10 +0000389 : Constant(T, ConstantVectorVal, new Use[V.size()], V.size()) {
Chris Lattnere4671472005-01-29 00:34:39 +0000390 Use *OL = OperandList;
Chris Lattnerdfdd6c52005-10-03 21:56:24 +0000391 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
392 I != E; ++I, ++OL) {
Chris Lattner71abaab2005-10-07 05:23:36 +0000393 Constant *C = *I;
394 assert((C->getType() == T->getElementType() ||
Alkis Evlogimenoscad90ad2004-09-10 04:16:59 +0000395 (T->isAbstract() &&
Chris Lattner71abaab2005-10-07 05:23:36 +0000396 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
Dan Gohmanfa73ea22007-05-24 14:36:04 +0000397 "Initializer for vector element doesn't match vector element type!");
Chris Lattner71abaab2005-10-07 05:23:36 +0000398 OL->init(C, this);
Brian Gaeke715c90b2004-08-20 06:00:58 +0000399 }
400}
401
Gordon Henriksenafba8fe2007-12-10 02:14:30 +0000402ConstantVector::~ConstantVector() {
403 delete [] OperandList;
Vikram S. Adve345e0cf2002-07-14 23:13:17 +0000404}
405
Gordon Henriksenafba8fe2007-12-10 02:14:30 +0000406// We declare several classes private to this file, so use an anonymous
407// namespace
408namespace {
Reid Spencer728b6db2006-12-03 05:48:19 +0000409
Gordon Henriksenafba8fe2007-12-10 02:14:30 +0000410/// UnaryConstantExpr - This class is private to Constants.cpp, and is used
411/// behind the scenes to implement unary constant exprs.
412class VISIBILITY_HIDDEN UnaryConstantExpr : public ConstantExpr {
Gabor Greif051a9502008-04-06 20:25:17 +0000413 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
Gordon Henriksenafba8fe2007-12-10 02:14:30 +0000414 Use Op;
415public:
Gabor Greif051a9502008-04-06 20:25:17 +0000416 // allocate space for exactly one operand
417 void *operator new(size_t s) {
418 return User::operator new(s, 1);
419 }
Gordon Henriksenafba8fe2007-12-10 02:14:30 +0000420 UnaryConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
421 : ConstantExpr(Ty, Opcode, &Op, 1), Op(C, this) {}
422};
Reid Spencer728b6db2006-12-03 05:48:19 +0000423
Gordon Henriksenafba8fe2007-12-10 02:14:30 +0000424/// BinaryConstantExpr - This class is private to Constants.cpp, and is used
425/// behind the scenes to implement binary constant exprs.
426class VISIBILITY_HIDDEN BinaryConstantExpr : public ConstantExpr {
Gabor Greif051a9502008-04-06 20:25:17 +0000427 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
Gordon Henriksenafba8fe2007-12-10 02:14:30 +0000428 Use Ops[2];
429public:
Gabor Greif051a9502008-04-06 20:25:17 +0000430 // allocate space for exactly two operands
431 void *operator new(size_t s) {
432 return User::operator new(s, 2);
433 }
Gordon Henriksenafba8fe2007-12-10 02:14:30 +0000434 BinaryConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
435 : ConstantExpr(C1->getType(), Opcode, Ops, 2) {
436 Ops[0].init(C1, this);
437 Ops[1].init(C2, this);
438 }
439};
Vikram S. Adve345e0cf2002-07-14 23:13:17 +0000440
Gordon Henriksenafba8fe2007-12-10 02:14:30 +0000441/// SelectConstantExpr - This class is private to Constants.cpp, and is used
442/// behind the scenes to implement select constant exprs.
443class VISIBILITY_HIDDEN SelectConstantExpr : public ConstantExpr {
Gabor Greif051a9502008-04-06 20:25:17 +0000444 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
Gordon Henriksenafba8fe2007-12-10 02:14:30 +0000445 Use Ops[3];
446public:
Gabor Greif051a9502008-04-06 20:25:17 +0000447 // allocate space for exactly three operands
448 void *operator new(size_t s) {
449 return User::operator new(s, 3);
450 }
Gordon Henriksenafba8fe2007-12-10 02:14:30 +0000451 SelectConstantExpr(Constant *C1, Constant *C2, Constant *C3)
452 : ConstantExpr(C2->getType(), Instruction::Select, Ops, 3) {
453 Ops[0].init(C1, this);
454 Ops[1].init(C2, this);
455 Ops[2].init(C3, this);
456 }
457};
Chris Lattnere4671472005-01-29 00:34:39 +0000458
Gordon Henriksenafba8fe2007-12-10 02:14:30 +0000459/// ExtractElementConstantExpr - This class is private to
460/// Constants.cpp, and is used behind the scenes to implement
461/// extractelement constant exprs.
462class VISIBILITY_HIDDEN ExtractElementConstantExpr : public ConstantExpr {
Gabor Greif051a9502008-04-06 20:25:17 +0000463 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
Gordon Henriksenafba8fe2007-12-10 02:14:30 +0000464 Use Ops[2];
465public:
Gabor Greif051a9502008-04-06 20:25:17 +0000466 // allocate space for exactly two operands
467 void *operator new(size_t s) {
468 return User::operator new(s, 2);
469 }
Gordon Henriksenafba8fe2007-12-10 02:14:30 +0000470 ExtractElementConstantExpr(Constant *C1, Constant *C2)
471 : ConstantExpr(cast<VectorType>(C1->getType())->getElementType(),
472 Instruction::ExtractElement, Ops, 2) {
473 Ops[0].init(C1, this);
474 Ops[1].init(C2, this);
475 }
476};
Robert Bocchinob52ee7f2006-01-10 19:05:34 +0000477
Gordon Henriksenafba8fe2007-12-10 02:14:30 +0000478/// InsertElementConstantExpr - This class is private to
479/// Constants.cpp, and is used behind the scenes to implement
480/// insertelement constant exprs.
481class VISIBILITY_HIDDEN InsertElementConstantExpr : public ConstantExpr {
Gabor Greif051a9502008-04-06 20:25:17 +0000482 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
Gordon Henriksenafba8fe2007-12-10 02:14:30 +0000483 Use Ops[3];
484public:
Gabor Greif051a9502008-04-06 20:25:17 +0000485 // allocate space for exactly three operands
486 void *operator new(size_t s) {
487 return User::operator new(s, 3);
488 }
Gordon Henriksenafba8fe2007-12-10 02:14:30 +0000489 InsertElementConstantExpr(Constant *C1, Constant *C2, Constant *C3)
490 : ConstantExpr(C1->getType(), Instruction::InsertElement,
491 Ops, 3) {
492 Ops[0].init(C1, this);
493 Ops[1].init(C2, this);
494 Ops[2].init(C3, this);
495 }
496};
Robert Bocchinoc152f9c2006-01-17 20:07:22 +0000497
Gordon Henriksenafba8fe2007-12-10 02:14:30 +0000498/// ShuffleVectorConstantExpr - This class is private to
499/// Constants.cpp, and is used behind the scenes to implement
500/// shufflevector constant exprs.
501class VISIBILITY_HIDDEN ShuffleVectorConstantExpr : public ConstantExpr {
Gabor Greif051a9502008-04-06 20:25:17 +0000502 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
Gordon Henriksenafba8fe2007-12-10 02:14:30 +0000503 Use Ops[3];
504public:
Gabor Greif051a9502008-04-06 20:25:17 +0000505 // allocate space for exactly three operands
506 void *operator new(size_t s) {
507 return User::operator new(s, 3);
508 }
Gordon Henriksenafba8fe2007-12-10 02:14:30 +0000509 ShuffleVectorConstantExpr(Constant *C1, Constant *C2, Constant *C3)
510 : ConstantExpr(C1->getType(), Instruction::ShuffleVector,
511 Ops, 3) {
512 Ops[0].init(C1, this);
513 Ops[1].init(C2, this);
514 Ops[2].init(C3, this);
515 }
516};
517
518/// GetElementPtrConstantExpr - This class is private to Constants.cpp, and is
519/// used behind the scenes to implement getelementpr constant exprs.
Gabor Greif051a9502008-04-06 20:25:17 +0000520class VISIBILITY_HIDDEN GetElementPtrConstantExpr : public ConstantExpr {
Gordon Henriksenafba8fe2007-12-10 02:14:30 +0000521 GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
522 const Type *DestTy)
523 : ConstantExpr(DestTy, Instruction::GetElementPtr,
524 new Use[IdxList.size()+1], IdxList.size()+1) {
525 OperandList[0].init(C, this);
526 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
527 OperandList[i+1].init(IdxList[i], this);
528 }
Gabor Greif051a9502008-04-06 20:25:17 +0000529public:
530 static GetElementPtrConstantExpr *Create(Constant *C, const std::vector<Constant*> &IdxList,
531 const Type *DestTy) {
532 return new(IdxList.size() + 1/*FIXME*/) GetElementPtrConstantExpr(C, IdxList, DestTy);
533 }
Gordon Henriksenafba8fe2007-12-10 02:14:30 +0000534 ~GetElementPtrConstantExpr() {
535 delete [] OperandList;
536 }
537};
538
539// CompareConstantExpr - This class is private to Constants.cpp, and is used
540// behind the scenes to implement ICmp and FCmp constant expressions. This is
541// needed in order to store the predicate value for these instructions.
542struct VISIBILITY_HIDDEN CompareConstantExpr : public ConstantExpr {
Gabor Greif051a9502008-04-06 20:25:17 +0000543 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
544 // allocate space for exactly two operands
545 void *operator new(size_t s) {
546 return User::operator new(s, 2);
547 }
Gordon Henriksenafba8fe2007-12-10 02:14:30 +0000548 unsigned short predicate;
549 Use Ops[2];
550 CompareConstantExpr(Instruction::OtherOps opc, unsigned short pred,
551 Constant* LHS, Constant* RHS)
552 : ConstantExpr(Type::Int1Ty, opc, Ops, 2), predicate(pred) {
553 OperandList[0].init(LHS, this);
554 OperandList[1].init(RHS, this);
555 }
556};
557
558} // end anonymous namespace
559
Reid Spencer3da59db2006-11-27 01:05:10 +0000560
561// Utility function for determining if a ConstantExpr is a CastOp or not. This
562// can't be inline because we don't want to #include Instruction.h into
563// Constant.h
564bool ConstantExpr::isCast() const {
565 return Instruction::isCast(getOpcode());
566}
567
Reid Spencer077d0eb2006-12-04 05:19:50 +0000568bool ConstantExpr::isCompare() const {
569 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
570}
571
Chris Lattner4dcb5402004-03-29 02:37:53 +0000572/// ConstantExpr::get* - Return some common constants without having to
573/// specify the full Instruction::OPCODE identifier.
574///
575Constant *ConstantExpr::getNeg(Constant *C) {
Reid Spencer24d6da52007-01-21 00:29:26 +0000576 return get(Instruction::Sub,
577 ConstantExpr::getZeroValueForNegationExpr(C->getType()),
578 C);
Chris Lattner4dcb5402004-03-29 02:37:53 +0000579}
580Constant *ConstantExpr::getNot(Constant *C) {
Gordon Henriksen46475692007-10-06 14:29:36 +0000581 assert(isa<IntegerType>(C->getType()) && "Cannot NOT a nonintegral value!");
Chris Lattner4dcb5402004-03-29 02:37:53 +0000582 return get(Instruction::Xor, C,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000583 ConstantInt::getAllOnesValue(C->getType()));
Chris Lattner4dcb5402004-03-29 02:37:53 +0000584}
585Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2) {
586 return get(Instruction::Add, C1, C2);
587}
588Constant *ConstantExpr::getSub(Constant *C1, Constant *C2) {
589 return get(Instruction::Sub, C1, C2);
590}
591Constant *ConstantExpr::getMul(Constant *C1, Constant *C2) {
592 return get(Instruction::Mul, C1, C2);
593}
Reid Spencer1628cec2006-10-26 06:15:43 +0000594Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2) {
595 return get(Instruction::UDiv, C1, C2);
596}
597Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2) {
598 return get(Instruction::SDiv, C1, C2);
599}
600Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
601 return get(Instruction::FDiv, C1, C2);
Chris Lattner4dcb5402004-03-29 02:37:53 +0000602}
Reid Spencer0a783f72006-11-02 01:53:59 +0000603Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
604 return get(Instruction::URem, C1, C2);
605}
606Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
607 return get(Instruction::SRem, C1, C2);
608}
609Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
610 return get(Instruction::FRem, C1, C2);
Chris Lattner4dcb5402004-03-29 02:37:53 +0000611}
612Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
613 return get(Instruction::And, C1, C2);
614}
615Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
616 return get(Instruction::Or, C1, C2);
617}
618Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
619 return get(Instruction::Xor, C1, C2);
620}
Reid Spencer728b6db2006-12-03 05:48:19 +0000621unsigned ConstantExpr::getPredicate() const {
622 assert(getOpcode() == Instruction::FCmp || getOpcode() == Instruction::ICmp);
Chris Lattnerb7daa842007-10-18 16:26:24 +0000623 return ((const CompareConstantExpr*)this)->predicate;
Reid Spencer728b6db2006-12-03 05:48:19 +0000624}
Chris Lattner4dcb5402004-03-29 02:37:53 +0000625Constant *ConstantExpr::getShl(Constant *C1, Constant *C2) {
626 return get(Instruction::Shl, C1, C2);
627}
Reid Spencer3822ff52006-11-08 06:47:33 +0000628Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2) {
629 return get(Instruction::LShr, C1, C2);
Chris Lattner4dcb5402004-03-29 02:37:53 +0000630}
Reid Spencer3822ff52006-11-08 06:47:33 +0000631Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2) {
632 return get(Instruction::AShr, C1, C2);
Chris Lattnerc9710252004-05-25 05:32:43 +0000633}
Chris Lattnerf4ba6c72001-10-03 06:12:09 +0000634
Chris Lattner1fe8f6b2006-07-14 19:37:40 +0000635/// getWithOperandReplaced - Return a constant expression identical to this
636/// one, but with the specified operand set to the specified value.
Reid Spencer3da59db2006-11-27 01:05:10 +0000637Constant *
638ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
Chris Lattner1fe8f6b2006-07-14 19:37:40 +0000639 assert(OpNo < getNumOperands() && "Operand num is out of range!");
640 assert(Op->getType() == getOperand(OpNo)->getType() &&
641 "Replacing operand with value of different type!");
Chris Lattnerb88a7fb2006-07-14 22:20:01 +0000642 if (getOperand(OpNo) == Op)
643 return const_cast<ConstantExpr*>(this);
Chris Lattner1fe8f6b2006-07-14 19:37:40 +0000644
Chris Lattnerb88a7fb2006-07-14 22:20:01 +0000645 Constant *Op0, *Op1, *Op2;
Chris Lattner1fe8f6b2006-07-14 19:37:40 +0000646 switch (getOpcode()) {
Reid Spencer3da59db2006-11-27 01:05:10 +0000647 case Instruction::Trunc:
648 case Instruction::ZExt:
649 case Instruction::SExt:
650 case Instruction::FPTrunc:
651 case Instruction::FPExt:
652 case Instruction::UIToFP:
653 case Instruction::SIToFP:
654 case Instruction::FPToUI:
655 case Instruction::FPToSI:
656 case Instruction::PtrToInt:
657 case Instruction::IntToPtr:
658 case Instruction::BitCast:
659 return ConstantExpr::getCast(getOpcode(), Op, getType());
Chris Lattnerb88a7fb2006-07-14 22:20:01 +0000660 case Instruction::Select:
661 Op0 = (OpNo == 0) ? Op : getOperand(0);
662 Op1 = (OpNo == 1) ? Op : getOperand(1);
663 Op2 = (OpNo == 2) ? Op : getOperand(2);
664 return ConstantExpr::getSelect(Op0, Op1, Op2);
665 case Instruction::InsertElement:
666 Op0 = (OpNo == 0) ? Op : getOperand(0);
667 Op1 = (OpNo == 1) ? Op : getOperand(1);
668 Op2 = (OpNo == 2) ? Op : getOperand(2);
669 return ConstantExpr::getInsertElement(Op0, Op1, Op2);
670 case Instruction::ExtractElement:
671 Op0 = (OpNo == 0) ? Op : getOperand(0);
672 Op1 = (OpNo == 1) ? Op : getOperand(1);
673 return ConstantExpr::getExtractElement(Op0, Op1);
674 case Instruction::ShuffleVector:
675 Op0 = (OpNo == 0) ? Op : getOperand(0);
676 Op1 = (OpNo == 1) ? Op : getOperand(1);
677 Op2 = (OpNo == 2) ? Op : getOperand(2);
678 return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Chris Lattner1fe8f6b2006-07-14 19:37:40 +0000679 case Instruction::GetElementPtr: {
Chris Lattnerf9021ff2007-02-19 20:01:23 +0000680 SmallVector<Constant*, 8> Ops;
681 Ops.resize(getNumOperands());
Chris Lattner1fe8f6b2006-07-14 19:37:40 +0000682 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
Chris Lattnerf9021ff2007-02-19 20:01:23 +0000683 Ops[i] = getOperand(i);
Chris Lattner1fe8f6b2006-07-14 19:37:40 +0000684 if (OpNo == 0)
Chris Lattnerf9021ff2007-02-19 20:01:23 +0000685 return ConstantExpr::getGetElementPtr(Op, &Ops[0], Ops.size());
Chris Lattner1fe8f6b2006-07-14 19:37:40 +0000686 Ops[OpNo-1] = Op;
Chris Lattnerf9021ff2007-02-19 20:01:23 +0000687 return ConstantExpr::getGetElementPtr(getOperand(0), &Ops[0], Ops.size());
Chris Lattner1fe8f6b2006-07-14 19:37:40 +0000688 }
Chris Lattner1fe8f6b2006-07-14 19:37:40 +0000689 default:
690 assert(getNumOperands() == 2 && "Must be binary operator?");
Chris Lattnerb88a7fb2006-07-14 22:20:01 +0000691 Op0 = (OpNo == 0) ? Op : getOperand(0);
692 Op1 = (OpNo == 1) ? Op : getOperand(1);
693 return ConstantExpr::get(getOpcode(), Op0, Op1);
694 }
695}
696
697/// getWithOperands - This returns the current constant expression with the
698/// operands replaced with the specified values. The specified operands must
699/// match count and type with the existing ones.
700Constant *ConstantExpr::
701getWithOperands(const std::vector<Constant*> &Ops) const {
702 assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
703 bool AnyChange = false;
704 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
705 assert(Ops[i]->getType() == getOperand(i)->getType() &&
706 "Operand type mismatch!");
707 AnyChange |= Ops[i] != getOperand(i);
708 }
709 if (!AnyChange) // No operands changed, return self.
710 return const_cast<ConstantExpr*>(this);
711
712 switch (getOpcode()) {
Reid Spencer3da59db2006-11-27 01:05:10 +0000713 case Instruction::Trunc:
714 case Instruction::ZExt:
715 case Instruction::SExt:
716 case Instruction::FPTrunc:
717 case Instruction::FPExt:
718 case Instruction::UIToFP:
719 case Instruction::SIToFP:
720 case Instruction::FPToUI:
721 case Instruction::FPToSI:
722 case Instruction::PtrToInt:
723 case Instruction::IntToPtr:
724 case Instruction::BitCast:
725 return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
Chris Lattnerb88a7fb2006-07-14 22:20:01 +0000726 case Instruction::Select:
727 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
728 case Instruction::InsertElement:
729 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
730 case Instruction::ExtractElement:
731 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
732 case Instruction::ShuffleVector:
733 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
Chris Lattnerf9021ff2007-02-19 20:01:23 +0000734 case Instruction::GetElementPtr:
735 return ConstantExpr::getGetElementPtr(Ops[0], &Ops[1], Ops.size()-1);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000736 case Instruction::ICmp:
737 case Instruction::FCmp:
738 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
Chris Lattnerb88a7fb2006-07-14 22:20:01 +0000739 default:
740 assert(getNumOperands() == 2 && "Must be binary operator?");
741 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1]);
Chris Lattner1fe8f6b2006-07-14 19:37:40 +0000742 }
743}
744
Chris Lattner00950542001-06-06 20:29:01 +0000745
746//===----------------------------------------------------------------------===//
Chris Lattner00950542001-06-06 20:29:01 +0000747// isValueValidForType implementations
748
Reid Spencer9b11d512006-12-19 01:28:19 +0000749bool ConstantInt::isValueValidForType(const Type *Ty, uint64_t Val) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000750 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
Reid Spencera54b7cb2007-01-12 07:05:14 +0000751 if (Ty == Type::Int1Ty)
752 return Val == 0 || Val == 1;
Reid Spencer554cec62007-02-05 23:47:56 +0000753 if (NumBits >= 64)
Reid Spencera54b7cb2007-01-12 07:05:14 +0000754 return true; // always true, has to fit in largest type
755 uint64_t Max = (1ll << NumBits) - 1;
756 return Val <= Max;
Reid Spencer9b11d512006-12-19 01:28:19 +0000757}
758
Reid Spencerb83eb642006-10-20 07:07:24 +0000759bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000760 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
Reid Spencera54b7cb2007-01-12 07:05:14 +0000761 if (Ty == Type::Int1Ty)
Reid Spencerc1030572007-01-19 21:13:56 +0000762 return Val == 0 || Val == 1 || Val == -1;
Reid Spencer554cec62007-02-05 23:47:56 +0000763 if (NumBits >= 64)
Reid Spencera54b7cb2007-01-12 07:05:14 +0000764 return true; // always true, has to fit in largest type
765 int64_t Min = -(1ll << (NumBits-1));
766 int64_t Max = (1ll << (NumBits-1)) - 1;
767 return (Val >= Min && Val <= Max);
Chris Lattner00950542001-06-06 20:29:01 +0000768}
769
Dale Johannesenf04afdb2007-08-30 00:23:21 +0000770bool ConstantFP::isValueValidForType(const Type *Ty, const APFloat& Val) {
771 // convert modifies in place, so make a copy.
772 APFloat Val2 = APFloat(Val);
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000773 switch (Ty->getTypeID()) {
Chris Lattner00950542001-06-06 20:29:01 +0000774 default:
775 return false; // These can't be represented as floating point!
776
Dale Johannesenf04afdb2007-08-30 00:23:21 +0000777 // FIXME rounding mode needs to be more flexible
Chris Lattner00950542001-06-06 20:29:01 +0000778 case Type::FloatTyID:
Dale Johannesenf04afdb2007-08-30 00:23:21 +0000779 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
780 Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven) ==
781 APFloat::opOK;
Chris Lattner00950542001-06-06 20:29:01 +0000782 case Type::DoubleTyID:
Dale Johannesenf04afdb2007-08-30 00:23:21 +0000783 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
784 &Val2.getSemantics() == &APFloat::IEEEdouble ||
785 Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven) ==
786 APFloat::opOK;
Dale Johannesenebbc95d2007-08-09 22:51:36 +0000787 case Type::X86_FP80TyID:
Dale Johannesen9d5f4562007-09-12 03:30:33 +0000788 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
789 &Val2.getSemantics() == &APFloat::IEEEdouble ||
790 &Val2.getSemantics() == &APFloat::x87DoubleExtended;
Dale Johannesenebbc95d2007-08-09 22:51:36 +0000791 case Type::FP128TyID:
Dale Johannesen9d5f4562007-09-12 03:30:33 +0000792 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
793 &Val2.getSemantics() == &APFloat::IEEEdouble ||
794 &Val2.getSemantics() == &APFloat::IEEEquad;
Dale Johannesena471c2e2007-10-11 18:07:22 +0000795 case Type::PPC_FP128TyID:
796 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
797 &Val2.getSemantics() == &APFloat::IEEEdouble ||
798 &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
Chris Lattner00950542001-06-06 20:29:01 +0000799 }
Chris Lattnerd74ea2b2006-05-24 17:04:05 +0000800}
Chris Lattner37bf6302001-07-20 19:16:02 +0000801
Chris Lattner531daef2001-09-07 16:46:31 +0000802//===----------------------------------------------------------------------===//
Chris Lattner531daef2001-09-07 16:46:31 +0000803// Factory Function Implementation
804
Chris Lattner02ec5ed2003-05-23 20:03:32 +0000805// ConstantCreator - A class that is used to create constants by
806// ValueMap*. This class should be partially specialized if there is
807// something strange that needs to be done to interface to the ctor for the
808// constant.
809//
Chris Lattner31f84992003-11-21 20:23:48 +0000810namespace llvm {
811 template<class ConstantClass, class TypeClass, class ValType>
Chris Lattnerf190d382006-06-28 21:38:54 +0000812 struct VISIBILITY_HIDDEN ConstantCreator {
Chris Lattner31f84992003-11-21 20:23:48 +0000813 static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
Gabor Greif051a9502008-04-06 20:25:17 +0000814 unsigned FIXME; // = traits<ValType>::uses(V)
815 return new(FIXME) ConstantClass(Ty, V);
Chris Lattner31f84992003-11-21 20:23:48 +0000816 }
817 };
Misha Brukmanfd939082005-04-21 23:48:37 +0000818
Chris Lattner31f84992003-11-21 20:23:48 +0000819 template<class ConstantClass, class TypeClass>
Chris Lattnerf190d382006-06-28 21:38:54 +0000820 struct VISIBILITY_HIDDEN ConvertConstantType {
Chris Lattner31f84992003-11-21 20:23:48 +0000821 static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
822 assert(0 && "This type cannot be converted!\n");
823 abort();
824 }
825 };
Chris Lattnered468e372003-10-05 00:17:43 +0000826
Chris Lattnera55b30a2005-10-04 17:48:46 +0000827 template<class ValType, class TypeClass, class ConstantClass,
828 bool HasLargeKey = false /*true for arrays and structs*/ >
Chris Lattnerf190d382006-06-28 21:38:54 +0000829 class VISIBILITY_HIDDEN ValueMap : public AbstractTypeUser {
Chris Lattnercea141f2005-10-03 22:51:37 +0000830 public:
Jim Laskeyede5aa42006-07-17 17:38:29 +0000831 typedef std::pair<const Type*, ValType> MapKey;
832 typedef std::map<MapKey, Constant *> MapTy;
833 typedef std::map<Constant*, typename MapTy::iterator> InverseMapTy;
834 typedef std::map<const Type*, typename MapTy::iterator> AbstractTypeMapTy;
Chris Lattnercea141f2005-10-03 22:51:37 +0000835 private:
Chris Lattnerd7a3fc62005-10-04 16:52:46 +0000836 /// Map - This is the main map from the element descriptor to the Constants.
837 /// This is the primary way we avoid creating two of the same shape
838 /// constant.
Chris Lattnered468e372003-10-05 00:17:43 +0000839 MapTy Map;
Chris Lattnera55b30a2005-10-04 17:48:46 +0000840
841 /// InverseMap - If "HasLargeKey" is true, this contains an inverse mapping
842 /// from the constants to their element in Map. This is important for
843 /// removal of constants from the array, which would otherwise have to scan
844 /// through the map with very large keys.
Jim Laskeyede5aa42006-07-17 17:38:29 +0000845 InverseMapTy InverseMap;
Chris Lattnered468e372003-10-05 00:17:43 +0000846
Jim Laskeyede5aa42006-07-17 17:38:29 +0000847 /// AbstractTypeMap - Map for abstract type constants.
848 ///
Chris Lattnered468e372003-10-05 00:17:43 +0000849 AbstractTypeMapTy AbstractTypeMap;
Chris Lattner8a7ad2d2004-11-19 16:39:44 +0000850
Chris Lattner02ec5ed2003-05-23 20:03:32 +0000851 public:
Jim Laskeyede5aa42006-07-17 17:38:29 +0000852 typename MapTy::iterator map_end() { return Map.end(); }
Chris Lattnercea141f2005-10-03 22:51:37 +0000853
854 /// InsertOrGetItem - Return an iterator for the specified element.
855 /// If the element exists in the map, the returned iterator points to the
856 /// entry and Exists=true. If not, the iterator points to the newly
857 /// inserted entry and returns Exists=false. Newly inserted entries have
858 /// I->second == 0, and should be filled in.
Jim Laskeyede5aa42006-07-17 17:38:29 +0000859 typename MapTy::iterator InsertOrGetItem(std::pair<MapKey, Constant *>
860 &InsertVal,
Chris Lattnercea141f2005-10-03 22:51:37 +0000861 bool &Exists) {
Jim Laskeyede5aa42006-07-17 17:38:29 +0000862 std::pair<typename MapTy::iterator, bool> IP = Map.insert(InsertVal);
Chris Lattnercea141f2005-10-03 22:51:37 +0000863 Exists = !IP.second;
864 return IP.first;
865 }
Chris Lattnerd7a3fc62005-10-04 16:52:46 +0000866
Chris Lattnera55b30a2005-10-04 17:48:46 +0000867private:
Jim Laskeyede5aa42006-07-17 17:38:29 +0000868 typename MapTy::iterator FindExistingElement(ConstantClass *CP) {
Chris Lattnera55b30a2005-10-04 17:48:46 +0000869 if (HasLargeKey) {
Jim Laskeyede5aa42006-07-17 17:38:29 +0000870 typename InverseMapTy::iterator IMI = InverseMap.find(CP);
Chris Lattnera55b30a2005-10-04 17:48:46 +0000871 assert(IMI != InverseMap.end() && IMI->second != Map.end() &&
872 IMI->second->second == CP &&
873 "InverseMap corrupt!");
874 return IMI->second;
875 }
876
Jim Laskeyede5aa42006-07-17 17:38:29 +0000877 typename MapTy::iterator I =
Chris Lattnera55b30a2005-10-04 17:48:46 +0000878 Map.find(MapKey((TypeClass*)CP->getRawType(), getValType(CP)));
Chris Lattnerd7a3fc62005-10-04 16:52:46 +0000879 if (I == Map.end() || I->second != CP) {
880 // FIXME: This should not use a linear scan. If this gets to be a
881 // performance problem, someone should look at this.
882 for (I = Map.begin(); I != Map.end() && I->second != CP; ++I)
883 /* empty */;
884 }
Chris Lattnera55b30a2005-10-04 17:48:46 +0000885 return I;
886 }
887public:
888
Chris Lattnercea141f2005-10-03 22:51:37 +0000889 /// getOrCreate - Return the specified constant from the map, creating it if
890 /// necessary.
Chris Lattner02ec5ed2003-05-23 20:03:32 +0000891 ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
Chris Lattnered468e372003-10-05 00:17:43 +0000892 MapKey Lookup(Ty, V);
Jim Laskeyede5aa42006-07-17 17:38:29 +0000893 typename MapTy::iterator I = Map.lower_bound(Lookup);
Reid Spencerb83eb642006-10-20 07:07:24 +0000894 // Is it in the map?
Chris Lattner02ec5ed2003-05-23 20:03:32 +0000895 if (I != Map.end() && I->first == Lookup)
Reid Spencerb83eb642006-10-20 07:07:24 +0000896 return static_cast<ConstantClass *>(I->second);
Chris Lattner02ec5ed2003-05-23 20:03:32 +0000897
898 // If no preexisting value, create one now...
899 ConstantClass *Result =
900 ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
901
Chris Lattnered468e372003-10-05 00:17:43 +0000902 /// FIXME: why does this assert fail when loading 176.gcc?
903 //assert(Result->getType() == Ty && "Type specified is not correct!");
904 I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
905
Chris Lattnera55b30a2005-10-04 17:48:46 +0000906 if (HasLargeKey) // Remember the reverse mapping if needed.
907 InverseMap.insert(std::make_pair(Result, I));
908
Chris Lattnered468e372003-10-05 00:17:43 +0000909 // If the type of the constant is abstract, make sure that an entry exists
910 // for it in the AbstractTypeMap.
911 if (Ty->isAbstract()) {
912 typename AbstractTypeMapTy::iterator TI =
913 AbstractTypeMap.lower_bound(Ty);
914
915 if (TI == AbstractTypeMap.end() || TI->first != Ty) {
916 // Add ourselves to the ATU list of the type.
917 cast<DerivedType>(Ty)->addAbstractTypeUser(this);
918
919 AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
920 }
921 }
Chris Lattner02ec5ed2003-05-23 20:03:32 +0000922 return Result;
923 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000924
Chris Lattner02ec5ed2003-05-23 20:03:32 +0000925 void remove(ConstantClass *CP) {
Jim Laskeyede5aa42006-07-17 17:38:29 +0000926 typename MapTy::iterator I = FindExistingElement(CP);
Chris Lattnered468e372003-10-05 00:17:43 +0000927 assert(I != Map.end() && "Constant not found in constant table!");
Chris Lattner6823c9f2004-08-04 04:48:01 +0000928 assert(I->second == CP && "Didn't find correct element?");
Chris Lattnered468e372003-10-05 00:17:43 +0000929
Chris Lattnera55b30a2005-10-04 17:48:46 +0000930 if (HasLargeKey) // Remember the reverse mapping if needed.
931 InverseMap.erase(CP);
932
Chris Lattnered468e372003-10-05 00:17:43 +0000933 // Now that we found the entry, make sure this isn't the entry that
934 // the AbstractTypeMap points to.
Jim Laskeyede5aa42006-07-17 17:38:29 +0000935 const TypeClass *Ty = static_cast<const TypeClass *>(I->first.first);
Chris Lattnered468e372003-10-05 00:17:43 +0000936 if (Ty->isAbstract()) {
937 assert(AbstractTypeMap.count(Ty) &&
938 "Abstract type not in AbstractTypeMap?");
Jim Laskeyede5aa42006-07-17 17:38:29 +0000939 typename MapTy::iterator &ATMEntryIt = AbstractTypeMap[Ty];
Chris Lattnered468e372003-10-05 00:17:43 +0000940 if (ATMEntryIt == I) {
941 // Yes, we are removing the representative entry for this type.
942 // See if there are any other entries of the same type.
Jim Laskeyede5aa42006-07-17 17:38:29 +0000943 typename MapTy::iterator TmpIt = ATMEntryIt;
Misha Brukmanfd939082005-04-21 23:48:37 +0000944
Chris Lattnered468e372003-10-05 00:17:43 +0000945 // First check the entry before this one...
946 if (TmpIt != Map.begin()) {
947 --TmpIt;
948 if (TmpIt->first.first != Ty) // Not the same type, move back...
949 ++TmpIt;
950 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000951
Chris Lattnered468e372003-10-05 00:17:43 +0000952 // If we didn't find the same type, try to move forward...
953 if (TmpIt == ATMEntryIt) {
954 ++TmpIt;
955 if (TmpIt == Map.end() || TmpIt->first.first != Ty)
956 --TmpIt; // No entry afterwards with the same type
957 }
958
959 // If there is another entry in the map of the same abstract type,
960 // update the AbstractTypeMap entry now.
961 if (TmpIt != ATMEntryIt) {
962 ATMEntryIt = TmpIt;
963 } else {
964 // Otherwise, we are removing the last instance of this type
965 // from the table. Remove from the ATM, and from user list.
966 cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
967 AbstractTypeMap.erase(Ty);
968 }
Chris Lattner02ec5ed2003-05-23 20:03:32 +0000969 }
Chris Lattnered468e372003-10-05 00:17:43 +0000970 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000971
Chris Lattnered468e372003-10-05 00:17:43 +0000972 Map.erase(I);
973 }
974
Chris Lattnera1e3f542005-10-04 21:35:50 +0000975
976 /// MoveConstantToNewSlot - If we are about to change C to be the element
977 /// specified by I, update our internal data structures to reflect this
978 /// fact.
Jim Laskeyede5aa42006-07-17 17:38:29 +0000979 void MoveConstantToNewSlot(ConstantClass *C, typename MapTy::iterator I) {
Chris Lattnera1e3f542005-10-04 21:35:50 +0000980 // First, remove the old location of the specified constant in the map.
Jim Laskeyede5aa42006-07-17 17:38:29 +0000981 typename MapTy::iterator OldI = FindExistingElement(C);
Chris Lattnera1e3f542005-10-04 21:35:50 +0000982 assert(OldI != Map.end() && "Constant not found in constant table!");
983 assert(OldI->second == C && "Didn't find correct element?");
984
985 // If this constant is the representative element for its abstract type,
986 // update the AbstractTypeMap so that the representative element is I.
987 if (C->getType()->isAbstract()) {
988 typename AbstractTypeMapTy::iterator ATI =
989 AbstractTypeMap.find(C->getType());
990 assert(ATI != AbstractTypeMap.end() &&
991 "Abstract type not in AbstractTypeMap?");
992 if (ATI->second == OldI)
993 ATI->second = I;
994 }
995
996 // Remove the old entry from the map.
997 Map.erase(OldI);
998
999 // Update the inverse map so that we know that this constant is now
1000 // located at descriptor I.
1001 if (HasLargeKey) {
1002 assert(I->second == C && "Bad inversemap entry!");
1003 InverseMap[C] = I;
1004 }
1005 }
1006
Chris Lattnered468e372003-10-05 00:17:43 +00001007 void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
Misha Brukmanfd939082005-04-21 23:48:37 +00001008 typename AbstractTypeMapTy::iterator I =
Jim Laskeyede5aa42006-07-17 17:38:29 +00001009 AbstractTypeMap.find(cast<Type>(OldTy));
Chris Lattnered468e372003-10-05 00:17:43 +00001010
1011 assert(I != AbstractTypeMap.end() &&
1012 "Abstract type not in AbstractTypeMap?");
1013
1014 // Convert a constant at a time until the last one is gone. The last one
1015 // leaving will remove() itself, causing the AbstractTypeMapEntry to be
1016 // eliminated eventually.
1017 do {
1018 ConvertConstantType<ConstantClass,
Jim Laskeyede5aa42006-07-17 17:38:29 +00001019 TypeClass>::convert(
1020 static_cast<ConstantClass *>(I->second->second),
Chris Lattnered468e372003-10-05 00:17:43 +00001021 cast<TypeClass>(NewTy));
1022
Jim Laskeyede5aa42006-07-17 17:38:29 +00001023 I = AbstractTypeMap.find(cast<Type>(OldTy));
Chris Lattnered468e372003-10-05 00:17:43 +00001024 } while (I != AbstractTypeMap.end());
1025 }
1026
1027 // If the type became concrete without being refined to any other existing
1028 // type, we just remove ourselves from the ATU list.
1029 void typeBecameConcrete(const DerivedType *AbsTy) {
1030 AbsTy->removeAbstractTypeUser(this);
1031 }
1032
1033 void dump() const {
Bill Wendling2e3def12006-11-17 08:03:48 +00001034 DOUT << "Constant.cpp: ValueMap\n";
Chris Lattner02ec5ed2003-05-23 20:03:32 +00001035 }
1036 };
1037}
1038
Chris Lattner003cbf32006-09-28 23:36:21 +00001039
Chris Lattnerd1afbd02007-02-20 06:11:36 +00001040
Chris Lattner40bbeb52004-02-15 05:53:04 +00001041//---- ConstantAggregateZero::get() implementation...
1042//
1043namespace llvm {
1044 // ConstantAggregateZero does not take extra "value" argument...
1045 template<class ValType>
1046 struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
1047 static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
1048 return new ConstantAggregateZero(Ty);
1049 }
1050 };
1051
1052 template<>
1053 struct ConvertConstantType<ConstantAggregateZero, Type> {
1054 static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
1055 // Make everyone now use a constant of the new type...
1056 Constant *New = ConstantAggregateZero::get(NewTy);
1057 assert(New != OldC && "Didn't replace constant??");
1058 OldC->uncheckedReplaceAllUsesWith(New);
1059 OldC->destroyConstant(); // This constant is now dead, destroy it.
1060 }
1061 };
1062}
1063
Chris Lattner8a94bf12006-09-28 00:35:06 +00001064static ManagedStatic<ValueMap<char, Type,
1065 ConstantAggregateZero> > AggZeroConstants;
Chris Lattner40bbeb52004-02-15 05:53:04 +00001066
Chris Lattner6823c9f2004-08-04 04:48:01 +00001067static char getValType(ConstantAggregateZero *CPZ) { return 0; }
1068
Chris Lattner40bbeb52004-02-15 05:53:04 +00001069Constant *ConstantAggregateZero::get(const Type *Ty) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001070 assert((isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) &&
Chris Lattner31d1a2c2006-06-10 04:16:23 +00001071 "Cannot create an aggregate zero of non-aggregate type!");
Chris Lattner8a94bf12006-09-28 00:35:06 +00001072 return AggZeroConstants->getOrCreate(Ty, 0);
Chris Lattner40bbeb52004-02-15 05:53:04 +00001073}
1074
1075// destroyConstant - Remove the constant from the constant table...
1076//
1077void ConstantAggregateZero::destroyConstant() {
Chris Lattner8a94bf12006-09-28 00:35:06 +00001078 AggZeroConstants->remove(this);
Chris Lattner40bbeb52004-02-15 05:53:04 +00001079 destroyConstantImpl();
1080}
1081
Chris Lattnere9bb2df2001-12-03 22:26:30 +00001082//---- ConstantArray::get() implementation...
Chris Lattner531daef2001-09-07 16:46:31 +00001083//
Chris Lattner31f84992003-11-21 20:23:48 +00001084namespace llvm {
1085 template<>
1086 struct ConvertConstantType<ConstantArray, ArrayType> {
1087 static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
1088 // Make everyone now use a constant of the new type...
1089 std::vector<Constant*> C;
1090 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1091 C.push_back(cast<Constant>(OldC->getOperand(i)));
1092 Constant *New = ConstantArray::get(NewTy, C);
1093 assert(New != OldC && "Didn't replace constant??");
1094 OldC->uncheckedReplaceAllUsesWith(New);
1095 OldC->destroyConstant(); // This constant is now dead, destroy it.
1096 }
1097 };
1098}
Chris Lattnered468e372003-10-05 00:17:43 +00001099
Chris Lattner6823c9f2004-08-04 04:48:01 +00001100static std::vector<Constant*> getValType(ConstantArray *CA) {
1101 std::vector<Constant*> Elements;
1102 Elements.reserve(CA->getNumOperands());
1103 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1104 Elements.push_back(cast<Constant>(CA->getOperand(i)));
1105 return Elements;
1106}
1107
Chris Lattnercea141f2005-10-03 22:51:37 +00001108typedef ValueMap<std::vector<Constant*>, ArrayType,
Chris Lattnera55b30a2005-10-04 17:48:46 +00001109 ConstantArray, true /*largekey*/> ArrayConstantsTy;
Chris Lattner8a94bf12006-09-28 00:35:06 +00001110static ManagedStatic<ArrayConstantsTy> ArrayConstants;
Chris Lattner531daef2001-09-07 16:46:31 +00001111
Chris Lattnerca705fa2004-02-15 04:14:47 +00001112Constant *ConstantArray::get(const ArrayType *Ty,
Chris Lattner40bbeb52004-02-15 05:53:04 +00001113 const std::vector<Constant*> &V) {
1114 // If this is an all-zero array, return a ConstantAggregateZero object
1115 if (!V.empty()) {
1116 Constant *C = V[0];
1117 if (!C->isNullValue())
Chris Lattner8a94bf12006-09-28 00:35:06 +00001118 return ArrayConstants->getOrCreate(Ty, V);
Chris Lattner40bbeb52004-02-15 05:53:04 +00001119 for (unsigned i = 1, e = V.size(); i != e; ++i)
1120 if (V[i] != C)
Chris Lattner8a94bf12006-09-28 00:35:06 +00001121 return ArrayConstants->getOrCreate(Ty, V);
Chris Lattner40bbeb52004-02-15 05:53:04 +00001122 }
1123 return ConstantAggregateZero::get(Ty);
Chris Lattner531daef2001-09-07 16:46:31 +00001124}
1125
Chris Lattner02ec5ed2003-05-23 20:03:32 +00001126// destroyConstant - Remove the constant from the constant table...
1127//
1128void ConstantArray::destroyConstant() {
Chris Lattner8a94bf12006-09-28 00:35:06 +00001129 ArrayConstants->remove(this);
Chris Lattner02ec5ed2003-05-23 20:03:32 +00001130 destroyConstantImpl();
1131}
1132
Reid Spencer89494772006-05-30 08:23:18 +00001133/// ConstantArray::get(const string&) - Return an array that is initialized to
1134/// contain the specified string. If length is zero then a null terminator is
1135/// added to the specified string so that it may be used in a natural way.
1136/// Otherwise, the length parameter specifies how much of the string to use
1137/// and it won't be null terminated.
1138///
Reid Spencer461bed22006-05-30 18:15:07 +00001139Constant *ConstantArray::get(const std::string &Str, bool AddNull) {
Chris Lattner697954c2002-01-20 22:54:45 +00001140 std::vector<Constant*> ElementVals;
Reid Spencer461bed22006-05-30 18:15:07 +00001141 for (unsigned i = 0; i < Str.length(); ++i)
Reid Spencer79e21d32006-12-31 05:26:44 +00001142 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, Str[i]));
Chris Lattnerc5bdb242001-10-14 23:54:12 +00001143
1144 // Add a null terminator to the string...
Reid Spencer461bed22006-05-30 18:15:07 +00001145 if (AddNull) {
Reid Spencer79e21d32006-12-31 05:26:44 +00001146 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, 0));
Reid Spencer89494772006-05-30 08:23:18 +00001147 }
Chris Lattnerc5bdb242001-10-14 23:54:12 +00001148
Reid Spencer79e21d32006-12-31 05:26:44 +00001149 ArrayType *ATy = ArrayType::get(Type::Int8Ty, ElementVals.size());
Chris Lattnere9bb2df2001-12-03 22:26:30 +00001150 return ConstantArray::get(ATy, ElementVals);
Vikram S. Advedb2da492001-10-14 23:17:20 +00001151}
1152
Reid Spencer3d10b0b2007-01-26 07:37:34 +00001153/// isString - This method returns true if the array is an array of i8, and
1154/// if the elements of the array are all ConstantInt's.
Chris Lattner13cfdea2004-01-14 17:06:38 +00001155bool ConstantArray::isString() const {
Reid Spencer3d10b0b2007-01-26 07:37:34 +00001156 // Check the element type for i8...
Reid Spencer79e21d32006-12-31 05:26:44 +00001157 if (getType()->getElementType() != Type::Int8Ty)
Chris Lattner13cfdea2004-01-14 17:06:38 +00001158 return false;
1159 // Check the elements to make sure they are all integers, not constant
1160 // expressions.
1161 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1162 if (!isa<ConstantInt>(getOperand(i)))
1163 return false;
1164 return true;
1165}
1166
Evan Cheng22c70302006-10-26 19:15:05 +00001167/// isCString - This method returns true if the array is a string (see
1168/// isString) and it ends in a null byte \0 and does not contains any other
1169/// null bytes except its terminator.
1170bool ConstantArray::isCString() const {
Reid Spencer3d10b0b2007-01-26 07:37:34 +00001171 // Check the element type for i8...
Reid Spencer79e21d32006-12-31 05:26:44 +00001172 if (getType()->getElementType() != Type::Int8Ty)
Evan Chengabf63452006-10-26 21:48:03 +00001173 return false;
1174 Constant *Zero = Constant::getNullValue(getOperand(0)->getType());
1175 // Last element must be a null.
1176 if (getOperand(getNumOperands()-1) != Zero)
1177 return false;
1178 // Other elements must be non-null integers.
1179 for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
1180 if (!isa<ConstantInt>(getOperand(i)))
Evan Cheng22c70302006-10-26 19:15:05 +00001181 return false;
Evan Chengabf63452006-10-26 21:48:03 +00001182 if (getOperand(i) == Zero)
1183 return false;
1184 }
Evan Cheng22c70302006-10-26 19:15:05 +00001185 return true;
1186}
1187
1188
Reid Spencer3d10b0b2007-01-26 07:37:34 +00001189// getAsString - If the sub-element type of this array is i8
Chris Lattner93aeea32002-08-26 17:53:56 +00001190// then this method converts the array to an std::string and returns it.
1191// Otherwise, it asserts out.
1192//
1193std::string ConstantArray::getAsString() const {
Chris Lattner13cfdea2004-01-14 17:06:38 +00001194 assert(isString() && "Not a string!");
Chris Lattner93aeea32002-08-26 17:53:56 +00001195 std::string Result;
Chris Lattnerc07736a2003-07-23 15:22:26 +00001196 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
Reid Spencerb83eb642006-10-20 07:07:24 +00001197 Result += (char)cast<ConstantInt>(getOperand(i))->getZExtValue();
Chris Lattner93aeea32002-08-26 17:53:56 +00001198 return Result;
1199}
1200
1201
Chris Lattnere9bb2df2001-12-03 22:26:30 +00001202//---- ConstantStruct::get() implementation...
Chris Lattner531daef2001-09-07 16:46:31 +00001203//
Chris Lattnered468e372003-10-05 00:17:43 +00001204
Chris Lattner31f84992003-11-21 20:23:48 +00001205namespace llvm {
1206 template<>
1207 struct ConvertConstantType<ConstantStruct, StructType> {
1208 static void convert(ConstantStruct *OldC, const StructType *NewTy) {
1209 // Make everyone now use a constant of the new type...
1210 std::vector<Constant*> C;
1211 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1212 C.push_back(cast<Constant>(OldC->getOperand(i)));
1213 Constant *New = ConstantStruct::get(NewTy, C);
1214 assert(New != OldC && "Didn't replace constant??");
Misha Brukmanfd939082005-04-21 23:48:37 +00001215
Chris Lattner31f84992003-11-21 20:23:48 +00001216 OldC->uncheckedReplaceAllUsesWith(New);
1217 OldC->destroyConstant(); // This constant is now dead, destroy it.
1218 }
1219 };
1220}
Chris Lattnered468e372003-10-05 00:17:43 +00001221
Chris Lattnerc182a882005-10-04 01:17:50 +00001222typedef ValueMap<std::vector<Constant*>, StructType,
Chris Lattnera55b30a2005-10-04 17:48:46 +00001223 ConstantStruct, true /*largekey*/> StructConstantsTy;
Chris Lattner8a94bf12006-09-28 00:35:06 +00001224static ManagedStatic<StructConstantsTy> StructConstants;
Chris Lattner531daef2001-09-07 16:46:31 +00001225
Chris Lattner6823c9f2004-08-04 04:48:01 +00001226static std::vector<Constant*> getValType(ConstantStruct *CS) {
1227 std::vector<Constant*> Elements;
1228 Elements.reserve(CS->getNumOperands());
1229 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1230 Elements.push_back(cast<Constant>(CS->getOperand(i)));
1231 return Elements;
1232}
1233
Chris Lattnerca705fa2004-02-15 04:14:47 +00001234Constant *ConstantStruct::get(const StructType *Ty,
1235 const std::vector<Constant*> &V) {
Chris Lattner40bbeb52004-02-15 05:53:04 +00001236 // Create a ConstantAggregateZero value if all elements are zeros...
1237 for (unsigned i = 0, e = V.size(); i != e; ++i)
1238 if (!V[i]->isNullValue())
Chris Lattner8a94bf12006-09-28 00:35:06 +00001239 return StructConstants->getOrCreate(Ty, V);
Chris Lattner40bbeb52004-02-15 05:53:04 +00001240
1241 return ConstantAggregateZero::get(Ty);
Chris Lattner531daef2001-09-07 16:46:31 +00001242}
Chris Lattner6a57baa2001-10-03 15:39:36 +00001243
Andrew Lenharth38ecbf12006-12-08 18:06:16 +00001244Constant *ConstantStruct::get(const std::vector<Constant*> &V, bool packed) {
Chris Lattnerb370c7a2004-07-12 20:35:11 +00001245 std::vector<const Type*> StructEls;
1246 StructEls.reserve(V.size());
1247 for (unsigned i = 0, e = V.size(); i != e; ++i)
1248 StructEls.push_back(V[i]->getType());
Andrew Lenharth38ecbf12006-12-08 18:06:16 +00001249 return get(StructType::get(StructEls, packed), V);
Chris Lattnerb370c7a2004-07-12 20:35:11 +00001250}
1251
Chris Lattnerf5ec48d2001-10-13 06:57:33 +00001252// destroyConstant - Remove the constant from the constant table...
Chris Lattner6a57baa2001-10-03 15:39:36 +00001253//
Chris Lattnere9bb2df2001-12-03 22:26:30 +00001254void ConstantStruct::destroyConstant() {
Chris Lattner8a94bf12006-09-28 00:35:06 +00001255 StructConstants->remove(this);
Chris Lattnerf5ec48d2001-10-13 06:57:33 +00001256 destroyConstantImpl();
1257}
Chris Lattner6a57baa2001-10-03 15:39:36 +00001258
Reid Spencer9d6565a2007-02-15 02:26:10 +00001259//---- ConstantVector::get() implementation...
Brian Gaeke715c90b2004-08-20 06:00:58 +00001260//
1261namespace llvm {
1262 template<>
Reid Spencer9d6565a2007-02-15 02:26:10 +00001263 struct ConvertConstantType<ConstantVector, VectorType> {
1264 static void convert(ConstantVector *OldC, const VectorType *NewTy) {
Brian Gaeke715c90b2004-08-20 06:00:58 +00001265 // Make everyone now use a constant of the new type...
1266 std::vector<Constant*> C;
1267 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1268 C.push_back(cast<Constant>(OldC->getOperand(i)));
Reid Spencer9d6565a2007-02-15 02:26:10 +00001269 Constant *New = ConstantVector::get(NewTy, C);
Brian Gaeke715c90b2004-08-20 06:00:58 +00001270 assert(New != OldC && "Didn't replace constant??");
1271 OldC->uncheckedReplaceAllUsesWith(New);
1272 OldC->destroyConstant(); // This constant is now dead, destroy it.
1273 }
1274 };
1275}
1276
Reid Spencer9d6565a2007-02-15 02:26:10 +00001277static std::vector<Constant*> getValType(ConstantVector *CP) {
Brian Gaeke715c90b2004-08-20 06:00:58 +00001278 std::vector<Constant*> Elements;
1279 Elements.reserve(CP->getNumOperands());
1280 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1281 Elements.push_back(CP->getOperand(i));
1282 return Elements;
1283}
1284
Reid Spencer9d6565a2007-02-15 02:26:10 +00001285static ManagedStatic<ValueMap<std::vector<Constant*>, VectorType,
Reid Spencerac9dcb92007-02-15 03:39:18 +00001286 ConstantVector> > VectorConstants;
Brian Gaeke715c90b2004-08-20 06:00:58 +00001287
Reid Spencer9d6565a2007-02-15 02:26:10 +00001288Constant *ConstantVector::get(const VectorType *Ty,
Brian Gaeke715c90b2004-08-20 06:00:58 +00001289 const std::vector<Constant*> &V) {
Dan Gohmanfa73ea22007-05-24 14:36:04 +00001290 // If this is an all-zero vector, return a ConstantAggregateZero object
Brian Gaeke715c90b2004-08-20 06:00:58 +00001291 if (!V.empty()) {
1292 Constant *C = V[0];
1293 if (!C->isNullValue())
Reid Spencerac9dcb92007-02-15 03:39:18 +00001294 return VectorConstants->getOrCreate(Ty, V);
Brian Gaeke715c90b2004-08-20 06:00:58 +00001295 for (unsigned i = 1, e = V.size(); i != e; ++i)
1296 if (V[i] != C)
Reid Spencerac9dcb92007-02-15 03:39:18 +00001297 return VectorConstants->getOrCreate(Ty, V);
Brian Gaeke715c90b2004-08-20 06:00:58 +00001298 }
1299 return ConstantAggregateZero::get(Ty);
1300}
1301
Reid Spencer9d6565a2007-02-15 02:26:10 +00001302Constant *ConstantVector::get(const std::vector<Constant*> &V) {
Brian Gaeke715c90b2004-08-20 06:00:58 +00001303 assert(!V.empty() && "Cannot infer type if V is empty");
Reid Spencer9d6565a2007-02-15 02:26:10 +00001304 return get(VectorType::get(V.front()->getType(),V.size()), V);
Brian Gaeke715c90b2004-08-20 06:00:58 +00001305}
1306
1307// destroyConstant - Remove the constant from the constant table...
1308//
Reid Spencer9d6565a2007-02-15 02:26:10 +00001309void ConstantVector::destroyConstant() {
Reid Spencerac9dcb92007-02-15 03:39:18 +00001310 VectorConstants->remove(this);
Brian Gaeke715c90b2004-08-20 06:00:58 +00001311 destroyConstantImpl();
1312}
1313
Dan Gohmanfa73ea22007-05-24 14:36:04 +00001314/// This function will return true iff every element in this vector constant
Jim Laskeyfa301822007-01-12 22:39:14 +00001315/// is set to all ones.
1316/// @returns true iff this constant's emements are all set to all ones.
1317/// @brief Determine if the value is all ones.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001318bool ConstantVector::isAllOnesValue() const {
Jim Laskeyfa301822007-01-12 22:39:14 +00001319 // Check out first element.
1320 const Constant *Elt = getOperand(0);
1321 const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1322 if (!CI || !CI->isAllOnesValue()) return false;
1323 // Then make sure all remaining elements point to the same value.
1324 for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
1325 if (getOperand(I) != Elt) return false;
1326 }
1327 return true;
1328}
1329
Dan Gohman3b7cf0a2007-10-17 17:51:30 +00001330/// getSplatValue - If this is a splat constant, where all of the
1331/// elements have the same value, return that value. Otherwise return null.
1332Constant *ConstantVector::getSplatValue() {
1333 // Check out first element.
1334 Constant *Elt = getOperand(0);
1335 // Then make sure all remaining elements point to the same value.
1336 for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
1337 if (getOperand(I) != Elt) return 0;
1338 return Elt;
1339}
1340
Chris Lattnere9bb2df2001-12-03 22:26:30 +00001341//---- ConstantPointerNull::get() implementation...
Chris Lattnerf5ec48d2001-10-13 06:57:33 +00001342//
Chris Lattner02ec5ed2003-05-23 20:03:32 +00001343
Chris Lattner31f84992003-11-21 20:23:48 +00001344namespace llvm {
1345 // ConstantPointerNull does not take extra "value" argument...
1346 template<class ValType>
1347 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1348 static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1349 return new ConstantPointerNull(Ty);
1350 }
1351 };
Chris Lattner02ec5ed2003-05-23 20:03:32 +00001352
Chris Lattner31f84992003-11-21 20:23:48 +00001353 template<>
1354 struct ConvertConstantType<ConstantPointerNull, PointerType> {
1355 static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1356 // Make everyone now use a constant of the new type...
1357 Constant *New = ConstantPointerNull::get(NewTy);
1358 assert(New != OldC && "Didn't replace constant??");
1359 OldC->uncheckedReplaceAllUsesWith(New);
1360 OldC->destroyConstant(); // This constant is now dead, destroy it.
1361 }
1362 };
1363}
Chris Lattnered468e372003-10-05 00:17:43 +00001364
Chris Lattner8a94bf12006-09-28 00:35:06 +00001365static ManagedStatic<ValueMap<char, PointerType,
1366 ConstantPointerNull> > NullPtrConstants;
Chris Lattnerf5ec48d2001-10-13 06:57:33 +00001367
Chris Lattner6823c9f2004-08-04 04:48:01 +00001368static char getValType(ConstantPointerNull *) {
1369 return 0;
1370}
1371
1372
Chris Lattnere9bb2df2001-12-03 22:26:30 +00001373ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
Chris Lattner8a94bf12006-09-28 00:35:06 +00001374 return NullPtrConstants->getOrCreate(Ty, 0);
Chris Lattner6a57baa2001-10-03 15:39:36 +00001375}
1376
Chris Lattner41661fd2002-08-18 00:40:04 +00001377// destroyConstant - Remove the constant from the constant table...
1378//
1379void ConstantPointerNull::destroyConstant() {
Chris Lattner8a94bf12006-09-28 00:35:06 +00001380 NullPtrConstants->remove(this);
Chris Lattner41661fd2002-08-18 00:40:04 +00001381 destroyConstantImpl();
1382}
1383
1384
Chris Lattnerb9f18592004-10-16 18:07:16 +00001385//---- UndefValue::get() implementation...
1386//
1387
1388namespace llvm {
1389 // UndefValue does not take extra "value" argument...
1390 template<class ValType>
1391 struct ConstantCreator<UndefValue, Type, ValType> {
1392 static UndefValue *create(const Type *Ty, const ValType &V) {
1393 return new UndefValue(Ty);
1394 }
1395 };
1396
1397 template<>
1398 struct ConvertConstantType<UndefValue, Type> {
1399 static void convert(UndefValue *OldC, const Type *NewTy) {
1400 // Make everyone now use a constant of the new type.
1401 Constant *New = UndefValue::get(NewTy);
1402 assert(New != OldC && "Didn't replace constant??");
1403 OldC->uncheckedReplaceAllUsesWith(New);
1404 OldC->destroyConstant(); // This constant is now dead, destroy it.
1405 }
1406 };
1407}
1408
Chris Lattner8a94bf12006-09-28 00:35:06 +00001409static ManagedStatic<ValueMap<char, Type, UndefValue> > UndefValueConstants;
Chris Lattnerb9f18592004-10-16 18:07:16 +00001410
1411static char getValType(UndefValue *) {
1412 return 0;
1413}
1414
1415
1416UndefValue *UndefValue::get(const Type *Ty) {
Chris Lattner8a94bf12006-09-28 00:35:06 +00001417 return UndefValueConstants->getOrCreate(Ty, 0);
Chris Lattnerb9f18592004-10-16 18:07:16 +00001418}
1419
1420// destroyConstant - Remove the constant from the constant table.
1421//
1422void UndefValue::destroyConstant() {
Chris Lattner8a94bf12006-09-28 00:35:06 +00001423 UndefValueConstants->remove(this);
Chris Lattnerb9f18592004-10-16 18:07:16 +00001424 destroyConstantImpl();
1425}
1426
1427
Vikram S. Adve345e0cf2002-07-14 23:13:17 +00001428//---- ConstantExpr::get() implementations...
Vikram S. Adve345e0cf2002-07-14 23:13:17 +00001429//
Reid Spencer79e21d32006-12-31 05:26:44 +00001430
Reid Spencer077d0eb2006-12-04 05:19:50 +00001431struct ExprMapKeyType {
1432 explicit ExprMapKeyType(unsigned opc, std::vector<Constant*> ops,
Reid Spencer8d5a6ae2006-12-04 18:38:05 +00001433 unsigned short pred = 0) : opcode(opc), predicate(pred), operands(ops) { }
1434 uint16_t opcode;
1435 uint16_t predicate;
Reid Spencer077d0eb2006-12-04 05:19:50 +00001436 std::vector<Constant*> operands;
Reid Spencer077d0eb2006-12-04 05:19:50 +00001437 bool operator==(const ExprMapKeyType& that) const {
1438 return this->opcode == that.opcode &&
1439 this->predicate == that.predicate &&
1440 this->operands == that.operands;
1441 }
1442 bool operator<(const ExprMapKeyType & that) const {
1443 return this->opcode < that.opcode ||
1444 (this->opcode == that.opcode && this->predicate < that.predicate) ||
1445 (this->opcode == that.opcode && this->predicate == that.predicate &&
1446 this->operands < that.operands);
1447 }
1448
1449 bool operator!=(const ExprMapKeyType& that) const {
1450 return !(*this == that);
1451 }
1452};
Chris Lattner02ec5ed2003-05-23 20:03:32 +00001453
Chris Lattner31f84992003-11-21 20:23:48 +00001454namespace llvm {
1455 template<>
1456 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
Reid Spencer728b6db2006-12-03 05:48:19 +00001457 static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V,
1458 unsigned short pred = 0) {
Reid Spencer077d0eb2006-12-04 05:19:50 +00001459 if (Instruction::isCast(V.opcode))
1460 return new UnaryConstantExpr(V.opcode, V.operands[0], Ty);
1461 if ((V.opcode >= Instruction::BinaryOpsBegin &&
Reid Spencer832254e2007-02-02 02:16:23 +00001462 V.opcode < Instruction::BinaryOpsEnd))
Reid Spencer077d0eb2006-12-04 05:19:50 +00001463 return new BinaryConstantExpr(V.opcode, V.operands[0], V.operands[1]);
1464 if (V.opcode == Instruction::Select)
1465 return new SelectConstantExpr(V.operands[0], V.operands[1],
1466 V.operands[2]);
1467 if (V.opcode == Instruction::ExtractElement)
1468 return new ExtractElementConstantExpr(V.operands[0], V.operands[1]);
1469 if (V.opcode == Instruction::InsertElement)
1470 return new InsertElementConstantExpr(V.operands[0], V.operands[1],
1471 V.operands[2]);
1472 if (V.opcode == Instruction::ShuffleVector)
1473 return new ShuffleVectorConstantExpr(V.operands[0], V.operands[1],
1474 V.operands[2]);
1475 if (V.opcode == Instruction::GetElementPtr) {
1476 std::vector<Constant*> IdxList(V.operands.begin()+1, V.operands.end());
Gabor Greif051a9502008-04-06 20:25:17 +00001477 return GetElementPtrConstantExpr::Create(V.operands[0], IdxList, Ty);
Reid Spencer077d0eb2006-12-04 05:19:50 +00001478 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001479
Reid Spencer077d0eb2006-12-04 05:19:50 +00001480 // The compare instructions are weird. We have to encode the predicate
1481 // value and it is combined with the instruction opcode by multiplying
1482 // the opcode by one hundred. We must decode this to get the predicate.
1483 if (V.opcode == Instruction::ICmp)
1484 return new CompareConstantExpr(Instruction::ICmp, V.predicate,
1485 V.operands[0], V.operands[1]);
1486 if (V.opcode == Instruction::FCmp)
1487 return new CompareConstantExpr(Instruction::FCmp, V.predicate,
1488 V.operands[0], V.operands[1]);
1489 assert(0 && "Invalid ConstantExpr!");
Jeff Cohen6ebe2352006-12-15 21:47:01 +00001490 return 0;
Chris Lattnered468e372003-10-05 00:17:43 +00001491 }
Chris Lattner31f84992003-11-21 20:23:48 +00001492 };
Chris Lattnered468e372003-10-05 00:17:43 +00001493
Chris Lattner31f84992003-11-21 20:23:48 +00001494 template<>
1495 struct ConvertConstantType<ConstantExpr, Type> {
1496 static void convert(ConstantExpr *OldC, const Type *NewTy) {
1497 Constant *New;
1498 switch (OldC->getOpcode()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001499 case Instruction::Trunc:
1500 case Instruction::ZExt:
1501 case Instruction::SExt:
1502 case Instruction::FPTrunc:
1503 case Instruction::FPExt:
1504 case Instruction::UIToFP:
1505 case Instruction::SIToFP:
1506 case Instruction::FPToUI:
1507 case Instruction::FPToSI:
1508 case Instruction::PtrToInt:
1509 case Instruction::IntToPtr:
1510 case Instruction::BitCast:
Reid Spencerd977d862006-12-12 23:36:14 +00001511 New = ConstantExpr::getCast(OldC->getOpcode(), OldC->getOperand(0),
1512 NewTy);
Chris Lattner31f84992003-11-21 20:23:48 +00001513 break;
Chris Lattner08a45cc2004-03-12 05:54:04 +00001514 case Instruction::Select:
1515 New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1516 OldC->getOperand(1),
1517 OldC->getOperand(2));
1518 break;
Chris Lattner31f84992003-11-21 20:23:48 +00001519 default:
1520 assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
Reid Spencer0a783f72006-11-02 01:53:59 +00001521 OldC->getOpcode() < Instruction::BinaryOpsEnd);
Chris Lattner31f84992003-11-21 20:23:48 +00001522 New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1523 OldC->getOperand(1));
1524 break;
1525 case Instruction::GetElementPtr:
Misha Brukmanfd939082005-04-21 23:48:37 +00001526 // Make everyone now use a constant of the new type...
Chris Lattner7fa6e662004-10-11 22:52:25 +00001527 std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
Chris Lattner2b9a5da2007-01-31 04:40:28 +00001528 New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0),
1529 &Idx[0], Idx.size());
Chris Lattner31f84992003-11-21 20:23:48 +00001530 break;
1531 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001532
Chris Lattner31f84992003-11-21 20:23:48 +00001533 assert(New != OldC && "Didn't replace constant??");
1534 OldC->uncheckedReplaceAllUsesWith(New);
1535 OldC->destroyConstant(); // This constant is now dead, destroy it.
1536 }
1537 };
1538} // end namespace llvm
Chris Lattnered468e372003-10-05 00:17:43 +00001539
1540
Chris Lattner6823c9f2004-08-04 04:48:01 +00001541static ExprMapKeyType getValType(ConstantExpr *CE) {
1542 std::vector<Constant*> Operands;
1543 Operands.reserve(CE->getNumOperands());
1544 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
1545 Operands.push_back(cast<Constant>(CE->getOperand(i)));
Reid Spencer077d0eb2006-12-04 05:19:50 +00001546 return ExprMapKeyType(CE->getOpcode(), Operands,
1547 CE->isCompare() ? CE->getPredicate() : 0);
Chris Lattner6823c9f2004-08-04 04:48:01 +00001548}
1549
Chris Lattner8a94bf12006-09-28 00:35:06 +00001550static ManagedStatic<ValueMap<ExprMapKeyType, Type,
1551 ConstantExpr> > ExprConstants;
Vikram S. Adved0b1bb02002-07-15 18:19:33 +00001552
Reid Spencer3da59db2006-11-27 01:05:10 +00001553/// This is a utility function to handle folding of casts and lookup of the
Duncan Sands66a1a052008-03-30 19:38:55 +00001554/// cast in the ExprConstants map. It is used by the various get* methods below.
Reid Spencer3da59db2006-11-27 01:05:10 +00001555static inline Constant *getFoldedCast(
1556 Instruction::CastOps opc, Constant *C, const Type *Ty) {
Chris Lattner9eacf8a2003-10-07 22:19:19 +00001557 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
Reid Spencer3da59db2006-11-27 01:05:10 +00001558 // Fold a few common cases
1559 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
1560 return FC;
Chris Lattnerd628f6a2003-04-17 19:24:48 +00001561
Vikram S. Adved0b1bb02002-07-15 18:19:33 +00001562 // Look up the constant in the table first to ensure uniqueness
Chris Lattner9bc02a42003-05-13 21:37:02 +00001563 std::vector<Constant*> argVec(1, C);
Reid Spencer077d0eb2006-12-04 05:19:50 +00001564 ExprMapKeyType Key(opc, argVec);
Chris Lattner8a94bf12006-09-28 00:35:06 +00001565 return ExprConstants->getOrCreate(Ty, Key);
Vikram S. Adve345e0cf2002-07-14 23:13:17 +00001566}
Reid Spencer7858b332006-12-05 19:14:13 +00001567
Reid Spencer3da59db2006-11-27 01:05:10 +00001568Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
1569 Instruction::CastOps opc = Instruction::CastOps(oc);
1570 assert(Instruction::isCast(opc) && "opcode out of range");
1571 assert(C && Ty && "Null arguments to getCast");
1572 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1573
1574 switch (opc) {
1575 default:
1576 assert(0 && "Invalid cast opcode");
1577 break;
1578 case Instruction::Trunc: return getTrunc(C, Ty);
Reid Spencerd977d862006-12-12 23:36:14 +00001579 case Instruction::ZExt: return getZExt(C, Ty);
1580 case Instruction::SExt: return getSExt(C, Ty);
Reid Spencer3da59db2006-11-27 01:05:10 +00001581 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
1582 case Instruction::FPExt: return getFPExtend(C, Ty);
1583 case Instruction::UIToFP: return getUIToFP(C, Ty);
1584 case Instruction::SIToFP: return getSIToFP(C, Ty);
1585 case Instruction::FPToUI: return getFPToUI(C, Ty);
1586 case Instruction::FPToSI: return getFPToSI(C, Ty);
1587 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1588 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1589 case Instruction::BitCast: return getBitCast(C, Ty);
Chris Lattnerf5ac6c22005-01-01 15:59:57 +00001590 }
Reid Spencer3da59db2006-11-27 01:05:10 +00001591 return 0;
Reid Spencer7858b332006-12-05 19:14:13 +00001592}
1593
Reid Spencer848414e2006-12-04 20:17:56 +00001594Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
1595 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1596 return getCast(Instruction::BitCast, C, Ty);
1597 return getCast(Instruction::ZExt, C, Ty);
1598}
1599
1600Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
1601 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1602 return getCast(Instruction::BitCast, C, Ty);
1603 return getCast(Instruction::SExt, C, Ty);
1604}
1605
1606Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
1607 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1608 return getCast(Instruction::BitCast, C, Ty);
1609 return getCast(Instruction::Trunc, C, Ty);
1610}
1611
Reid Spencerc0459fb2006-12-05 03:25:26 +00001612Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
1613 assert(isa<PointerType>(S->getType()) && "Invalid cast");
Chris Lattner42a75512007-01-15 02:27:26 +00001614 assert((Ty->isInteger() || isa<PointerType>(Ty)) && "Invalid cast");
Reid Spencerc0459fb2006-12-05 03:25:26 +00001615
Chris Lattner42a75512007-01-15 02:27:26 +00001616 if (Ty->isInteger())
Reid Spencerc0459fb2006-12-05 03:25:26 +00001617 return getCast(Instruction::PtrToInt, S, Ty);
1618 return getCast(Instruction::BitCast, S, Ty);
1619}
1620
Reid Spencer84f3eab2006-12-12 00:51:07 +00001621Constant *ConstantExpr::getIntegerCast(Constant *C, const Type *Ty,
1622 bool isSigned) {
Chris Lattner42a75512007-01-15 02:27:26 +00001623 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
Reid Spencer84f3eab2006-12-12 00:51:07 +00001624 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1625 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1626 Instruction::CastOps opcode =
1627 (SrcBits == DstBits ? Instruction::BitCast :
1628 (SrcBits > DstBits ? Instruction::Trunc :
1629 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1630 return getCast(opcode, C, Ty);
1631}
1632
1633Constant *ConstantExpr::getFPCast(Constant *C, const Type *Ty) {
1634 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1635 "Invalid cast");
1636 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1637 unsigned DstBits = Ty->getPrimitiveSizeInBits();
Reid Spencerf25212a2006-12-12 05:38:50 +00001638 if (SrcBits == DstBits)
1639 return C; // Avoid a useless cast
Reid Spencer84f3eab2006-12-12 00:51:07 +00001640 Instruction::CastOps opcode =
Reid Spencerf25212a2006-12-12 05:38:50 +00001641 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
Reid Spencer84f3eab2006-12-12 00:51:07 +00001642 return getCast(opcode, C, Ty);
1643}
1644
Reid Spencer3da59db2006-11-27 01:05:10 +00001645Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
Chris Lattner42a75512007-01-15 02:27:26 +00001646 assert(C->getType()->isInteger() && "Trunc operand must be integer");
1647 assert(Ty->isInteger() && "Trunc produces only integral");
Reid Spencer3da59db2006-11-27 01:05:10 +00001648 assert(C->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()&&
1649 "SrcTy must be larger than DestTy for Trunc!");
1650
1651 return getFoldedCast(Instruction::Trunc, C, Ty);
1652}
1653
Reid Spencerd977d862006-12-12 23:36:14 +00001654Constant *ConstantExpr::getSExt(Constant *C, const Type *Ty) {
Chris Lattner42a75512007-01-15 02:27:26 +00001655 assert(C->getType()->isInteger() && "SEXt operand must be integral");
1656 assert(Ty->isInteger() && "SExt produces only integer");
Reid Spencer3da59db2006-11-27 01:05:10 +00001657 assert(C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1658 "SrcTy must be smaller than DestTy for SExt!");
1659
1660 return getFoldedCast(Instruction::SExt, C, Ty);
Chris Lattnerd144f422004-04-04 23:20:30 +00001661}
1662
Reid Spencerd977d862006-12-12 23:36:14 +00001663Constant *ConstantExpr::getZExt(Constant *C, const Type *Ty) {
Chris Lattner42a75512007-01-15 02:27:26 +00001664 assert(C->getType()->isInteger() && "ZEXt operand must be integral");
1665 assert(Ty->isInteger() && "ZExt produces only integer");
Reid Spencer3da59db2006-11-27 01:05:10 +00001666 assert(C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1667 "SrcTy must be smaller than DestTy for ZExt!");
1668
1669 return getFoldedCast(Instruction::ZExt, C, Ty);
1670}
1671
1672Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
1673 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1674 C->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()&&
1675 "This is an illegal floating point truncation!");
1676 return getFoldedCast(Instruction::FPTrunc, C, Ty);
1677}
1678
1679Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
1680 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1681 C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1682 "This is an illegal floating point extension!");
1683 return getFoldedCast(Instruction::FPExt, C, Ty);
1684}
1685
1686Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
Nate Begemanb348d182007-11-17 03:58:34 +00001687 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1688 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1689 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1690 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
1691 "This is an illegal uint to floating point cast!");
Reid Spencer3da59db2006-11-27 01:05:10 +00001692 return getFoldedCast(Instruction::UIToFP, C, Ty);
1693}
1694
1695Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
Nate Begemanb348d182007-11-17 03:58:34 +00001696 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1697 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1698 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1699 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
Reid Spencer3da59db2006-11-27 01:05:10 +00001700 "This is an illegal sint to floating point cast!");
1701 return getFoldedCast(Instruction::SIToFP, C, Ty);
1702}
1703
1704Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
Nate Begemanb348d182007-11-17 03:58:34 +00001705 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1706 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1707 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1708 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
1709 "This is an illegal floating point to uint cast!");
Reid Spencer3da59db2006-11-27 01:05:10 +00001710 return getFoldedCast(Instruction::FPToUI, C, Ty);
1711}
1712
1713Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
Nate Begemanb348d182007-11-17 03:58:34 +00001714 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1715 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1716 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1717 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
1718 "This is an illegal floating point to sint cast!");
Reid Spencer3da59db2006-11-27 01:05:10 +00001719 return getFoldedCast(Instruction::FPToSI, C, Ty);
1720}
1721
1722Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
1723 assert(isa<PointerType>(C->getType()) && "PtrToInt source must be pointer");
Chris Lattner42a75512007-01-15 02:27:26 +00001724 assert(DstTy->isInteger() && "PtrToInt destination must be integral");
Reid Spencer3da59db2006-11-27 01:05:10 +00001725 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
1726}
1727
1728Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
Chris Lattner42a75512007-01-15 02:27:26 +00001729 assert(C->getType()->isInteger() && "IntToPtr source must be integral");
Reid Spencer3da59db2006-11-27 01:05:10 +00001730 assert(isa<PointerType>(DstTy) && "IntToPtr destination must be a pointer");
1731 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
1732}
1733
1734Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
1735 // BitCast implies a no-op cast of type only. No bits change. However, you
1736 // can't cast pointers to anything but pointers.
1737 const Type *SrcTy = C->getType();
1738 assert((isa<PointerType>(SrcTy) == isa<PointerType>(DstTy)) &&
Reid Spencer848414e2006-12-04 20:17:56 +00001739 "BitCast cannot cast pointer to non-pointer and vice versa");
Reid Spencer3da59db2006-11-27 01:05:10 +00001740
1741 // Now we know we're not dealing with mismatched pointer casts (ptr->nonptr
1742 // or nonptr->ptr). For all the other types, the cast is okay if source and
1743 // destination bit widths are identical.
1744 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1745 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
Reid Spencer848414e2006-12-04 20:17:56 +00001746 assert(SrcBitSize == DstBitSize && "BitCast requies types of same width");
Reid Spencer3da59db2006-11-27 01:05:10 +00001747 return getFoldedCast(Instruction::BitCast, C, DstTy);
Chris Lattnerd144f422004-04-04 23:20:30 +00001748}
1749
Alkis Evlogimenos60ab1402004-10-24 01:41:10 +00001750Constant *ConstantExpr::getSizeOf(const Type *Ty) {
Gordon Henriksen46475692007-10-06 14:29:36 +00001751 // sizeof is implemented as: (i64) gep (Ty*)null, 1
Chris Lattnerf9021ff2007-02-19 20:01:23 +00001752 Constant *GEPIdx = ConstantInt::get(Type::Int32Ty, 1);
1753 Constant *GEP =
Christopher Lamb43ad6b32007-12-17 01:12:55 +00001754 getGetElementPtr(getNullValue(PointerType::getUnqual(Ty)), &GEPIdx, 1);
Chris Lattnerf9021ff2007-02-19 20:01:23 +00001755 return getCast(Instruction::PtrToInt, GEP, Type::Int64Ty);
Alkis Evlogimenos1cecd3a2005-03-19 11:40:31 +00001756}
1757
Chris Lattnered468e372003-10-05 00:17:43 +00001758Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
Reid Spencer67263fe2006-12-04 21:35:24 +00001759 Constant *C1, Constant *C2) {
Chris Lattnerf31f5832003-05-21 17:49:25 +00001760 // Check the operands for consistency first
Reid Spencer0a783f72006-11-02 01:53:59 +00001761 assert(Opcode >= Instruction::BinaryOpsBegin &&
1762 Opcode < Instruction::BinaryOpsEnd &&
Chris Lattnerf31f5832003-05-21 17:49:25 +00001763 "Invalid opcode in binary constant expression");
1764 assert(C1->getType() == C2->getType() &&
1765 "Operand types in binary constant expression should match");
Chris Lattnered468e372003-10-05 00:17:43 +00001766
Reid Spencer4fe16d62007-01-11 18:21:29 +00001767 if (ReqTy == C1->getType() || ReqTy == Type::Int1Ty)
Chris Lattnered468e372003-10-05 00:17:43 +00001768 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1769 return FC; // Fold a few common cases...
Chris Lattnerd628f6a2003-04-17 19:24:48 +00001770
Chris Lattner9bc02a42003-05-13 21:37:02 +00001771 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
Reid Spencer67263fe2006-12-04 21:35:24 +00001772 ExprMapKeyType Key(Opcode, argVec);
Chris Lattner8a94bf12006-09-28 00:35:06 +00001773 return ExprConstants->getOrCreate(ReqTy, Key);
Vikram S. Adve345e0cf2002-07-14 23:13:17 +00001774}
1775
Reid Spencere4d87aa2006-12-23 06:05:41 +00001776Constant *ConstantExpr::getCompareTy(unsigned short predicate,
Reid Spencer67263fe2006-12-04 21:35:24 +00001777 Constant *C1, Constant *C2) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001778 switch (predicate) {
1779 default: assert(0 && "Invalid CmpInst predicate");
1780 case FCmpInst::FCMP_FALSE: case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_OGT:
1781 case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OLE:
1782 case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_ORD: case FCmpInst::FCMP_UNO:
1783 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UGT: case FCmpInst::FCMP_UGE:
1784 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_ULE: case FCmpInst::FCMP_UNE:
1785 case FCmpInst::FCMP_TRUE:
1786 return getFCmp(predicate, C1, C2);
1787 case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_UGT:
1788 case ICmpInst::ICMP_UGE: case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE:
1789 case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_SGE: case ICmpInst::ICMP_SLT:
1790 case ICmpInst::ICMP_SLE:
1791 return getICmp(predicate, C1, C2);
1792 }
Reid Spencer67263fe2006-12-04 21:35:24 +00001793}
1794
1795Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
Chris Lattner91b362b2004-08-17 17:28:46 +00001796#ifndef NDEBUG
1797 switch (Opcode) {
Reid Spencer0a783f72006-11-02 01:53:59 +00001798 case Instruction::Add:
1799 case Instruction::Sub:
Reid Spencer1628cec2006-10-26 06:15:43 +00001800 case Instruction::Mul:
Chris Lattner91b362b2004-08-17 17:28:46 +00001801 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Chris Lattner42a75512007-01-15 02:27:26 +00001802 assert((C1->getType()->isInteger() || C1->getType()->isFloatingPoint() ||
Reid Spencer9d6565a2007-02-15 02:26:10 +00001803 isa<VectorType>(C1->getType())) &&
Chris Lattner91b362b2004-08-17 17:28:46 +00001804 "Tried to create an arithmetic operation on a non-arithmetic type!");
1805 break;
Reid Spencer1628cec2006-10-26 06:15:43 +00001806 case Instruction::UDiv:
1807 case Instruction::SDiv:
1808 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Reid Spencer9d6565a2007-02-15 02:26:10 +00001809 assert((C1->getType()->isInteger() || (isa<VectorType>(C1->getType()) &&
1810 cast<VectorType>(C1->getType())->getElementType()->isInteger())) &&
Reid Spencer1628cec2006-10-26 06:15:43 +00001811 "Tried to create an arithmetic operation on a non-arithmetic type!");
1812 break;
1813 case Instruction::FDiv:
1814 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Reid Spencer9d6565a2007-02-15 02:26:10 +00001815 assert((C1->getType()->isFloatingPoint() || (isa<VectorType>(C1->getType())
1816 && cast<VectorType>(C1->getType())->getElementType()->isFloatingPoint()))
Reid Spencer1628cec2006-10-26 06:15:43 +00001817 && "Tried to create an arithmetic operation on a non-arithmetic type!");
1818 break;
Reid Spencer0a783f72006-11-02 01:53:59 +00001819 case Instruction::URem:
1820 case Instruction::SRem:
1821 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Reid Spencer9d6565a2007-02-15 02:26:10 +00001822 assert((C1->getType()->isInteger() || (isa<VectorType>(C1->getType()) &&
1823 cast<VectorType>(C1->getType())->getElementType()->isInteger())) &&
Reid Spencer0a783f72006-11-02 01:53:59 +00001824 "Tried to create an arithmetic operation on a non-arithmetic type!");
1825 break;
1826 case Instruction::FRem:
1827 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Reid Spencer9d6565a2007-02-15 02:26:10 +00001828 assert((C1->getType()->isFloatingPoint() || (isa<VectorType>(C1->getType())
1829 && cast<VectorType>(C1->getType())->getElementType()->isFloatingPoint()))
Reid Spencer0a783f72006-11-02 01:53:59 +00001830 && "Tried to create an arithmetic operation on a non-arithmetic type!");
1831 break;
Chris Lattner91b362b2004-08-17 17:28:46 +00001832 case Instruction::And:
1833 case Instruction::Or:
1834 case Instruction::Xor:
1835 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Reid Spencer9d6565a2007-02-15 02:26:10 +00001836 assert((C1->getType()->isInteger() || isa<VectorType>(C1->getType())) &&
Misha Brukman1bae2912005-01-27 06:46:38 +00001837 "Tried to create a logical operation on a non-integral type!");
Chris Lattner91b362b2004-08-17 17:28:46 +00001838 break;
Chris Lattner91b362b2004-08-17 17:28:46 +00001839 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00001840 case Instruction::LShr:
1841 case Instruction::AShr:
Reid Spencer832254e2007-02-02 02:16:23 +00001842 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Chris Lattner42a75512007-01-15 02:27:26 +00001843 assert(C1->getType()->isInteger() &&
Chris Lattner91b362b2004-08-17 17:28:46 +00001844 "Tried to create a shift operation on a non-integer type!");
1845 break;
1846 default:
1847 break;
1848 }
1849#endif
1850
Reid Spencer67263fe2006-12-04 21:35:24 +00001851 return getTy(C1->getType(), Opcode, C1, C2);
1852}
1853
Reid Spencere4d87aa2006-12-23 06:05:41 +00001854Constant *ConstantExpr::getCompare(unsigned short pred,
Reid Spencer67263fe2006-12-04 21:35:24 +00001855 Constant *C1, Constant *C2) {
1856 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00001857 return getCompareTy(pred, C1, C2);
Chris Lattnerc3d12f02004-08-04 18:50:09 +00001858}
1859
Chris Lattner08a45cc2004-03-12 05:54:04 +00001860Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
1861 Constant *V1, Constant *V2) {
Reid Spencer3d10b0b2007-01-26 07:37:34 +00001862 assert(C->getType() == Type::Int1Ty && "Select condition must be i1!");
Chris Lattner08a45cc2004-03-12 05:54:04 +00001863 assert(V1->getType() == V2->getType() && "Select value types must match!");
1864 assert(V1->getType()->isFirstClassType() && "Cannot select aggregate type!");
1865
1866 if (ReqTy == V1->getType())
1867 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1868 return SC; // Fold common cases
1869
1870 std::vector<Constant*> argVec(3, C);
1871 argVec[1] = V1;
1872 argVec[2] = V2;
Reid Spencer077d0eb2006-12-04 05:19:50 +00001873 ExprMapKeyType Key(Instruction::Select, argVec);
Chris Lattner8a94bf12006-09-28 00:35:06 +00001874 return ExprConstants->getOrCreate(ReqTy, Key);
Chris Lattner08a45cc2004-03-12 05:54:04 +00001875}
1876
Chris Lattnered468e372003-10-05 00:17:43 +00001877Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
Chris Lattner2b9a5da2007-01-31 04:40:28 +00001878 Value* const *Idxs,
1879 unsigned NumIdx) {
David Greeneb8f74792007-09-04 15:46:09 +00001880 assert(GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx, true) &&
Chris Lattner2e9bb1a2004-02-16 20:46:13 +00001881 "GEP indices invalid!");
1882
Chris Lattner2b9a5da2007-01-31 04:40:28 +00001883 if (Constant *FC = ConstantFoldGetElementPtr(C, (Constant**)Idxs, NumIdx))
Chris Lattnerd628f6a2003-04-17 19:24:48 +00001884 return FC; // Fold a few common cases...
Chris Lattner2e9bb1a2004-02-16 20:46:13 +00001885
Chris Lattnered468e372003-10-05 00:17:43 +00001886 assert(isa<PointerType>(C->getType()) &&
Chris Lattner02ec5ed2003-05-23 20:03:32 +00001887 "Non-pointer type for constant GetElementPtr expression");
Vikram S. Adved0b1bb02002-07-15 18:19:33 +00001888 // Look up the constant in the table first to ensure uniqueness
Chris Lattner7fa6e662004-10-11 22:52:25 +00001889 std::vector<Constant*> ArgVec;
Chris Lattner2b9a5da2007-01-31 04:40:28 +00001890 ArgVec.reserve(NumIdx+1);
Chris Lattner7fa6e662004-10-11 22:52:25 +00001891 ArgVec.push_back(C);
Chris Lattner2b9a5da2007-01-31 04:40:28 +00001892 for (unsigned i = 0; i != NumIdx; ++i)
1893 ArgVec.push_back(cast<Constant>(Idxs[i]));
1894 const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec);
Chris Lattner8a94bf12006-09-28 00:35:06 +00001895 return ExprConstants->getOrCreate(ReqTy, Key);
Vikram S. Adved0b1bb02002-07-15 18:19:33 +00001896}
1897
Chris Lattner2b9a5da2007-01-31 04:40:28 +00001898Constant *ConstantExpr::getGetElementPtr(Constant *C, Value* const *Idxs,
1899 unsigned NumIdx) {
Chris Lattnered468e372003-10-05 00:17:43 +00001900 // Get the result type of the getelementptr!
Chris Lattner2b9a5da2007-01-31 04:40:28 +00001901 const Type *Ty =
David Greeneb8f74792007-09-04 15:46:09 +00001902 GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx, true);
Chris Lattnered468e372003-10-05 00:17:43 +00001903 assert(Ty && "GEP indices invalid!");
Christopher Lambfe63fb92007-12-11 08:59:05 +00001904 unsigned As = cast<PointerType>(C->getType())->getAddressSpace();
1905 return getGetElementPtrTy(PointerType::get(Ty, As), C, Idxs, NumIdx);
Chris Lattner7fa6e662004-10-11 22:52:25 +00001906}
1907
Chris Lattner2b9a5da2007-01-31 04:40:28 +00001908Constant *ConstantExpr::getGetElementPtr(Constant *C, Constant* const *Idxs,
1909 unsigned NumIdx) {
1910 return getGetElementPtr(C, (Value* const *)Idxs, NumIdx);
Chris Lattnered468e372003-10-05 00:17:43 +00001911}
1912
Chris Lattner2b9a5da2007-01-31 04:40:28 +00001913
Reid Spencer077d0eb2006-12-04 05:19:50 +00001914Constant *
1915ConstantExpr::getICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1916 assert(LHS->getType() == RHS->getType());
1917 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
1918 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
1919
Reid Spencere4d87aa2006-12-23 06:05:41 +00001920 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
Reid Spencer077d0eb2006-12-04 05:19:50 +00001921 return FC; // Fold a few common cases...
1922
1923 // Look up the constant in the table first to ensure uniqueness
1924 std::vector<Constant*> ArgVec;
1925 ArgVec.push_back(LHS);
1926 ArgVec.push_back(RHS);
Reid Spencer4fa021a2006-12-24 18:42:29 +00001927 // Get the key type with both the opcode and predicate
Reid Spencer077d0eb2006-12-04 05:19:50 +00001928 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
Reid Spencer4fe16d62007-01-11 18:21:29 +00001929 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
Reid Spencer077d0eb2006-12-04 05:19:50 +00001930}
1931
1932Constant *
1933ConstantExpr::getFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1934 assert(LHS->getType() == RHS->getType());
1935 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
1936
Reid Spencere4d87aa2006-12-23 06:05:41 +00001937 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
Reid Spencer077d0eb2006-12-04 05:19:50 +00001938 return FC; // Fold a few common cases...
1939
1940 // Look up the constant in the table first to ensure uniqueness
1941 std::vector<Constant*> ArgVec;
1942 ArgVec.push_back(LHS);
1943 ArgVec.push_back(RHS);
Reid Spencer4fa021a2006-12-24 18:42:29 +00001944 // Get the key type with both the opcode and predicate
Reid Spencer077d0eb2006-12-04 05:19:50 +00001945 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
Reid Spencer4fe16d62007-01-11 18:21:29 +00001946 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
Reid Spencer077d0eb2006-12-04 05:19:50 +00001947}
1948
Robert Bocchinob52ee7f2006-01-10 19:05:34 +00001949Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
1950 Constant *Idx) {
Robert Bocchinobb90a7a2006-01-10 20:03:46 +00001951 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
1952 return FC; // Fold a few common cases...
Robert Bocchinob52ee7f2006-01-10 19:05:34 +00001953 // Look up the constant in the table first to ensure uniqueness
1954 std::vector<Constant*> ArgVec(1, Val);
1955 ArgVec.push_back(Idx);
Reid Spencer077d0eb2006-12-04 05:19:50 +00001956 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
Chris Lattner8a94bf12006-09-28 00:35:06 +00001957 return ExprConstants->getOrCreate(ReqTy, Key);
Robert Bocchinob52ee7f2006-01-10 19:05:34 +00001958}
1959
1960Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001961 assert(isa<VectorType>(Val->getType()) &&
Reid Spencerac9dcb92007-02-15 03:39:18 +00001962 "Tried to create extractelement operation on non-vector type!");
Reid Spencer79e21d32006-12-31 05:26:44 +00001963 assert(Idx->getType() == Type::Int32Ty &&
Reid Spencer3d10b0b2007-01-26 07:37:34 +00001964 "Extractelement index must be i32 type!");
Reid Spencer9d6565a2007-02-15 02:26:10 +00001965 return getExtractElementTy(cast<VectorType>(Val->getType())->getElementType(),
Robert Bocchinob52ee7f2006-01-10 19:05:34 +00001966 Val, Idx);
1967}
Chris Lattnered468e372003-10-05 00:17:43 +00001968
Robert Bocchinoc152f9c2006-01-17 20:07:22 +00001969Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
1970 Constant *Elt, Constant *Idx) {
1971 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
1972 return FC; // Fold a few common cases...
1973 // Look up the constant in the table first to ensure uniqueness
1974 std::vector<Constant*> ArgVec(1, Val);
1975 ArgVec.push_back(Elt);
1976 ArgVec.push_back(Idx);
Reid Spencer077d0eb2006-12-04 05:19:50 +00001977 const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
Chris Lattner8a94bf12006-09-28 00:35:06 +00001978 return ExprConstants->getOrCreate(ReqTy, Key);
Robert Bocchinoc152f9c2006-01-17 20:07:22 +00001979}
1980
1981Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
1982 Constant *Idx) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001983 assert(isa<VectorType>(Val->getType()) &&
Reid Spencerac9dcb92007-02-15 03:39:18 +00001984 "Tried to create insertelement operation on non-vector type!");
Reid Spencer9d6565a2007-02-15 02:26:10 +00001985 assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType()
Robert Bocchinoc152f9c2006-01-17 20:07:22 +00001986 && "Insertelement types must match!");
Reid Spencer79e21d32006-12-31 05:26:44 +00001987 assert(Idx->getType() == Type::Int32Ty &&
Reid Spencer3d10b0b2007-01-26 07:37:34 +00001988 "Insertelement index must be i32 type!");
Reid Spencer9d6565a2007-02-15 02:26:10 +00001989 return getInsertElementTy(cast<VectorType>(Val->getType())->getElementType(),
Robert Bocchinoc152f9c2006-01-17 20:07:22 +00001990 Val, Elt, Idx);
1991}
1992
Chris Lattner00f10232006-04-08 01:18:18 +00001993Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
1994 Constant *V2, Constant *Mask) {
1995 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
1996 return FC; // Fold a few common cases...
1997 // Look up the constant in the table first to ensure uniqueness
1998 std::vector<Constant*> ArgVec(1, V1);
1999 ArgVec.push_back(V2);
2000 ArgVec.push_back(Mask);
Reid Spencer077d0eb2006-12-04 05:19:50 +00002001 const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
Chris Lattner8a94bf12006-09-28 00:35:06 +00002002 return ExprConstants->getOrCreate(ReqTy, Key);
Chris Lattner00f10232006-04-08 01:18:18 +00002003}
2004
2005Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
2006 Constant *Mask) {
2007 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
2008 "Invalid shuffle vector constant expr operands!");
2009 return getShuffleVectorTy(V1->getType(), V1, V2, Mask);
2010}
2011
Reid Spencer24d6da52007-01-21 00:29:26 +00002012Constant *ConstantExpr::getZeroValueForNegationExpr(const Type *Ty) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00002013 if (const VectorType *PTy = dyn_cast<VectorType>(Ty))
Reid Spencer2c7123c2007-01-21 02:29:10 +00002014 if (PTy->getElementType()->isFloatingPoint()) {
2015 std::vector<Constant*> zeros(PTy->getNumElements(),
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002016 ConstantFP::getNegativeZero(PTy->getElementType()));
Reid Spencer9d6565a2007-02-15 02:26:10 +00002017 return ConstantVector::get(PTy, zeros);
Reid Spencer2c7123c2007-01-21 02:29:10 +00002018 }
Reid Spencer24d6da52007-01-21 00:29:26 +00002019
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002020 if (Ty->isFloatingPoint())
2021 return ConstantFP::getNegativeZero(Ty);
Reid Spencer24d6da52007-01-21 00:29:26 +00002022
2023 return Constant::getNullValue(Ty);
2024}
2025
Vikram S. Adved0b1bb02002-07-15 18:19:33 +00002026// destroyConstant - Remove the constant from the constant table...
2027//
2028void ConstantExpr::destroyConstant() {
Chris Lattner8a94bf12006-09-28 00:35:06 +00002029 ExprConstants->remove(this);
Vikram S. Adved0b1bb02002-07-15 18:19:33 +00002030 destroyConstantImpl();
Vikram S. Adve345e0cf2002-07-14 23:13:17 +00002031}
2032
Chris Lattnerc188eeb2002-07-30 18:54:25 +00002033const char *ConstantExpr::getOpcodeName() const {
2034 return Instruction::getOpcodeName(getOpcode());
Vikram S. Adve345e0cf2002-07-14 23:13:17 +00002035}
Reid Spencer1c9c8e62004-07-17 23:48:33 +00002036
Chris Lattner5cbade92005-10-03 21:58:36 +00002037//===----------------------------------------------------------------------===//
2038// replaceUsesOfWithOnConstant implementations
2039
Chris Lattner54984052007-08-21 00:55:23 +00002040/// replaceUsesOfWithOnConstant - Update this constant array to change uses of
2041/// 'From' to be uses of 'To'. This must update the uniquing data structures
2042/// etc.
2043///
2044/// Note that we intentionally replace all uses of From with To here. Consider
2045/// a large array that uses 'From' 1000 times. By handling this case all here,
2046/// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
2047/// single invocation handles all 1000 uses. Handling them one at a time would
2048/// work, but would be really slow because it would have to unique each updated
2049/// array instance.
Chris Lattner5cbade92005-10-03 21:58:36 +00002050void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
Chris Lattnerd0ff1ad2005-10-04 18:13:04 +00002051 Use *U) {
Chris Lattner5cbade92005-10-03 21:58:36 +00002052 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
Chris Lattnerc182a882005-10-04 01:17:50 +00002053 Constant *ToC = cast<Constant>(To);
Chris Lattner23ec01f2005-10-04 18:47:09 +00002054
Jim Laskeyede5aa42006-07-17 17:38:29 +00002055 std::pair<ArrayConstantsTy::MapKey, Constant*> Lookup;
Chris Lattnercea141f2005-10-03 22:51:37 +00002056 Lookup.first.first = getType();
2057 Lookup.second = this;
Chris Lattner23ec01f2005-10-04 18:47:09 +00002058
Chris Lattnercea141f2005-10-03 22:51:37 +00002059 std::vector<Constant*> &Values = Lookup.first.second;
2060 Values.reserve(getNumOperands()); // Build replacement array.
Chris Lattner23ec01f2005-10-04 18:47:09 +00002061
Chris Lattnerc182a882005-10-04 01:17:50 +00002062 // Fill values with the modified operands of the constant array. Also,
2063 // compute whether this turns into an all-zeros array.
Chris Lattner23ec01f2005-10-04 18:47:09 +00002064 bool isAllZeros = false;
Chris Lattner54984052007-08-21 00:55:23 +00002065 unsigned NumUpdated = 0;
Chris Lattner23ec01f2005-10-04 18:47:09 +00002066 if (!ToC->isNullValue()) {
Chris Lattner54984052007-08-21 00:55:23 +00002067 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2068 Constant *Val = cast<Constant>(O->get());
2069 if (Val == From) {
2070 Val = ToC;
2071 ++NumUpdated;
2072 }
2073 Values.push_back(Val);
2074 }
Chris Lattner23ec01f2005-10-04 18:47:09 +00002075 } else {
2076 isAllZeros = true;
2077 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2078 Constant *Val = cast<Constant>(O->get());
Chris Lattner54984052007-08-21 00:55:23 +00002079 if (Val == From) {
2080 Val = ToC;
2081 ++NumUpdated;
2082 }
Chris Lattner23ec01f2005-10-04 18:47:09 +00002083 Values.push_back(Val);
2084 if (isAllZeros) isAllZeros = Val->isNullValue();
2085 }
Chris Lattner5cbade92005-10-03 21:58:36 +00002086 }
2087
Chris Lattnercea141f2005-10-03 22:51:37 +00002088 Constant *Replacement = 0;
2089 if (isAllZeros) {
2090 Replacement = ConstantAggregateZero::get(getType());
2091 } else {
2092 // Check to see if we have this array type already.
2093 bool Exists;
Jim Laskeyede5aa42006-07-17 17:38:29 +00002094 ArrayConstantsTy::MapTy::iterator I =
Chris Lattner8a94bf12006-09-28 00:35:06 +00002095 ArrayConstants->InsertOrGetItem(Lookup, Exists);
Chris Lattnercea141f2005-10-03 22:51:37 +00002096
2097 if (Exists) {
2098 Replacement = I->second;
2099 } else {
2100 // Okay, the new shape doesn't exist in the system yet. Instead of
2101 // creating a new constant array, inserting it, replaceallusesof'ing the
2102 // old with the new, then deleting the old... just update the current one
2103 // in place!
Chris Lattner8a94bf12006-09-28 00:35:06 +00002104 ArrayConstants->MoveConstantToNewSlot(this, I);
Chris Lattnercea141f2005-10-03 22:51:37 +00002105
Chris Lattner54984052007-08-21 00:55:23 +00002106 // Update to the new value. Optimize for the case when we have a single
2107 // operand that we're changing, but handle bulk updates efficiently.
2108 if (NumUpdated == 1) {
2109 unsigned OperandToUpdate = U-OperandList;
2110 assert(getOperand(OperandToUpdate) == From &&
2111 "ReplaceAllUsesWith broken!");
2112 setOperand(OperandToUpdate, ToC);
2113 } else {
2114 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2115 if (getOperand(i) == From)
2116 setOperand(i, ToC);
2117 }
Chris Lattnercea141f2005-10-03 22:51:37 +00002118 return;
2119 }
2120 }
2121
2122 // Otherwise, I do need to replace this with an existing value.
Chris Lattner5cbade92005-10-03 21:58:36 +00002123 assert(Replacement != this && "I didn't contain From!");
2124
Chris Lattnerd0ff1ad2005-10-04 18:13:04 +00002125 // Everyone using this now uses the replacement.
2126 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattner5cbade92005-10-03 21:58:36 +00002127
2128 // Delete the old constant!
2129 destroyConstant();
2130}
2131
2132void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
Chris Lattnerd0ff1ad2005-10-04 18:13:04 +00002133 Use *U) {
Chris Lattner5cbade92005-10-03 21:58:36 +00002134 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
Chris Lattnerc182a882005-10-04 01:17:50 +00002135 Constant *ToC = cast<Constant>(To);
2136
Chris Lattner23ec01f2005-10-04 18:47:09 +00002137 unsigned OperandToUpdate = U-OperandList;
2138 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
2139
Jim Laskeyede5aa42006-07-17 17:38:29 +00002140 std::pair<StructConstantsTy::MapKey, Constant*> Lookup;
Chris Lattnerc182a882005-10-04 01:17:50 +00002141 Lookup.first.first = getType();
2142 Lookup.second = this;
2143 std::vector<Constant*> &Values = Lookup.first.second;
2144 Values.reserve(getNumOperands()); // Build replacement struct.
Chris Lattner5cbade92005-10-03 21:58:36 +00002145
Chris Lattner23ec01f2005-10-04 18:47:09 +00002146
Chris Lattnerc182a882005-10-04 01:17:50 +00002147 // Fill values with the modified operands of the constant struct. Also,
2148 // compute whether this turns into an all-zeros struct.
Chris Lattner23ec01f2005-10-04 18:47:09 +00002149 bool isAllZeros = false;
2150 if (!ToC->isNullValue()) {
2151 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
2152 Values.push_back(cast<Constant>(O->get()));
2153 } else {
2154 isAllZeros = true;
2155 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2156 Constant *Val = cast<Constant>(O->get());
2157 Values.push_back(Val);
2158 if (isAllZeros) isAllZeros = Val->isNullValue();
2159 }
Chris Lattnerc182a882005-10-04 01:17:50 +00002160 }
Chris Lattner23ec01f2005-10-04 18:47:09 +00002161 Values[OperandToUpdate] = ToC;
2162
Chris Lattnerc182a882005-10-04 01:17:50 +00002163 Constant *Replacement = 0;
2164 if (isAllZeros) {
2165 Replacement = ConstantAggregateZero::get(getType());
2166 } else {
2167 // Check to see if we have this array type already.
2168 bool Exists;
Jim Laskeyede5aa42006-07-17 17:38:29 +00002169 StructConstantsTy::MapTy::iterator I =
Chris Lattner8a94bf12006-09-28 00:35:06 +00002170 StructConstants->InsertOrGetItem(Lookup, Exists);
Chris Lattnerc182a882005-10-04 01:17:50 +00002171
2172 if (Exists) {
2173 Replacement = I->second;
2174 } else {
2175 // Okay, the new shape doesn't exist in the system yet. Instead of
2176 // creating a new constant struct, inserting it, replaceallusesof'ing the
2177 // old with the new, then deleting the old... just update the current one
2178 // in place!
Chris Lattner8a94bf12006-09-28 00:35:06 +00002179 StructConstants->MoveConstantToNewSlot(this, I);
Chris Lattnerc182a882005-10-04 01:17:50 +00002180
Chris Lattner23ec01f2005-10-04 18:47:09 +00002181 // Update to the new value.
2182 setOperand(OperandToUpdate, ToC);
Chris Lattnerc182a882005-10-04 01:17:50 +00002183 return;
2184 }
Chris Lattner5cbade92005-10-03 21:58:36 +00002185 }
2186
Chris Lattner5cbade92005-10-03 21:58:36 +00002187 assert(Replacement != this && "I didn't contain From!");
2188
Chris Lattnerd0ff1ad2005-10-04 18:13:04 +00002189 // Everyone using this now uses the replacement.
2190 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattner5cbade92005-10-03 21:58:36 +00002191
2192 // Delete the old constant!
2193 destroyConstant();
2194}
2195
Reid Spencer9d6565a2007-02-15 02:26:10 +00002196void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
Chris Lattnerd0ff1ad2005-10-04 18:13:04 +00002197 Use *U) {
Chris Lattner5cbade92005-10-03 21:58:36 +00002198 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2199
2200 std::vector<Constant*> Values;
2201 Values.reserve(getNumOperands()); // Build replacement array...
2202 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2203 Constant *Val = getOperand(i);
2204 if (Val == From) Val = cast<Constant>(To);
2205 Values.push_back(Val);
2206 }
2207
Reid Spencer9d6565a2007-02-15 02:26:10 +00002208 Constant *Replacement = ConstantVector::get(getType(), Values);
Chris Lattner5cbade92005-10-03 21:58:36 +00002209 assert(Replacement != this && "I didn't contain From!");
2210
Chris Lattnerd0ff1ad2005-10-04 18:13:04 +00002211 // Everyone using this now uses the replacement.
2212 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattner5cbade92005-10-03 21:58:36 +00002213
2214 // Delete the old constant!
2215 destroyConstant();
2216}
2217
2218void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
Chris Lattnerd0ff1ad2005-10-04 18:13:04 +00002219 Use *U) {
Chris Lattner5cbade92005-10-03 21:58:36 +00002220 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2221 Constant *To = cast<Constant>(ToV);
2222
2223 Constant *Replacement = 0;
2224 if (getOpcode() == Instruction::GetElementPtr) {
Chris Lattnerf9021ff2007-02-19 20:01:23 +00002225 SmallVector<Constant*, 8> Indices;
Chris Lattner5cbade92005-10-03 21:58:36 +00002226 Constant *Pointer = getOperand(0);
2227 Indices.reserve(getNumOperands()-1);
2228 if (Pointer == From) Pointer = To;
2229
2230 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2231 Constant *Val = getOperand(i);
2232 if (Val == From) Val = To;
2233 Indices.push_back(Val);
2234 }
Chris Lattnerf9021ff2007-02-19 20:01:23 +00002235 Replacement = ConstantExpr::getGetElementPtr(Pointer,
2236 &Indices[0], Indices.size());
Reid Spencer3da59db2006-11-27 01:05:10 +00002237 } else if (isCast()) {
Chris Lattner5cbade92005-10-03 21:58:36 +00002238 assert(getOperand(0) == From && "Cast only has one use!");
Reid Spencer3da59db2006-11-27 01:05:10 +00002239 Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
Chris Lattner5cbade92005-10-03 21:58:36 +00002240 } else if (getOpcode() == Instruction::Select) {
2241 Constant *C1 = getOperand(0);
2242 Constant *C2 = getOperand(1);
2243 Constant *C3 = getOperand(2);
2244 if (C1 == From) C1 = To;
2245 if (C2 == From) C2 = To;
2246 if (C3 == From) C3 = To;
2247 Replacement = ConstantExpr::getSelect(C1, C2, C3);
Robert Bocchinob52ee7f2006-01-10 19:05:34 +00002248 } else if (getOpcode() == Instruction::ExtractElement) {
2249 Constant *C1 = getOperand(0);
2250 Constant *C2 = getOperand(1);
2251 if (C1 == From) C1 = To;
2252 if (C2 == From) C2 = To;
2253 Replacement = ConstantExpr::getExtractElement(C1, C2);
Chris Lattner42b55802006-04-08 05:09:48 +00002254 } else if (getOpcode() == Instruction::InsertElement) {
2255 Constant *C1 = getOperand(0);
2256 Constant *C2 = getOperand(1);
2257 Constant *C3 = getOperand(1);
2258 if (C1 == From) C1 = To;
2259 if (C2 == From) C2 = To;
2260 if (C3 == From) C3 = To;
2261 Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2262 } else if (getOpcode() == Instruction::ShuffleVector) {
2263 Constant *C1 = getOperand(0);
2264 Constant *C2 = getOperand(1);
2265 Constant *C3 = getOperand(2);
2266 if (C1 == From) C1 = To;
2267 if (C2 == From) C2 = To;
2268 if (C3 == From) C3 = To;
2269 Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
Reid Spencer077d0eb2006-12-04 05:19:50 +00002270 } else if (isCompare()) {
2271 Constant *C1 = getOperand(0);
2272 Constant *C2 = getOperand(1);
2273 if (C1 == From) C1 = To;
2274 if (C2 == From) C2 = To;
2275 if (getOpcode() == Instruction::ICmp)
2276 Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
2277 else
2278 Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
Chris Lattner5cbade92005-10-03 21:58:36 +00002279 } else if (getNumOperands() == 2) {
2280 Constant *C1 = getOperand(0);
2281 Constant *C2 = getOperand(1);
2282 if (C1 == From) C1 = To;
2283 if (C2 == From) C2 = To;
2284 Replacement = ConstantExpr::get(getOpcode(), C1, C2);
2285 } else {
2286 assert(0 && "Unknown ConstantExpr type!");
2287 return;
2288 }
2289
2290 assert(Replacement != this && "I didn't contain From!");
2291
Chris Lattnerd0ff1ad2005-10-04 18:13:04 +00002292 // Everyone using this now uses the replacement.
2293 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattner5cbade92005-10-03 21:58:36 +00002294
2295 // Delete the old constant!
2296 destroyConstant();
2297}
2298
2299
Jim Laskey21b6c9d2006-03-08 18:11:07 +00002300/// getStringValue - Turn an LLVM constant pointer that eventually points to a
2301/// global into a string value. Return an empty string if we can't do it.
Evan Cheng09371032006-03-10 23:52:03 +00002302/// Parameter Chop determines if the result is chopped at the first null
2303/// terminator.
Jim Laskey21b6c9d2006-03-08 18:11:07 +00002304///
Evan Cheng09371032006-03-10 23:52:03 +00002305std::string Constant::getStringValue(bool Chop, unsigned Offset) {
Jim Laskey21b6c9d2006-03-08 18:11:07 +00002306 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(this)) {
2307 if (GV->hasInitializer() && isa<ConstantArray>(GV->getInitializer())) {
2308 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
2309 if (Init->isString()) {
2310 std::string Result = Init->getAsString();
2311 if (Offset < Result.size()) {
2312 // If we are pointing INTO The string, erase the beginning...
2313 Result.erase(Result.begin(), Result.begin()+Offset);
2314
2315 // Take off the null terminator, and any string fragments after it.
Evan Cheng09371032006-03-10 23:52:03 +00002316 if (Chop) {
2317 std::string::size_type NullPos = Result.find_first_of((char)0);
2318 if (NullPos != std::string::npos)
2319 Result.erase(Result.begin()+NullPos, Result.end());
2320 }
Jim Laskey21b6c9d2006-03-08 18:11:07 +00002321 return Result;
2322 }
2323 }
2324 }
Chris Lattnere41dcdc2007-11-01 02:30:35 +00002325 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(this)) {
2326 if (CE->getOpcode() == Instruction::GetElementPtr) {
2327 // Turn a gep into the specified offset.
2328 if (CE->getNumOperands() == 3 &&
2329 cast<Constant>(CE->getOperand(1))->isNullValue() &&
2330 isa<ConstantInt>(CE->getOperand(2))) {
2331 Offset += cast<ConstantInt>(CE->getOperand(2))->getZExtValue();
2332 return CE->getOperand(0)->getStringValue(Chop, Offset);
Jim Laskey21b6c9d2006-03-08 18:11:07 +00002333 }
2334 }
2335 }
2336 return "";
2337}