blob: 28b7e45bf55fa2b3db57bfd088d1ffeff7859430 [file] [log] [blame]
Chris Lattner2b383d2e2003-05-13 21:37:02 +00001//===-- Constants.cpp - Implement Constant nodes --------------------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner2f7c9632001-06-06 20:29:01 +00009//
Chris Lattner3462ae32001-12-03 22:26:30 +000010// This file implements the Constant* classes...
Chris Lattner2f7c9632001-06-06 20:29:01 +000011//
12//===----------------------------------------------------------------------===//
13
Chris Lattnerca142372002-04-28 19:55:58 +000014#include "llvm/Constants.h"
Chris Lattner33e93b82007-02-27 03:05:06 +000015#include "ConstantFold.h"
Chris Lattner2f7c9632001-06-06 20:29:01 +000016#include "llvm/DerivedTypes.h"
Reid Spencer1ebe1ab2004-07-17 23:48:33 +000017#include "llvm/GlobalValue.h"
Misha Brukman63b38bd2004-07-29 17:30:56 +000018#include "llvm/Instructions.h"
Chris Lattnerd7a73302001-10-13 06:57:33 +000019#include "llvm/Module.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000020#include "llvm/ADT/StringExtras.h"
Chris Lattner3d27be12006-08-27 12:54:02 +000021#include "llvm/Support/Compiler.h"
Bill Wendling6a462f12006-11-17 08:03:48 +000022#include "llvm/Support/Debug.h"
Chris Lattner69edc982006-09-28 00:35:06 +000023#include "llvm/Support/ManagedStatic.h"
Bill Wendling6a462f12006-11-17 08:03:48 +000024#include "llvm/Support/MathExtras.h"
Chris Lattnera80bf0b2007-02-20 06:39:57 +000025#include "llvm/ADT/DenseMap.h"
Chris Lattnerb5d70302007-02-19 20:01:23 +000026#include "llvm/ADT/SmallVector.h"
Chris Lattner2f7c9632001-06-06 20:29:01 +000027#include <algorithm>
Reid Spencer3aaaa0b2007-02-05 20:47:22 +000028#include <map>
Chris Lattner189d19f2003-11-21 20:23:48 +000029using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000030
Chris Lattner2f7c9632001-06-06 20:29:01 +000031//===----------------------------------------------------------------------===//
Chris Lattner3462ae32001-12-03 22:26:30 +000032// Constant Class
Chris Lattner2f7c9632001-06-06 20:29:01 +000033//===----------------------------------------------------------------------===//
34
Chris Lattner3462ae32001-12-03 22:26:30 +000035void Constant::destroyConstantImpl() {
36 // When a Constant is destroyed, there may be lingering
Chris Lattnerd7a73302001-10-13 06:57:33 +000037 // references to the constant by other constants in the constant pool. These
Misha Brukmanbe372b92003-08-21 22:14:26 +000038 // constants are implicitly dependent on the module that is being deleted,
Chris Lattnerd7a73302001-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 Lattner3462ae32001-12-03 22:26:30 +000041 // Constants) that they are, in fact, invalid now and should be deleted.
Chris Lattnerd7a73302001-10-13 06:57:33 +000042 //
43 while (!use_empty()) {
44 Value *V = use_back();
45#ifndef NDEBUG // Only in -g mode...
Chris Lattnerd9f4ac662002-07-18 00:14:50 +000046 if (!isa<Constant>(V))
Bill Wendling6a462f12006-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 Lattnerd7a73302001-10-13 06:57:33 +000050#endif
Vikram S. Adve4e537b22002-07-14 23:13:17 +000051 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
Reid Spencer1ebe1ab2004-07-17 23:48:33 +000052 Constant *CV = cast<Constant>(V);
53 CV->destroyConstant();
Chris Lattnerd7a73302001-10-13 06:57:33 +000054
55 // The constant should remove itself from our use list...
Vikram S. Adve4e537b22002-07-14 23:13:17 +000056 assert((use_empty() || use_back() != V) && "Constant not removed!");
Chris Lattnerd7a73302001-10-13 06:57:33 +000057 }
58
59 // Value has no outstanding references it is safe to delete it now...
60 delete this;
Chris Lattner38569342001-10-01 20:11:19 +000061}
Chris Lattner2f7c9632001-06-06 20:29:01 +000062
Chris Lattner23dd1f62006-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 Spencer7e80b0b2006-10-26 06:15:43 +000080 case Instruction::UDiv:
81 case Instruction::SDiv:
82 case Instruction::FDiv:
Reid Spencer7eb55b32006-11-02 01:53:59 +000083 case Instruction::URem:
84 case Instruction::SRem:
85 case Instruction::FRem:
Chris Lattner23dd1f62006-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 Chengf9e003b2007-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 Lattnerb1585a92002-08-13 17:50:20 +0000104// Static constructor to create a '0' constant of arbitrary type...
105Constant *Constant::getNullValue(const Type *Ty) {
Dale Johannesen98d3a082007-09-14 22:26:36 +0000106 static uint64_t zero[2] = {0, 0};
Chris Lattner6b727592004-06-17 18:19:28 +0000107 switch (Ty->getTypeID()) {
Chris Lattnerdbcb0d32007-02-20 05:46:39 +0000108 case Type::IntegerTyID:
109 return ConstantInt::get(Ty, 0);
110 case Type::FloatTyID:
Dale Johannesen98d3a082007-09-14 22:26:36 +0000111 return ConstantFP::get(Ty, APFloat(APInt(32, 0)));
Chris Lattnerdbcb0d32007-02-20 05:46:39 +0000112 case Type::DoubleTyID:
Dale Johannesen98d3a082007-09-14 22:26:36 +0000113 return ConstantFP::get(Ty, APFloat(APInt(64, 0)));
Dale Johannesenbdad8092007-08-09 22:51:36 +0000114 case Type::X86_FP80TyID:
Dale Johannesen98d3a082007-09-14 22:26:36 +0000115 return ConstantFP::get(Ty, APFloat(APInt(80, 2, zero)));
Dale Johannesenbdad8092007-08-09 22:51:36 +0000116 case Type::FP128TyID:
Dale Johannesen98d3a082007-09-14 22:26:36 +0000117 case Type::PPC_FP128TyID:
118 return ConstantFP::get(Ty, APFloat(APInt(128, 2, zero)));
Misha Brukmanb1c93172005-04-21 23:48:37 +0000119 case Type::PointerTyID:
Chris Lattnerb1585a92002-08-13 17:50:20 +0000120 return ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattner9fba3da2004-02-15 05:53:04 +0000121 case Type::StructTyID:
122 case Type::ArrayTyID:
Reid Spencerd84d35b2007-02-15 02:26:10 +0000123 case Type::VectorTyID:
Chris Lattner9fba3da2004-02-15 05:53:04 +0000124 return ConstantAggregateZero::get(Ty);
Chris Lattnerb1585a92002-08-13 17:50:20 +0000125 default:
Reid Spencercf394bf2004-07-04 11:51:24 +0000126 // Function, Label, or Opaque type?
127 assert(!"Cannot create a null constant of that type!");
Chris Lattnerb1585a92002-08-13 17:50:20 +0000128 return 0;
129 }
130}
131
Chris Lattner72e39582007-06-15 06:10:53 +0000132Constant *Constant::getAllOnesValue(const Type *Ty) {
133 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty))
134 return ConstantInt::get(APInt::getAllOnesValue(ITy->getBitWidth()));
135 return ConstantVector::getAllOnesValue(cast<VectorType>(Ty));
136}
Chris Lattnerb1585a92002-08-13 17:50:20 +0000137
138// Static constructor to create an integral constant with all bits set
Zhou Sheng75b871f2007-01-11 12:24:14 +0000139ConstantInt *ConstantInt::getAllOnesValue(const Type *Ty) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000140 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty))
Reid Spencerd1bbfa52007-03-01 19:30:34 +0000141 return ConstantInt::get(APInt::getAllOnesValue(ITy->getBitWidth()));
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000142 return 0;
Chris Lattnerb1585a92002-08-13 17:50:20 +0000143}
144
Dan Gohman30978072007-05-24 14:36:04 +0000145/// @returns the value for a vector integer constant of the given type that
Chris Lattnerecab54c2007-01-04 01:49:26 +0000146/// has all its bits set to true.
147/// @brief Get the all ones value
Reid Spencerd84d35b2007-02-15 02:26:10 +0000148ConstantVector *ConstantVector::getAllOnesValue(const VectorType *Ty) {
Chris Lattnerecab54c2007-01-04 01:49:26 +0000149 std::vector<Constant*> Elts;
150 Elts.resize(Ty->getNumElements(),
Zhou Sheng75b871f2007-01-11 12:24:14 +0000151 ConstantInt::getAllOnesValue(Ty->getElementType()));
Dan Gohman30978072007-05-24 14:36:04 +0000152 assert(Elts[0] && "Not a vector integer type!");
Reid Spencerd84d35b2007-02-15 02:26:10 +0000153 return cast<ConstantVector>(ConstantVector::get(Elts));
Chris Lattnerecab54c2007-01-04 01:49:26 +0000154}
155
156
Chris Lattner2f7c9632001-06-06 20:29:01 +0000157//===----------------------------------------------------------------------===//
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000158// ConstantInt
Chris Lattner2f7c9632001-06-06 20:29:01 +0000159//===----------------------------------------------------------------------===//
160
Reid Spencerb31bffe2007-02-26 23:54:03 +0000161ConstantInt::ConstantInt(const IntegerType *Ty, const APInt& V)
Chris Lattner5db2f472007-02-20 05:55:46 +0000162 : Constant(Ty, ConstantIntVal, 0, 0), Val(V) {
Reid Spencerb31bffe2007-02-26 23:54:03 +0000163 assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
Chris Lattner2f7c9632001-06-06 20:29:01 +0000164}
165
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000166ConstantInt *ConstantInt::TheTrueVal = 0;
167ConstantInt *ConstantInt::TheFalseVal = 0;
168
169namespace llvm {
170 void CleanupTrueFalse(void *) {
171 ConstantInt::ResetTrueFalse();
172 }
173}
174
175static ManagedCleanup<llvm::CleanupTrueFalse> TrueFalseCleanup;
176
177ConstantInt *ConstantInt::CreateTrueFalseVals(bool WhichOne) {
178 assert(TheTrueVal == 0 && TheFalseVal == 0);
179 TheTrueVal = get(Type::Int1Ty, 1);
180 TheFalseVal = get(Type::Int1Ty, 0);
181
182 // Ensure that llvm_shutdown nulls out TheTrueVal/TheFalseVal.
183 TrueFalseCleanup.Register();
184
185 return WhichOne ? TheTrueVal : TheFalseVal;
186}
187
188
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000189namespace {
Reid Spencerb31bffe2007-02-26 23:54:03 +0000190 struct DenseMapAPIntKeyInfo {
191 struct KeyTy {
192 APInt val;
193 const Type* type;
194 KeyTy(const APInt& V, const Type* Ty) : val(V), type(Ty) {}
195 KeyTy(const KeyTy& that) : val(that.val), type(that.type) {}
196 bool operator==(const KeyTy& that) const {
197 return type == that.type && this->val == that.val;
198 }
199 bool operator!=(const KeyTy& that) const {
200 return !this->operator==(that);
201 }
202 };
203 static inline KeyTy getEmptyKey() { return KeyTy(APInt(1,0), 0); }
204 static inline KeyTy getTombstoneKey() { return KeyTy(APInt(1,1), 0); }
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000205 static unsigned getHashValue(const KeyTy &Key) {
Chris Lattner0625bd62007-09-17 18:34:04 +0000206 return DenseMapInfo<void*>::getHashValue(Key.type) ^
Reid Spencerb31bffe2007-02-26 23:54:03 +0000207 Key.val.getHashValue();
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000208 }
Chris Lattner0625bd62007-09-17 18:34:04 +0000209 static bool isEqual(const KeyTy &LHS, const KeyTy &RHS) {
210 return LHS == RHS;
211 }
Dale Johannesena719a602007-08-24 00:56:33 +0000212 static bool isPod() { return false; }
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000213 };
214}
215
216
Reid Spencerb31bffe2007-02-26 23:54:03 +0000217typedef DenseMap<DenseMapAPIntKeyInfo::KeyTy, ConstantInt*,
218 DenseMapAPIntKeyInfo> IntMapTy;
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000219static ManagedStatic<IntMapTy> IntConstants;
220
Reid Spencer362fb292007-03-19 20:39:08 +0000221ConstantInt *ConstantInt::get(const Type *Ty, uint64_t V, bool isSigned) {
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000222 const IntegerType *ITy = cast<IntegerType>(Ty);
Reid Spencer362fb292007-03-19 20:39:08 +0000223 return get(APInt(ITy->getBitWidth(), V, isSigned));
Reid Spencerb31bffe2007-02-26 23:54:03 +0000224}
225
Reid Spencerd1bbfa52007-03-01 19:30:34 +0000226// Get a ConstantInt from an APInt. Note that the value stored in the DenseMap
227// as the key, is a DensMapAPIntKeyInfo::KeyTy which has provided the
Reid Spencerb31bffe2007-02-26 23:54:03 +0000228// operator== and operator!= to ensure that the DenseMap doesn't attempt to
229// compare APInt's of different widths, which would violate an APInt class
230// invariant which generates an assertion.
Reid Spencerd1bbfa52007-03-01 19:30:34 +0000231ConstantInt *ConstantInt::get(const APInt& V) {
232 // Get the corresponding integer type for the bit width of the value.
233 const IntegerType *ITy = IntegerType::get(V.getBitWidth());
Reid Spencerb31bffe2007-02-26 23:54:03 +0000234 // get an existing value or the insertion position
Reid Spencerd1bbfa52007-03-01 19:30:34 +0000235 DenseMapAPIntKeyInfo::KeyTy Key(V, ITy);
Reid Spencerb31bffe2007-02-26 23:54:03 +0000236 ConstantInt *&Slot = (*IntConstants)[Key];
237 // if it exists, return it.
238 if (Slot)
239 return Slot;
240 // otherwise create a new one, insert it, and return it.
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000241 return Slot = new ConstantInt(ITy, V);
242}
243
244//===----------------------------------------------------------------------===//
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000245// ConstantFP
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000246//===----------------------------------------------------------------------===//
247
Dale Johannesend246b2c2007-08-30 00:23:21 +0000248ConstantFP::ConstantFP(const Type *Ty, const APFloat& V)
249 : Constant(Ty, ConstantFPVal, 0, 0), Val(V) {
250 // temporary
251 if (Ty==Type::FloatTy)
252 assert(&V.getSemantics()==&APFloat::IEEEsingle);
Dale Johannesen028084e2007-09-12 03:30:33 +0000253 else if (Ty==Type::DoubleTy)
Dale Johannesend246b2c2007-08-30 00:23:21 +0000254 assert(&V.getSemantics()==&APFloat::IEEEdouble);
Dale Johannesen028084e2007-09-12 03:30:33 +0000255 else if (Ty==Type::X86_FP80Ty)
256 assert(&V.getSemantics()==&APFloat::x87DoubleExtended);
257 else if (Ty==Type::FP128Ty)
258 assert(&V.getSemantics()==&APFloat::IEEEquad);
259 else
260 assert(0);
Chris Lattner2f7c9632001-06-06 20:29:01 +0000261}
262
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000263bool ConstantFP::isNullValue() const {
Dale Johannesena719a602007-08-24 00:56:33 +0000264 return Val.isZero() && !Val.isNegative();
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000265}
266
Dale Johannesen98d3a082007-09-14 22:26:36 +0000267ConstantFP *ConstantFP::getNegativeZero(const Type *Ty) {
268 APFloat apf = cast <ConstantFP>(Constant::getNullValue(Ty))->getValueAPF();
269 apf.changeSign();
270 return ConstantFP::get(Ty, apf);
271}
272
Dale Johannesend246b2c2007-08-30 00:23:21 +0000273bool ConstantFP::isExactlyValue(const APFloat& V) const {
274 return Val.bitwiseIsEqual(V);
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000275}
276
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000277namespace {
Dale Johannesena719a602007-08-24 00:56:33 +0000278 struct DenseMapAPFloatKeyInfo {
Dale Johannesenbdea32d2007-08-24 22:09:56 +0000279 struct KeyTy {
280 APFloat val;
281 KeyTy(const APFloat& V) : val(V){}
282 KeyTy(const KeyTy& that) : val(that.val) {}
283 bool operator==(const KeyTy& that) const {
284 return this->val.bitwiseIsEqual(that.val);
285 }
286 bool operator!=(const KeyTy& that) const {
287 return !this->operator==(that);
288 }
289 };
290 static inline KeyTy getEmptyKey() {
291 return KeyTy(APFloat(APFloat::Bogus,1));
Reid Spencerb31bffe2007-02-26 23:54:03 +0000292 }
Dale Johannesenbdea32d2007-08-24 22:09:56 +0000293 static inline KeyTy getTombstoneKey() {
294 return KeyTy(APFloat(APFloat::Bogus,2));
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000295 }
Dale Johannesenbdea32d2007-08-24 22:09:56 +0000296 static unsigned getHashValue(const KeyTy &Key) {
297 return Key.val.getHashValue();
Dale Johannesena719a602007-08-24 00:56:33 +0000298 }
Chris Lattner0625bd62007-09-17 18:34:04 +0000299 static bool isEqual(const KeyTy &LHS, const KeyTy &RHS) {
300 return LHS == RHS;
301 }
Dale Johannesena719a602007-08-24 00:56:33 +0000302 static bool isPod() { return false; }
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000303 };
304}
305
306//---- ConstantFP::get() implementation...
307//
Dale Johannesenbdea32d2007-08-24 22:09:56 +0000308typedef DenseMap<DenseMapAPFloatKeyInfo::KeyTy, ConstantFP*,
Dale Johannesena719a602007-08-24 00:56:33 +0000309 DenseMapAPFloatKeyInfo> FPMapTy;
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000310
Dale Johannesena719a602007-08-24 00:56:33 +0000311static ManagedStatic<FPMapTy> FPConstants;
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000312
Dale Johannesend246b2c2007-08-30 00:23:21 +0000313ConstantFP *ConstantFP::get(const Type *Ty, const APFloat& V) {
314 // temporary
315 if (Ty==Type::FloatTy)
316 assert(&V.getSemantics()==&APFloat::IEEEsingle);
Dale Johannesen028084e2007-09-12 03:30:33 +0000317 else if (Ty==Type::DoubleTy)
Dale Johannesend246b2c2007-08-30 00:23:21 +0000318 assert(&V.getSemantics()==&APFloat::IEEEdouble);
Dale Johannesen028084e2007-09-12 03:30:33 +0000319 else if (Ty==Type::X86_FP80Ty)
320 assert(&V.getSemantics()==&APFloat::x87DoubleExtended);
321 else if (Ty==Type::FP128Ty)
322 assert(&V.getSemantics()==&APFloat::IEEEquad);
323 else
324 assert(0);
Dale Johannesend246b2c2007-08-30 00:23:21 +0000325
326 DenseMapAPFloatKeyInfo::KeyTy Key(V);
327 ConstantFP *&Slot = (*FPConstants)[Key];
328 if (Slot) return Slot;
329 return Slot = new ConstantFP(Ty, V);
330}
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000331
332//===----------------------------------------------------------------------===//
333// ConstantXXX Classes
334//===----------------------------------------------------------------------===//
335
336
Chris Lattner3462ae32001-12-03 22:26:30 +0000337ConstantArray::ConstantArray(const ArrayType *T,
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000338 const std::vector<Constant*> &V)
Chris Lattnere7e139e2005-09-27 06:09:08 +0000339 : Constant(T, ConstantArrayVal, new Use[V.size()], V.size()) {
Alkis Evlogimenos0507ffe2004-09-15 02:32:15 +0000340 assert(V.size() == T->getNumElements() &&
341 "Invalid initializer vector for constant array");
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000342 Use *OL = OperandList;
Chris Lattner0144fad2005-10-03 21:56:24 +0000343 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
344 I != E; ++I, ++OL) {
Chris Lattner20a24452005-10-07 05:23:36 +0000345 Constant *C = *I;
346 assert((C->getType() == T->getElementType() ||
Alkis Evlogimenoscb031d92004-09-10 04:16:59 +0000347 (T->isAbstract() &&
Chris Lattner20a24452005-10-07 05:23:36 +0000348 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
Alkis Evlogimenoscb031d92004-09-10 04:16:59 +0000349 "Initializer for array element doesn't match array element type!");
Chris Lattner20a24452005-10-07 05:23:36 +0000350 OL->init(C, this);
Chris Lattner2f7c9632001-06-06 20:29:01 +0000351 }
352}
353
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000354ConstantArray::~ConstantArray() {
355 delete [] OperandList;
356}
357
Chris Lattner3462ae32001-12-03 22:26:30 +0000358ConstantStruct::ConstantStruct(const StructType *T,
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000359 const std::vector<Constant*> &V)
Chris Lattnere7e139e2005-09-27 06:09:08 +0000360 : Constant(T, ConstantStructVal, new Use[V.size()], V.size()) {
Chris Lattnerac6db752004-02-09 04:37:31 +0000361 assert(V.size() == T->getNumElements() &&
Vikram S. Adve4e537b22002-07-14 23:13:17 +0000362 "Invalid initializer vector for constant structure");
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000363 Use *OL = OperandList;
Chris Lattner0144fad2005-10-03 21:56:24 +0000364 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
365 I != E; ++I, ++OL) {
Chris Lattner20a24452005-10-07 05:23:36 +0000366 Constant *C = *I;
367 assert((C->getType() == T->getElementType(I-V.begin()) ||
Chris Lattner0144fad2005-10-03 21:56:24 +0000368 ((T->getElementType(I-V.begin())->isAbstract() ||
Chris Lattner20a24452005-10-07 05:23:36 +0000369 C->getType()->isAbstract()) &&
Chris Lattner0144fad2005-10-03 21:56:24 +0000370 T->getElementType(I-V.begin())->getTypeID() ==
Chris Lattner20a24452005-10-07 05:23:36 +0000371 C->getType()->getTypeID())) &&
Chris Lattner93c8f142003-06-02 17:42:47 +0000372 "Initializer for struct element doesn't match struct element type!");
Chris Lattner20a24452005-10-07 05:23:36 +0000373 OL->init(C, this);
Chris Lattner2f7c9632001-06-06 20:29:01 +0000374 }
375}
376
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000377ConstantStruct::~ConstantStruct() {
378 delete [] OperandList;
379}
380
381
Reid Spencerd84d35b2007-02-15 02:26:10 +0000382ConstantVector::ConstantVector(const VectorType *T,
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000383 const std::vector<Constant*> &V)
Reid Spencerd84d35b2007-02-15 02:26:10 +0000384 : Constant(T, ConstantVectorVal, new Use[V.size()], V.size()) {
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000385 Use *OL = OperandList;
Chris Lattner0144fad2005-10-03 21:56:24 +0000386 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
387 I != E; ++I, ++OL) {
Chris Lattner20a24452005-10-07 05:23:36 +0000388 Constant *C = *I;
389 assert((C->getType() == T->getElementType() ||
Alkis Evlogimenoscb031d92004-09-10 04:16:59 +0000390 (T->isAbstract() &&
Chris Lattner20a24452005-10-07 05:23:36 +0000391 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
Dan Gohman30978072007-05-24 14:36:04 +0000392 "Initializer for vector element doesn't match vector element type!");
Chris Lattner20a24452005-10-07 05:23:36 +0000393 OL->init(C, this);
Brian Gaeke02209042004-08-20 06:00:58 +0000394 }
395}
396
Reid Spencerd84d35b2007-02-15 02:26:10 +0000397ConstantVector::~ConstantVector() {
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000398 delete [] OperandList;
Vikram S. Adve4e537b22002-07-14 23:13:17 +0000399}
400
Reid Spencer10fbf0e2006-12-03 05:48:19 +0000401// We declare several classes private to this file, so use an anonymous
402// namespace
403namespace {
404
405/// UnaryConstantExpr - This class is private to Constants.cpp, and is used
406/// behind the scenes to implement unary constant exprs.
407class VISIBILITY_HIDDEN UnaryConstantExpr : public ConstantExpr {
408 Use Op;
409public:
410 UnaryConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
411 : ConstantExpr(Ty, Opcode, &Op, 1), Op(C, this) {}
412};
413
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000414/// BinaryConstantExpr - This class is private to Constants.cpp, and is used
415/// behind the scenes to implement binary constant exprs.
Chris Lattner02157b02006-06-28 21:38:54 +0000416class VISIBILITY_HIDDEN BinaryConstantExpr : public ConstantExpr {
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000417 Use Ops[2];
418public:
419 BinaryConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
Reid Spencer266e42b2006-12-23 06:05:41 +0000420 : ConstantExpr(C1->getType(), Opcode, Ops, 2) {
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000421 Ops[0].init(C1, this);
422 Ops[1].init(C2, this);
423 }
424};
Vikram S. Adve4e537b22002-07-14 23:13:17 +0000425
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000426/// SelectConstantExpr - This class is private to Constants.cpp, and is used
427/// behind the scenes to implement select constant exprs.
Chris Lattner02157b02006-06-28 21:38:54 +0000428class VISIBILITY_HIDDEN SelectConstantExpr : public ConstantExpr {
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000429 Use Ops[3];
430public:
431 SelectConstantExpr(Constant *C1, Constant *C2, Constant *C3)
432 : ConstantExpr(C2->getType(), Instruction::Select, Ops, 3) {
433 Ops[0].init(C1, this);
434 Ops[1].init(C2, this);
435 Ops[2].init(C3, this);
436 }
437};
438
Robert Bocchinoca27f032006-01-17 20:07:22 +0000439/// ExtractElementConstantExpr - This class is private to
440/// Constants.cpp, and is used behind the scenes to implement
441/// extractelement constant exprs.
Chris Lattner02157b02006-06-28 21:38:54 +0000442class VISIBILITY_HIDDEN ExtractElementConstantExpr : public ConstantExpr {
Robert Bocchino23004482006-01-10 19:05:34 +0000443 Use Ops[2];
444public:
445 ExtractElementConstantExpr(Constant *C1, Constant *C2)
Reid Spencerd84d35b2007-02-15 02:26:10 +0000446 : ConstantExpr(cast<VectorType>(C1->getType())->getElementType(),
Robert Bocchino23004482006-01-10 19:05:34 +0000447 Instruction::ExtractElement, Ops, 2) {
448 Ops[0].init(C1, this);
449 Ops[1].init(C2, this);
450 }
451};
452
Robert Bocchinoca27f032006-01-17 20:07:22 +0000453/// InsertElementConstantExpr - This class is private to
454/// Constants.cpp, and is used behind the scenes to implement
455/// insertelement constant exprs.
Chris Lattner02157b02006-06-28 21:38:54 +0000456class VISIBILITY_HIDDEN InsertElementConstantExpr : public ConstantExpr {
Robert Bocchinoca27f032006-01-17 20:07:22 +0000457 Use Ops[3];
458public:
459 InsertElementConstantExpr(Constant *C1, Constant *C2, Constant *C3)
460 : ConstantExpr(C1->getType(), Instruction::InsertElement,
461 Ops, 3) {
462 Ops[0].init(C1, this);
463 Ops[1].init(C2, this);
464 Ops[2].init(C3, this);
465 }
466};
467
Chris Lattnerbbe0a422006-04-08 01:18:18 +0000468/// ShuffleVectorConstantExpr - This class is private to
469/// Constants.cpp, and is used behind the scenes to implement
470/// shufflevector constant exprs.
Chris Lattner02157b02006-06-28 21:38:54 +0000471class VISIBILITY_HIDDEN ShuffleVectorConstantExpr : public ConstantExpr {
Chris Lattnerbbe0a422006-04-08 01:18:18 +0000472 Use Ops[3];
473public:
474 ShuffleVectorConstantExpr(Constant *C1, Constant *C2, Constant *C3)
475 : ConstantExpr(C1->getType(), Instruction::ShuffleVector,
476 Ops, 3) {
477 Ops[0].init(C1, this);
478 Ops[1].init(C2, this);
479 Ops[2].init(C3, this);
480 }
481};
482
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000483/// GetElementPtrConstantExpr - This class is private to Constants.cpp, and is
484/// used behind the scenes to implement getelementpr constant exprs.
Chris Lattner02157b02006-06-28 21:38:54 +0000485struct VISIBILITY_HIDDEN GetElementPtrConstantExpr : public ConstantExpr {
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000486 GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
487 const Type *DestTy)
488 : ConstantExpr(DestTy, Instruction::GetElementPtr,
489 new Use[IdxList.size()+1], IdxList.size()+1) {
490 OperandList[0].init(C, this);
491 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
492 OperandList[i+1].init(IdxList[i], this);
493 }
494 ~GetElementPtrConstantExpr() {
Misha Brukmanb1c93172005-04-21 23:48:37 +0000495 delete [] OperandList;
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000496 }
497};
Reid Spencer10fbf0e2006-12-03 05:48:19 +0000498
499// CompareConstantExpr - This class is private to Constants.cpp, and is used
500// behind the scenes to implement ICmp and FCmp constant expressions. This is
501// needed in order to store the predicate value for these instructions.
502struct VISIBILITY_HIDDEN CompareConstantExpr : public ConstantExpr {
503 unsigned short predicate;
504 Use Ops[2];
505 CompareConstantExpr(Instruction::OtherOps opc, unsigned short pred,
506 Constant* LHS, Constant* RHS)
Reid Spencer542964f2007-01-11 18:21:29 +0000507 : ConstantExpr(Type::Int1Ty, opc, Ops, 2), predicate(pred) {
Reid Spencer10fbf0e2006-12-03 05:48:19 +0000508 OperandList[0].init(LHS, this);
509 OperandList[1].init(RHS, this);
510 }
511};
512
513} // end anonymous namespace
Vikram S. Adve4e537b22002-07-14 23:13:17 +0000514
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000515
516// Utility function for determining if a ConstantExpr is a CastOp or not. This
517// can't be inline because we don't want to #include Instruction.h into
518// Constant.h
519bool ConstantExpr::isCast() const {
520 return Instruction::isCast(getOpcode());
521}
522
Reid Spenceree3c9912006-12-04 05:19:50 +0000523bool ConstantExpr::isCompare() const {
524 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
525}
526
Chris Lattner817175f2004-03-29 02:37:53 +0000527/// ConstantExpr::get* - Return some common constants without having to
528/// specify the full Instruction::OPCODE identifier.
529///
530Constant *ConstantExpr::getNeg(Constant *C) {
Reid Spencer2eadb532007-01-21 00:29:26 +0000531 return get(Instruction::Sub,
532 ConstantExpr::getZeroValueForNegationExpr(C->getType()),
533 C);
Chris Lattner817175f2004-03-29 02:37:53 +0000534}
535Constant *ConstantExpr::getNot(Constant *C) {
Zhou Sheng75b871f2007-01-11 12:24:14 +0000536 assert(isa<ConstantInt>(C) && "Cannot NOT a nonintegral type!");
Chris Lattner817175f2004-03-29 02:37:53 +0000537 return get(Instruction::Xor, C,
Zhou Sheng75b871f2007-01-11 12:24:14 +0000538 ConstantInt::getAllOnesValue(C->getType()));
Chris Lattner817175f2004-03-29 02:37:53 +0000539}
540Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2) {
541 return get(Instruction::Add, C1, C2);
542}
543Constant *ConstantExpr::getSub(Constant *C1, Constant *C2) {
544 return get(Instruction::Sub, C1, C2);
545}
546Constant *ConstantExpr::getMul(Constant *C1, Constant *C2) {
547 return get(Instruction::Mul, C1, C2);
548}
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000549Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2) {
550 return get(Instruction::UDiv, C1, C2);
551}
552Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2) {
553 return get(Instruction::SDiv, C1, C2);
554}
555Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
556 return get(Instruction::FDiv, C1, C2);
Chris Lattner817175f2004-03-29 02:37:53 +0000557}
Reid Spencer7eb55b32006-11-02 01:53:59 +0000558Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
559 return get(Instruction::URem, C1, C2);
560}
561Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
562 return get(Instruction::SRem, C1, C2);
563}
564Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
565 return get(Instruction::FRem, C1, C2);
Chris Lattner817175f2004-03-29 02:37:53 +0000566}
567Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
568 return get(Instruction::And, C1, C2);
569}
570Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
571 return get(Instruction::Or, C1, C2);
572}
573Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
574 return get(Instruction::Xor, C1, C2);
575}
Reid Spencer10fbf0e2006-12-03 05:48:19 +0000576unsigned ConstantExpr::getPredicate() const {
577 assert(getOpcode() == Instruction::FCmp || getOpcode() == Instruction::ICmp);
578 return dynamic_cast<const CompareConstantExpr*>(this)->predicate;
579}
Chris Lattner817175f2004-03-29 02:37:53 +0000580Constant *ConstantExpr::getShl(Constant *C1, Constant *C2) {
581 return get(Instruction::Shl, C1, C2);
582}
Reid Spencerfdff9382006-11-08 06:47:33 +0000583Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2) {
584 return get(Instruction::LShr, C1, C2);
Chris Lattner817175f2004-03-29 02:37:53 +0000585}
Reid Spencerfdff9382006-11-08 06:47:33 +0000586Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2) {
587 return get(Instruction::AShr, C1, C2);
Chris Lattnerdb8bdba2004-05-25 05:32:43 +0000588}
Chris Lattner60e0dd72001-10-03 06:12:09 +0000589
Chris Lattner7c1018a2006-07-14 19:37:40 +0000590/// getWithOperandReplaced - Return a constant expression identical to this
591/// one, but with the specified operand set to the specified value.
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000592Constant *
593ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
Chris Lattner7c1018a2006-07-14 19:37:40 +0000594 assert(OpNo < getNumOperands() && "Operand num is out of range!");
595 assert(Op->getType() == getOperand(OpNo)->getType() &&
596 "Replacing operand with value of different type!");
Chris Lattner227816342006-07-14 22:20:01 +0000597 if (getOperand(OpNo) == Op)
598 return const_cast<ConstantExpr*>(this);
Chris Lattner7c1018a2006-07-14 19:37:40 +0000599
Chris Lattner227816342006-07-14 22:20:01 +0000600 Constant *Op0, *Op1, *Op2;
Chris Lattner7c1018a2006-07-14 19:37:40 +0000601 switch (getOpcode()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000602 case Instruction::Trunc:
603 case Instruction::ZExt:
604 case Instruction::SExt:
605 case Instruction::FPTrunc:
606 case Instruction::FPExt:
607 case Instruction::UIToFP:
608 case Instruction::SIToFP:
609 case Instruction::FPToUI:
610 case Instruction::FPToSI:
611 case Instruction::PtrToInt:
612 case Instruction::IntToPtr:
613 case Instruction::BitCast:
614 return ConstantExpr::getCast(getOpcode(), Op, getType());
Chris Lattner227816342006-07-14 22:20:01 +0000615 case Instruction::Select:
616 Op0 = (OpNo == 0) ? Op : getOperand(0);
617 Op1 = (OpNo == 1) ? Op : getOperand(1);
618 Op2 = (OpNo == 2) ? Op : getOperand(2);
619 return ConstantExpr::getSelect(Op0, Op1, Op2);
620 case Instruction::InsertElement:
621 Op0 = (OpNo == 0) ? Op : getOperand(0);
622 Op1 = (OpNo == 1) ? Op : getOperand(1);
623 Op2 = (OpNo == 2) ? Op : getOperand(2);
624 return ConstantExpr::getInsertElement(Op0, Op1, Op2);
625 case Instruction::ExtractElement:
626 Op0 = (OpNo == 0) ? Op : getOperand(0);
627 Op1 = (OpNo == 1) ? Op : getOperand(1);
628 return ConstantExpr::getExtractElement(Op0, Op1);
629 case Instruction::ShuffleVector:
630 Op0 = (OpNo == 0) ? Op : getOperand(0);
631 Op1 = (OpNo == 1) ? Op : getOperand(1);
632 Op2 = (OpNo == 2) ? Op : getOperand(2);
633 return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Chris Lattner7c1018a2006-07-14 19:37:40 +0000634 case Instruction::GetElementPtr: {
Chris Lattnerb5d70302007-02-19 20:01:23 +0000635 SmallVector<Constant*, 8> Ops;
636 Ops.resize(getNumOperands());
Chris Lattner7c1018a2006-07-14 19:37:40 +0000637 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
Chris Lattnerb5d70302007-02-19 20:01:23 +0000638 Ops[i] = getOperand(i);
Chris Lattner7c1018a2006-07-14 19:37:40 +0000639 if (OpNo == 0)
Chris Lattnerb5d70302007-02-19 20:01:23 +0000640 return ConstantExpr::getGetElementPtr(Op, &Ops[0], Ops.size());
Chris Lattner7c1018a2006-07-14 19:37:40 +0000641 Ops[OpNo-1] = Op;
Chris Lattnerb5d70302007-02-19 20:01:23 +0000642 return ConstantExpr::getGetElementPtr(getOperand(0), &Ops[0], Ops.size());
Chris Lattner7c1018a2006-07-14 19:37:40 +0000643 }
Chris Lattner7c1018a2006-07-14 19:37:40 +0000644 default:
645 assert(getNumOperands() == 2 && "Must be binary operator?");
Chris Lattner227816342006-07-14 22:20:01 +0000646 Op0 = (OpNo == 0) ? Op : getOperand(0);
647 Op1 = (OpNo == 1) ? Op : getOperand(1);
648 return ConstantExpr::get(getOpcode(), Op0, Op1);
649 }
650}
651
652/// getWithOperands - This returns the current constant expression with the
653/// operands replaced with the specified values. The specified operands must
654/// match count and type with the existing ones.
655Constant *ConstantExpr::
656getWithOperands(const std::vector<Constant*> &Ops) const {
657 assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
658 bool AnyChange = false;
659 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
660 assert(Ops[i]->getType() == getOperand(i)->getType() &&
661 "Operand type mismatch!");
662 AnyChange |= Ops[i] != getOperand(i);
663 }
664 if (!AnyChange) // No operands changed, return self.
665 return const_cast<ConstantExpr*>(this);
666
667 switch (getOpcode()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000668 case Instruction::Trunc:
669 case Instruction::ZExt:
670 case Instruction::SExt:
671 case Instruction::FPTrunc:
672 case Instruction::FPExt:
673 case Instruction::UIToFP:
674 case Instruction::SIToFP:
675 case Instruction::FPToUI:
676 case Instruction::FPToSI:
677 case Instruction::PtrToInt:
678 case Instruction::IntToPtr:
679 case Instruction::BitCast:
680 return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
Chris Lattner227816342006-07-14 22:20:01 +0000681 case Instruction::Select:
682 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
683 case Instruction::InsertElement:
684 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
685 case Instruction::ExtractElement:
686 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
687 case Instruction::ShuffleVector:
688 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
Chris Lattnerb5d70302007-02-19 20:01:23 +0000689 case Instruction::GetElementPtr:
690 return ConstantExpr::getGetElementPtr(Ops[0], &Ops[1], Ops.size()-1);
Reid Spencer266e42b2006-12-23 06:05:41 +0000691 case Instruction::ICmp:
692 case Instruction::FCmp:
693 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
Chris Lattner227816342006-07-14 22:20:01 +0000694 default:
695 assert(getNumOperands() == 2 && "Must be binary operator?");
696 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1]);
Chris Lattner7c1018a2006-07-14 19:37:40 +0000697 }
698}
699
Chris Lattner2f7c9632001-06-06 20:29:01 +0000700
701//===----------------------------------------------------------------------===//
Chris Lattner2f7c9632001-06-06 20:29:01 +0000702// isValueValidForType implementations
703
Reid Spencere7334722006-12-19 01:28:19 +0000704bool ConstantInt::isValueValidForType(const Type *Ty, uint64_t Val) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000705 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000706 if (Ty == Type::Int1Ty)
707 return Val == 0 || Val == 1;
Reid Spencerd7a00d72007-02-05 23:47:56 +0000708 if (NumBits >= 64)
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000709 return true; // always true, has to fit in largest type
710 uint64_t Max = (1ll << NumBits) - 1;
711 return Val <= Max;
Reid Spencere7334722006-12-19 01:28:19 +0000712}
713
Reid Spencere0fc4df2006-10-20 07:07:24 +0000714bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000715 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000716 if (Ty == Type::Int1Ty)
Reid Spencera94d3942007-01-19 21:13:56 +0000717 return Val == 0 || Val == 1 || Val == -1;
Reid Spencerd7a00d72007-02-05 23:47:56 +0000718 if (NumBits >= 64)
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000719 return true; // always true, has to fit in largest type
720 int64_t Min = -(1ll << (NumBits-1));
721 int64_t Max = (1ll << (NumBits-1)) - 1;
722 return (Val >= Min && Val <= Max);
Chris Lattner2f7c9632001-06-06 20:29:01 +0000723}
724
Dale Johannesend246b2c2007-08-30 00:23:21 +0000725bool ConstantFP::isValueValidForType(const Type *Ty, const APFloat& Val) {
726 // convert modifies in place, so make a copy.
727 APFloat Val2 = APFloat(Val);
Chris Lattner6b727592004-06-17 18:19:28 +0000728 switch (Ty->getTypeID()) {
Chris Lattner2f7c9632001-06-06 20:29:01 +0000729 default:
730 return false; // These can't be represented as floating point!
731
Dale Johannesend246b2c2007-08-30 00:23:21 +0000732 // FIXME rounding mode needs to be more flexible
Chris Lattner2f7c9632001-06-06 20:29:01 +0000733 case Type::FloatTyID:
Dale Johannesend246b2c2007-08-30 00:23:21 +0000734 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
735 Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven) ==
736 APFloat::opOK;
Chris Lattner2f7c9632001-06-06 20:29:01 +0000737 case Type::DoubleTyID:
Dale Johannesend246b2c2007-08-30 00:23:21 +0000738 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
739 &Val2.getSemantics() == &APFloat::IEEEdouble ||
740 Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven) ==
741 APFloat::opOK;
Dale Johannesenbdad8092007-08-09 22:51:36 +0000742 case Type::X86_FP80TyID:
Dale Johannesen028084e2007-09-12 03:30:33 +0000743 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
744 &Val2.getSemantics() == &APFloat::IEEEdouble ||
745 &Val2.getSemantics() == &APFloat::x87DoubleExtended;
Dale Johannesenbdad8092007-08-09 22:51:36 +0000746 case Type::FP128TyID:
Dale Johannesen028084e2007-09-12 03:30:33 +0000747 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
748 &Val2.getSemantics() == &APFloat::IEEEdouble ||
749 &Val2.getSemantics() == &APFloat::IEEEquad;
Chris Lattner2f7c9632001-06-06 20:29:01 +0000750 }
Chris Lattneraa2372562006-05-24 17:04:05 +0000751}
Chris Lattner9655e542001-07-20 19:16:02 +0000752
Chris Lattner49d855c2001-09-07 16:46:31 +0000753//===----------------------------------------------------------------------===//
Chris Lattner49d855c2001-09-07 16:46:31 +0000754// Factory Function Implementation
755
Chris Lattner98fa07b2003-05-23 20:03:32 +0000756// ConstantCreator - A class that is used to create constants by
757// ValueMap*. This class should be partially specialized if there is
758// something strange that needs to be done to interface to the ctor for the
759// constant.
760//
Chris Lattner189d19f2003-11-21 20:23:48 +0000761namespace llvm {
762 template<class ConstantClass, class TypeClass, class ValType>
Chris Lattner02157b02006-06-28 21:38:54 +0000763 struct VISIBILITY_HIDDEN ConstantCreator {
Chris Lattner189d19f2003-11-21 20:23:48 +0000764 static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
765 return new ConstantClass(Ty, V);
766 }
767 };
Misha Brukmanb1c93172005-04-21 23:48:37 +0000768
Chris Lattner189d19f2003-11-21 20:23:48 +0000769 template<class ConstantClass, class TypeClass>
Chris Lattner02157b02006-06-28 21:38:54 +0000770 struct VISIBILITY_HIDDEN ConvertConstantType {
Chris Lattner189d19f2003-11-21 20:23:48 +0000771 static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
772 assert(0 && "This type cannot be converted!\n");
773 abort();
774 }
775 };
Chris Lattnerb50d1352003-10-05 00:17:43 +0000776
Chris Lattner935aa922005-10-04 17:48:46 +0000777 template<class ValType, class TypeClass, class ConstantClass,
778 bool HasLargeKey = false /*true for arrays and structs*/ >
Chris Lattner02157b02006-06-28 21:38:54 +0000779 class VISIBILITY_HIDDEN ValueMap : public AbstractTypeUser {
Chris Lattnerb64419a2005-10-03 22:51:37 +0000780 public:
Jim Laskeyc03caef2006-07-17 17:38:29 +0000781 typedef std::pair<const Type*, ValType> MapKey;
782 typedef std::map<MapKey, Constant *> MapTy;
783 typedef std::map<Constant*, typename MapTy::iterator> InverseMapTy;
784 typedef std::map<const Type*, typename MapTy::iterator> AbstractTypeMapTy;
Chris Lattnerb64419a2005-10-03 22:51:37 +0000785 private:
Chris Lattner5bbf60a52005-10-04 16:52:46 +0000786 /// Map - This is the main map from the element descriptor to the Constants.
787 /// This is the primary way we avoid creating two of the same shape
788 /// constant.
Chris Lattnerb50d1352003-10-05 00:17:43 +0000789 MapTy Map;
Chris Lattner935aa922005-10-04 17:48:46 +0000790
791 /// InverseMap - If "HasLargeKey" is true, this contains an inverse mapping
792 /// from the constants to their element in Map. This is important for
793 /// removal of constants from the array, which would otherwise have to scan
794 /// through the map with very large keys.
Jim Laskeyc03caef2006-07-17 17:38:29 +0000795 InverseMapTy InverseMap;
Chris Lattnerb50d1352003-10-05 00:17:43 +0000796
Jim Laskeyc03caef2006-07-17 17:38:29 +0000797 /// AbstractTypeMap - Map for abstract type constants.
798 ///
Chris Lattnerb50d1352003-10-05 00:17:43 +0000799 AbstractTypeMapTy AbstractTypeMap;
Chris Lattner99a669b2004-11-19 16:39:44 +0000800
Chris Lattner98fa07b2003-05-23 20:03:32 +0000801 public:
Jim Laskeyc03caef2006-07-17 17:38:29 +0000802 typename MapTy::iterator map_end() { return Map.end(); }
Chris Lattnerb64419a2005-10-03 22:51:37 +0000803
804 /// InsertOrGetItem - Return an iterator for the specified element.
805 /// If the element exists in the map, the returned iterator points to the
806 /// entry and Exists=true. If not, the iterator points to the newly
807 /// inserted entry and returns Exists=false. Newly inserted entries have
808 /// I->second == 0, and should be filled in.
Jim Laskeyc03caef2006-07-17 17:38:29 +0000809 typename MapTy::iterator InsertOrGetItem(std::pair<MapKey, Constant *>
810 &InsertVal,
Chris Lattnerb64419a2005-10-03 22:51:37 +0000811 bool &Exists) {
Jim Laskeyc03caef2006-07-17 17:38:29 +0000812 std::pair<typename MapTy::iterator, bool> IP = Map.insert(InsertVal);
Chris Lattnerb64419a2005-10-03 22:51:37 +0000813 Exists = !IP.second;
814 return IP.first;
815 }
Chris Lattner5bbf60a52005-10-04 16:52:46 +0000816
Chris Lattner935aa922005-10-04 17:48:46 +0000817private:
Jim Laskeyc03caef2006-07-17 17:38:29 +0000818 typename MapTy::iterator FindExistingElement(ConstantClass *CP) {
Chris Lattner935aa922005-10-04 17:48:46 +0000819 if (HasLargeKey) {
Jim Laskeyc03caef2006-07-17 17:38:29 +0000820 typename InverseMapTy::iterator IMI = InverseMap.find(CP);
Chris Lattner935aa922005-10-04 17:48:46 +0000821 assert(IMI != InverseMap.end() && IMI->second != Map.end() &&
822 IMI->second->second == CP &&
823 "InverseMap corrupt!");
824 return IMI->second;
825 }
826
Jim Laskeyc03caef2006-07-17 17:38:29 +0000827 typename MapTy::iterator I =
Chris Lattner935aa922005-10-04 17:48:46 +0000828 Map.find(MapKey((TypeClass*)CP->getRawType(), getValType(CP)));
Chris Lattner5bbf60a52005-10-04 16:52:46 +0000829 if (I == Map.end() || I->second != CP) {
830 // FIXME: This should not use a linear scan. If this gets to be a
831 // performance problem, someone should look at this.
832 for (I = Map.begin(); I != Map.end() && I->second != CP; ++I)
833 /* empty */;
834 }
Chris Lattner935aa922005-10-04 17:48:46 +0000835 return I;
836 }
837public:
838
Chris Lattnerb64419a2005-10-03 22:51:37 +0000839 /// getOrCreate - Return the specified constant from the map, creating it if
840 /// necessary.
Chris Lattner98fa07b2003-05-23 20:03:32 +0000841 ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
Chris Lattnerb50d1352003-10-05 00:17:43 +0000842 MapKey Lookup(Ty, V);
Jim Laskeyc03caef2006-07-17 17:38:29 +0000843 typename MapTy::iterator I = Map.lower_bound(Lookup);
Reid Spencere0fc4df2006-10-20 07:07:24 +0000844 // Is it in the map?
Chris Lattner98fa07b2003-05-23 20:03:32 +0000845 if (I != Map.end() && I->first == Lookup)
Reid Spencere0fc4df2006-10-20 07:07:24 +0000846 return static_cast<ConstantClass *>(I->second);
Chris Lattner98fa07b2003-05-23 20:03:32 +0000847
848 // If no preexisting value, create one now...
849 ConstantClass *Result =
850 ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
851
Chris Lattnerb50d1352003-10-05 00:17:43 +0000852 /// FIXME: why does this assert fail when loading 176.gcc?
853 //assert(Result->getType() == Ty && "Type specified is not correct!");
854 I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
855
Chris Lattner935aa922005-10-04 17:48:46 +0000856 if (HasLargeKey) // Remember the reverse mapping if needed.
857 InverseMap.insert(std::make_pair(Result, I));
858
Chris Lattnerb50d1352003-10-05 00:17:43 +0000859 // If the type of the constant is abstract, make sure that an entry exists
860 // for it in the AbstractTypeMap.
861 if (Ty->isAbstract()) {
862 typename AbstractTypeMapTy::iterator TI =
863 AbstractTypeMap.lower_bound(Ty);
864
865 if (TI == AbstractTypeMap.end() || TI->first != Ty) {
866 // Add ourselves to the ATU list of the type.
867 cast<DerivedType>(Ty)->addAbstractTypeUser(this);
868
869 AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
870 }
871 }
Chris Lattner98fa07b2003-05-23 20:03:32 +0000872 return Result;
873 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000874
Chris Lattner98fa07b2003-05-23 20:03:32 +0000875 void remove(ConstantClass *CP) {
Jim Laskeyc03caef2006-07-17 17:38:29 +0000876 typename MapTy::iterator I = FindExistingElement(CP);
Chris Lattnerb50d1352003-10-05 00:17:43 +0000877 assert(I != Map.end() && "Constant not found in constant table!");
Chris Lattner3e650af2004-08-04 04:48:01 +0000878 assert(I->second == CP && "Didn't find correct element?");
Chris Lattnerb50d1352003-10-05 00:17:43 +0000879
Chris Lattner935aa922005-10-04 17:48:46 +0000880 if (HasLargeKey) // Remember the reverse mapping if needed.
881 InverseMap.erase(CP);
882
Chris Lattnerb50d1352003-10-05 00:17:43 +0000883 // Now that we found the entry, make sure this isn't the entry that
884 // the AbstractTypeMap points to.
Jim Laskeyc03caef2006-07-17 17:38:29 +0000885 const TypeClass *Ty = static_cast<const TypeClass *>(I->first.first);
Chris Lattnerb50d1352003-10-05 00:17:43 +0000886 if (Ty->isAbstract()) {
887 assert(AbstractTypeMap.count(Ty) &&
888 "Abstract type not in AbstractTypeMap?");
Jim Laskeyc03caef2006-07-17 17:38:29 +0000889 typename MapTy::iterator &ATMEntryIt = AbstractTypeMap[Ty];
Chris Lattnerb50d1352003-10-05 00:17:43 +0000890 if (ATMEntryIt == I) {
891 // Yes, we are removing the representative entry for this type.
892 // See if there are any other entries of the same type.
Jim Laskeyc03caef2006-07-17 17:38:29 +0000893 typename MapTy::iterator TmpIt = ATMEntryIt;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000894
Chris Lattnerb50d1352003-10-05 00:17:43 +0000895 // First check the entry before this one...
896 if (TmpIt != Map.begin()) {
897 --TmpIt;
898 if (TmpIt->first.first != Ty) // Not the same type, move back...
899 ++TmpIt;
900 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000901
Chris Lattnerb50d1352003-10-05 00:17:43 +0000902 // If we didn't find the same type, try to move forward...
903 if (TmpIt == ATMEntryIt) {
904 ++TmpIt;
905 if (TmpIt == Map.end() || TmpIt->first.first != Ty)
906 --TmpIt; // No entry afterwards with the same type
907 }
908
909 // If there is another entry in the map of the same abstract type,
910 // update the AbstractTypeMap entry now.
911 if (TmpIt != ATMEntryIt) {
912 ATMEntryIt = TmpIt;
913 } else {
914 // Otherwise, we are removing the last instance of this type
915 // from the table. Remove from the ATM, and from user list.
916 cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
917 AbstractTypeMap.erase(Ty);
918 }
Chris Lattner98fa07b2003-05-23 20:03:32 +0000919 }
Chris Lattnerb50d1352003-10-05 00:17:43 +0000920 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000921
Chris Lattnerb50d1352003-10-05 00:17:43 +0000922 Map.erase(I);
923 }
924
Chris Lattner3b793c62005-10-04 21:35:50 +0000925
926 /// MoveConstantToNewSlot - If we are about to change C to be the element
927 /// specified by I, update our internal data structures to reflect this
928 /// fact.
Jim Laskeyc03caef2006-07-17 17:38:29 +0000929 void MoveConstantToNewSlot(ConstantClass *C, typename MapTy::iterator I) {
Chris Lattner3b793c62005-10-04 21:35:50 +0000930 // First, remove the old location of the specified constant in the map.
Jim Laskeyc03caef2006-07-17 17:38:29 +0000931 typename MapTy::iterator OldI = FindExistingElement(C);
Chris Lattner3b793c62005-10-04 21:35:50 +0000932 assert(OldI != Map.end() && "Constant not found in constant table!");
933 assert(OldI->second == C && "Didn't find correct element?");
934
935 // If this constant is the representative element for its abstract type,
936 // update the AbstractTypeMap so that the representative element is I.
937 if (C->getType()->isAbstract()) {
938 typename AbstractTypeMapTy::iterator ATI =
939 AbstractTypeMap.find(C->getType());
940 assert(ATI != AbstractTypeMap.end() &&
941 "Abstract type not in AbstractTypeMap?");
942 if (ATI->second == OldI)
943 ATI->second = I;
944 }
945
946 // Remove the old entry from the map.
947 Map.erase(OldI);
948
949 // Update the inverse map so that we know that this constant is now
950 // located at descriptor I.
951 if (HasLargeKey) {
952 assert(I->second == C && "Bad inversemap entry!");
953 InverseMap[C] = I;
954 }
955 }
956
Chris Lattnerb50d1352003-10-05 00:17:43 +0000957 void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
Misha Brukmanb1c93172005-04-21 23:48:37 +0000958 typename AbstractTypeMapTy::iterator I =
Jim Laskeyc03caef2006-07-17 17:38:29 +0000959 AbstractTypeMap.find(cast<Type>(OldTy));
Chris Lattnerb50d1352003-10-05 00:17:43 +0000960
961 assert(I != AbstractTypeMap.end() &&
962 "Abstract type not in AbstractTypeMap?");
963
964 // Convert a constant at a time until the last one is gone. The last one
965 // leaving will remove() itself, causing the AbstractTypeMapEntry to be
966 // eliminated eventually.
967 do {
968 ConvertConstantType<ConstantClass,
Jim Laskeyc03caef2006-07-17 17:38:29 +0000969 TypeClass>::convert(
970 static_cast<ConstantClass *>(I->second->second),
Chris Lattnerb50d1352003-10-05 00:17:43 +0000971 cast<TypeClass>(NewTy));
972
Jim Laskeyc03caef2006-07-17 17:38:29 +0000973 I = AbstractTypeMap.find(cast<Type>(OldTy));
Chris Lattnerb50d1352003-10-05 00:17:43 +0000974 } while (I != AbstractTypeMap.end());
975 }
976
977 // If the type became concrete without being refined to any other existing
978 // type, we just remove ourselves from the ATU list.
979 void typeBecameConcrete(const DerivedType *AbsTy) {
980 AbsTy->removeAbstractTypeUser(this);
981 }
982
983 void dump() const {
Bill Wendling6a462f12006-11-17 08:03:48 +0000984 DOUT << "Constant.cpp: ValueMap\n";
Chris Lattner98fa07b2003-05-23 20:03:32 +0000985 }
986 };
987}
988
Chris Lattnera84df0a22006-09-28 23:36:21 +0000989
Chris Lattner28173502007-02-20 06:11:36 +0000990
Chris Lattner9fba3da2004-02-15 05:53:04 +0000991//---- ConstantAggregateZero::get() implementation...
992//
993namespace llvm {
994 // ConstantAggregateZero does not take extra "value" argument...
995 template<class ValType>
996 struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
997 static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
998 return new ConstantAggregateZero(Ty);
999 }
1000 };
1001
1002 template<>
1003 struct ConvertConstantType<ConstantAggregateZero, Type> {
1004 static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
1005 // Make everyone now use a constant of the new type...
1006 Constant *New = ConstantAggregateZero::get(NewTy);
1007 assert(New != OldC && "Didn't replace constant??");
1008 OldC->uncheckedReplaceAllUsesWith(New);
1009 OldC->destroyConstant(); // This constant is now dead, destroy it.
1010 }
1011 };
1012}
1013
Chris Lattner69edc982006-09-28 00:35:06 +00001014static ManagedStatic<ValueMap<char, Type,
1015 ConstantAggregateZero> > AggZeroConstants;
Chris Lattner9fba3da2004-02-15 05:53:04 +00001016
Chris Lattner3e650af2004-08-04 04:48:01 +00001017static char getValType(ConstantAggregateZero *CPZ) { return 0; }
1018
Chris Lattner9fba3da2004-02-15 05:53:04 +00001019Constant *ConstantAggregateZero::get(const Type *Ty) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001020 assert((isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) &&
Chris Lattnerbfd0b6d2006-06-10 04:16:23 +00001021 "Cannot create an aggregate zero of non-aggregate type!");
Chris Lattner69edc982006-09-28 00:35:06 +00001022 return AggZeroConstants->getOrCreate(Ty, 0);
Chris Lattner9fba3da2004-02-15 05:53:04 +00001023}
1024
1025// destroyConstant - Remove the constant from the constant table...
1026//
1027void ConstantAggregateZero::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00001028 AggZeroConstants->remove(this);
Chris Lattner9fba3da2004-02-15 05:53:04 +00001029 destroyConstantImpl();
1030}
1031
Chris Lattner3462ae32001-12-03 22:26:30 +00001032//---- ConstantArray::get() implementation...
Chris Lattner49d855c2001-09-07 16:46:31 +00001033//
Chris Lattner189d19f2003-11-21 20:23:48 +00001034namespace llvm {
1035 template<>
1036 struct ConvertConstantType<ConstantArray, ArrayType> {
1037 static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
1038 // Make everyone now use a constant of the new type...
1039 std::vector<Constant*> C;
1040 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1041 C.push_back(cast<Constant>(OldC->getOperand(i)));
1042 Constant *New = ConstantArray::get(NewTy, C);
1043 assert(New != OldC && "Didn't replace constant??");
1044 OldC->uncheckedReplaceAllUsesWith(New);
1045 OldC->destroyConstant(); // This constant is now dead, destroy it.
1046 }
1047 };
1048}
Chris Lattnerb50d1352003-10-05 00:17:43 +00001049
Chris Lattner3e650af2004-08-04 04:48:01 +00001050static std::vector<Constant*> getValType(ConstantArray *CA) {
1051 std::vector<Constant*> Elements;
1052 Elements.reserve(CA->getNumOperands());
1053 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1054 Elements.push_back(cast<Constant>(CA->getOperand(i)));
1055 return Elements;
1056}
1057
Chris Lattnerb64419a2005-10-03 22:51:37 +00001058typedef ValueMap<std::vector<Constant*>, ArrayType,
Chris Lattner935aa922005-10-04 17:48:46 +00001059 ConstantArray, true /*largekey*/> ArrayConstantsTy;
Chris Lattner69edc982006-09-28 00:35:06 +00001060static ManagedStatic<ArrayConstantsTy> ArrayConstants;
Chris Lattner49d855c2001-09-07 16:46:31 +00001061
Chris Lattner015e8212004-02-15 04:14:47 +00001062Constant *ConstantArray::get(const ArrayType *Ty,
Chris Lattner9fba3da2004-02-15 05:53:04 +00001063 const std::vector<Constant*> &V) {
1064 // If this is an all-zero array, return a ConstantAggregateZero object
1065 if (!V.empty()) {
1066 Constant *C = V[0];
1067 if (!C->isNullValue())
Chris Lattner69edc982006-09-28 00:35:06 +00001068 return ArrayConstants->getOrCreate(Ty, V);
Chris Lattner9fba3da2004-02-15 05:53:04 +00001069 for (unsigned i = 1, e = V.size(); i != e; ++i)
1070 if (V[i] != C)
Chris Lattner69edc982006-09-28 00:35:06 +00001071 return ArrayConstants->getOrCreate(Ty, V);
Chris Lattner9fba3da2004-02-15 05:53:04 +00001072 }
1073 return ConstantAggregateZero::get(Ty);
Chris Lattner49d855c2001-09-07 16:46:31 +00001074}
1075
Chris Lattner98fa07b2003-05-23 20:03:32 +00001076// destroyConstant - Remove the constant from the constant table...
1077//
1078void ConstantArray::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00001079 ArrayConstants->remove(this);
Chris Lattner98fa07b2003-05-23 20:03:32 +00001080 destroyConstantImpl();
1081}
1082
Reid Spencer6f614532006-05-30 08:23:18 +00001083/// ConstantArray::get(const string&) - Return an array that is initialized to
1084/// contain the specified string. If length is zero then a null terminator is
1085/// added to the specified string so that it may be used in a natural way.
1086/// Otherwise, the length parameter specifies how much of the string to use
1087/// and it won't be null terminated.
1088///
Reid Spencer82ebaba2006-05-30 18:15:07 +00001089Constant *ConstantArray::get(const std::string &Str, bool AddNull) {
Chris Lattner7f74a562002-01-20 22:54:45 +00001090 std::vector<Constant*> ElementVals;
Reid Spencer82ebaba2006-05-30 18:15:07 +00001091 for (unsigned i = 0; i < Str.length(); ++i)
Reid Spencer8d9336d2006-12-31 05:26:44 +00001092 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, Str[i]));
Chris Lattner8f80fe02001-10-14 23:54:12 +00001093
1094 // Add a null terminator to the string...
Reid Spencer82ebaba2006-05-30 18:15:07 +00001095 if (AddNull) {
Reid Spencer8d9336d2006-12-31 05:26:44 +00001096 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, 0));
Reid Spencer6f614532006-05-30 08:23:18 +00001097 }
Chris Lattner8f80fe02001-10-14 23:54:12 +00001098
Reid Spencer8d9336d2006-12-31 05:26:44 +00001099 ArrayType *ATy = ArrayType::get(Type::Int8Ty, ElementVals.size());
Chris Lattner3462ae32001-12-03 22:26:30 +00001100 return ConstantArray::get(ATy, ElementVals);
Vikram S. Adve34410432001-10-14 23:17:20 +00001101}
1102
Reid Spencer2546b762007-01-26 07:37:34 +00001103/// isString - This method returns true if the array is an array of i8, and
1104/// if the elements of the array are all ConstantInt's.
Chris Lattnere8dfcca2004-01-14 17:06:38 +00001105bool ConstantArray::isString() const {
Reid Spencer2546b762007-01-26 07:37:34 +00001106 // Check the element type for i8...
Reid Spencer8d9336d2006-12-31 05:26:44 +00001107 if (getType()->getElementType() != Type::Int8Ty)
Chris Lattnere8dfcca2004-01-14 17:06:38 +00001108 return false;
1109 // Check the elements to make sure they are all integers, not constant
1110 // expressions.
1111 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1112 if (!isa<ConstantInt>(getOperand(i)))
1113 return false;
1114 return true;
1115}
1116
Evan Cheng3763c5b2006-10-26 19:15:05 +00001117/// isCString - This method returns true if the array is a string (see
1118/// isString) and it ends in a null byte \0 and does not contains any other
1119/// null bytes except its terminator.
1120bool ConstantArray::isCString() const {
Reid Spencer2546b762007-01-26 07:37:34 +00001121 // Check the element type for i8...
Reid Spencer8d9336d2006-12-31 05:26:44 +00001122 if (getType()->getElementType() != Type::Int8Ty)
Evan Chenge974da62006-10-26 21:48:03 +00001123 return false;
1124 Constant *Zero = Constant::getNullValue(getOperand(0)->getType());
1125 // Last element must be a null.
1126 if (getOperand(getNumOperands()-1) != Zero)
1127 return false;
1128 // Other elements must be non-null integers.
1129 for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
1130 if (!isa<ConstantInt>(getOperand(i)))
Evan Cheng3763c5b2006-10-26 19:15:05 +00001131 return false;
Evan Chenge974da62006-10-26 21:48:03 +00001132 if (getOperand(i) == Zero)
1133 return false;
1134 }
Evan Cheng3763c5b2006-10-26 19:15:05 +00001135 return true;
1136}
1137
1138
Reid Spencer2546b762007-01-26 07:37:34 +00001139// getAsString - If the sub-element type of this array is i8
Chris Lattner81fabb02002-08-26 17:53:56 +00001140// then this method converts the array to an std::string and returns it.
1141// Otherwise, it asserts out.
1142//
1143std::string ConstantArray::getAsString() const {
Chris Lattnere8dfcca2004-01-14 17:06:38 +00001144 assert(isString() && "Not a string!");
Chris Lattner81fabb02002-08-26 17:53:56 +00001145 std::string Result;
Chris Lattner6077c312003-07-23 15:22:26 +00001146 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
Reid Spencere0fc4df2006-10-20 07:07:24 +00001147 Result += (char)cast<ConstantInt>(getOperand(i))->getZExtValue();
Chris Lattner81fabb02002-08-26 17:53:56 +00001148 return Result;
1149}
1150
1151
Chris Lattner3462ae32001-12-03 22:26:30 +00001152//---- ConstantStruct::get() implementation...
Chris Lattner49d855c2001-09-07 16:46:31 +00001153//
Chris Lattnerb50d1352003-10-05 00:17:43 +00001154
Chris Lattner189d19f2003-11-21 20:23:48 +00001155namespace llvm {
1156 template<>
1157 struct ConvertConstantType<ConstantStruct, StructType> {
1158 static void convert(ConstantStruct *OldC, const StructType *NewTy) {
1159 // Make everyone now use a constant of the new type...
1160 std::vector<Constant*> C;
1161 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1162 C.push_back(cast<Constant>(OldC->getOperand(i)));
1163 Constant *New = ConstantStruct::get(NewTy, C);
1164 assert(New != OldC && "Didn't replace constant??");
Misha Brukmanb1c93172005-04-21 23:48:37 +00001165
Chris Lattner189d19f2003-11-21 20:23:48 +00001166 OldC->uncheckedReplaceAllUsesWith(New);
1167 OldC->destroyConstant(); // This constant is now dead, destroy it.
1168 }
1169 };
1170}
Chris Lattnerb50d1352003-10-05 00:17:43 +00001171
Chris Lattner8760ec72005-10-04 01:17:50 +00001172typedef ValueMap<std::vector<Constant*>, StructType,
Chris Lattner935aa922005-10-04 17:48:46 +00001173 ConstantStruct, true /*largekey*/> StructConstantsTy;
Chris Lattner69edc982006-09-28 00:35:06 +00001174static ManagedStatic<StructConstantsTy> StructConstants;
Chris Lattner49d855c2001-09-07 16:46:31 +00001175
Chris Lattner3e650af2004-08-04 04:48:01 +00001176static std::vector<Constant*> getValType(ConstantStruct *CS) {
1177 std::vector<Constant*> Elements;
1178 Elements.reserve(CS->getNumOperands());
1179 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1180 Elements.push_back(cast<Constant>(CS->getOperand(i)));
1181 return Elements;
1182}
1183
Chris Lattner015e8212004-02-15 04:14:47 +00001184Constant *ConstantStruct::get(const StructType *Ty,
1185 const std::vector<Constant*> &V) {
Chris Lattner9fba3da2004-02-15 05:53:04 +00001186 // Create a ConstantAggregateZero value if all elements are zeros...
1187 for (unsigned i = 0, e = V.size(); i != e; ++i)
1188 if (!V[i]->isNullValue())
Chris Lattner69edc982006-09-28 00:35:06 +00001189 return StructConstants->getOrCreate(Ty, V);
Chris Lattner9fba3da2004-02-15 05:53:04 +00001190
1191 return ConstantAggregateZero::get(Ty);
Chris Lattner49d855c2001-09-07 16:46:31 +00001192}
Chris Lattner883ad0b2001-10-03 15:39:36 +00001193
Andrew Lenharthdcb3c972006-12-08 18:06:16 +00001194Constant *ConstantStruct::get(const std::vector<Constant*> &V, bool packed) {
Chris Lattnerd6108ca2004-07-12 20:35:11 +00001195 std::vector<const Type*> StructEls;
1196 StructEls.reserve(V.size());
1197 for (unsigned i = 0, e = V.size(); i != e; ++i)
1198 StructEls.push_back(V[i]->getType());
Andrew Lenharthdcb3c972006-12-08 18:06:16 +00001199 return get(StructType::get(StructEls, packed), V);
Chris Lattnerd6108ca2004-07-12 20:35:11 +00001200}
1201
Chris Lattnerd7a73302001-10-13 06:57:33 +00001202// destroyConstant - Remove the constant from the constant table...
Chris Lattner883ad0b2001-10-03 15:39:36 +00001203//
Chris Lattner3462ae32001-12-03 22:26:30 +00001204void ConstantStruct::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00001205 StructConstants->remove(this);
Chris Lattnerd7a73302001-10-13 06:57:33 +00001206 destroyConstantImpl();
1207}
Chris Lattner883ad0b2001-10-03 15:39:36 +00001208
Reid Spencerd84d35b2007-02-15 02:26:10 +00001209//---- ConstantVector::get() implementation...
Brian Gaeke02209042004-08-20 06:00:58 +00001210//
1211namespace llvm {
1212 template<>
Reid Spencerd84d35b2007-02-15 02:26:10 +00001213 struct ConvertConstantType<ConstantVector, VectorType> {
1214 static void convert(ConstantVector *OldC, const VectorType *NewTy) {
Brian Gaeke02209042004-08-20 06:00:58 +00001215 // Make everyone now use a constant of the new type...
1216 std::vector<Constant*> C;
1217 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1218 C.push_back(cast<Constant>(OldC->getOperand(i)));
Reid Spencerd84d35b2007-02-15 02:26:10 +00001219 Constant *New = ConstantVector::get(NewTy, C);
Brian Gaeke02209042004-08-20 06:00:58 +00001220 assert(New != OldC && "Didn't replace constant??");
1221 OldC->uncheckedReplaceAllUsesWith(New);
1222 OldC->destroyConstant(); // This constant is now dead, destroy it.
1223 }
1224 };
1225}
1226
Reid Spencerd84d35b2007-02-15 02:26:10 +00001227static std::vector<Constant*> getValType(ConstantVector *CP) {
Brian Gaeke02209042004-08-20 06:00:58 +00001228 std::vector<Constant*> Elements;
1229 Elements.reserve(CP->getNumOperands());
1230 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1231 Elements.push_back(CP->getOperand(i));
1232 return Elements;
1233}
1234
Reid Spencerd84d35b2007-02-15 02:26:10 +00001235static ManagedStatic<ValueMap<std::vector<Constant*>, VectorType,
Reid Spencer09575ba2007-02-15 03:39:18 +00001236 ConstantVector> > VectorConstants;
Brian Gaeke02209042004-08-20 06:00:58 +00001237
Reid Spencerd84d35b2007-02-15 02:26:10 +00001238Constant *ConstantVector::get(const VectorType *Ty,
Brian Gaeke02209042004-08-20 06:00:58 +00001239 const std::vector<Constant*> &V) {
Dan Gohman30978072007-05-24 14:36:04 +00001240 // If this is an all-zero vector, return a ConstantAggregateZero object
Brian Gaeke02209042004-08-20 06:00:58 +00001241 if (!V.empty()) {
1242 Constant *C = V[0];
1243 if (!C->isNullValue())
Reid Spencer09575ba2007-02-15 03:39:18 +00001244 return VectorConstants->getOrCreate(Ty, V);
Brian Gaeke02209042004-08-20 06:00:58 +00001245 for (unsigned i = 1, e = V.size(); i != e; ++i)
1246 if (V[i] != C)
Reid Spencer09575ba2007-02-15 03:39:18 +00001247 return VectorConstants->getOrCreate(Ty, V);
Brian Gaeke02209042004-08-20 06:00:58 +00001248 }
1249 return ConstantAggregateZero::get(Ty);
1250}
1251
Reid Spencerd84d35b2007-02-15 02:26:10 +00001252Constant *ConstantVector::get(const std::vector<Constant*> &V) {
Brian Gaeke02209042004-08-20 06:00:58 +00001253 assert(!V.empty() && "Cannot infer type if V is empty");
Reid Spencerd84d35b2007-02-15 02:26:10 +00001254 return get(VectorType::get(V.front()->getType(),V.size()), V);
Brian Gaeke02209042004-08-20 06:00:58 +00001255}
1256
1257// destroyConstant - Remove the constant from the constant table...
1258//
Reid Spencerd84d35b2007-02-15 02:26:10 +00001259void ConstantVector::destroyConstant() {
Reid Spencer09575ba2007-02-15 03:39:18 +00001260 VectorConstants->remove(this);
Brian Gaeke02209042004-08-20 06:00:58 +00001261 destroyConstantImpl();
1262}
1263
Dan Gohman30978072007-05-24 14:36:04 +00001264/// This function will return true iff every element in this vector constant
Jim Laskeyf0478822007-01-12 22:39:14 +00001265/// is set to all ones.
1266/// @returns true iff this constant's emements are all set to all ones.
1267/// @brief Determine if the value is all ones.
Reid Spencerd84d35b2007-02-15 02:26:10 +00001268bool ConstantVector::isAllOnesValue() const {
Jim Laskeyf0478822007-01-12 22:39:14 +00001269 // Check out first element.
1270 const Constant *Elt = getOperand(0);
1271 const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1272 if (!CI || !CI->isAllOnesValue()) return false;
1273 // Then make sure all remaining elements point to the same value.
1274 for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
1275 if (getOperand(I) != Elt) return false;
1276 }
1277 return true;
1278}
1279
Chris Lattner3462ae32001-12-03 22:26:30 +00001280//---- ConstantPointerNull::get() implementation...
Chris Lattnerd7a73302001-10-13 06:57:33 +00001281//
Chris Lattner98fa07b2003-05-23 20:03:32 +00001282
Chris Lattner189d19f2003-11-21 20:23:48 +00001283namespace llvm {
1284 // ConstantPointerNull does not take extra "value" argument...
1285 template<class ValType>
1286 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1287 static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1288 return new ConstantPointerNull(Ty);
1289 }
1290 };
Chris Lattner98fa07b2003-05-23 20:03:32 +00001291
Chris Lattner189d19f2003-11-21 20:23:48 +00001292 template<>
1293 struct ConvertConstantType<ConstantPointerNull, PointerType> {
1294 static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1295 // Make everyone now use a constant of the new type...
1296 Constant *New = ConstantPointerNull::get(NewTy);
1297 assert(New != OldC && "Didn't replace constant??");
1298 OldC->uncheckedReplaceAllUsesWith(New);
1299 OldC->destroyConstant(); // This constant is now dead, destroy it.
1300 }
1301 };
1302}
Chris Lattnerb50d1352003-10-05 00:17:43 +00001303
Chris Lattner69edc982006-09-28 00:35:06 +00001304static ManagedStatic<ValueMap<char, PointerType,
1305 ConstantPointerNull> > NullPtrConstants;
Chris Lattnerd7a73302001-10-13 06:57:33 +00001306
Chris Lattner3e650af2004-08-04 04:48:01 +00001307static char getValType(ConstantPointerNull *) {
1308 return 0;
1309}
1310
1311
Chris Lattner3462ae32001-12-03 22:26:30 +00001312ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
Chris Lattner69edc982006-09-28 00:35:06 +00001313 return NullPtrConstants->getOrCreate(Ty, 0);
Chris Lattner883ad0b2001-10-03 15:39:36 +00001314}
1315
Chris Lattner0c6e0b92002-08-18 00:40:04 +00001316// destroyConstant - Remove the constant from the constant table...
1317//
1318void ConstantPointerNull::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00001319 NullPtrConstants->remove(this);
Chris Lattner0c6e0b92002-08-18 00:40:04 +00001320 destroyConstantImpl();
1321}
1322
1323
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001324//---- UndefValue::get() implementation...
1325//
1326
1327namespace llvm {
1328 // UndefValue does not take extra "value" argument...
1329 template<class ValType>
1330 struct ConstantCreator<UndefValue, Type, ValType> {
1331 static UndefValue *create(const Type *Ty, const ValType &V) {
1332 return new UndefValue(Ty);
1333 }
1334 };
1335
1336 template<>
1337 struct ConvertConstantType<UndefValue, Type> {
1338 static void convert(UndefValue *OldC, const Type *NewTy) {
1339 // Make everyone now use a constant of the new type.
1340 Constant *New = UndefValue::get(NewTy);
1341 assert(New != OldC && "Didn't replace constant??");
1342 OldC->uncheckedReplaceAllUsesWith(New);
1343 OldC->destroyConstant(); // This constant is now dead, destroy it.
1344 }
1345 };
1346}
1347
Chris Lattner69edc982006-09-28 00:35:06 +00001348static ManagedStatic<ValueMap<char, Type, UndefValue> > UndefValueConstants;
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001349
1350static char getValType(UndefValue *) {
1351 return 0;
1352}
1353
1354
1355UndefValue *UndefValue::get(const Type *Ty) {
Chris Lattner69edc982006-09-28 00:35:06 +00001356 return UndefValueConstants->getOrCreate(Ty, 0);
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001357}
1358
1359// destroyConstant - Remove the constant from the constant table.
1360//
1361void UndefValue::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00001362 UndefValueConstants->remove(this);
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001363 destroyConstantImpl();
1364}
1365
1366
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001367//---- ConstantExpr::get() implementations...
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001368//
Reid Spencer8d9336d2006-12-31 05:26:44 +00001369
Reid Spenceree3c9912006-12-04 05:19:50 +00001370struct ExprMapKeyType {
1371 explicit ExprMapKeyType(unsigned opc, std::vector<Constant*> ops,
Reid Spencerdba6aa42006-12-04 18:38:05 +00001372 unsigned short pred = 0) : opcode(opc), predicate(pred), operands(ops) { }
1373 uint16_t opcode;
1374 uint16_t predicate;
Reid Spenceree3c9912006-12-04 05:19:50 +00001375 std::vector<Constant*> operands;
Reid Spenceree3c9912006-12-04 05:19:50 +00001376 bool operator==(const ExprMapKeyType& that) const {
1377 return this->opcode == that.opcode &&
1378 this->predicate == that.predicate &&
1379 this->operands == that.operands;
1380 }
1381 bool operator<(const ExprMapKeyType & that) const {
1382 return this->opcode < that.opcode ||
1383 (this->opcode == that.opcode && this->predicate < that.predicate) ||
1384 (this->opcode == that.opcode && this->predicate == that.predicate &&
1385 this->operands < that.operands);
1386 }
1387
1388 bool operator!=(const ExprMapKeyType& that) const {
1389 return !(*this == that);
1390 }
1391};
Chris Lattner98fa07b2003-05-23 20:03:32 +00001392
Chris Lattner189d19f2003-11-21 20:23:48 +00001393namespace llvm {
1394 template<>
1395 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
Reid Spencer10fbf0e2006-12-03 05:48:19 +00001396 static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V,
1397 unsigned short pred = 0) {
Reid Spenceree3c9912006-12-04 05:19:50 +00001398 if (Instruction::isCast(V.opcode))
1399 return new UnaryConstantExpr(V.opcode, V.operands[0], Ty);
1400 if ((V.opcode >= Instruction::BinaryOpsBegin &&
Reid Spencer2341c222007-02-02 02:16:23 +00001401 V.opcode < Instruction::BinaryOpsEnd))
Reid Spenceree3c9912006-12-04 05:19:50 +00001402 return new BinaryConstantExpr(V.opcode, V.operands[0], V.operands[1]);
1403 if (V.opcode == Instruction::Select)
1404 return new SelectConstantExpr(V.operands[0], V.operands[1],
1405 V.operands[2]);
1406 if (V.opcode == Instruction::ExtractElement)
1407 return new ExtractElementConstantExpr(V.operands[0], V.operands[1]);
1408 if (V.opcode == Instruction::InsertElement)
1409 return new InsertElementConstantExpr(V.operands[0], V.operands[1],
1410 V.operands[2]);
1411 if (V.opcode == Instruction::ShuffleVector)
1412 return new ShuffleVectorConstantExpr(V.operands[0], V.operands[1],
1413 V.operands[2]);
1414 if (V.opcode == Instruction::GetElementPtr) {
1415 std::vector<Constant*> IdxList(V.operands.begin()+1, V.operands.end());
1416 return new GetElementPtrConstantExpr(V.operands[0], IdxList, Ty);
1417 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001418
Reid Spenceree3c9912006-12-04 05:19:50 +00001419 // The compare instructions are weird. We have to encode the predicate
1420 // value and it is combined with the instruction opcode by multiplying
1421 // the opcode by one hundred. We must decode this to get the predicate.
1422 if (V.opcode == Instruction::ICmp)
1423 return new CompareConstantExpr(Instruction::ICmp, V.predicate,
1424 V.operands[0], V.operands[1]);
1425 if (V.opcode == Instruction::FCmp)
1426 return new CompareConstantExpr(Instruction::FCmp, V.predicate,
1427 V.operands[0], V.operands[1]);
1428 assert(0 && "Invalid ConstantExpr!");
Jeff Cohen9f469632006-12-15 21:47:01 +00001429 return 0;
Chris Lattnerb50d1352003-10-05 00:17:43 +00001430 }
Chris Lattner189d19f2003-11-21 20:23:48 +00001431 };
Chris Lattnerb50d1352003-10-05 00:17:43 +00001432
Chris Lattner189d19f2003-11-21 20:23:48 +00001433 template<>
1434 struct ConvertConstantType<ConstantExpr, Type> {
1435 static void convert(ConstantExpr *OldC, const Type *NewTy) {
1436 Constant *New;
1437 switch (OldC->getOpcode()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001438 case Instruction::Trunc:
1439 case Instruction::ZExt:
1440 case Instruction::SExt:
1441 case Instruction::FPTrunc:
1442 case Instruction::FPExt:
1443 case Instruction::UIToFP:
1444 case Instruction::SIToFP:
1445 case Instruction::FPToUI:
1446 case Instruction::FPToSI:
1447 case Instruction::PtrToInt:
1448 case Instruction::IntToPtr:
1449 case Instruction::BitCast:
Reid Spencerbb65ebf2006-12-12 23:36:14 +00001450 New = ConstantExpr::getCast(OldC->getOpcode(), OldC->getOperand(0),
1451 NewTy);
Chris Lattner189d19f2003-11-21 20:23:48 +00001452 break;
Chris Lattner6e415c02004-03-12 05:54:04 +00001453 case Instruction::Select:
1454 New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1455 OldC->getOperand(1),
1456 OldC->getOperand(2));
1457 break;
Chris Lattner189d19f2003-11-21 20:23:48 +00001458 default:
1459 assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
Reid Spencer7eb55b32006-11-02 01:53:59 +00001460 OldC->getOpcode() < Instruction::BinaryOpsEnd);
Chris Lattner189d19f2003-11-21 20:23:48 +00001461 New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1462 OldC->getOperand(1));
1463 break;
1464 case Instruction::GetElementPtr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00001465 // Make everyone now use a constant of the new type...
Chris Lattner13128ab2004-10-11 22:52:25 +00001466 std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
Chris Lattner302116a2007-01-31 04:40:28 +00001467 New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0),
1468 &Idx[0], Idx.size());
Chris Lattner189d19f2003-11-21 20:23:48 +00001469 break;
1470 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001471
Chris Lattner189d19f2003-11-21 20:23:48 +00001472 assert(New != OldC && "Didn't replace constant??");
1473 OldC->uncheckedReplaceAllUsesWith(New);
1474 OldC->destroyConstant(); // This constant is now dead, destroy it.
1475 }
1476 };
1477} // end namespace llvm
Chris Lattnerb50d1352003-10-05 00:17:43 +00001478
1479
Chris Lattner3e650af2004-08-04 04:48:01 +00001480static ExprMapKeyType getValType(ConstantExpr *CE) {
1481 std::vector<Constant*> Operands;
1482 Operands.reserve(CE->getNumOperands());
1483 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
1484 Operands.push_back(cast<Constant>(CE->getOperand(i)));
Reid Spenceree3c9912006-12-04 05:19:50 +00001485 return ExprMapKeyType(CE->getOpcode(), Operands,
1486 CE->isCompare() ? CE->getPredicate() : 0);
Chris Lattner3e650af2004-08-04 04:48:01 +00001487}
1488
Chris Lattner69edc982006-09-28 00:35:06 +00001489static ManagedStatic<ValueMap<ExprMapKeyType, Type,
1490 ConstantExpr> > ExprConstants;
Vikram S. Adve4c485332002-07-15 18:19:33 +00001491
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001492/// This is a utility function to handle folding of casts and lookup of the
1493/// cast in the ExprConstants map. It is usedby the various get* methods below.
1494static inline Constant *getFoldedCast(
1495 Instruction::CastOps opc, Constant *C, const Type *Ty) {
Chris Lattner815ae2b2003-10-07 22:19:19 +00001496 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001497 // Fold a few common cases
1498 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
1499 return FC;
Chris Lattneracdbe712003-04-17 19:24:48 +00001500
Vikram S. Adve4c485332002-07-15 18:19:33 +00001501 // Look up the constant in the table first to ensure uniqueness
Chris Lattner2b383d2e2003-05-13 21:37:02 +00001502 std::vector<Constant*> argVec(1, C);
Reid Spenceree3c9912006-12-04 05:19:50 +00001503 ExprMapKeyType Key(opc, argVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001504 return ExprConstants->getOrCreate(Ty, Key);
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001505}
Reid Spencerf37dc652006-12-05 19:14:13 +00001506
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001507Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
1508 Instruction::CastOps opc = Instruction::CastOps(oc);
1509 assert(Instruction::isCast(opc) && "opcode out of range");
1510 assert(C && Ty && "Null arguments to getCast");
1511 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1512
1513 switch (opc) {
1514 default:
1515 assert(0 && "Invalid cast opcode");
1516 break;
1517 case Instruction::Trunc: return getTrunc(C, Ty);
Reid Spencerbb65ebf2006-12-12 23:36:14 +00001518 case Instruction::ZExt: return getZExt(C, Ty);
1519 case Instruction::SExt: return getSExt(C, Ty);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001520 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
1521 case Instruction::FPExt: return getFPExtend(C, Ty);
1522 case Instruction::UIToFP: return getUIToFP(C, Ty);
1523 case Instruction::SIToFP: return getSIToFP(C, Ty);
1524 case Instruction::FPToUI: return getFPToUI(C, Ty);
1525 case Instruction::FPToSI: return getFPToSI(C, Ty);
1526 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1527 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1528 case Instruction::BitCast: return getBitCast(C, Ty);
Chris Lattner1ece6f82005-01-01 15:59:57 +00001529 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001530 return 0;
Reid Spencerf37dc652006-12-05 19:14:13 +00001531}
1532
Reid Spencer5c140882006-12-04 20:17:56 +00001533Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
1534 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1535 return getCast(Instruction::BitCast, C, Ty);
1536 return getCast(Instruction::ZExt, C, Ty);
1537}
1538
1539Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
1540 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1541 return getCast(Instruction::BitCast, C, Ty);
1542 return getCast(Instruction::SExt, C, Ty);
1543}
1544
1545Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
1546 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1547 return getCast(Instruction::BitCast, C, Ty);
1548 return getCast(Instruction::Trunc, C, Ty);
1549}
1550
Reid Spencerbc245a02006-12-05 03:25:26 +00001551Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
1552 assert(isa<PointerType>(S->getType()) && "Invalid cast");
Chris Lattner03c49532007-01-15 02:27:26 +00001553 assert((Ty->isInteger() || isa<PointerType>(Ty)) && "Invalid cast");
Reid Spencerbc245a02006-12-05 03:25:26 +00001554
Chris Lattner03c49532007-01-15 02:27:26 +00001555 if (Ty->isInteger())
Reid Spencerbc245a02006-12-05 03:25:26 +00001556 return getCast(Instruction::PtrToInt, S, Ty);
1557 return getCast(Instruction::BitCast, S, Ty);
1558}
1559
Reid Spencer56521c42006-12-12 00:51:07 +00001560Constant *ConstantExpr::getIntegerCast(Constant *C, const Type *Ty,
1561 bool isSigned) {
Chris Lattner03c49532007-01-15 02:27:26 +00001562 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
Reid Spencer56521c42006-12-12 00:51:07 +00001563 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1564 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1565 Instruction::CastOps opcode =
1566 (SrcBits == DstBits ? Instruction::BitCast :
1567 (SrcBits > DstBits ? Instruction::Trunc :
1568 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1569 return getCast(opcode, C, Ty);
1570}
1571
1572Constant *ConstantExpr::getFPCast(Constant *C, const Type *Ty) {
1573 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1574 "Invalid cast");
1575 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1576 unsigned DstBits = Ty->getPrimitiveSizeInBits();
Reid Spencerca104e82006-12-12 05:38:50 +00001577 if (SrcBits == DstBits)
1578 return C; // Avoid a useless cast
Reid Spencer56521c42006-12-12 00:51:07 +00001579 Instruction::CastOps opcode =
Reid Spencerca104e82006-12-12 05:38:50 +00001580 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
Reid Spencer56521c42006-12-12 00:51:07 +00001581 return getCast(opcode, C, Ty);
1582}
1583
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001584Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
Chris Lattner03c49532007-01-15 02:27:26 +00001585 assert(C->getType()->isInteger() && "Trunc operand must be integer");
1586 assert(Ty->isInteger() && "Trunc produces only integral");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001587 assert(C->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()&&
1588 "SrcTy must be larger than DestTy for Trunc!");
1589
1590 return getFoldedCast(Instruction::Trunc, C, Ty);
1591}
1592
Reid Spencerbb65ebf2006-12-12 23:36:14 +00001593Constant *ConstantExpr::getSExt(Constant *C, const Type *Ty) {
Chris Lattner03c49532007-01-15 02:27:26 +00001594 assert(C->getType()->isInteger() && "SEXt operand must be integral");
1595 assert(Ty->isInteger() && "SExt produces only integer");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001596 assert(C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1597 "SrcTy must be smaller than DestTy for SExt!");
1598
1599 return getFoldedCast(Instruction::SExt, C, Ty);
Chris Lattnerdd284742004-04-04 23:20:30 +00001600}
1601
Reid Spencerbb65ebf2006-12-12 23:36:14 +00001602Constant *ConstantExpr::getZExt(Constant *C, const Type *Ty) {
Chris Lattner03c49532007-01-15 02:27:26 +00001603 assert(C->getType()->isInteger() && "ZEXt operand must be integral");
1604 assert(Ty->isInteger() && "ZExt produces only integer");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001605 assert(C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1606 "SrcTy must be smaller than DestTy for ZExt!");
1607
1608 return getFoldedCast(Instruction::ZExt, C, Ty);
1609}
1610
1611Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
1612 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1613 C->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()&&
1614 "This is an illegal floating point truncation!");
1615 return getFoldedCast(Instruction::FPTrunc, C, Ty);
1616}
1617
1618Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
1619 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1620 C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1621 "This is an illegal floating point extension!");
1622 return getFoldedCast(Instruction::FPExt, C, Ty);
1623}
1624
1625Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
Chris Lattner03c49532007-01-15 02:27:26 +00001626 assert(C->getType()->isInteger() && Ty->isFloatingPoint() &&
Reid Spencer2546b762007-01-26 07:37:34 +00001627 "This is an illegal i32 to floating point cast!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001628 return getFoldedCast(Instruction::UIToFP, C, Ty);
1629}
1630
1631Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
Chris Lattner03c49532007-01-15 02:27:26 +00001632 assert(C->getType()->isInteger() && Ty->isFloatingPoint() &&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001633 "This is an illegal sint to floating point cast!");
1634 return getFoldedCast(Instruction::SIToFP, C, Ty);
1635}
1636
1637Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
Chris Lattner03c49532007-01-15 02:27:26 +00001638 assert(C->getType()->isFloatingPoint() && Ty->isInteger() &&
Reid Spencer2546b762007-01-26 07:37:34 +00001639 "This is an illegal floating point to i32 cast!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001640 return getFoldedCast(Instruction::FPToUI, C, Ty);
1641}
1642
1643Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
Chris Lattner03c49532007-01-15 02:27:26 +00001644 assert(C->getType()->isFloatingPoint() && Ty->isInteger() &&
Reid Spencer2546b762007-01-26 07:37:34 +00001645 "This is an illegal floating point to i32 cast!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001646 return getFoldedCast(Instruction::FPToSI, C, Ty);
1647}
1648
1649Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
1650 assert(isa<PointerType>(C->getType()) && "PtrToInt source must be pointer");
Chris Lattner03c49532007-01-15 02:27:26 +00001651 assert(DstTy->isInteger() && "PtrToInt destination must be integral");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001652 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
1653}
1654
1655Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
Chris Lattner03c49532007-01-15 02:27:26 +00001656 assert(C->getType()->isInteger() && "IntToPtr source must be integral");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001657 assert(isa<PointerType>(DstTy) && "IntToPtr destination must be a pointer");
1658 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
1659}
1660
1661Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
1662 // BitCast implies a no-op cast of type only. No bits change. However, you
1663 // can't cast pointers to anything but pointers.
1664 const Type *SrcTy = C->getType();
1665 assert((isa<PointerType>(SrcTy) == isa<PointerType>(DstTy)) &&
Reid Spencer5c140882006-12-04 20:17:56 +00001666 "BitCast cannot cast pointer to non-pointer and vice versa");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001667
1668 // Now we know we're not dealing with mismatched pointer casts (ptr->nonptr
1669 // or nonptr->ptr). For all the other types, the cast is okay if source and
1670 // destination bit widths are identical.
1671 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1672 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
Reid Spencer5c140882006-12-04 20:17:56 +00001673 assert(SrcBitSize == DstBitSize && "BitCast requies types of same width");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001674 return getFoldedCast(Instruction::BitCast, C, DstTy);
Chris Lattnerdd284742004-04-04 23:20:30 +00001675}
1676
Alkis Evlogimenosda5de052004-10-24 01:41:10 +00001677Constant *ConstantExpr::getSizeOf(const Type *Ty) {
Chris Lattneracc4e542004-12-13 19:48:51 +00001678 // sizeof is implemented as: (ulong) gep (Ty*)null, 1
Chris Lattnerb5d70302007-02-19 20:01:23 +00001679 Constant *GEPIdx = ConstantInt::get(Type::Int32Ty, 1);
1680 Constant *GEP =
1681 getGetElementPtr(getNullValue(PointerType::get(Ty)), &GEPIdx, 1);
1682 return getCast(Instruction::PtrToInt, GEP, Type::Int64Ty);
Alkis Evlogimenos9160d5f2005-03-19 11:40:31 +00001683}
1684
Chris Lattnerb50d1352003-10-05 00:17:43 +00001685Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
Reid Spencera009d0d2006-12-04 21:35:24 +00001686 Constant *C1, Constant *C2) {
Chris Lattner38a9bcd2003-05-21 17:49:25 +00001687 // Check the operands for consistency first
Reid Spencer7eb55b32006-11-02 01:53:59 +00001688 assert(Opcode >= Instruction::BinaryOpsBegin &&
1689 Opcode < Instruction::BinaryOpsEnd &&
Chris Lattner38a9bcd2003-05-21 17:49:25 +00001690 "Invalid opcode in binary constant expression");
1691 assert(C1->getType() == C2->getType() &&
1692 "Operand types in binary constant expression should match");
Chris Lattnerb50d1352003-10-05 00:17:43 +00001693
Reid Spencer542964f2007-01-11 18:21:29 +00001694 if (ReqTy == C1->getType() || ReqTy == Type::Int1Ty)
Chris Lattnerb50d1352003-10-05 00:17:43 +00001695 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1696 return FC; // Fold a few common cases...
Chris Lattneracdbe712003-04-17 19:24:48 +00001697
Chris Lattner2b383d2e2003-05-13 21:37:02 +00001698 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
Reid Spencera009d0d2006-12-04 21:35:24 +00001699 ExprMapKeyType Key(Opcode, argVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001700 return ExprConstants->getOrCreate(ReqTy, Key);
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001701}
1702
Reid Spencer266e42b2006-12-23 06:05:41 +00001703Constant *ConstantExpr::getCompareTy(unsigned short predicate,
Reid Spencera009d0d2006-12-04 21:35:24 +00001704 Constant *C1, Constant *C2) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001705 switch (predicate) {
1706 default: assert(0 && "Invalid CmpInst predicate");
1707 case FCmpInst::FCMP_FALSE: case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_OGT:
1708 case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OLE:
1709 case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_ORD: case FCmpInst::FCMP_UNO:
1710 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UGT: case FCmpInst::FCMP_UGE:
1711 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_ULE: case FCmpInst::FCMP_UNE:
1712 case FCmpInst::FCMP_TRUE:
1713 return getFCmp(predicate, C1, C2);
1714 case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_UGT:
1715 case ICmpInst::ICMP_UGE: case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE:
1716 case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_SGE: case ICmpInst::ICMP_SLT:
1717 case ICmpInst::ICMP_SLE:
1718 return getICmp(predicate, C1, C2);
1719 }
Reid Spencera009d0d2006-12-04 21:35:24 +00001720}
1721
1722Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001723#ifndef NDEBUG
1724 switch (Opcode) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00001725 case Instruction::Add:
1726 case Instruction::Sub:
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001727 case Instruction::Mul:
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001728 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Chris Lattner03c49532007-01-15 02:27:26 +00001729 assert((C1->getType()->isInteger() || C1->getType()->isFloatingPoint() ||
Reid Spencerd84d35b2007-02-15 02:26:10 +00001730 isa<VectorType>(C1->getType())) &&
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001731 "Tried to create an arithmetic operation on a non-arithmetic type!");
1732 break;
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001733 case Instruction::UDiv:
1734 case Instruction::SDiv:
1735 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00001736 assert((C1->getType()->isInteger() || (isa<VectorType>(C1->getType()) &&
1737 cast<VectorType>(C1->getType())->getElementType()->isInteger())) &&
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001738 "Tried to create an arithmetic operation on a non-arithmetic type!");
1739 break;
1740 case Instruction::FDiv:
1741 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00001742 assert((C1->getType()->isFloatingPoint() || (isa<VectorType>(C1->getType())
1743 && cast<VectorType>(C1->getType())->getElementType()->isFloatingPoint()))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001744 && "Tried to create an arithmetic operation on a non-arithmetic type!");
1745 break;
Reid Spencer7eb55b32006-11-02 01:53:59 +00001746 case Instruction::URem:
1747 case Instruction::SRem:
1748 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00001749 assert((C1->getType()->isInteger() || (isa<VectorType>(C1->getType()) &&
1750 cast<VectorType>(C1->getType())->getElementType()->isInteger())) &&
Reid Spencer7eb55b32006-11-02 01:53:59 +00001751 "Tried to create an arithmetic operation on a non-arithmetic type!");
1752 break;
1753 case Instruction::FRem:
1754 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00001755 assert((C1->getType()->isFloatingPoint() || (isa<VectorType>(C1->getType())
1756 && cast<VectorType>(C1->getType())->getElementType()->isFloatingPoint()))
Reid Spencer7eb55b32006-11-02 01:53:59 +00001757 && "Tried to create an arithmetic operation on a non-arithmetic type!");
1758 break;
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001759 case Instruction::And:
1760 case Instruction::Or:
1761 case Instruction::Xor:
1762 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00001763 assert((C1->getType()->isInteger() || isa<VectorType>(C1->getType())) &&
Misha Brukman3852f652005-01-27 06:46:38 +00001764 "Tried to create a logical operation on a non-integral type!");
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001765 break;
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001766 case Instruction::Shl:
Reid Spencerfdff9382006-11-08 06:47:33 +00001767 case Instruction::LShr:
1768 case Instruction::AShr:
Reid Spencer2341c222007-02-02 02:16:23 +00001769 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Chris Lattner03c49532007-01-15 02:27:26 +00001770 assert(C1->getType()->isInteger() &&
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001771 "Tried to create a shift operation on a non-integer type!");
1772 break;
1773 default:
1774 break;
1775 }
1776#endif
1777
Reid Spencera009d0d2006-12-04 21:35:24 +00001778 return getTy(C1->getType(), Opcode, C1, C2);
1779}
1780
Reid Spencer266e42b2006-12-23 06:05:41 +00001781Constant *ConstantExpr::getCompare(unsigned short pred,
Reid Spencera009d0d2006-12-04 21:35:24 +00001782 Constant *C1, Constant *C2) {
1783 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Reid Spencer266e42b2006-12-23 06:05:41 +00001784 return getCompareTy(pred, C1, C2);
Chris Lattner29ca2c62004-08-04 18:50:09 +00001785}
1786
Chris Lattner6e415c02004-03-12 05:54:04 +00001787Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
1788 Constant *V1, Constant *V2) {
Reid Spencer2546b762007-01-26 07:37:34 +00001789 assert(C->getType() == Type::Int1Ty && "Select condition must be i1!");
Chris Lattner6e415c02004-03-12 05:54:04 +00001790 assert(V1->getType() == V2->getType() && "Select value types must match!");
1791 assert(V1->getType()->isFirstClassType() && "Cannot select aggregate type!");
1792
1793 if (ReqTy == V1->getType())
1794 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1795 return SC; // Fold common cases
1796
1797 std::vector<Constant*> argVec(3, C);
1798 argVec[1] = V1;
1799 argVec[2] = V2;
Reid Spenceree3c9912006-12-04 05:19:50 +00001800 ExprMapKeyType Key(Instruction::Select, argVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001801 return ExprConstants->getOrCreate(ReqTy, Key);
Chris Lattner6e415c02004-03-12 05:54:04 +00001802}
1803
Chris Lattnerb50d1352003-10-05 00:17:43 +00001804Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
Chris Lattner302116a2007-01-31 04:40:28 +00001805 Value* const *Idxs,
1806 unsigned NumIdx) {
David Greenec656cbb2007-09-04 15:46:09 +00001807 assert(GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx, true) &&
Chris Lattner04b60fe2004-02-16 20:46:13 +00001808 "GEP indices invalid!");
1809
Chris Lattner302116a2007-01-31 04:40:28 +00001810 if (Constant *FC = ConstantFoldGetElementPtr(C, (Constant**)Idxs, NumIdx))
Chris Lattneracdbe712003-04-17 19:24:48 +00001811 return FC; // Fold a few common cases...
Chris Lattner04b60fe2004-02-16 20:46:13 +00001812
Chris Lattnerb50d1352003-10-05 00:17:43 +00001813 assert(isa<PointerType>(C->getType()) &&
Chris Lattner98fa07b2003-05-23 20:03:32 +00001814 "Non-pointer type for constant GetElementPtr expression");
Vikram S. Adve4c485332002-07-15 18:19:33 +00001815 // Look up the constant in the table first to ensure uniqueness
Chris Lattner13128ab2004-10-11 22:52:25 +00001816 std::vector<Constant*> ArgVec;
Chris Lattner302116a2007-01-31 04:40:28 +00001817 ArgVec.reserve(NumIdx+1);
Chris Lattner13128ab2004-10-11 22:52:25 +00001818 ArgVec.push_back(C);
Chris Lattner302116a2007-01-31 04:40:28 +00001819 for (unsigned i = 0; i != NumIdx; ++i)
1820 ArgVec.push_back(cast<Constant>(Idxs[i]));
1821 const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001822 return ExprConstants->getOrCreate(ReqTy, Key);
Vikram S. Adve4c485332002-07-15 18:19:33 +00001823}
1824
Chris Lattner302116a2007-01-31 04:40:28 +00001825Constant *ConstantExpr::getGetElementPtr(Constant *C, Value* const *Idxs,
1826 unsigned NumIdx) {
Chris Lattnerb50d1352003-10-05 00:17:43 +00001827 // Get the result type of the getelementptr!
Chris Lattner302116a2007-01-31 04:40:28 +00001828 const Type *Ty =
David Greenec656cbb2007-09-04 15:46:09 +00001829 GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx, true);
Chris Lattnerb50d1352003-10-05 00:17:43 +00001830 assert(Ty && "GEP indices invalid!");
Chris Lattner302116a2007-01-31 04:40:28 +00001831 return getGetElementPtrTy(PointerType::get(Ty), C, Idxs, NumIdx);
Chris Lattner13128ab2004-10-11 22:52:25 +00001832}
1833
Chris Lattner302116a2007-01-31 04:40:28 +00001834Constant *ConstantExpr::getGetElementPtr(Constant *C, Constant* const *Idxs,
1835 unsigned NumIdx) {
1836 return getGetElementPtr(C, (Value* const *)Idxs, NumIdx);
Chris Lattnerb50d1352003-10-05 00:17:43 +00001837}
1838
Chris Lattner302116a2007-01-31 04:40:28 +00001839
Reid Spenceree3c9912006-12-04 05:19:50 +00001840Constant *
1841ConstantExpr::getICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1842 assert(LHS->getType() == RHS->getType());
1843 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
1844 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
1845
Reid Spencer266e42b2006-12-23 06:05:41 +00001846 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
Reid Spenceree3c9912006-12-04 05:19:50 +00001847 return FC; // Fold a few common cases...
1848
1849 // Look up the constant in the table first to ensure uniqueness
1850 std::vector<Constant*> ArgVec;
1851 ArgVec.push_back(LHS);
1852 ArgVec.push_back(RHS);
Reid Spencerb1537492006-12-24 18:42:29 +00001853 // Get the key type with both the opcode and predicate
Reid Spenceree3c9912006-12-04 05:19:50 +00001854 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
Reid Spencer542964f2007-01-11 18:21:29 +00001855 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
Reid Spenceree3c9912006-12-04 05:19:50 +00001856}
1857
1858Constant *
1859ConstantExpr::getFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1860 assert(LHS->getType() == RHS->getType());
1861 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
1862
Reid Spencer266e42b2006-12-23 06:05:41 +00001863 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
Reid Spenceree3c9912006-12-04 05:19:50 +00001864 return FC; // Fold a few common cases...
1865
1866 // Look up the constant in the table first to ensure uniqueness
1867 std::vector<Constant*> ArgVec;
1868 ArgVec.push_back(LHS);
1869 ArgVec.push_back(RHS);
Reid Spencerb1537492006-12-24 18:42:29 +00001870 // Get the key type with both the opcode and predicate
Reid Spenceree3c9912006-12-04 05:19:50 +00001871 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
Reid Spencer542964f2007-01-11 18:21:29 +00001872 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
Reid Spenceree3c9912006-12-04 05:19:50 +00001873}
1874
Robert Bocchino23004482006-01-10 19:05:34 +00001875Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
1876 Constant *Idx) {
Robert Bocchinode7f1c92006-01-10 20:03:46 +00001877 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
1878 return FC; // Fold a few common cases...
Robert Bocchino23004482006-01-10 19:05:34 +00001879 // Look up the constant in the table first to ensure uniqueness
1880 std::vector<Constant*> ArgVec(1, Val);
1881 ArgVec.push_back(Idx);
Reid Spenceree3c9912006-12-04 05:19:50 +00001882 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001883 return ExprConstants->getOrCreate(ReqTy, Key);
Robert Bocchino23004482006-01-10 19:05:34 +00001884}
1885
1886Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001887 assert(isa<VectorType>(Val->getType()) &&
Reid Spencer09575ba2007-02-15 03:39:18 +00001888 "Tried to create extractelement operation on non-vector type!");
Reid Spencer8d9336d2006-12-31 05:26:44 +00001889 assert(Idx->getType() == Type::Int32Ty &&
Reid Spencer2546b762007-01-26 07:37:34 +00001890 "Extractelement index must be i32 type!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00001891 return getExtractElementTy(cast<VectorType>(Val->getType())->getElementType(),
Robert Bocchino23004482006-01-10 19:05:34 +00001892 Val, Idx);
1893}
Chris Lattnerb50d1352003-10-05 00:17:43 +00001894
Robert Bocchinoca27f032006-01-17 20:07:22 +00001895Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
1896 Constant *Elt, Constant *Idx) {
1897 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
1898 return FC; // Fold a few common cases...
1899 // Look up the constant in the table first to ensure uniqueness
1900 std::vector<Constant*> ArgVec(1, Val);
1901 ArgVec.push_back(Elt);
1902 ArgVec.push_back(Idx);
Reid Spenceree3c9912006-12-04 05:19:50 +00001903 const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001904 return ExprConstants->getOrCreate(ReqTy, Key);
Robert Bocchinoca27f032006-01-17 20:07:22 +00001905}
1906
1907Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
1908 Constant *Idx) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001909 assert(isa<VectorType>(Val->getType()) &&
Reid Spencer09575ba2007-02-15 03:39:18 +00001910 "Tried to create insertelement operation on non-vector type!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00001911 assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType()
Robert Bocchinoca27f032006-01-17 20:07:22 +00001912 && "Insertelement types must match!");
Reid Spencer8d9336d2006-12-31 05:26:44 +00001913 assert(Idx->getType() == Type::Int32Ty &&
Reid Spencer2546b762007-01-26 07:37:34 +00001914 "Insertelement index must be i32 type!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00001915 return getInsertElementTy(cast<VectorType>(Val->getType())->getElementType(),
Robert Bocchinoca27f032006-01-17 20:07:22 +00001916 Val, Elt, Idx);
1917}
1918
Chris Lattnerbbe0a422006-04-08 01:18:18 +00001919Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
1920 Constant *V2, Constant *Mask) {
1921 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
1922 return FC; // Fold a few common cases...
1923 // Look up the constant in the table first to ensure uniqueness
1924 std::vector<Constant*> ArgVec(1, V1);
1925 ArgVec.push_back(V2);
1926 ArgVec.push_back(Mask);
Reid Spenceree3c9912006-12-04 05:19:50 +00001927 const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001928 return ExprConstants->getOrCreate(ReqTy, Key);
Chris Lattnerbbe0a422006-04-08 01:18:18 +00001929}
1930
1931Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
1932 Constant *Mask) {
1933 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
1934 "Invalid shuffle vector constant expr operands!");
1935 return getShuffleVectorTy(V1->getType(), V1, V2, Mask);
1936}
1937
Reid Spencer2eadb532007-01-21 00:29:26 +00001938Constant *ConstantExpr::getZeroValueForNegationExpr(const Type *Ty) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001939 if (const VectorType *PTy = dyn_cast<VectorType>(Ty))
Reid Spencer6598ca82007-01-21 02:29:10 +00001940 if (PTy->getElementType()->isFloatingPoint()) {
1941 std::vector<Constant*> zeros(PTy->getNumElements(),
Dale Johannesen98d3a082007-09-14 22:26:36 +00001942 ConstantFP::getNegativeZero(PTy->getElementType()));
Reid Spencerd84d35b2007-02-15 02:26:10 +00001943 return ConstantVector::get(PTy, zeros);
Reid Spencer6598ca82007-01-21 02:29:10 +00001944 }
Reid Spencer2eadb532007-01-21 00:29:26 +00001945
Dale Johannesen98d3a082007-09-14 22:26:36 +00001946 if (Ty->isFloatingPoint())
1947 return ConstantFP::getNegativeZero(Ty);
Reid Spencer2eadb532007-01-21 00:29:26 +00001948
1949 return Constant::getNullValue(Ty);
1950}
1951
Vikram S. Adve4c485332002-07-15 18:19:33 +00001952// destroyConstant - Remove the constant from the constant table...
1953//
1954void ConstantExpr::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00001955 ExprConstants->remove(this);
Vikram S. Adve4c485332002-07-15 18:19:33 +00001956 destroyConstantImpl();
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001957}
1958
Chris Lattner3cd8c562002-07-30 18:54:25 +00001959const char *ConstantExpr::getOpcodeName() const {
1960 return Instruction::getOpcodeName(getOpcode());
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001961}
Reid Spencer1ebe1ab2004-07-17 23:48:33 +00001962
Chris Lattnerc4062ba2005-10-03 21:58:36 +00001963//===----------------------------------------------------------------------===//
1964// replaceUsesOfWithOnConstant implementations
1965
Chris Lattner913849b2007-08-21 00:55:23 +00001966/// replaceUsesOfWithOnConstant - Update this constant array to change uses of
1967/// 'From' to be uses of 'To'. This must update the uniquing data structures
1968/// etc.
1969///
1970/// Note that we intentionally replace all uses of From with To here. Consider
1971/// a large array that uses 'From' 1000 times. By handling this case all here,
1972/// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
1973/// single invocation handles all 1000 uses. Handling them one at a time would
1974/// work, but would be really slow because it would have to unique each updated
1975/// array instance.
Chris Lattnerc4062ba2005-10-03 21:58:36 +00001976void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
Chris Lattner7a1450d2005-10-04 18:13:04 +00001977 Use *U) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00001978 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
Chris Lattner8760ec72005-10-04 01:17:50 +00001979 Constant *ToC = cast<Constant>(To);
Chris Lattnerdff59112005-10-04 18:47:09 +00001980
Jim Laskeyc03caef2006-07-17 17:38:29 +00001981 std::pair<ArrayConstantsTy::MapKey, Constant*> Lookup;
Chris Lattnerb64419a2005-10-03 22:51:37 +00001982 Lookup.first.first = getType();
1983 Lookup.second = this;
Chris Lattnerdff59112005-10-04 18:47:09 +00001984
Chris Lattnerb64419a2005-10-03 22:51:37 +00001985 std::vector<Constant*> &Values = Lookup.first.second;
1986 Values.reserve(getNumOperands()); // Build replacement array.
Chris Lattnerdff59112005-10-04 18:47:09 +00001987
Chris Lattner8760ec72005-10-04 01:17:50 +00001988 // Fill values with the modified operands of the constant array. Also,
1989 // compute whether this turns into an all-zeros array.
Chris Lattnerdff59112005-10-04 18:47:09 +00001990 bool isAllZeros = false;
Chris Lattner913849b2007-08-21 00:55:23 +00001991 unsigned NumUpdated = 0;
Chris Lattnerdff59112005-10-04 18:47:09 +00001992 if (!ToC->isNullValue()) {
Chris Lattner913849b2007-08-21 00:55:23 +00001993 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1994 Constant *Val = cast<Constant>(O->get());
1995 if (Val == From) {
1996 Val = ToC;
1997 ++NumUpdated;
1998 }
1999 Values.push_back(Val);
2000 }
Chris Lattnerdff59112005-10-04 18:47:09 +00002001 } else {
2002 isAllZeros = true;
2003 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2004 Constant *Val = cast<Constant>(O->get());
Chris Lattner913849b2007-08-21 00:55:23 +00002005 if (Val == From) {
2006 Val = ToC;
2007 ++NumUpdated;
2008 }
Chris Lattnerdff59112005-10-04 18:47:09 +00002009 Values.push_back(Val);
2010 if (isAllZeros) isAllZeros = Val->isNullValue();
2011 }
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002012 }
2013
Chris Lattnerb64419a2005-10-03 22:51:37 +00002014 Constant *Replacement = 0;
2015 if (isAllZeros) {
2016 Replacement = ConstantAggregateZero::get(getType());
2017 } else {
2018 // Check to see if we have this array type already.
2019 bool Exists;
Jim Laskeyc03caef2006-07-17 17:38:29 +00002020 ArrayConstantsTy::MapTy::iterator I =
Chris Lattner69edc982006-09-28 00:35:06 +00002021 ArrayConstants->InsertOrGetItem(Lookup, Exists);
Chris Lattnerb64419a2005-10-03 22:51:37 +00002022
2023 if (Exists) {
2024 Replacement = I->second;
2025 } else {
2026 // Okay, the new shape doesn't exist in the system yet. Instead of
2027 // creating a new constant array, inserting it, replaceallusesof'ing the
2028 // old with the new, then deleting the old... just update the current one
2029 // in place!
Chris Lattner69edc982006-09-28 00:35:06 +00002030 ArrayConstants->MoveConstantToNewSlot(this, I);
Chris Lattnerb64419a2005-10-03 22:51:37 +00002031
Chris Lattner913849b2007-08-21 00:55:23 +00002032 // Update to the new value. Optimize for the case when we have a single
2033 // operand that we're changing, but handle bulk updates efficiently.
2034 if (NumUpdated == 1) {
2035 unsigned OperandToUpdate = U-OperandList;
2036 assert(getOperand(OperandToUpdate) == From &&
2037 "ReplaceAllUsesWith broken!");
2038 setOperand(OperandToUpdate, ToC);
2039 } else {
2040 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2041 if (getOperand(i) == From)
2042 setOperand(i, ToC);
2043 }
Chris Lattnerb64419a2005-10-03 22:51:37 +00002044 return;
2045 }
2046 }
2047
2048 // Otherwise, I do need to replace this with an existing value.
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002049 assert(Replacement != this && "I didn't contain From!");
2050
Chris Lattner7a1450d2005-10-04 18:13:04 +00002051 // Everyone using this now uses the replacement.
2052 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002053
2054 // Delete the old constant!
2055 destroyConstant();
2056}
2057
2058void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
Chris Lattner7a1450d2005-10-04 18:13:04 +00002059 Use *U) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002060 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
Chris Lattner8760ec72005-10-04 01:17:50 +00002061 Constant *ToC = cast<Constant>(To);
2062
Chris Lattnerdff59112005-10-04 18:47:09 +00002063 unsigned OperandToUpdate = U-OperandList;
2064 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
2065
Jim Laskeyc03caef2006-07-17 17:38:29 +00002066 std::pair<StructConstantsTy::MapKey, Constant*> Lookup;
Chris Lattner8760ec72005-10-04 01:17:50 +00002067 Lookup.first.first = getType();
2068 Lookup.second = this;
2069 std::vector<Constant*> &Values = Lookup.first.second;
2070 Values.reserve(getNumOperands()); // Build replacement struct.
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002071
Chris Lattnerdff59112005-10-04 18:47:09 +00002072
Chris Lattner8760ec72005-10-04 01:17:50 +00002073 // Fill values with the modified operands of the constant struct. Also,
2074 // compute whether this turns into an all-zeros struct.
Chris Lattnerdff59112005-10-04 18:47:09 +00002075 bool isAllZeros = false;
2076 if (!ToC->isNullValue()) {
2077 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
2078 Values.push_back(cast<Constant>(O->get()));
2079 } else {
2080 isAllZeros = true;
2081 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2082 Constant *Val = cast<Constant>(O->get());
2083 Values.push_back(Val);
2084 if (isAllZeros) isAllZeros = Val->isNullValue();
2085 }
Chris Lattner8760ec72005-10-04 01:17:50 +00002086 }
Chris Lattnerdff59112005-10-04 18:47:09 +00002087 Values[OperandToUpdate] = ToC;
2088
Chris Lattner8760ec72005-10-04 01:17:50 +00002089 Constant *Replacement = 0;
2090 if (isAllZeros) {
2091 Replacement = ConstantAggregateZero::get(getType());
2092 } else {
2093 // Check to see if we have this array type already.
2094 bool Exists;
Jim Laskeyc03caef2006-07-17 17:38:29 +00002095 StructConstantsTy::MapTy::iterator I =
Chris Lattner69edc982006-09-28 00:35:06 +00002096 StructConstants->InsertOrGetItem(Lookup, Exists);
Chris Lattner8760ec72005-10-04 01:17:50 +00002097
2098 if (Exists) {
2099 Replacement = I->second;
2100 } else {
2101 // Okay, the new shape doesn't exist in the system yet. Instead of
2102 // creating a new constant struct, inserting it, replaceallusesof'ing the
2103 // old with the new, then deleting the old... just update the current one
2104 // in place!
Chris Lattner69edc982006-09-28 00:35:06 +00002105 StructConstants->MoveConstantToNewSlot(this, I);
Chris Lattner8760ec72005-10-04 01:17:50 +00002106
Chris Lattnerdff59112005-10-04 18:47:09 +00002107 // Update to the new value.
2108 setOperand(OperandToUpdate, ToC);
Chris Lattner8760ec72005-10-04 01:17:50 +00002109 return;
2110 }
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002111 }
2112
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002113 assert(Replacement != this && "I didn't contain From!");
2114
Chris Lattner7a1450d2005-10-04 18:13:04 +00002115 // Everyone using this now uses the replacement.
2116 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002117
2118 // Delete the old constant!
2119 destroyConstant();
2120}
2121
Reid Spencerd84d35b2007-02-15 02:26:10 +00002122void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
Chris Lattner7a1450d2005-10-04 18:13:04 +00002123 Use *U) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002124 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2125
2126 std::vector<Constant*> Values;
2127 Values.reserve(getNumOperands()); // Build replacement array...
2128 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2129 Constant *Val = getOperand(i);
2130 if (Val == From) Val = cast<Constant>(To);
2131 Values.push_back(Val);
2132 }
2133
Reid Spencerd84d35b2007-02-15 02:26:10 +00002134 Constant *Replacement = ConstantVector::get(getType(), Values);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002135 assert(Replacement != this && "I didn't contain From!");
2136
Chris Lattner7a1450d2005-10-04 18:13:04 +00002137 // Everyone using this now uses the replacement.
2138 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002139
2140 // Delete the old constant!
2141 destroyConstant();
2142}
2143
2144void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
Chris Lattner7a1450d2005-10-04 18:13:04 +00002145 Use *U) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002146 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2147 Constant *To = cast<Constant>(ToV);
2148
2149 Constant *Replacement = 0;
2150 if (getOpcode() == Instruction::GetElementPtr) {
Chris Lattnerb5d70302007-02-19 20:01:23 +00002151 SmallVector<Constant*, 8> Indices;
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002152 Constant *Pointer = getOperand(0);
2153 Indices.reserve(getNumOperands()-1);
2154 if (Pointer == From) Pointer = To;
2155
2156 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2157 Constant *Val = getOperand(i);
2158 if (Val == From) Val = To;
2159 Indices.push_back(Val);
2160 }
Chris Lattnerb5d70302007-02-19 20:01:23 +00002161 Replacement = ConstantExpr::getGetElementPtr(Pointer,
2162 &Indices[0], Indices.size());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002163 } else if (isCast()) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002164 assert(getOperand(0) == From && "Cast only has one use!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002165 Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002166 } else if (getOpcode() == Instruction::Select) {
2167 Constant *C1 = getOperand(0);
2168 Constant *C2 = getOperand(1);
2169 Constant *C3 = getOperand(2);
2170 if (C1 == From) C1 = To;
2171 if (C2 == From) C2 = To;
2172 if (C3 == From) C3 = To;
2173 Replacement = ConstantExpr::getSelect(C1, C2, C3);
Robert Bocchino23004482006-01-10 19:05:34 +00002174 } else if (getOpcode() == Instruction::ExtractElement) {
2175 Constant *C1 = getOperand(0);
2176 Constant *C2 = getOperand(1);
2177 if (C1 == From) C1 = To;
2178 if (C2 == From) C2 = To;
2179 Replacement = ConstantExpr::getExtractElement(C1, C2);
Chris Lattnera93b4b52006-04-08 05:09:48 +00002180 } else if (getOpcode() == Instruction::InsertElement) {
2181 Constant *C1 = getOperand(0);
2182 Constant *C2 = getOperand(1);
2183 Constant *C3 = getOperand(1);
2184 if (C1 == From) C1 = To;
2185 if (C2 == From) C2 = To;
2186 if (C3 == From) C3 = To;
2187 Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2188 } else if (getOpcode() == Instruction::ShuffleVector) {
2189 Constant *C1 = getOperand(0);
2190 Constant *C2 = getOperand(1);
2191 Constant *C3 = getOperand(2);
2192 if (C1 == From) C1 = To;
2193 if (C2 == From) C2 = To;
2194 if (C3 == From) C3 = To;
2195 Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
Reid Spenceree3c9912006-12-04 05:19:50 +00002196 } else if (isCompare()) {
2197 Constant *C1 = getOperand(0);
2198 Constant *C2 = getOperand(1);
2199 if (C1 == From) C1 = To;
2200 if (C2 == From) C2 = To;
2201 if (getOpcode() == Instruction::ICmp)
2202 Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
2203 else
2204 Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002205 } else if (getNumOperands() == 2) {
2206 Constant *C1 = getOperand(0);
2207 Constant *C2 = getOperand(1);
2208 if (C1 == From) C1 = To;
2209 if (C2 == From) C2 = To;
2210 Replacement = ConstantExpr::get(getOpcode(), C1, C2);
2211 } else {
2212 assert(0 && "Unknown ConstantExpr type!");
2213 return;
2214 }
2215
2216 assert(Replacement != this && "I didn't contain From!");
2217
Chris Lattner7a1450d2005-10-04 18:13:04 +00002218 // Everyone using this now uses the replacement.
2219 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002220
2221 // Delete the old constant!
2222 destroyConstant();
2223}
2224
2225
Jim Laskey2698f0d2006-03-08 18:11:07 +00002226/// getStringValue - Turn an LLVM constant pointer that eventually points to a
2227/// global into a string value. Return an empty string if we can't do it.
Evan Cheng38280c02006-03-10 23:52:03 +00002228/// Parameter Chop determines if the result is chopped at the first null
2229/// terminator.
Jim Laskey2698f0d2006-03-08 18:11:07 +00002230///
Evan Cheng38280c02006-03-10 23:52:03 +00002231std::string Constant::getStringValue(bool Chop, unsigned Offset) {
Jim Laskey2698f0d2006-03-08 18:11:07 +00002232 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(this)) {
2233 if (GV->hasInitializer() && isa<ConstantArray>(GV->getInitializer())) {
2234 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
2235 if (Init->isString()) {
2236 std::string Result = Init->getAsString();
2237 if (Offset < Result.size()) {
2238 // If we are pointing INTO The string, erase the beginning...
2239 Result.erase(Result.begin(), Result.begin()+Offset);
2240
2241 // Take off the null terminator, and any string fragments after it.
Evan Cheng38280c02006-03-10 23:52:03 +00002242 if (Chop) {
2243 std::string::size_type NullPos = Result.find_first_of((char)0);
2244 if (NullPos != std::string::npos)
2245 Result.erase(Result.begin()+NullPos, Result.end());
2246 }
Jim Laskey2698f0d2006-03-08 18:11:07 +00002247 return Result;
2248 }
2249 }
2250 }
2251 } else if (Constant *C = dyn_cast<Constant>(this)) {
2252 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
Evan Cheng2c5e5302006-03-11 00:13:10 +00002253 return GV->getStringValue(Chop, Offset);
Jim Laskey2698f0d2006-03-08 18:11:07 +00002254 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2255 if (CE->getOpcode() == Instruction::GetElementPtr) {
2256 // Turn a gep into the specified offset.
2257 if (CE->getNumOperands() == 3 &&
2258 cast<Constant>(CE->getOperand(1))->isNullValue() &&
2259 isa<ConstantInt>(CE->getOperand(2))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002260 Offset += cast<ConstantInt>(CE->getOperand(2))->getZExtValue();
Evan Cheng2c5e5302006-03-11 00:13:10 +00002261 return CE->getOperand(0)->getStringValue(Chop, Offset);
Jim Laskey2698f0d2006-03-08 18:11:07 +00002262 }
2263 }
2264 }
2265 }
2266 return "";
2267}