blob: 0f7ca0aaa0811c746652771cc588b0d4261840c3 [file] [log] [blame]
Chris Lattner2b383d2e2003-05-13 21:37:02 +00001//===-- Constants.cpp - Implement Constant nodes --------------------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner2f7c9632001-06-06 20:29:01 +00009//
Chris 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:
Chris Lattnerb5b3e312008-04-09 00:45:01 +0000111 return ConstantFP::get(APFloat(APInt(32, 0)));
Chris Lattnerdbcb0d32007-02-20 05:46:39 +0000112 case Type::DoubleTyID:
Chris Lattnerb5b3e312008-04-09 00:45:01 +0000113 return ConstantFP::get(APFloat(APInt(64, 0)));
Dale Johannesenbdad8092007-08-09 22:51:36 +0000114 case Type::X86_FP80TyID:
Chris Lattnerb5b3e312008-04-09 00:45:01 +0000115 return ConstantFP::get(APFloat(APInt(80, 2, zero)));
Dale Johannesenbdad8092007-08-09 22:51:36 +0000116 case Type::FP128TyID:
Chris Lattnerb5b3e312008-04-09 00:45:01 +0000117 return ConstantFP::get(APFloat(APInt(128, 2, zero), true));
Dale Johannesen98d3a082007-09-14 22:26:36 +0000118 case Type::PPC_FP128TyID:
Chris Lattnerb5b3e312008-04-09 00:45:01 +0000119 return ConstantFP::get(APFloat(APInt(128, 2, zero)));
Misha Brukmanb1c93172005-04-21 23:48:37 +0000120 case Type::PointerTyID:
Chris Lattnerb1585a92002-08-13 17:50:20 +0000121 return ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattner9fba3da2004-02-15 05:53:04 +0000122 case Type::StructTyID:
123 case Type::ArrayTyID:
Reid Spencerd84d35b2007-02-15 02:26:10 +0000124 case Type::VectorTyID:
Chris Lattner9fba3da2004-02-15 05:53:04 +0000125 return ConstantAggregateZero::get(Ty);
Chris Lattnerb1585a92002-08-13 17:50:20 +0000126 default:
Reid Spencercf394bf2004-07-04 11:51:24 +0000127 // Function, Label, or Opaque type?
128 assert(!"Cannot create a null constant of that type!");
Chris Lattnerb1585a92002-08-13 17:50:20 +0000129 return 0;
130 }
131}
132
Chris Lattner72e39582007-06-15 06:10:53 +0000133Constant *Constant::getAllOnesValue(const Type *Ty) {
134 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty))
135 return ConstantInt::get(APInt::getAllOnesValue(ITy->getBitWidth()));
136 return ConstantVector::getAllOnesValue(cast<VectorType>(Ty));
137}
Chris Lattnerb1585a92002-08-13 17:50:20 +0000138
139// Static constructor to create an integral constant with all bits set
Zhou Sheng75b871f2007-01-11 12:24:14 +0000140ConstantInt *ConstantInt::getAllOnesValue(const Type *Ty) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000141 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty))
Reid Spencerd1bbfa52007-03-01 19:30:34 +0000142 return ConstantInt::get(APInt::getAllOnesValue(ITy->getBitWidth()));
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000143 return 0;
Chris Lattnerb1585a92002-08-13 17:50:20 +0000144}
145
Dan Gohman30978072007-05-24 14:36:04 +0000146/// @returns the value for a vector integer constant of the given type that
Chris Lattnerecab54c2007-01-04 01:49:26 +0000147/// has all its bits set to true.
148/// @brief Get the all ones value
Reid Spencerd84d35b2007-02-15 02:26:10 +0000149ConstantVector *ConstantVector::getAllOnesValue(const VectorType *Ty) {
Chris Lattnerecab54c2007-01-04 01:49:26 +0000150 std::vector<Constant*> Elts;
151 Elts.resize(Ty->getNumElements(),
Zhou Sheng75b871f2007-01-11 12:24:14 +0000152 ConstantInt::getAllOnesValue(Ty->getElementType()));
Dan Gohman30978072007-05-24 14:36:04 +0000153 assert(Elts[0] && "Not a vector integer type!");
Reid Spencerd84d35b2007-02-15 02:26:10 +0000154 return cast<ConstantVector>(ConstantVector::get(Elts));
Chris Lattnerecab54c2007-01-04 01:49:26 +0000155}
156
157
Chris Lattner2f7c9632001-06-06 20:29:01 +0000158//===----------------------------------------------------------------------===//
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000159// ConstantInt
Chris Lattner2f7c9632001-06-06 20:29:01 +0000160//===----------------------------------------------------------------------===//
161
Reid Spencerb31bffe2007-02-26 23:54:03 +0000162ConstantInt::ConstantInt(const IntegerType *Ty, const APInt& V)
Chris Lattner5db2f472007-02-20 05:55:46 +0000163 : Constant(Ty, ConstantIntVal, 0, 0), Val(V) {
Reid Spencerb31bffe2007-02-26 23:54:03 +0000164 assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
Chris Lattner2f7c9632001-06-06 20:29:01 +0000165}
166
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000167ConstantInt *ConstantInt::TheTrueVal = 0;
168ConstantInt *ConstantInt::TheFalseVal = 0;
169
170namespace llvm {
171 void CleanupTrueFalse(void *) {
172 ConstantInt::ResetTrueFalse();
173 }
174}
175
176static ManagedCleanup<llvm::CleanupTrueFalse> TrueFalseCleanup;
177
178ConstantInt *ConstantInt::CreateTrueFalseVals(bool WhichOne) {
179 assert(TheTrueVal == 0 && TheFalseVal == 0);
180 TheTrueVal = get(Type::Int1Ty, 1);
181 TheFalseVal = get(Type::Int1Ty, 0);
182
183 // Ensure that llvm_shutdown nulls out TheTrueVal/TheFalseVal.
184 TrueFalseCleanup.Register();
185
186 return WhichOne ? TheTrueVal : TheFalseVal;
187}
188
189
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000190namespace {
Reid Spencerb31bffe2007-02-26 23:54:03 +0000191 struct DenseMapAPIntKeyInfo {
192 struct KeyTy {
193 APInt val;
194 const Type* type;
195 KeyTy(const APInt& V, const Type* Ty) : val(V), type(Ty) {}
196 KeyTy(const KeyTy& that) : val(that.val), type(that.type) {}
197 bool operator==(const KeyTy& that) const {
198 return type == that.type && this->val == that.val;
199 }
200 bool operator!=(const KeyTy& that) const {
201 return !this->operator==(that);
202 }
203 };
204 static inline KeyTy getEmptyKey() { return KeyTy(APInt(1,0), 0); }
205 static inline KeyTy getTombstoneKey() { return KeyTy(APInt(1,1), 0); }
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000206 static unsigned getHashValue(const KeyTy &Key) {
Chris Lattner0625bd62007-09-17 18:34:04 +0000207 return DenseMapInfo<void*>::getHashValue(Key.type) ^
Reid Spencerb31bffe2007-02-26 23:54:03 +0000208 Key.val.getHashValue();
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000209 }
Chris Lattner0625bd62007-09-17 18:34:04 +0000210 static bool isEqual(const KeyTy &LHS, const KeyTy &RHS) {
211 return LHS == RHS;
212 }
Dale Johannesena719a602007-08-24 00:56:33 +0000213 static bool isPod() { return false; }
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000214 };
215}
216
217
Reid Spencerb31bffe2007-02-26 23:54:03 +0000218typedef DenseMap<DenseMapAPIntKeyInfo::KeyTy, ConstantInt*,
219 DenseMapAPIntKeyInfo> IntMapTy;
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000220static ManagedStatic<IntMapTy> IntConstants;
221
Reid Spencer362fb292007-03-19 20:39:08 +0000222ConstantInt *ConstantInt::get(const Type *Ty, uint64_t V, bool isSigned) {
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000223 const IntegerType *ITy = cast<IntegerType>(Ty);
Reid Spencer362fb292007-03-19 20:39:08 +0000224 return get(APInt(ITy->getBitWidth(), V, isSigned));
Reid Spencerb31bffe2007-02-26 23:54:03 +0000225}
226
Reid Spencerd1bbfa52007-03-01 19:30:34 +0000227// Get a ConstantInt from an APInt. Note that the value stored in the DenseMap
Dan Gohmanb3efe032008-02-07 02:30:40 +0000228// as the key, is a DenseMapAPIntKeyInfo::KeyTy which has provided the
Reid Spencerb31bffe2007-02-26 23:54:03 +0000229// operator== and operator!= to ensure that the DenseMap doesn't attempt to
230// compare APInt's of different widths, which would violate an APInt class
231// invariant which generates an assertion.
Reid Spencerd1bbfa52007-03-01 19:30:34 +0000232ConstantInt *ConstantInt::get(const APInt& V) {
233 // Get the corresponding integer type for the bit width of the value.
234 const IntegerType *ITy = IntegerType::get(V.getBitWidth());
Reid Spencerb31bffe2007-02-26 23:54:03 +0000235 // get an existing value or the insertion position
Reid Spencerd1bbfa52007-03-01 19:30:34 +0000236 DenseMapAPIntKeyInfo::KeyTy Key(V, ITy);
Reid Spencerb31bffe2007-02-26 23:54:03 +0000237 ConstantInt *&Slot = (*IntConstants)[Key];
238 // if it exists, return it.
239 if (Slot)
240 return Slot;
241 // otherwise create a new one, insert it, and return it.
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000242 return Slot = new ConstantInt(ITy, V);
243}
244
245//===----------------------------------------------------------------------===//
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000246// ConstantFP
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000247//===----------------------------------------------------------------------===//
248
Chris Lattner98bd9392008-04-09 06:38:30 +0000249static const fltSemantics *TypeToFloatSemantics(const Type *Ty) {
250 if (Ty == Type::FloatTy)
251 return &APFloat::IEEEsingle;
252 if (Ty == Type::DoubleTy)
253 return &APFloat::IEEEdouble;
254 if (Ty == Type::X86_FP80Ty)
255 return &APFloat::x87DoubleExtended;
256 else if (Ty == Type::FP128Ty)
257 return &APFloat::IEEEquad;
258
259 assert(Ty == Type::PPC_FP128Ty && "Unknown FP format");
260 return &APFloat::PPCDoubleDouble;
261}
262
Dale Johannesend246b2c2007-08-30 00:23:21 +0000263ConstantFP::ConstantFP(const Type *Ty, const APFloat& V)
264 : Constant(Ty, ConstantFPVal, 0, 0), Val(V) {
Chris Lattner98bd9392008-04-09 06:38:30 +0000265 assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
266 "FP type Mismatch");
Chris Lattner2f7c9632001-06-06 20:29:01 +0000267}
268
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000269bool ConstantFP::isNullValue() const {
Dale Johannesena719a602007-08-24 00:56:33 +0000270 return Val.isZero() && !Val.isNegative();
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000271}
272
Dale Johannesen98d3a082007-09-14 22:26:36 +0000273ConstantFP *ConstantFP::getNegativeZero(const Type *Ty) {
274 APFloat apf = cast <ConstantFP>(Constant::getNullValue(Ty))->getValueAPF();
275 apf.changeSign();
Chris Lattnerb5b3e312008-04-09 00:45:01 +0000276 return ConstantFP::get(apf);
Dale Johannesen98d3a082007-09-14 22:26:36 +0000277}
278
Dale Johannesend246b2c2007-08-30 00:23:21 +0000279bool ConstantFP::isExactlyValue(const APFloat& V) const {
280 return Val.bitwiseIsEqual(V);
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000281}
282
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000283namespace {
Dale Johannesena719a602007-08-24 00:56:33 +0000284 struct DenseMapAPFloatKeyInfo {
Dale Johannesenbdea32d2007-08-24 22:09:56 +0000285 struct KeyTy {
286 APFloat val;
287 KeyTy(const APFloat& V) : val(V){}
288 KeyTy(const KeyTy& that) : val(that.val) {}
289 bool operator==(const KeyTy& that) const {
290 return this->val.bitwiseIsEqual(that.val);
291 }
292 bool operator!=(const KeyTy& that) const {
293 return !this->operator==(that);
294 }
295 };
296 static inline KeyTy getEmptyKey() {
297 return KeyTy(APFloat(APFloat::Bogus,1));
Reid Spencerb31bffe2007-02-26 23:54:03 +0000298 }
Dale Johannesenbdea32d2007-08-24 22:09:56 +0000299 static inline KeyTy getTombstoneKey() {
300 return KeyTy(APFloat(APFloat::Bogus,2));
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000301 }
Dale Johannesenbdea32d2007-08-24 22:09:56 +0000302 static unsigned getHashValue(const KeyTy &Key) {
303 return Key.val.getHashValue();
Dale Johannesena719a602007-08-24 00:56:33 +0000304 }
Chris Lattner0625bd62007-09-17 18:34:04 +0000305 static bool isEqual(const KeyTy &LHS, const KeyTy &RHS) {
306 return LHS == RHS;
307 }
Dale Johannesena719a602007-08-24 00:56:33 +0000308 static bool isPod() { return false; }
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000309 };
310}
311
312//---- ConstantFP::get() implementation...
313//
Dale Johannesenbdea32d2007-08-24 22:09:56 +0000314typedef DenseMap<DenseMapAPFloatKeyInfo::KeyTy, ConstantFP*,
Dale Johannesena719a602007-08-24 00:56:33 +0000315 DenseMapAPFloatKeyInfo> FPMapTy;
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000316
Dale Johannesena719a602007-08-24 00:56:33 +0000317static ManagedStatic<FPMapTy> FPConstants;
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000318
Chris Lattnerb5b3e312008-04-09 00:45:01 +0000319ConstantFP *ConstantFP::get(const APFloat &V) {
Dale Johannesend246b2c2007-08-30 00:23:21 +0000320 DenseMapAPFloatKeyInfo::KeyTy Key(V);
321 ConstantFP *&Slot = (*FPConstants)[Key];
322 if (Slot) return Slot;
Chris Lattnerb5b3e312008-04-09 00:45:01 +0000323
324 const Type *Ty;
325 if (&V.getSemantics() == &APFloat::IEEEsingle)
326 Ty = Type::FloatTy;
327 else if (&V.getSemantics() == &APFloat::IEEEdouble)
328 Ty = Type::DoubleTy;
329 else if (&V.getSemantics() == &APFloat::x87DoubleExtended)
330 Ty = Type::X86_FP80Ty;
331 else if (&V.getSemantics() == &APFloat::IEEEquad)
332 Ty = Type::FP128Ty;
333 else {
334 assert(&V.getSemantics() == &APFloat::PPCDoubleDouble&&"Unknown FP format");
335 Ty = Type::PPC_FP128Ty;
336 }
337
Dale Johannesend246b2c2007-08-30 00:23:21 +0000338 return Slot = new ConstantFP(Ty, V);
339}
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000340
Chris Lattner98bd9392008-04-09 06:38:30 +0000341/// get() - This returns a constant fp for the specified value in the
342/// specified type. This should only be used for simple constant values like
343/// 2.0/1.0 etc, that are known-valid both as double and as the target format.
344ConstantFP *ConstantFP::get(const Type *Ty, double V) {
345 APFloat FV(V);
346 FV.convert(*TypeToFloatSemantics(Ty), APFloat::rmNearestTiesToEven);
347 return get(FV);
348}
349
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000350//===----------------------------------------------------------------------===//
351// ConstantXXX Classes
352//===----------------------------------------------------------------------===//
353
354
Chris Lattner3462ae32001-12-03 22:26:30 +0000355ConstantArray::ConstantArray(const ArrayType *T,
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000356 const std::vector<Constant*> &V)
Gabor Greiff6caff662008-05-10 08:32:32 +0000357 : Constant(T, ConstantArrayVal,
358 OperandTraits<ConstantArray>::op_end(this) - V.size(),
359 V.size()) {
Alkis Evlogimenos0507ffe2004-09-15 02:32:15 +0000360 assert(V.size() == T->getNumElements() &&
361 "Invalid initializer vector for constant array");
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000362 Use *OL = OperandList;
Chris Lattner0144fad2005-10-03 21:56:24 +0000363 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
364 I != E; ++I, ++OL) {
Chris Lattner20a24452005-10-07 05:23:36 +0000365 Constant *C = *I;
366 assert((C->getType() == T->getElementType() ||
Alkis Evlogimenoscb031d92004-09-10 04:16:59 +0000367 (T->isAbstract() &&
Chris Lattner20a24452005-10-07 05:23:36 +0000368 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
Alkis Evlogimenoscb031d92004-09-10 04:16:59 +0000369 "Initializer for array element doesn't match array element type!");
Chris Lattner20a24452005-10-07 05:23:36 +0000370 OL->init(C, this);
Chris Lattner2f7c9632001-06-06 20:29:01 +0000371 }
372}
373
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000374
Chris Lattner3462ae32001-12-03 22:26:30 +0000375ConstantStruct::ConstantStruct(const StructType *T,
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000376 const std::vector<Constant*> &V)
Gabor Greiff6caff662008-05-10 08:32:32 +0000377 : Constant(T, ConstantStructVal,
378 OperandTraits<ConstantStruct>::op_end(this) - V.size(),
379 V.size()) {
Chris Lattnerac6db752004-02-09 04:37:31 +0000380 assert(V.size() == T->getNumElements() &&
Vikram S. Adve4e537b22002-07-14 23:13:17 +0000381 "Invalid initializer vector for constant structure");
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000382 Use *OL = OperandList;
Chris Lattner0144fad2005-10-03 21:56:24 +0000383 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
384 I != E; ++I, ++OL) {
Chris Lattner20a24452005-10-07 05:23:36 +0000385 Constant *C = *I;
386 assert((C->getType() == T->getElementType(I-V.begin()) ||
Chris Lattner0144fad2005-10-03 21:56:24 +0000387 ((T->getElementType(I-V.begin())->isAbstract() ||
Chris Lattner20a24452005-10-07 05:23:36 +0000388 C->getType()->isAbstract()) &&
Chris Lattner0144fad2005-10-03 21:56:24 +0000389 T->getElementType(I-V.begin())->getTypeID() ==
Chris Lattner20a24452005-10-07 05:23:36 +0000390 C->getType()->getTypeID())) &&
Chris Lattner93c8f142003-06-02 17:42:47 +0000391 "Initializer for struct element doesn't match struct element type!");
Chris Lattner20a24452005-10-07 05:23:36 +0000392 OL->init(C, this);
Chris Lattner2f7c9632001-06-06 20:29:01 +0000393 }
394}
395
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000396
Reid Spencerd84d35b2007-02-15 02:26:10 +0000397ConstantVector::ConstantVector(const VectorType *T,
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000398 const std::vector<Constant*> &V)
Gabor Greiff6caff662008-05-10 08:32:32 +0000399 : Constant(T, ConstantVectorVal,
400 OperandTraits<ConstantVector>::op_end(this) - V.size(),
401 V.size()) {
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000402 Use *OL = OperandList;
Chris Lattner0144fad2005-10-03 21:56:24 +0000403 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
404 I != E; ++I, ++OL) {
Chris Lattner20a24452005-10-07 05:23:36 +0000405 Constant *C = *I;
406 assert((C->getType() == T->getElementType() ||
Alkis Evlogimenoscb031d92004-09-10 04:16:59 +0000407 (T->isAbstract() &&
Chris Lattner20a24452005-10-07 05:23:36 +0000408 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
Dan Gohman30978072007-05-24 14:36:04 +0000409 "Initializer for vector element doesn't match vector element type!");
Chris Lattner20a24452005-10-07 05:23:36 +0000410 OL->init(C, this);
Brian Gaeke02209042004-08-20 06:00:58 +0000411 }
412}
413
Vikram S. Adve4e537b22002-07-14 23:13:17 +0000414
Gabor Greiff6caff662008-05-10 08:32:32 +0000415namespace llvm {
Gordon Henriksen14a55692007-12-10 02:14:30 +0000416// We declare several classes private to this file, so use an anonymous
417// namespace
418namespace {
Reid Spencer10fbf0e2006-12-03 05:48:19 +0000419
Gordon Henriksen14a55692007-12-10 02:14:30 +0000420/// UnaryConstantExpr - This class is private to Constants.cpp, and is used
421/// behind the scenes to implement unary constant exprs.
422class VISIBILITY_HIDDEN UnaryConstantExpr : public ConstantExpr {
Gabor Greife9ecc682008-04-06 20:25:17 +0000423 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
Gordon Henriksen14a55692007-12-10 02:14:30 +0000424public:
Gabor Greife9ecc682008-04-06 20:25:17 +0000425 // allocate space for exactly one operand
426 void *operator new(size_t s) {
427 return User::operator new(s, 1);
428 }
Gordon Henriksen14a55692007-12-10 02:14:30 +0000429 UnaryConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
Gabor Greiff6caff662008-05-10 08:32:32 +0000430 : ConstantExpr(Ty, Opcode, &Op<0>(), 1) {
431 Op<0>() = C;
432 }
433 /// Transparently provide more efficient getOperand methods.
434 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Gordon Henriksen14a55692007-12-10 02:14:30 +0000435};
Reid Spencer10fbf0e2006-12-03 05:48:19 +0000436
Gordon Henriksen14a55692007-12-10 02:14:30 +0000437/// BinaryConstantExpr - This class is private to Constants.cpp, and is used
438/// behind the scenes to implement binary constant exprs.
439class VISIBILITY_HIDDEN BinaryConstantExpr : public ConstantExpr {
Gabor Greife9ecc682008-04-06 20:25:17 +0000440 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
Gordon Henriksen14a55692007-12-10 02:14:30 +0000441public:
Gabor Greife9ecc682008-04-06 20:25:17 +0000442 // allocate space for exactly two operands
443 void *operator new(size_t s) {
444 return User::operator new(s, 2);
445 }
Gordon Henriksen14a55692007-12-10 02:14:30 +0000446 BinaryConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
Gabor Greiff6caff662008-05-10 08:32:32 +0000447 : ConstantExpr(C1->getType(), Opcode, &Op<0>(), 2) {
448 Op<0>().init(C1, this);
449 Op<1>().init(C2, this);
Gordon Henriksen14a55692007-12-10 02:14:30 +0000450 }
Gabor Greiff6caff662008-05-10 08:32:32 +0000451 /// Transparently provide more efficient getOperand methods.
452 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Gordon Henriksen14a55692007-12-10 02:14:30 +0000453};
Vikram S. Adve4e537b22002-07-14 23:13:17 +0000454
Gordon Henriksen14a55692007-12-10 02:14:30 +0000455/// SelectConstantExpr - This class is private to Constants.cpp, and is used
456/// behind the scenes to implement select constant exprs.
457class VISIBILITY_HIDDEN SelectConstantExpr : public ConstantExpr {
Gabor Greife9ecc682008-04-06 20:25:17 +0000458 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
Gordon Henriksen14a55692007-12-10 02:14:30 +0000459public:
Gabor Greife9ecc682008-04-06 20:25:17 +0000460 // allocate space for exactly three operands
461 void *operator new(size_t s) {
462 return User::operator new(s, 3);
463 }
Gordon Henriksen14a55692007-12-10 02:14:30 +0000464 SelectConstantExpr(Constant *C1, Constant *C2, Constant *C3)
Gabor Greiff6caff662008-05-10 08:32:32 +0000465 : ConstantExpr(C2->getType(), Instruction::Select, &Op<0>(), 3) {
466 Op<0>().init(C1, this);
467 Op<1>().init(C2, this);
468 Op<2>().init(C3, this);
Gordon Henriksen14a55692007-12-10 02:14:30 +0000469 }
Gabor Greiff6caff662008-05-10 08:32:32 +0000470 /// Transparently provide more efficient getOperand methods.
471 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Gordon Henriksen14a55692007-12-10 02:14:30 +0000472};
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000473
Gordon Henriksen14a55692007-12-10 02:14:30 +0000474/// ExtractElementConstantExpr - This class is private to
475/// Constants.cpp, and is used behind the scenes to implement
476/// extractelement constant exprs.
477class VISIBILITY_HIDDEN ExtractElementConstantExpr : public ConstantExpr {
Gabor Greife9ecc682008-04-06 20:25:17 +0000478 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
Gordon Henriksen14a55692007-12-10 02:14:30 +0000479public:
Gabor Greife9ecc682008-04-06 20:25:17 +0000480 // allocate space for exactly two operands
481 void *operator new(size_t s) {
482 return User::operator new(s, 2);
483 }
Gordon Henriksen14a55692007-12-10 02:14:30 +0000484 ExtractElementConstantExpr(Constant *C1, Constant *C2)
485 : ConstantExpr(cast<VectorType>(C1->getType())->getElementType(),
Gabor Greiff6caff662008-05-10 08:32:32 +0000486 Instruction::ExtractElement, &Op<0>(), 2) {
487 Op<0>().init(C1, this);
488 Op<1>().init(C2, this);
Gordon Henriksen14a55692007-12-10 02:14:30 +0000489 }
Gabor Greiff6caff662008-05-10 08:32:32 +0000490 /// Transparently provide more efficient getOperand methods.
491 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Gordon Henriksen14a55692007-12-10 02:14:30 +0000492};
Robert Bocchino23004482006-01-10 19:05:34 +0000493
Gordon Henriksen14a55692007-12-10 02:14:30 +0000494/// InsertElementConstantExpr - This class is private to
495/// Constants.cpp, and is used behind the scenes to implement
496/// insertelement constant exprs.
497class VISIBILITY_HIDDEN InsertElementConstantExpr : public ConstantExpr {
Gabor Greife9ecc682008-04-06 20:25:17 +0000498 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
Gordon Henriksen14a55692007-12-10 02:14:30 +0000499public:
Gabor Greife9ecc682008-04-06 20:25:17 +0000500 // allocate space for exactly three operands
501 void *operator new(size_t s) {
502 return User::operator new(s, 3);
503 }
Gordon Henriksen14a55692007-12-10 02:14:30 +0000504 InsertElementConstantExpr(Constant *C1, Constant *C2, Constant *C3)
505 : ConstantExpr(C1->getType(), Instruction::InsertElement,
Gabor Greiff6caff662008-05-10 08:32:32 +0000506 &Op<0>(), 3) {
507 Op<0>().init(C1, this);
508 Op<1>().init(C2, this);
509 Op<2>().init(C3, this);
Gordon Henriksen14a55692007-12-10 02:14:30 +0000510 }
Gabor Greiff6caff662008-05-10 08:32:32 +0000511 /// Transparently provide more efficient getOperand methods.
512 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Gordon Henriksen14a55692007-12-10 02:14:30 +0000513};
Robert Bocchinoca27f032006-01-17 20:07:22 +0000514
Gordon Henriksen14a55692007-12-10 02:14:30 +0000515/// ShuffleVectorConstantExpr - This class is private to
516/// Constants.cpp, and is used behind the scenes to implement
517/// shufflevector constant exprs.
518class VISIBILITY_HIDDEN ShuffleVectorConstantExpr : public ConstantExpr {
Gabor Greife9ecc682008-04-06 20:25:17 +0000519 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
Gordon Henriksen14a55692007-12-10 02:14:30 +0000520public:
Gabor Greife9ecc682008-04-06 20:25:17 +0000521 // allocate space for exactly three operands
522 void *operator new(size_t s) {
523 return User::operator new(s, 3);
524 }
Gordon Henriksen14a55692007-12-10 02:14:30 +0000525 ShuffleVectorConstantExpr(Constant *C1, Constant *C2, Constant *C3)
526 : ConstantExpr(C1->getType(), Instruction::ShuffleVector,
Gabor Greiff6caff662008-05-10 08:32:32 +0000527 &Op<0>(), 3) {
528 Op<0>().init(C1, this);
529 Op<1>().init(C2, this);
530 Op<2>().init(C3, this);
Gordon Henriksen14a55692007-12-10 02:14:30 +0000531 }
Gabor Greiff6caff662008-05-10 08:32:32 +0000532 /// Transparently provide more efficient getOperand methods.
533 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Gordon Henriksen14a55692007-12-10 02:14:30 +0000534};
535
536/// GetElementPtrConstantExpr - This class is private to Constants.cpp, and is
537/// used behind the scenes to implement getelementpr constant exprs.
Gabor Greife9ecc682008-04-06 20:25:17 +0000538class VISIBILITY_HIDDEN GetElementPtrConstantExpr : public ConstantExpr {
Gordon Henriksen14a55692007-12-10 02:14:30 +0000539 GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
Gabor Greiff6caff662008-05-10 08:32:32 +0000540 const Type *DestTy);
Gabor Greife9ecc682008-04-06 20:25:17 +0000541public:
Gabor Greif697e94c2008-05-15 10:04:30 +0000542 static GetElementPtrConstantExpr *Create(Constant *C,
543 const std::vector<Constant*>&IdxList,
Gabor Greiff6caff662008-05-10 08:32:32 +0000544 const Type *DestTy) {
Gabor Greif697e94c2008-05-15 10:04:30 +0000545 return new(IdxList.size() + 1)
546 GetElementPtrConstantExpr(C, IdxList, DestTy);
Gabor Greife9ecc682008-04-06 20:25:17 +0000547 }
Gabor Greiff6caff662008-05-10 08:32:32 +0000548 /// Transparently provide more efficient getOperand methods.
549 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Gordon Henriksen14a55692007-12-10 02:14:30 +0000550};
551
552// CompareConstantExpr - This class is private to Constants.cpp, and is used
553// behind the scenes to implement ICmp and FCmp constant expressions. This is
554// needed in order to store the predicate value for these instructions.
555struct VISIBILITY_HIDDEN CompareConstantExpr : public ConstantExpr {
Gabor Greife9ecc682008-04-06 20:25:17 +0000556 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
557 // allocate space for exactly two operands
558 void *operator new(size_t s) {
559 return User::operator new(s, 2);
560 }
Gordon Henriksen14a55692007-12-10 02:14:30 +0000561 unsigned short predicate;
Nate Begemand2195702008-05-12 19:01:56 +0000562 CompareConstantExpr(const Type *ty, Instruction::OtherOps opc,
563 unsigned short pred, Constant* LHS, Constant* RHS)
564 : ConstantExpr(ty, opc, &Op<0>(), 2), predicate(pred) {
Gabor Greiff6caff662008-05-10 08:32:32 +0000565 Op<0>().init(LHS, this);
566 Op<1>().init(RHS, this);
Gordon Henriksen14a55692007-12-10 02:14:30 +0000567 }
Gabor Greiff6caff662008-05-10 08:32:32 +0000568 /// Transparently provide more efficient getOperand methods.
569 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Gordon Henriksen14a55692007-12-10 02:14:30 +0000570};
571
572} // end anonymous namespace
573
Gabor Greiff6caff662008-05-10 08:32:32 +0000574template <>
575struct OperandTraits<UnaryConstantExpr> : FixedNumOperandTraits<1> {
576};
577DEFINE_TRANSPARENT_OPERAND_ACCESSORS(UnaryConstantExpr, Value)
578
579template <>
580struct OperandTraits<BinaryConstantExpr> : FixedNumOperandTraits<2> {
581};
582DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BinaryConstantExpr, Value)
583
584template <>
585struct OperandTraits<SelectConstantExpr> : FixedNumOperandTraits<3> {
586};
587DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SelectConstantExpr, Value)
588
589template <>
590struct OperandTraits<ExtractElementConstantExpr> : FixedNumOperandTraits<2> {
591};
592DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractElementConstantExpr, Value)
593
594template <>
595struct OperandTraits<InsertElementConstantExpr> : FixedNumOperandTraits<3> {
596};
597DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertElementConstantExpr, Value)
598
599template <>
600struct OperandTraits<ShuffleVectorConstantExpr> : FixedNumOperandTraits<3> {
601};
602DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ShuffleVectorConstantExpr, Value)
603
604
605template <>
606struct OperandTraits<GetElementPtrConstantExpr> : VariadicOperandTraits<1> {
607};
608
609GetElementPtrConstantExpr::GetElementPtrConstantExpr
610 (Constant *C,
611 const std::vector<Constant*> &IdxList,
612 const Type *DestTy)
613 : ConstantExpr(DestTy, Instruction::GetElementPtr,
614 OperandTraits<GetElementPtrConstantExpr>::op_end(this)
615 - (IdxList.size()+1),
616 IdxList.size()+1) {
617 OperandList[0].init(C, this);
618 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
619 OperandList[i+1].init(IdxList[i], this);
620}
621
622DEFINE_TRANSPARENT_OPERAND_ACCESSORS(GetElementPtrConstantExpr, Value)
623
624
625template <>
626struct OperandTraits<CompareConstantExpr> : FixedNumOperandTraits<2> {
627};
628DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CompareConstantExpr, Value)
629
630
631} // End llvm namespace
632
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000633
634// Utility function for determining if a ConstantExpr is a CastOp or not. This
635// can't be inline because we don't want to #include Instruction.h into
636// Constant.h
637bool ConstantExpr::isCast() const {
638 return Instruction::isCast(getOpcode());
639}
640
Reid Spenceree3c9912006-12-04 05:19:50 +0000641bool ConstantExpr::isCompare() const {
642 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
643}
644
Chris Lattner817175f2004-03-29 02:37:53 +0000645/// ConstantExpr::get* - Return some common constants without having to
646/// specify the full Instruction::OPCODE identifier.
647///
648Constant *ConstantExpr::getNeg(Constant *C) {
Reid Spencer2eadb532007-01-21 00:29:26 +0000649 return get(Instruction::Sub,
650 ConstantExpr::getZeroValueForNegationExpr(C->getType()),
651 C);
Chris Lattner817175f2004-03-29 02:37:53 +0000652}
653Constant *ConstantExpr::getNot(Constant *C) {
Gordon Henriksen7ce31762007-10-06 14:29:36 +0000654 assert(isa<IntegerType>(C->getType()) && "Cannot NOT a nonintegral value!");
Chris Lattner817175f2004-03-29 02:37:53 +0000655 return get(Instruction::Xor, C,
Zhou Sheng75b871f2007-01-11 12:24:14 +0000656 ConstantInt::getAllOnesValue(C->getType()));
Chris Lattner817175f2004-03-29 02:37:53 +0000657}
658Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2) {
659 return get(Instruction::Add, C1, C2);
660}
661Constant *ConstantExpr::getSub(Constant *C1, Constant *C2) {
662 return get(Instruction::Sub, C1, C2);
663}
664Constant *ConstantExpr::getMul(Constant *C1, Constant *C2) {
665 return get(Instruction::Mul, C1, C2);
666}
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000667Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2) {
668 return get(Instruction::UDiv, C1, C2);
669}
670Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2) {
671 return get(Instruction::SDiv, C1, C2);
672}
673Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
674 return get(Instruction::FDiv, C1, C2);
Chris Lattner817175f2004-03-29 02:37:53 +0000675}
Reid Spencer7eb55b32006-11-02 01:53:59 +0000676Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
677 return get(Instruction::URem, C1, C2);
678}
679Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
680 return get(Instruction::SRem, C1, C2);
681}
682Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
683 return get(Instruction::FRem, C1, C2);
Chris Lattner817175f2004-03-29 02:37:53 +0000684}
685Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
686 return get(Instruction::And, C1, C2);
687}
688Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
689 return get(Instruction::Or, C1, C2);
690}
691Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
692 return get(Instruction::Xor, C1, C2);
693}
Reid Spencer10fbf0e2006-12-03 05:48:19 +0000694unsigned ConstantExpr::getPredicate() const {
Nate Begemand2195702008-05-12 19:01:56 +0000695 assert(getOpcode() == Instruction::FCmp ||
696 getOpcode() == Instruction::ICmp ||
697 getOpcode() == Instruction::VFCmp ||
698 getOpcode() == Instruction::VICmp);
Chris Lattneref650092007-10-18 16:26:24 +0000699 return ((const CompareConstantExpr*)this)->predicate;
Reid Spencer10fbf0e2006-12-03 05:48:19 +0000700}
Chris Lattner817175f2004-03-29 02:37:53 +0000701Constant *ConstantExpr::getShl(Constant *C1, Constant *C2) {
702 return get(Instruction::Shl, C1, C2);
703}
Reid Spencerfdff9382006-11-08 06:47:33 +0000704Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2) {
705 return get(Instruction::LShr, C1, C2);
Chris Lattner817175f2004-03-29 02:37:53 +0000706}
Reid Spencerfdff9382006-11-08 06:47:33 +0000707Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2) {
708 return get(Instruction::AShr, C1, C2);
Chris Lattnerdb8bdba2004-05-25 05:32:43 +0000709}
Chris Lattner60e0dd72001-10-03 06:12:09 +0000710
Chris Lattner7c1018a2006-07-14 19:37:40 +0000711/// getWithOperandReplaced - Return a constant expression identical to this
712/// one, but with the specified operand set to the specified value.
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000713Constant *
714ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
Chris Lattner7c1018a2006-07-14 19:37:40 +0000715 assert(OpNo < getNumOperands() && "Operand num is out of range!");
716 assert(Op->getType() == getOperand(OpNo)->getType() &&
717 "Replacing operand with value of different type!");
Chris Lattner227816342006-07-14 22:20:01 +0000718 if (getOperand(OpNo) == Op)
719 return const_cast<ConstantExpr*>(this);
Chris Lattner7c1018a2006-07-14 19:37:40 +0000720
Chris Lattner227816342006-07-14 22:20:01 +0000721 Constant *Op0, *Op1, *Op2;
Chris Lattner7c1018a2006-07-14 19:37:40 +0000722 switch (getOpcode()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000723 case Instruction::Trunc:
724 case Instruction::ZExt:
725 case Instruction::SExt:
726 case Instruction::FPTrunc:
727 case Instruction::FPExt:
728 case Instruction::UIToFP:
729 case Instruction::SIToFP:
730 case Instruction::FPToUI:
731 case Instruction::FPToSI:
732 case Instruction::PtrToInt:
733 case Instruction::IntToPtr:
734 case Instruction::BitCast:
735 return ConstantExpr::getCast(getOpcode(), Op, getType());
Chris Lattner227816342006-07-14 22:20:01 +0000736 case Instruction::Select:
737 Op0 = (OpNo == 0) ? Op : getOperand(0);
738 Op1 = (OpNo == 1) ? Op : getOperand(1);
739 Op2 = (OpNo == 2) ? Op : getOperand(2);
740 return ConstantExpr::getSelect(Op0, Op1, Op2);
741 case Instruction::InsertElement:
742 Op0 = (OpNo == 0) ? Op : getOperand(0);
743 Op1 = (OpNo == 1) ? Op : getOperand(1);
744 Op2 = (OpNo == 2) ? Op : getOperand(2);
745 return ConstantExpr::getInsertElement(Op0, Op1, Op2);
746 case Instruction::ExtractElement:
747 Op0 = (OpNo == 0) ? Op : getOperand(0);
748 Op1 = (OpNo == 1) ? Op : getOperand(1);
749 return ConstantExpr::getExtractElement(Op0, Op1);
750 case Instruction::ShuffleVector:
751 Op0 = (OpNo == 0) ? Op : getOperand(0);
752 Op1 = (OpNo == 1) ? Op : getOperand(1);
753 Op2 = (OpNo == 2) ? Op : getOperand(2);
754 return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Chris Lattner7c1018a2006-07-14 19:37:40 +0000755 case Instruction::GetElementPtr: {
Chris Lattnerb5d70302007-02-19 20:01:23 +0000756 SmallVector<Constant*, 8> Ops;
757 Ops.resize(getNumOperands());
Chris Lattner7c1018a2006-07-14 19:37:40 +0000758 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
Chris Lattnerb5d70302007-02-19 20:01:23 +0000759 Ops[i] = getOperand(i);
Chris Lattner7c1018a2006-07-14 19:37:40 +0000760 if (OpNo == 0)
Chris Lattnerb5d70302007-02-19 20:01:23 +0000761 return ConstantExpr::getGetElementPtr(Op, &Ops[0], Ops.size());
Chris Lattner7c1018a2006-07-14 19:37:40 +0000762 Ops[OpNo-1] = Op;
Chris Lattnerb5d70302007-02-19 20:01:23 +0000763 return ConstantExpr::getGetElementPtr(getOperand(0), &Ops[0], Ops.size());
Chris Lattner7c1018a2006-07-14 19:37:40 +0000764 }
Chris Lattner7c1018a2006-07-14 19:37:40 +0000765 default:
766 assert(getNumOperands() == 2 && "Must be binary operator?");
Chris Lattner227816342006-07-14 22:20:01 +0000767 Op0 = (OpNo == 0) ? Op : getOperand(0);
768 Op1 = (OpNo == 1) ? Op : getOperand(1);
769 return ConstantExpr::get(getOpcode(), Op0, Op1);
770 }
771}
772
773/// getWithOperands - This returns the current constant expression with the
774/// operands replaced with the specified values. The specified operands must
775/// match count and type with the existing ones.
776Constant *ConstantExpr::
777getWithOperands(const std::vector<Constant*> &Ops) const {
778 assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
779 bool AnyChange = false;
780 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
781 assert(Ops[i]->getType() == getOperand(i)->getType() &&
782 "Operand type mismatch!");
783 AnyChange |= Ops[i] != getOperand(i);
784 }
785 if (!AnyChange) // No operands changed, return self.
786 return const_cast<ConstantExpr*>(this);
787
788 switch (getOpcode()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000789 case Instruction::Trunc:
790 case Instruction::ZExt:
791 case Instruction::SExt:
792 case Instruction::FPTrunc:
793 case Instruction::FPExt:
794 case Instruction::UIToFP:
795 case Instruction::SIToFP:
796 case Instruction::FPToUI:
797 case Instruction::FPToSI:
798 case Instruction::PtrToInt:
799 case Instruction::IntToPtr:
800 case Instruction::BitCast:
801 return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
Chris Lattner227816342006-07-14 22:20:01 +0000802 case Instruction::Select:
803 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
804 case Instruction::InsertElement:
805 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
806 case Instruction::ExtractElement:
807 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
808 case Instruction::ShuffleVector:
809 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
Chris Lattnerb5d70302007-02-19 20:01:23 +0000810 case Instruction::GetElementPtr:
811 return ConstantExpr::getGetElementPtr(Ops[0], &Ops[1], Ops.size()-1);
Reid Spencer266e42b2006-12-23 06:05:41 +0000812 case Instruction::ICmp:
813 case Instruction::FCmp:
814 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
Chris Lattner227816342006-07-14 22:20:01 +0000815 default:
816 assert(getNumOperands() == 2 && "Must be binary operator?");
817 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1]);
Chris Lattner7c1018a2006-07-14 19:37:40 +0000818 }
819}
820
Chris Lattner2f7c9632001-06-06 20:29:01 +0000821
822//===----------------------------------------------------------------------===//
Chris Lattner2f7c9632001-06-06 20:29:01 +0000823// isValueValidForType implementations
824
Reid Spencere7334722006-12-19 01:28:19 +0000825bool ConstantInt::isValueValidForType(const Type *Ty, uint64_t Val) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000826 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000827 if (Ty == Type::Int1Ty)
828 return Val == 0 || Val == 1;
Reid Spencerd7a00d72007-02-05 23:47:56 +0000829 if (NumBits >= 64)
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000830 return true; // always true, has to fit in largest type
831 uint64_t Max = (1ll << NumBits) - 1;
832 return Val <= Max;
Reid Spencere7334722006-12-19 01:28:19 +0000833}
834
Reid Spencere0fc4df2006-10-20 07:07:24 +0000835bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000836 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000837 if (Ty == Type::Int1Ty)
Reid Spencera94d3942007-01-19 21:13:56 +0000838 return Val == 0 || Val == 1 || Val == -1;
Reid Spencerd7a00d72007-02-05 23:47:56 +0000839 if (NumBits >= 64)
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000840 return true; // always true, has to fit in largest type
841 int64_t Min = -(1ll << (NumBits-1));
842 int64_t Max = (1ll << (NumBits-1)) - 1;
843 return (Val >= Min && Val <= Max);
Chris Lattner2f7c9632001-06-06 20:29:01 +0000844}
845
Dale Johannesend246b2c2007-08-30 00:23:21 +0000846bool ConstantFP::isValueValidForType(const Type *Ty, const APFloat& Val) {
847 // convert modifies in place, so make a copy.
848 APFloat Val2 = APFloat(Val);
Chris Lattner6b727592004-06-17 18:19:28 +0000849 switch (Ty->getTypeID()) {
Chris Lattner2f7c9632001-06-06 20:29:01 +0000850 default:
851 return false; // These can't be represented as floating point!
852
Dale Johannesend246b2c2007-08-30 00:23:21 +0000853 // FIXME rounding mode needs to be more flexible
Chris Lattner2f7c9632001-06-06 20:29:01 +0000854 case Type::FloatTyID:
Dale Johannesend246b2c2007-08-30 00:23:21 +0000855 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
856 Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven) ==
857 APFloat::opOK;
Chris Lattner2f7c9632001-06-06 20:29:01 +0000858 case Type::DoubleTyID:
Dale Johannesend246b2c2007-08-30 00:23:21 +0000859 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
860 &Val2.getSemantics() == &APFloat::IEEEdouble ||
861 Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven) ==
862 APFloat::opOK;
Dale Johannesenbdad8092007-08-09 22:51:36 +0000863 case Type::X86_FP80TyID:
Dale Johannesen028084e2007-09-12 03:30:33 +0000864 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
865 &Val2.getSemantics() == &APFloat::IEEEdouble ||
866 &Val2.getSemantics() == &APFloat::x87DoubleExtended;
Dale Johannesenbdad8092007-08-09 22:51:36 +0000867 case Type::FP128TyID:
Dale Johannesen028084e2007-09-12 03:30:33 +0000868 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
869 &Val2.getSemantics() == &APFloat::IEEEdouble ||
870 &Val2.getSemantics() == &APFloat::IEEEquad;
Dale Johannesen007aa372007-10-11 18:07:22 +0000871 case Type::PPC_FP128TyID:
872 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
873 &Val2.getSemantics() == &APFloat::IEEEdouble ||
874 &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
Chris Lattner2f7c9632001-06-06 20:29:01 +0000875 }
Chris Lattneraa2372562006-05-24 17:04:05 +0000876}
Chris Lattner9655e542001-07-20 19:16:02 +0000877
Chris Lattner49d855c2001-09-07 16:46:31 +0000878//===----------------------------------------------------------------------===//
Chris Lattner49d855c2001-09-07 16:46:31 +0000879// Factory Function Implementation
880
Gabor Greiff6caff662008-05-10 08:32:32 +0000881
882// The number of operands for each ConstantCreator::create method is
883// determined by the ConstantTraits template.
Chris Lattner98fa07b2003-05-23 20:03:32 +0000884// ConstantCreator - A class that is used to create constants by
885// ValueMap*. This class should be partially specialized if there is
886// something strange that needs to be done to interface to the ctor for the
887// constant.
888//
Chris Lattner189d19f2003-11-21 20:23:48 +0000889namespace llvm {
Gabor Greiff6caff662008-05-10 08:32:32 +0000890 template<class ValType>
891 struct ConstantTraits;
892
893 template<typename T, typename Alloc>
894 struct VISIBILITY_HIDDEN ConstantTraits< std::vector<T, Alloc> > {
895 static unsigned uses(const std::vector<T, Alloc>& v) {
896 return v.size();
897 }
898 };
899
Chris Lattner189d19f2003-11-21 20:23:48 +0000900 template<class ConstantClass, class TypeClass, class ValType>
Chris Lattner02157b02006-06-28 21:38:54 +0000901 struct VISIBILITY_HIDDEN ConstantCreator {
Chris Lattner189d19f2003-11-21 20:23:48 +0000902 static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
Gabor Greiff6caff662008-05-10 08:32:32 +0000903 return new(ConstantTraits<ValType>::uses(V)) ConstantClass(Ty, V);
Chris Lattner189d19f2003-11-21 20:23:48 +0000904 }
905 };
Misha Brukmanb1c93172005-04-21 23:48:37 +0000906
Chris Lattner189d19f2003-11-21 20:23:48 +0000907 template<class ConstantClass, class TypeClass>
Chris Lattner02157b02006-06-28 21:38:54 +0000908 struct VISIBILITY_HIDDEN ConvertConstantType {
Chris Lattner189d19f2003-11-21 20:23:48 +0000909 static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
910 assert(0 && "This type cannot be converted!\n");
911 abort();
912 }
913 };
Chris Lattnerb50d1352003-10-05 00:17:43 +0000914
Chris Lattner935aa922005-10-04 17:48:46 +0000915 template<class ValType, class TypeClass, class ConstantClass,
916 bool HasLargeKey = false /*true for arrays and structs*/ >
Chris Lattner02157b02006-06-28 21:38:54 +0000917 class VISIBILITY_HIDDEN ValueMap : public AbstractTypeUser {
Chris Lattnerb64419a2005-10-03 22:51:37 +0000918 public:
Jim Laskeyc03caef2006-07-17 17:38:29 +0000919 typedef std::pair<const Type*, ValType> MapKey;
920 typedef std::map<MapKey, Constant *> MapTy;
921 typedef std::map<Constant*, typename MapTy::iterator> InverseMapTy;
922 typedef std::map<const Type*, typename MapTy::iterator> AbstractTypeMapTy;
Chris Lattnerb64419a2005-10-03 22:51:37 +0000923 private:
Chris Lattner5bbf60a52005-10-04 16:52:46 +0000924 /// Map - This is the main map from the element descriptor to the Constants.
925 /// This is the primary way we avoid creating two of the same shape
926 /// constant.
Chris Lattnerb50d1352003-10-05 00:17:43 +0000927 MapTy Map;
Chris Lattner935aa922005-10-04 17:48:46 +0000928
929 /// InverseMap - If "HasLargeKey" is true, this contains an inverse mapping
930 /// from the constants to their element in Map. This is important for
931 /// removal of constants from the array, which would otherwise have to scan
932 /// through the map with very large keys.
Jim Laskeyc03caef2006-07-17 17:38:29 +0000933 InverseMapTy InverseMap;
Chris Lattnerb50d1352003-10-05 00:17:43 +0000934
Jim Laskeyc03caef2006-07-17 17:38:29 +0000935 /// AbstractTypeMap - Map for abstract type constants.
936 ///
Chris Lattnerb50d1352003-10-05 00:17:43 +0000937 AbstractTypeMapTy AbstractTypeMap;
Chris Lattner99a669b2004-11-19 16:39:44 +0000938
Chris Lattner98fa07b2003-05-23 20:03:32 +0000939 public:
Jim Laskeyc03caef2006-07-17 17:38:29 +0000940 typename MapTy::iterator map_end() { return Map.end(); }
Chris Lattnerb64419a2005-10-03 22:51:37 +0000941
942 /// InsertOrGetItem - Return an iterator for the specified element.
943 /// If the element exists in the map, the returned iterator points to the
944 /// entry and Exists=true. If not, the iterator points to the newly
945 /// inserted entry and returns Exists=false. Newly inserted entries have
946 /// I->second == 0, and should be filled in.
Jim Laskeyc03caef2006-07-17 17:38:29 +0000947 typename MapTy::iterator InsertOrGetItem(std::pair<MapKey, Constant *>
948 &InsertVal,
Chris Lattnerb64419a2005-10-03 22:51:37 +0000949 bool &Exists) {
Jim Laskeyc03caef2006-07-17 17:38:29 +0000950 std::pair<typename MapTy::iterator, bool> IP = Map.insert(InsertVal);
Chris Lattnerb64419a2005-10-03 22:51:37 +0000951 Exists = !IP.second;
952 return IP.first;
953 }
Chris Lattner5bbf60a52005-10-04 16:52:46 +0000954
Chris Lattner935aa922005-10-04 17:48:46 +0000955private:
Jim Laskeyc03caef2006-07-17 17:38:29 +0000956 typename MapTy::iterator FindExistingElement(ConstantClass *CP) {
Chris Lattner935aa922005-10-04 17:48:46 +0000957 if (HasLargeKey) {
Jim Laskeyc03caef2006-07-17 17:38:29 +0000958 typename InverseMapTy::iterator IMI = InverseMap.find(CP);
Chris Lattner935aa922005-10-04 17:48:46 +0000959 assert(IMI != InverseMap.end() && IMI->second != Map.end() &&
960 IMI->second->second == CP &&
961 "InverseMap corrupt!");
962 return IMI->second;
963 }
964
Jim Laskeyc03caef2006-07-17 17:38:29 +0000965 typename MapTy::iterator I =
Chris Lattner935aa922005-10-04 17:48:46 +0000966 Map.find(MapKey((TypeClass*)CP->getRawType(), getValType(CP)));
Chris Lattner5bbf60a52005-10-04 16:52:46 +0000967 if (I == Map.end() || I->second != CP) {
968 // FIXME: This should not use a linear scan. If this gets to be a
969 // performance problem, someone should look at this.
970 for (I = Map.begin(); I != Map.end() && I->second != CP; ++I)
971 /* empty */;
972 }
Chris Lattner935aa922005-10-04 17:48:46 +0000973 return I;
974 }
975public:
976
Chris Lattnerb64419a2005-10-03 22:51:37 +0000977 /// getOrCreate - Return the specified constant from the map, creating it if
978 /// necessary.
Chris Lattner98fa07b2003-05-23 20:03:32 +0000979 ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
Chris Lattnerb50d1352003-10-05 00:17:43 +0000980 MapKey Lookup(Ty, V);
Jim Laskeyc03caef2006-07-17 17:38:29 +0000981 typename MapTy::iterator I = Map.lower_bound(Lookup);
Reid Spencere0fc4df2006-10-20 07:07:24 +0000982 // Is it in the map?
Chris Lattner98fa07b2003-05-23 20:03:32 +0000983 if (I != Map.end() && I->first == Lookup)
Reid Spencere0fc4df2006-10-20 07:07:24 +0000984 return static_cast<ConstantClass *>(I->second);
Chris Lattner98fa07b2003-05-23 20:03:32 +0000985
986 // If no preexisting value, create one now...
987 ConstantClass *Result =
988 ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
989
Chris Lattnerb50d1352003-10-05 00:17:43 +0000990 /// FIXME: why does this assert fail when loading 176.gcc?
991 //assert(Result->getType() == Ty && "Type specified is not correct!");
992 I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
993
Chris Lattner935aa922005-10-04 17:48:46 +0000994 if (HasLargeKey) // Remember the reverse mapping if needed.
995 InverseMap.insert(std::make_pair(Result, I));
996
Chris Lattnerb50d1352003-10-05 00:17:43 +0000997 // If the type of the constant is abstract, make sure that an entry exists
998 // for it in the AbstractTypeMap.
999 if (Ty->isAbstract()) {
1000 typename AbstractTypeMapTy::iterator TI =
1001 AbstractTypeMap.lower_bound(Ty);
1002
1003 if (TI == AbstractTypeMap.end() || TI->first != Ty) {
1004 // Add ourselves to the ATU list of the type.
1005 cast<DerivedType>(Ty)->addAbstractTypeUser(this);
1006
1007 AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
1008 }
1009 }
Chris Lattner98fa07b2003-05-23 20:03:32 +00001010 return Result;
1011 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001012
Chris Lattner98fa07b2003-05-23 20:03:32 +00001013 void remove(ConstantClass *CP) {
Jim Laskeyc03caef2006-07-17 17:38:29 +00001014 typename MapTy::iterator I = FindExistingElement(CP);
Chris Lattnerb50d1352003-10-05 00:17:43 +00001015 assert(I != Map.end() && "Constant not found in constant table!");
Chris Lattner3e650af2004-08-04 04:48:01 +00001016 assert(I->second == CP && "Didn't find correct element?");
Chris Lattnerb50d1352003-10-05 00:17:43 +00001017
Chris Lattner935aa922005-10-04 17:48:46 +00001018 if (HasLargeKey) // Remember the reverse mapping if needed.
1019 InverseMap.erase(CP);
1020
Chris Lattnerb50d1352003-10-05 00:17:43 +00001021 // Now that we found the entry, make sure this isn't the entry that
1022 // the AbstractTypeMap points to.
Jim Laskeyc03caef2006-07-17 17:38:29 +00001023 const TypeClass *Ty = static_cast<const TypeClass *>(I->first.first);
Chris Lattnerb50d1352003-10-05 00:17:43 +00001024 if (Ty->isAbstract()) {
1025 assert(AbstractTypeMap.count(Ty) &&
1026 "Abstract type not in AbstractTypeMap?");
Jim Laskeyc03caef2006-07-17 17:38:29 +00001027 typename MapTy::iterator &ATMEntryIt = AbstractTypeMap[Ty];
Chris Lattnerb50d1352003-10-05 00:17:43 +00001028 if (ATMEntryIt == I) {
1029 // Yes, we are removing the representative entry for this type.
1030 // See if there are any other entries of the same type.
Jim Laskeyc03caef2006-07-17 17:38:29 +00001031 typename MapTy::iterator TmpIt = ATMEntryIt;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001032
Chris Lattnerb50d1352003-10-05 00:17:43 +00001033 // First check the entry before this one...
1034 if (TmpIt != Map.begin()) {
1035 --TmpIt;
1036 if (TmpIt->first.first != Ty) // Not the same type, move back...
1037 ++TmpIt;
1038 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001039
Chris Lattnerb50d1352003-10-05 00:17:43 +00001040 // If we didn't find the same type, try to move forward...
1041 if (TmpIt == ATMEntryIt) {
1042 ++TmpIt;
1043 if (TmpIt == Map.end() || TmpIt->first.first != Ty)
1044 --TmpIt; // No entry afterwards with the same type
1045 }
1046
1047 // If there is another entry in the map of the same abstract type,
1048 // update the AbstractTypeMap entry now.
1049 if (TmpIt != ATMEntryIt) {
1050 ATMEntryIt = TmpIt;
1051 } else {
1052 // Otherwise, we are removing the last instance of this type
1053 // from the table. Remove from the ATM, and from user list.
1054 cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
1055 AbstractTypeMap.erase(Ty);
1056 }
Chris Lattner98fa07b2003-05-23 20:03:32 +00001057 }
Chris Lattnerb50d1352003-10-05 00:17:43 +00001058 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001059
Chris Lattnerb50d1352003-10-05 00:17:43 +00001060 Map.erase(I);
1061 }
1062
Chris Lattner3b793c62005-10-04 21:35:50 +00001063
1064 /// MoveConstantToNewSlot - If we are about to change C to be the element
1065 /// specified by I, update our internal data structures to reflect this
1066 /// fact.
Jim Laskeyc03caef2006-07-17 17:38:29 +00001067 void MoveConstantToNewSlot(ConstantClass *C, typename MapTy::iterator I) {
Chris Lattner3b793c62005-10-04 21:35:50 +00001068 // First, remove the old location of the specified constant in the map.
Jim Laskeyc03caef2006-07-17 17:38:29 +00001069 typename MapTy::iterator OldI = FindExistingElement(C);
Chris Lattner3b793c62005-10-04 21:35:50 +00001070 assert(OldI != Map.end() && "Constant not found in constant table!");
1071 assert(OldI->second == C && "Didn't find correct element?");
1072
1073 // If this constant is the representative element for its abstract type,
1074 // update the AbstractTypeMap so that the representative element is I.
1075 if (C->getType()->isAbstract()) {
1076 typename AbstractTypeMapTy::iterator ATI =
1077 AbstractTypeMap.find(C->getType());
1078 assert(ATI != AbstractTypeMap.end() &&
1079 "Abstract type not in AbstractTypeMap?");
1080 if (ATI->second == OldI)
1081 ATI->second = I;
1082 }
1083
1084 // Remove the old entry from the map.
1085 Map.erase(OldI);
1086
1087 // Update the inverse map so that we know that this constant is now
1088 // located at descriptor I.
1089 if (HasLargeKey) {
1090 assert(I->second == C && "Bad inversemap entry!");
1091 InverseMap[C] = I;
1092 }
1093 }
1094
Chris Lattnerb50d1352003-10-05 00:17:43 +00001095 void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00001096 typename AbstractTypeMapTy::iterator I =
Jim Laskeyc03caef2006-07-17 17:38:29 +00001097 AbstractTypeMap.find(cast<Type>(OldTy));
Chris Lattnerb50d1352003-10-05 00:17:43 +00001098
1099 assert(I != AbstractTypeMap.end() &&
1100 "Abstract type not in AbstractTypeMap?");
1101
1102 // Convert a constant at a time until the last one is gone. The last one
1103 // leaving will remove() itself, causing the AbstractTypeMapEntry to be
1104 // eliminated eventually.
1105 do {
1106 ConvertConstantType<ConstantClass,
Jim Laskeyc03caef2006-07-17 17:38:29 +00001107 TypeClass>::convert(
1108 static_cast<ConstantClass *>(I->second->second),
Chris Lattnerb50d1352003-10-05 00:17:43 +00001109 cast<TypeClass>(NewTy));
1110
Jim Laskeyc03caef2006-07-17 17:38:29 +00001111 I = AbstractTypeMap.find(cast<Type>(OldTy));
Chris Lattnerb50d1352003-10-05 00:17:43 +00001112 } while (I != AbstractTypeMap.end());
1113 }
1114
1115 // If the type became concrete without being refined to any other existing
1116 // type, we just remove ourselves from the ATU list.
1117 void typeBecameConcrete(const DerivedType *AbsTy) {
1118 AbsTy->removeAbstractTypeUser(this);
1119 }
1120
1121 void dump() const {
Bill Wendling6a462f12006-11-17 08:03:48 +00001122 DOUT << "Constant.cpp: ValueMap\n";
Chris Lattner98fa07b2003-05-23 20:03:32 +00001123 }
1124 };
1125}
1126
Chris Lattnera84df0a22006-09-28 23:36:21 +00001127
Chris Lattner28173502007-02-20 06:11:36 +00001128
Chris Lattner9fba3da2004-02-15 05:53:04 +00001129//---- ConstantAggregateZero::get() implementation...
1130//
1131namespace llvm {
1132 // ConstantAggregateZero does not take extra "value" argument...
1133 template<class ValType>
1134 struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
1135 static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
1136 return new ConstantAggregateZero(Ty);
1137 }
1138 };
1139
1140 template<>
1141 struct ConvertConstantType<ConstantAggregateZero, Type> {
1142 static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
1143 // Make everyone now use a constant of the new type...
1144 Constant *New = ConstantAggregateZero::get(NewTy);
1145 assert(New != OldC && "Didn't replace constant??");
1146 OldC->uncheckedReplaceAllUsesWith(New);
1147 OldC->destroyConstant(); // This constant is now dead, destroy it.
1148 }
1149 };
1150}
1151
Chris Lattner69edc982006-09-28 00:35:06 +00001152static ManagedStatic<ValueMap<char, Type,
1153 ConstantAggregateZero> > AggZeroConstants;
Chris Lattner9fba3da2004-02-15 05:53:04 +00001154
Chris Lattner3e650af2004-08-04 04:48:01 +00001155static char getValType(ConstantAggregateZero *CPZ) { return 0; }
1156
Chris Lattner9fba3da2004-02-15 05:53:04 +00001157Constant *ConstantAggregateZero::get(const Type *Ty) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001158 assert((isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) &&
Chris Lattnerbfd0b6d2006-06-10 04:16:23 +00001159 "Cannot create an aggregate zero of non-aggregate type!");
Chris Lattner69edc982006-09-28 00:35:06 +00001160 return AggZeroConstants->getOrCreate(Ty, 0);
Chris Lattner9fba3da2004-02-15 05:53:04 +00001161}
1162
1163// destroyConstant - Remove the constant from the constant table...
1164//
1165void ConstantAggregateZero::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00001166 AggZeroConstants->remove(this);
Chris Lattner9fba3da2004-02-15 05:53:04 +00001167 destroyConstantImpl();
1168}
1169
Chris Lattner3462ae32001-12-03 22:26:30 +00001170//---- ConstantArray::get() implementation...
Chris Lattner49d855c2001-09-07 16:46:31 +00001171//
Chris Lattner189d19f2003-11-21 20:23:48 +00001172namespace llvm {
1173 template<>
1174 struct ConvertConstantType<ConstantArray, ArrayType> {
1175 static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
1176 // Make everyone now use a constant of the new type...
1177 std::vector<Constant*> C;
1178 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1179 C.push_back(cast<Constant>(OldC->getOperand(i)));
1180 Constant *New = ConstantArray::get(NewTy, C);
1181 assert(New != OldC && "Didn't replace constant??");
1182 OldC->uncheckedReplaceAllUsesWith(New);
1183 OldC->destroyConstant(); // This constant is now dead, destroy it.
1184 }
1185 };
1186}
Chris Lattnerb50d1352003-10-05 00:17:43 +00001187
Chris Lattner3e650af2004-08-04 04:48:01 +00001188static std::vector<Constant*> getValType(ConstantArray *CA) {
1189 std::vector<Constant*> Elements;
1190 Elements.reserve(CA->getNumOperands());
1191 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1192 Elements.push_back(cast<Constant>(CA->getOperand(i)));
1193 return Elements;
1194}
1195
Chris Lattnerb64419a2005-10-03 22:51:37 +00001196typedef ValueMap<std::vector<Constant*>, ArrayType,
Chris Lattner935aa922005-10-04 17:48:46 +00001197 ConstantArray, true /*largekey*/> ArrayConstantsTy;
Chris Lattner69edc982006-09-28 00:35:06 +00001198static ManagedStatic<ArrayConstantsTy> ArrayConstants;
Chris Lattner49d855c2001-09-07 16:46:31 +00001199
Chris Lattner015e8212004-02-15 04:14:47 +00001200Constant *ConstantArray::get(const ArrayType *Ty,
Chris Lattner9fba3da2004-02-15 05:53:04 +00001201 const std::vector<Constant*> &V) {
1202 // If this is an all-zero array, return a ConstantAggregateZero object
1203 if (!V.empty()) {
1204 Constant *C = V[0];
1205 if (!C->isNullValue())
Chris Lattner69edc982006-09-28 00:35:06 +00001206 return ArrayConstants->getOrCreate(Ty, V);
Chris Lattner9fba3da2004-02-15 05:53:04 +00001207 for (unsigned i = 1, e = V.size(); i != e; ++i)
1208 if (V[i] != C)
Chris Lattner69edc982006-09-28 00:35:06 +00001209 return ArrayConstants->getOrCreate(Ty, V);
Chris Lattner9fba3da2004-02-15 05:53:04 +00001210 }
1211 return ConstantAggregateZero::get(Ty);
Chris Lattner49d855c2001-09-07 16:46:31 +00001212}
1213
Chris Lattner98fa07b2003-05-23 20:03:32 +00001214// destroyConstant - Remove the constant from the constant table...
1215//
1216void ConstantArray::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00001217 ArrayConstants->remove(this);
Chris Lattner98fa07b2003-05-23 20:03:32 +00001218 destroyConstantImpl();
1219}
1220
Reid Spencer6f614532006-05-30 08:23:18 +00001221/// ConstantArray::get(const string&) - Return an array that is initialized to
1222/// contain the specified string. If length is zero then a null terminator is
1223/// added to the specified string so that it may be used in a natural way.
1224/// Otherwise, the length parameter specifies how much of the string to use
1225/// and it won't be null terminated.
1226///
Reid Spencer82ebaba2006-05-30 18:15:07 +00001227Constant *ConstantArray::get(const std::string &Str, bool AddNull) {
Chris Lattner7f74a562002-01-20 22:54:45 +00001228 std::vector<Constant*> ElementVals;
Reid Spencer82ebaba2006-05-30 18:15:07 +00001229 for (unsigned i = 0; i < Str.length(); ++i)
Reid Spencer8d9336d2006-12-31 05:26:44 +00001230 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, Str[i]));
Chris Lattner8f80fe02001-10-14 23:54:12 +00001231
1232 // Add a null terminator to the string...
Reid Spencer82ebaba2006-05-30 18:15:07 +00001233 if (AddNull) {
Reid Spencer8d9336d2006-12-31 05:26:44 +00001234 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, 0));
Reid Spencer6f614532006-05-30 08:23:18 +00001235 }
Chris Lattner8f80fe02001-10-14 23:54:12 +00001236
Reid Spencer8d9336d2006-12-31 05:26:44 +00001237 ArrayType *ATy = ArrayType::get(Type::Int8Ty, ElementVals.size());
Chris Lattner3462ae32001-12-03 22:26:30 +00001238 return ConstantArray::get(ATy, ElementVals);
Vikram S. Adve34410432001-10-14 23:17:20 +00001239}
1240
Reid Spencer2546b762007-01-26 07:37:34 +00001241/// isString - This method returns true if the array is an array of i8, and
1242/// if the elements of the array are all ConstantInt's.
Chris Lattnere8dfcca2004-01-14 17:06:38 +00001243bool ConstantArray::isString() const {
Reid Spencer2546b762007-01-26 07:37:34 +00001244 // Check the element type for i8...
Reid Spencer8d9336d2006-12-31 05:26:44 +00001245 if (getType()->getElementType() != Type::Int8Ty)
Chris Lattnere8dfcca2004-01-14 17:06:38 +00001246 return false;
1247 // Check the elements to make sure they are all integers, not constant
1248 // expressions.
1249 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1250 if (!isa<ConstantInt>(getOperand(i)))
1251 return false;
1252 return true;
1253}
1254
Evan Cheng3763c5b2006-10-26 19:15:05 +00001255/// isCString - This method returns true if the array is a string (see
1256/// isString) and it ends in a null byte \0 and does not contains any other
1257/// null bytes except its terminator.
1258bool ConstantArray::isCString() const {
Reid Spencer2546b762007-01-26 07:37:34 +00001259 // Check the element type for i8...
Reid Spencer8d9336d2006-12-31 05:26:44 +00001260 if (getType()->getElementType() != Type::Int8Ty)
Evan Chenge974da62006-10-26 21:48:03 +00001261 return false;
1262 Constant *Zero = Constant::getNullValue(getOperand(0)->getType());
1263 // Last element must be a null.
1264 if (getOperand(getNumOperands()-1) != Zero)
1265 return false;
1266 // Other elements must be non-null integers.
1267 for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
1268 if (!isa<ConstantInt>(getOperand(i)))
Evan Cheng3763c5b2006-10-26 19:15:05 +00001269 return false;
Evan Chenge974da62006-10-26 21:48:03 +00001270 if (getOperand(i) == Zero)
1271 return false;
1272 }
Evan Cheng3763c5b2006-10-26 19:15:05 +00001273 return true;
1274}
1275
1276
Reid Spencer2546b762007-01-26 07:37:34 +00001277// getAsString - If the sub-element type of this array is i8
Chris Lattner81fabb02002-08-26 17:53:56 +00001278// then this method converts the array to an std::string and returns it.
1279// Otherwise, it asserts out.
1280//
1281std::string ConstantArray::getAsString() const {
Chris Lattnere8dfcca2004-01-14 17:06:38 +00001282 assert(isString() && "Not a string!");
Chris Lattner81fabb02002-08-26 17:53:56 +00001283 std::string Result;
Chris Lattner6077c312003-07-23 15:22:26 +00001284 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
Reid Spencere0fc4df2006-10-20 07:07:24 +00001285 Result += (char)cast<ConstantInt>(getOperand(i))->getZExtValue();
Chris Lattner81fabb02002-08-26 17:53:56 +00001286 return Result;
1287}
1288
1289
Chris Lattner3462ae32001-12-03 22:26:30 +00001290//---- ConstantStruct::get() implementation...
Chris Lattner49d855c2001-09-07 16:46:31 +00001291//
Chris Lattnerb50d1352003-10-05 00:17:43 +00001292
Chris Lattner189d19f2003-11-21 20:23:48 +00001293namespace llvm {
1294 template<>
1295 struct ConvertConstantType<ConstantStruct, StructType> {
1296 static void convert(ConstantStruct *OldC, const StructType *NewTy) {
1297 // Make everyone now use a constant of the new type...
1298 std::vector<Constant*> C;
1299 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1300 C.push_back(cast<Constant>(OldC->getOperand(i)));
1301 Constant *New = ConstantStruct::get(NewTy, C);
1302 assert(New != OldC && "Didn't replace constant??");
Misha Brukmanb1c93172005-04-21 23:48:37 +00001303
Chris Lattner189d19f2003-11-21 20:23:48 +00001304 OldC->uncheckedReplaceAllUsesWith(New);
1305 OldC->destroyConstant(); // This constant is now dead, destroy it.
1306 }
1307 };
1308}
Chris Lattnerb50d1352003-10-05 00:17:43 +00001309
Chris Lattner8760ec72005-10-04 01:17:50 +00001310typedef ValueMap<std::vector<Constant*>, StructType,
Chris Lattner935aa922005-10-04 17:48:46 +00001311 ConstantStruct, true /*largekey*/> StructConstantsTy;
Chris Lattner69edc982006-09-28 00:35:06 +00001312static ManagedStatic<StructConstantsTy> StructConstants;
Chris Lattner49d855c2001-09-07 16:46:31 +00001313
Chris Lattner3e650af2004-08-04 04:48:01 +00001314static std::vector<Constant*> getValType(ConstantStruct *CS) {
1315 std::vector<Constant*> Elements;
1316 Elements.reserve(CS->getNumOperands());
1317 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1318 Elements.push_back(cast<Constant>(CS->getOperand(i)));
1319 return Elements;
1320}
1321
Chris Lattner015e8212004-02-15 04:14:47 +00001322Constant *ConstantStruct::get(const StructType *Ty,
1323 const std::vector<Constant*> &V) {
Chris Lattner9fba3da2004-02-15 05:53:04 +00001324 // Create a ConstantAggregateZero value if all elements are zeros...
1325 for (unsigned i = 0, e = V.size(); i != e; ++i)
1326 if (!V[i]->isNullValue())
Chris Lattner69edc982006-09-28 00:35:06 +00001327 return StructConstants->getOrCreate(Ty, V);
Chris Lattner9fba3da2004-02-15 05:53:04 +00001328
1329 return ConstantAggregateZero::get(Ty);
Chris Lattner49d855c2001-09-07 16:46:31 +00001330}
Chris Lattner883ad0b2001-10-03 15:39:36 +00001331
Andrew Lenharthdcb3c972006-12-08 18:06:16 +00001332Constant *ConstantStruct::get(const std::vector<Constant*> &V, bool packed) {
Chris Lattnerd6108ca2004-07-12 20:35:11 +00001333 std::vector<const Type*> StructEls;
1334 StructEls.reserve(V.size());
1335 for (unsigned i = 0, e = V.size(); i != e; ++i)
1336 StructEls.push_back(V[i]->getType());
Andrew Lenharthdcb3c972006-12-08 18:06:16 +00001337 return get(StructType::get(StructEls, packed), V);
Chris Lattnerd6108ca2004-07-12 20:35:11 +00001338}
1339
Chris Lattnerd7a73302001-10-13 06:57:33 +00001340// destroyConstant - Remove the constant from the constant table...
Chris Lattner883ad0b2001-10-03 15:39:36 +00001341//
Chris Lattner3462ae32001-12-03 22:26:30 +00001342void ConstantStruct::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00001343 StructConstants->remove(this);
Chris Lattnerd7a73302001-10-13 06:57:33 +00001344 destroyConstantImpl();
1345}
Chris Lattner883ad0b2001-10-03 15:39:36 +00001346
Reid Spencerd84d35b2007-02-15 02:26:10 +00001347//---- ConstantVector::get() implementation...
Brian Gaeke02209042004-08-20 06:00:58 +00001348//
1349namespace llvm {
1350 template<>
Reid Spencerd84d35b2007-02-15 02:26:10 +00001351 struct ConvertConstantType<ConstantVector, VectorType> {
1352 static void convert(ConstantVector *OldC, const VectorType *NewTy) {
Brian Gaeke02209042004-08-20 06:00:58 +00001353 // Make everyone now use a constant of the new type...
1354 std::vector<Constant*> C;
1355 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1356 C.push_back(cast<Constant>(OldC->getOperand(i)));
Reid Spencerd84d35b2007-02-15 02:26:10 +00001357 Constant *New = ConstantVector::get(NewTy, C);
Brian Gaeke02209042004-08-20 06:00:58 +00001358 assert(New != OldC && "Didn't replace constant??");
1359 OldC->uncheckedReplaceAllUsesWith(New);
1360 OldC->destroyConstant(); // This constant is now dead, destroy it.
1361 }
1362 };
1363}
1364
Reid Spencerd84d35b2007-02-15 02:26:10 +00001365static std::vector<Constant*> getValType(ConstantVector *CP) {
Brian Gaeke02209042004-08-20 06:00:58 +00001366 std::vector<Constant*> Elements;
1367 Elements.reserve(CP->getNumOperands());
1368 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1369 Elements.push_back(CP->getOperand(i));
1370 return Elements;
1371}
1372
Reid Spencerd84d35b2007-02-15 02:26:10 +00001373static ManagedStatic<ValueMap<std::vector<Constant*>, VectorType,
Reid Spencer09575ba2007-02-15 03:39:18 +00001374 ConstantVector> > VectorConstants;
Brian Gaeke02209042004-08-20 06:00:58 +00001375
Reid Spencerd84d35b2007-02-15 02:26:10 +00001376Constant *ConstantVector::get(const VectorType *Ty,
Brian Gaeke02209042004-08-20 06:00:58 +00001377 const std::vector<Constant*> &V) {
Dan Gohman30978072007-05-24 14:36:04 +00001378 // If this is an all-zero vector, return a ConstantAggregateZero object
Brian Gaeke02209042004-08-20 06:00:58 +00001379 if (!V.empty()) {
1380 Constant *C = V[0];
1381 if (!C->isNullValue())
Reid Spencer09575ba2007-02-15 03:39:18 +00001382 return VectorConstants->getOrCreate(Ty, V);
Brian Gaeke02209042004-08-20 06:00:58 +00001383 for (unsigned i = 1, e = V.size(); i != e; ++i)
1384 if (V[i] != C)
Reid Spencer09575ba2007-02-15 03:39:18 +00001385 return VectorConstants->getOrCreate(Ty, V);
Brian Gaeke02209042004-08-20 06:00:58 +00001386 }
1387 return ConstantAggregateZero::get(Ty);
1388}
1389
Reid Spencerd84d35b2007-02-15 02:26:10 +00001390Constant *ConstantVector::get(const std::vector<Constant*> &V) {
Brian Gaeke02209042004-08-20 06:00:58 +00001391 assert(!V.empty() && "Cannot infer type if V is empty");
Reid Spencerd84d35b2007-02-15 02:26:10 +00001392 return get(VectorType::get(V.front()->getType(),V.size()), V);
Brian Gaeke02209042004-08-20 06:00:58 +00001393}
1394
1395// destroyConstant - Remove the constant from the constant table...
1396//
Reid Spencerd84d35b2007-02-15 02:26:10 +00001397void ConstantVector::destroyConstant() {
Reid Spencer09575ba2007-02-15 03:39:18 +00001398 VectorConstants->remove(this);
Brian Gaeke02209042004-08-20 06:00:58 +00001399 destroyConstantImpl();
1400}
1401
Dan Gohman30978072007-05-24 14:36:04 +00001402/// This function will return true iff every element in this vector constant
Jim Laskeyf0478822007-01-12 22:39:14 +00001403/// is set to all ones.
1404/// @returns true iff this constant's emements are all set to all ones.
1405/// @brief Determine if the value is all ones.
Reid Spencerd84d35b2007-02-15 02:26:10 +00001406bool ConstantVector::isAllOnesValue() const {
Jim Laskeyf0478822007-01-12 22:39:14 +00001407 // Check out first element.
1408 const Constant *Elt = getOperand(0);
1409 const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1410 if (!CI || !CI->isAllOnesValue()) return false;
1411 // Then make sure all remaining elements point to the same value.
1412 for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
1413 if (getOperand(I) != Elt) return false;
1414 }
1415 return true;
1416}
1417
Dan Gohman07159202007-10-17 17:51:30 +00001418/// getSplatValue - If this is a splat constant, where all of the
1419/// elements have the same value, return that value. Otherwise return null.
1420Constant *ConstantVector::getSplatValue() {
1421 // Check out first element.
1422 Constant *Elt = getOperand(0);
1423 // Then make sure all remaining elements point to the same value.
1424 for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
1425 if (getOperand(I) != Elt) return 0;
1426 return Elt;
1427}
1428
Chris Lattner3462ae32001-12-03 22:26:30 +00001429//---- ConstantPointerNull::get() implementation...
Chris Lattnerd7a73302001-10-13 06:57:33 +00001430//
Chris Lattner98fa07b2003-05-23 20:03:32 +00001431
Chris Lattner189d19f2003-11-21 20:23:48 +00001432namespace llvm {
1433 // ConstantPointerNull does not take extra "value" argument...
1434 template<class ValType>
1435 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1436 static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1437 return new ConstantPointerNull(Ty);
1438 }
1439 };
Chris Lattner98fa07b2003-05-23 20:03:32 +00001440
Chris Lattner189d19f2003-11-21 20:23:48 +00001441 template<>
1442 struct ConvertConstantType<ConstantPointerNull, PointerType> {
1443 static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1444 // Make everyone now use a constant of the new type...
1445 Constant *New = ConstantPointerNull::get(NewTy);
1446 assert(New != OldC && "Didn't replace constant??");
1447 OldC->uncheckedReplaceAllUsesWith(New);
1448 OldC->destroyConstant(); // This constant is now dead, destroy it.
1449 }
1450 };
1451}
Chris Lattnerb50d1352003-10-05 00:17:43 +00001452
Chris Lattner69edc982006-09-28 00:35:06 +00001453static ManagedStatic<ValueMap<char, PointerType,
1454 ConstantPointerNull> > NullPtrConstants;
Chris Lattnerd7a73302001-10-13 06:57:33 +00001455
Chris Lattner3e650af2004-08-04 04:48:01 +00001456static char getValType(ConstantPointerNull *) {
1457 return 0;
1458}
1459
1460
Chris Lattner3462ae32001-12-03 22:26:30 +00001461ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
Chris Lattner69edc982006-09-28 00:35:06 +00001462 return NullPtrConstants->getOrCreate(Ty, 0);
Chris Lattner883ad0b2001-10-03 15:39:36 +00001463}
1464
Chris Lattner0c6e0b92002-08-18 00:40:04 +00001465// destroyConstant - Remove the constant from the constant table...
1466//
1467void ConstantPointerNull::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00001468 NullPtrConstants->remove(this);
Chris Lattner0c6e0b92002-08-18 00:40:04 +00001469 destroyConstantImpl();
1470}
1471
1472
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001473//---- UndefValue::get() implementation...
1474//
1475
1476namespace llvm {
1477 // UndefValue does not take extra "value" argument...
1478 template<class ValType>
1479 struct ConstantCreator<UndefValue, Type, ValType> {
1480 static UndefValue *create(const Type *Ty, const ValType &V) {
1481 return new UndefValue(Ty);
1482 }
1483 };
1484
1485 template<>
1486 struct ConvertConstantType<UndefValue, Type> {
1487 static void convert(UndefValue *OldC, const Type *NewTy) {
1488 // Make everyone now use a constant of the new type.
1489 Constant *New = UndefValue::get(NewTy);
1490 assert(New != OldC && "Didn't replace constant??");
1491 OldC->uncheckedReplaceAllUsesWith(New);
1492 OldC->destroyConstant(); // This constant is now dead, destroy it.
1493 }
1494 };
1495}
1496
Chris Lattner69edc982006-09-28 00:35:06 +00001497static ManagedStatic<ValueMap<char, Type, UndefValue> > UndefValueConstants;
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001498
1499static char getValType(UndefValue *) {
1500 return 0;
1501}
1502
1503
1504UndefValue *UndefValue::get(const Type *Ty) {
Chris Lattner69edc982006-09-28 00:35:06 +00001505 return UndefValueConstants->getOrCreate(Ty, 0);
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001506}
1507
1508// destroyConstant - Remove the constant from the constant table.
1509//
1510void UndefValue::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00001511 UndefValueConstants->remove(this);
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001512 destroyConstantImpl();
1513}
1514
1515
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001516//---- ConstantExpr::get() implementations...
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001517//
Reid Spencer8d9336d2006-12-31 05:26:44 +00001518
Dan Gohmand78c4002008-05-13 00:00:25 +00001519namespace {
1520
Reid Spenceree3c9912006-12-04 05:19:50 +00001521struct ExprMapKeyType {
1522 explicit ExprMapKeyType(unsigned opc, std::vector<Constant*> ops,
Reid Spencerdba6aa42006-12-04 18:38:05 +00001523 unsigned short pred = 0) : opcode(opc), predicate(pred), operands(ops) { }
1524 uint16_t opcode;
1525 uint16_t predicate;
Reid Spenceree3c9912006-12-04 05:19:50 +00001526 std::vector<Constant*> operands;
Reid Spenceree3c9912006-12-04 05:19:50 +00001527 bool operator==(const ExprMapKeyType& that) const {
1528 return this->opcode == that.opcode &&
1529 this->predicate == that.predicate &&
1530 this->operands == that.operands;
1531 }
1532 bool operator<(const ExprMapKeyType & that) const {
1533 return this->opcode < that.opcode ||
1534 (this->opcode == that.opcode && this->predicate < that.predicate) ||
1535 (this->opcode == that.opcode && this->predicate == that.predicate &&
1536 this->operands < that.operands);
1537 }
1538
1539 bool operator!=(const ExprMapKeyType& that) const {
1540 return !(*this == that);
1541 }
1542};
Chris Lattner98fa07b2003-05-23 20:03:32 +00001543
Dan Gohmand78c4002008-05-13 00:00:25 +00001544}
1545
Chris Lattner189d19f2003-11-21 20:23:48 +00001546namespace llvm {
1547 template<>
1548 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
Reid Spencer10fbf0e2006-12-03 05:48:19 +00001549 static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V,
1550 unsigned short pred = 0) {
Reid Spenceree3c9912006-12-04 05:19:50 +00001551 if (Instruction::isCast(V.opcode))
1552 return new UnaryConstantExpr(V.opcode, V.operands[0], Ty);
1553 if ((V.opcode >= Instruction::BinaryOpsBegin &&
Reid Spencer2341c222007-02-02 02:16:23 +00001554 V.opcode < Instruction::BinaryOpsEnd))
Reid Spenceree3c9912006-12-04 05:19:50 +00001555 return new BinaryConstantExpr(V.opcode, V.operands[0], V.operands[1]);
1556 if (V.opcode == Instruction::Select)
1557 return new SelectConstantExpr(V.operands[0], V.operands[1],
1558 V.operands[2]);
1559 if (V.opcode == Instruction::ExtractElement)
1560 return new ExtractElementConstantExpr(V.operands[0], V.operands[1]);
1561 if (V.opcode == Instruction::InsertElement)
1562 return new InsertElementConstantExpr(V.operands[0], V.operands[1],
1563 V.operands[2]);
1564 if (V.opcode == Instruction::ShuffleVector)
1565 return new ShuffleVectorConstantExpr(V.operands[0], V.operands[1],
1566 V.operands[2]);
1567 if (V.opcode == Instruction::GetElementPtr) {
1568 std::vector<Constant*> IdxList(V.operands.begin()+1, V.operands.end());
Gabor Greife9ecc682008-04-06 20:25:17 +00001569 return GetElementPtrConstantExpr::Create(V.operands[0], IdxList, Ty);
Reid Spenceree3c9912006-12-04 05:19:50 +00001570 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001571
Reid Spenceree3c9912006-12-04 05:19:50 +00001572 // The compare instructions are weird. We have to encode the predicate
1573 // value and it is combined with the instruction opcode by multiplying
1574 // the opcode by one hundred. We must decode this to get the predicate.
1575 if (V.opcode == Instruction::ICmp)
Nate Begemand2195702008-05-12 19:01:56 +00001576 return new CompareConstantExpr(Ty, Instruction::ICmp, V.predicate,
Reid Spenceree3c9912006-12-04 05:19:50 +00001577 V.operands[0], V.operands[1]);
1578 if (V.opcode == Instruction::FCmp)
Nate Begemand2195702008-05-12 19:01:56 +00001579 return new CompareConstantExpr(Ty, Instruction::FCmp, V.predicate,
1580 V.operands[0], V.operands[1]);
1581 if (V.opcode == Instruction::VICmp)
1582 return new CompareConstantExpr(Ty, Instruction::VICmp, V.predicate,
1583 V.operands[0], V.operands[1]);
1584 if (V.opcode == Instruction::VFCmp)
1585 return new CompareConstantExpr(Ty, Instruction::VFCmp, V.predicate,
Reid Spenceree3c9912006-12-04 05:19:50 +00001586 V.operands[0], V.operands[1]);
1587 assert(0 && "Invalid ConstantExpr!");
Jeff Cohen9f469632006-12-15 21:47:01 +00001588 return 0;
Chris Lattnerb50d1352003-10-05 00:17:43 +00001589 }
Chris Lattner189d19f2003-11-21 20:23:48 +00001590 };
Chris Lattnerb50d1352003-10-05 00:17:43 +00001591
Chris Lattner189d19f2003-11-21 20:23:48 +00001592 template<>
1593 struct ConvertConstantType<ConstantExpr, Type> {
1594 static void convert(ConstantExpr *OldC, const Type *NewTy) {
1595 Constant *New;
1596 switch (OldC->getOpcode()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001597 case Instruction::Trunc:
1598 case Instruction::ZExt:
1599 case Instruction::SExt:
1600 case Instruction::FPTrunc:
1601 case Instruction::FPExt:
1602 case Instruction::UIToFP:
1603 case Instruction::SIToFP:
1604 case Instruction::FPToUI:
1605 case Instruction::FPToSI:
1606 case Instruction::PtrToInt:
1607 case Instruction::IntToPtr:
1608 case Instruction::BitCast:
Reid Spencerbb65ebf2006-12-12 23:36:14 +00001609 New = ConstantExpr::getCast(OldC->getOpcode(), OldC->getOperand(0),
1610 NewTy);
Chris Lattner189d19f2003-11-21 20:23:48 +00001611 break;
Chris Lattner6e415c02004-03-12 05:54:04 +00001612 case Instruction::Select:
1613 New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1614 OldC->getOperand(1),
1615 OldC->getOperand(2));
1616 break;
Chris Lattner189d19f2003-11-21 20:23:48 +00001617 default:
1618 assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
Reid Spencer7eb55b32006-11-02 01:53:59 +00001619 OldC->getOpcode() < Instruction::BinaryOpsEnd);
Chris Lattner189d19f2003-11-21 20:23:48 +00001620 New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1621 OldC->getOperand(1));
1622 break;
1623 case Instruction::GetElementPtr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00001624 // Make everyone now use a constant of the new type...
Chris Lattner13128ab2004-10-11 22:52:25 +00001625 std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
Chris Lattner302116a2007-01-31 04:40:28 +00001626 New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0),
1627 &Idx[0], Idx.size());
Chris Lattner189d19f2003-11-21 20:23:48 +00001628 break;
1629 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001630
Chris Lattner189d19f2003-11-21 20:23:48 +00001631 assert(New != OldC && "Didn't replace constant??");
1632 OldC->uncheckedReplaceAllUsesWith(New);
1633 OldC->destroyConstant(); // This constant is now dead, destroy it.
1634 }
1635 };
1636} // end namespace llvm
Chris Lattnerb50d1352003-10-05 00:17:43 +00001637
1638
Chris Lattner3e650af2004-08-04 04:48:01 +00001639static ExprMapKeyType getValType(ConstantExpr *CE) {
1640 std::vector<Constant*> Operands;
1641 Operands.reserve(CE->getNumOperands());
1642 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
1643 Operands.push_back(cast<Constant>(CE->getOperand(i)));
Reid Spenceree3c9912006-12-04 05:19:50 +00001644 return ExprMapKeyType(CE->getOpcode(), Operands,
1645 CE->isCompare() ? CE->getPredicate() : 0);
Chris Lattner3e650af2004-08-04 04:48:01 +00001646}
1647
Chris Lattner69edc982006-09-28 00:35:06 +00001648static ManagedStatic<ValueMap<ExprMapKeyType, Type,
1649 ConstantExpr> > ExprConstants;
Vikram S. Adve4c485332002-07-15 18:19:33 +00001650
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001651/// This is a utility function to handle folding of casts and lookup of the
Duncan Sands7d6c8ae2008-03-30 19:38:55 +00001652/// cast in the ExprConstants map. It is used by the various get* methods below.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001653static inline Constant *getFoldedCast(
1654 Instruction::CastOps opc, Constant *C, const Type *Ty) {
Chris Lattner815ae2b2003-10-07 22:19:19 +00001655 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001656 // Fold a few common cases
1657 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
1658 return FC;
Chris Lattneracdbe712003-04-17 19:24:48 +00001659
Vikram S. Adve4c485332002-07-15 18:19:33 +00001660 // Look up the constant in the table first to ensure uniqueness
Chris Lattner2b383d2e2003-05-13 21:37:02 +00001661 std::vector<Constant*> argVec(1, C);
Reid Spenceree3c9912006-12-04 05:19:50 +00001662 ExprMapKeyType Key(opc, argVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001663 return ExprConstants->getOrCreate(Ty, Key);
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001664}
Reid Spencerf37dc652006-12-05 19:14:13 +00001665
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001666Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
1667 Instruction::CastOps opc = Instruction::CastOps(oc);
1668 assert(Instruction::isCast(opc) && "opcode out of range");
1669 assert(C && Ty && "Null arguments to getCast");
1670 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1671
1672 switch (opc) {
1673 default:
1674 assert(0 && "Invalid cast opcode");
1675 break;
1676 case Instruction::Trunc: return getTrunc(C, Ty);
Reid Spencerbb65ebf2006-12-12 23:36:14 +00001677 case Instruction::ZExt: return getZExt(C, Ty);
1678 case Instruction::SExt: return getSExt(C, Ty);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001679 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
1680 case Instruction::FPExt: return getFPExtend(C, Ty);
1681 case Instruction::UIToFP: return getUIToFP(C, Ty);
1682 case Instruction::SIToFP: return getSIToFP(C, Ty);
1683 case Instruction::FPToUI: return getFPToUI(C, Ty);
1684 case Instruction::FPToSI: return getFPToSI(C, Ty);
1685 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1686 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1687 case Instruction::BitCast: return getBitCast(C, Ty);
Chris Lattner1ece6f82005-01-01 15:59:57 +00001688 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001689 return 0;
Reid Spencerf37dc652006-12-05 19:14:13 +00001690}
1691
Reid Spencer5c140882006-12-04 20:17:56 +00001692Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
1693 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1694 return getCast(Instruction::BitCast, C, Ty);
1695 return getCast(Instruction::ZExt, C, Ty);
1696}
1697
1698Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
1699 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1700 return getCast(Instruction::BitCast, C, Ty);
1701 return getCast(Instruction::SExt, C, Ty);
1702}
1703
1704Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
1705 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1706 return getCast(Instruction::BitCast, C, Ty);
1707 return getCast(Instruction::Trunc, C, Ty);
1708}
1709
Reid Spencerbc245a02006-12-05 03:25:26 +00001710Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
1711 assert(isa<PointerType>(S->getType()) && "Invalid cast");
Chris Lattner03c49532007-01-15 02:27:26 +00001712 assert((Ty->isInteger() || isa<PointerType>(Ty)) && "Invalid cast");
Reid Spencerbc245a02006-12-05 03:25:26 +00001713
Chris Lattner03c49532007-01-15 02:27:26 +00001714 if (Ty->isInteger())
Reid Spencerbc245a02006-12-05 03:25:26 +00001715 return getCast(Instruction::PtrToInt, S, Ty);
1716 return getCast(Instruction::BitCast, S, Ty);
1717}
1718
Reid Spencer56521c42006-12-12 00:51:07 +00001719Constant *ConstantExpr::getIntegerCast(Constant *C, const Type *Ty,
1720 bool isSigned) {
Chris Lattner03c49532007-01-15 02:27:26 +00001721 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
Reid Spencer56521c42006-12-12 00:51:07 +00001722 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1723 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1724 Instruction::CastOps opcode =
1725 (SrcBits == DstBits ? Instruction::BitCast :
1726 (SrcBits > DstBits ? Instruction::Trunc :
1727 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1728 return getCast(opcode, C, Ty);
1729}
1730
1731Constant *ConstantExpr::getFPCast(Constant *C, const Type *Ty) {
1732 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1733 "Invalid cast");
1734 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1735 unsigned DstBits = Ty->getPrimitiveSizeInBits();
Reid Spencerca104e82006-12-12 05:38:50 +00001736 if (SrcBits == DstBits)
1737 return C; // Avoid a useless cast
Reid Spencer56521c42006-12-12 00:51:07 +00001738 Instruction::CastOps opcode =
Reid Spencerca104e82006-12-12 05:38:50 +00001739 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
Reid Spencer56521c42006-12-12 00:51:07 +00001740 return getCast(opcode, C, Ty);
1741}
1742
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001743Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
Chris Lattner03c49532007-01-15 02:27:26 +00001744 assert(C->getType()->isInteger() && "Trunc operand must be integer");
1745 assert(Ty->isInteger() && "Trunc produces only integral");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001746 assert(C->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()&&
1747 "SrcTy must be larger than DestTy for Trunc!");
1748
1749 return getFoldedCast(Instruction::Trunc, C, Ty);
1750}
1751
Reid Spencerbb65ebf2006-12-12 23:36:14 +00001752Constant *ConstantExpr::getSExt(Constant *C, const Type *Ty) {
Chris Lattner03c49532007-01-15 02:27:26 +00001753 assert(C->getType()->isInteger() && "SEXt operand must be integral");
1754 assert(Ty->isInteger() && "SExt produces only integer");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001755 assert(C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1756 "SrcTy must be smaller than DestTy for SExt!");
1757
1758 return getFoldedCast(Instruction::SExt, C, Ty);
Chris Lattnerdd284742004-04-04 23:20:30 +00001759}
1760
Reid Spencerbb65ebf2006-12-12 23:36:14 +00001761Constant *ConstantExpr::getZExt(Constant *C, const Type *Ty) {
Chris Lattner03c49532007-01-15 02:27:26 +00001762 assert(C->getType()->isInteger() && "ZEXt operand must be integral");
1763 assert(Ty->isInteger() && "ZExt produces only integer");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001764 assert(C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1765 "SrcTy must be smaller than DestTy for ZExt!");
1766
1767 return getFoldedCast(Instruction::ZExt, C, Ty);
1768}
1769
1770Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
1771 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1772 C->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()&&
1773 "This is an illegal floating point truncation!");
1774 return getFoldedCast(Instruction::FPTrunc, C, Ty);
1775}
1776
1777Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
1778 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1779 C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1780 "This is an illegal floating point extension!");
1781 return getFoldedCast(Instruction::FPExt, C, Ty);
1782}
1783
1784Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
Nate Begemand4d45c22007-11-17 03:58:34 +00001785 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1786 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1787 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1788 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
1789 "This is an illegal uint to floating point cast!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001790 return getFoldedCast(Instruction::UIToFP, C, Ty);
1791}
1792
1793Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
Nate Begemand4d45c22007-11-17 03:58:34 +00001794 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1795 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1796 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1797 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001798 "This is an illegal sint to floating point cast!");
1799 return getFoldedCast(Instruction::SIToFP, C, Ty);
1800}
1801
1802Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
Nate Begemand4d45c22007-11-17 03:58:34 +00001803 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1804 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1805 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1806 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
1807 "This is an illegal floating point to uint cast!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001808 return getFoldedCast(Instruction::FPToUI, C, Ty);
1809}
1810
1811Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
Nate Begemand4d45c22007-11-17 03:58:34 +00001812 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1813 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1814 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1815 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
1816 "This is an illegal floating point to sint cast!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001817 return getFoldedCast(Instruction::FPToSI, C, Ty);
1818}
1819
1820Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
1821 assert(isa<PointerType>(C->getType()) && "PtrToInt source must be pointer");
Chris Lattner03c49532007-01-15 02:27:26 +00001822 assert(DstTy->isInteger() && "PtrToInt destination must be integral");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001823 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
1824}
1825
1826Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
Chris Lattner03c49532007-01-15 02:27:26 +00001827 assert(C->getType()->isInteger() && "IntToPtr source must be integral");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001828 assert(isa<PointerType>(DstTy) && "IntToPtr destination must be a pointer");
1829 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
1830}
1831
1832Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
1833 // BitCast implies a no-op cast of type only. No bits change. However, you
1834 // can't cast pointers to anything but pointers.
1835 const Type *SrcTy = C->getType();
1836 assert((isa<PointerType>(SrcTy) == isa<PointerType>(DstTy)) &&
Reid Spencer5c140882006-12-04 20:17:56 +00001837 "BitCast cannot cast pointer to non-pointer and vice versa");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001838
1839 // Now we know we're not dealing with mismatched pointer casts (ptr->nonptr
1840 // or nonptr->ptr). For all the other types, the cast is okay if source and
1841 // destination bit widths are identical.
1842 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1843 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
Reid Spencer5c140882006-12-04 20:17:56 +00001844 assert(SrcBitSize == DstBitSize && "BitCast requies types of same width");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001845 return getFoldedCast(Instruction::BitCast, C, DstTy);
Chris Lattnerdd284742004-04-04 23:20:30 +00001846}
1847
Alkis Evlogimenosda5de052004-10-24 01:41:10 +00001848Constant *ConstantExpr::getSizeOf(const Type *Ty) {
Gordon Henriksen7ce31762007-10-06 14:29:36 +00001849 // sizeof is implemented as: (i64) gep (Ty*)null, 1
Chris Lattnerb5d70302007-02-19 20:01:23 +00001850 Constant *GEPIdx = ConstantInt::get(Type::Int32Ty, 1);
1851 Constant *GEP =
Christopher Lambedf07882007-12-17 01:12:55 +00001852 getGetElementPtr(getNullValue(PointerType::getUnqual(Ty)), &GEPIdx, 1);
Chris Lattnerb5d70302007-02-19 20:01:23 +00001853 return getCast(Instruction::PtrToInt, GEP, Type::Int64Ty);
Alkis Evlogimenos9160d5f2005-03-19 11:40:31 +00001854}
1855
Chris Lattnerb50d1352003-10-05 00:17:43 +00001856Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
Reid Spencera009d0d2006-12-04 21:35:24 +00001857 Constant *C1, Constant *C2) {
Chris Lattner38a9bcd2003-05-21 17:49:25 +00001858 // Check the operands for consistency first
Reid Spencer7eb55b32006-11-02 01:53:59 +00001859 assert(Opcode >= Instruction::BinaryOpsBegin &&
1860 Opcode < Instruction::BinaryOpsEnd &&
Chris Lattner38a9bcd2003-05-21 17:49:25 +00001861 "Invalid opcode in binary constant expression");
1862 assert(C1->getType() == C2->getType() &&
1863 "Operand types in binary constant expression should match");
Chris Lattnerb50d1352003-10-05 00:17:43 +00001864
Reid Spencer542964f2007-01-11 18:21:29 +00001865 if (ReqTy == C1->getType() || ReqTy == Type::Int1Ty)
Chris Lattnerb50d1352003-10-05 00:17:43 +00001866 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1867 return FC; // Fold a few common cases...
Chris Lattneracdbe712003-04-17 19:24:48 +00001868
Chris Lattner2b383d2e2003-05-13 21:37:02 +00001869 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
Reid Spencera009d0d2006-12-04 21:35:24 +00001870 ExprMapKeyType Key(Opcode, argVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001871 return ExprConstants->getOrCreate(ReqTy, Key);
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001872}
1873
Reid Spencer266e42b2006-12-23 06:05:41 +00001874Constant *ConstantExpr::getCompareTy(unsigned short predicate,
Reid Spencera009d0d2006-12-04 21:35:24 +00001875 Constant *C1, Constant *C2) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001876 switch (predicate) {
1877 default: assert(0 && "Invalid CmpInst predicate");
1878 case FCmpInst::FCMP_FALSE: case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_OGT:
1879 case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OLE:
1880 case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_ORD: case FCmpInst::FCMP_UNO:
1881 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UGT: case FCmpInst::FCMP_UGE:
1882 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_ULE: case FCmpInst::FCMP_UNE:
1883 case FCmpInst::FCMP_TRUE:
1884 return getFCmp(predicate, C1, C2);
1885 case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_UGT:
1886 case ICmpInst::ICMP_UGE: case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE:
1887 case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_SGE: case ICmpInst::ICMP_SLT:
1888 case ICmpInst::ICMP_SLE:
1889 return getICmp(predicate, C1, C2);
1890 }
Reid Spencera009d0d2006-12-04 21:35:24 +00001891}
1892
1893Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001894#ifndef NDEBUG
1895 switch (Opcode) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00001896 case Instruction::Add:
1897 case Instruction::Sub:
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001898 case Instruction::Mul:
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001899 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Chris Lattner03c49532007-01-15 02:27:26 +00001900 assert((C1->getType()->isInteger() || C1->getType()->isFloatingPoint() ||
Reid Spencerd84d35b2007-02-15 02:26:10 +00001901 isa<VectorType>(C1->getType())) &&
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001902 "Tried to create an arithmetic operation on a non-arithmetic type!");
1903 break;
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001904 case Instruction::UDiv:
1905 case Instruction::SDiv:
1906 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00001907 assert((C1->getType()->isInteger() || (isa<VectorType>(C1->getType()) &&
1908 cast<VectorType>(C1->getType())->getElementType()->isInteger())) &&
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001909 "Tried to create an arithmetic operation on a non-arithmetic type!");
1910 break;
1911 case Instruction::FDiv:
1912 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00001913 assert((C1->getType()->isFloatingPoint() || (isa<VectorType>(C1->getType())
1914 && cast<VectorType>(C1->getType())->getElementType()->isFloatingPoint()))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001915 && "Tried to create an arithmetic operation on a non-arithmetic type!");
1916 break;
Reid Spencer7eb55b32006-11-02 01:53:59 +00001917 case Instruction::URem:
1918 case Instruction::SRem:
1919 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00001920 assert((C1->getType()->isInteger() || (isa<VectorType>(C1->getType()) &&
1921 cast<VectorType>(C1->getType())->getElementType()->isInteger())) &&
Reid Spencer7eb55b32006-11-02 01:53:59 +00001922 "Tried to create an arithmetic operation on a non-arithmetic type!");
1923 break;
1924 case Instruction::FRem:
1925 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00001926 assert((C1->getType()->isFloatingPoint() || (isa<VectorType>(C1->getType())
1927 && cast<VectorType>(C1->getType())->getElementType()->isFloatingPoint()))
Reid Spencer7eb55b32006-11-02 01:53:59 +00001928 && "Tried to create an arithmetic operation on a non-arithmetic type!");
1929 break;
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001930 case Instruction::And:
1931 case Instruction::Or:
1932 case Instruction::Xor:
1933 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00001934 assert((C1->getType()->isInteger() || isa<VectorType>(C1->getType())) &&
Misha Brukman3852f652005-01-27 06:46:38 +00001935 "Tried to create a logical operation on a non-integral type!");
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001936 break;
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001937 case Instruction::Shl:
Reid Spencerfdff9382006-11-08 06:47:33 +00001938 case Instruction::LShr:
1939 case Instruction::AShr:
Reid Spencer2341c222007-02-02 02:16:23 +00001940 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Chris Lattner03c49532007-01-15 02:27:26 +00001941 assert(C1->getType()->isInteger() &&
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001942 "Tried to create a shift operation on a non-integer type!");
1943 break;
1944 default:
1945 break;
1946 }
1947#endif
1948
Reid Spencera009d0d2006-12-04 21:35:24 +00001949 return getTy(C1->getType(), Opcode, C1, C2);
1950}
1951
Reid Spencer266e42b2006-12-23 06:05:41 +00001952Constant *ConstantExpr::getCompare(unsigned short pred,
Reid Spencera009d0d2006-12-04 21:35:24 +00001953 Constant *C1, Constant *C2) {
1954 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Reid Spencer266e42b2006-12-23 06:05:41 +00001955 return getCompareTy(pred, C1, C2);
Chris Lattner29ca2c62004-08-04 18:50:09 +00001956}
1957
Chris Lattner6e415c02004-03-12 05:54:04 +00001958Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
1959 Constant *V1, Constant *V2) {
Reid Spencer2546b762007-01-26 07:37:34 +00001960 assert(C->getType() == Type::Int1Ty && "Select condition must be i1!");
Chris Lattner6e415c02004-03-12 05:54:04 +00001961 assert(V1->getType() == V2->getType() && "Select value types must match!");
1962 assert(V1->getType()->isFirstClassType() && "Cannot select aggregate type!");
1963
1964 if (ReqTy == V1->getType())
1965 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1966 return SC; // Fold common cases
1967
1968 std::vector<Constant*> argVec(3, C);
1969 argVec[1] = V1;
1970 argVec[2] = V2;
Reid Spenceree3c9912006-12-04 05:19:50 +00001971 ExprMapKeyType Key(Instruction::Select, argVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001972 return ExprConstants->getOrCreate(ReqTy, Key);
Chris Lattner6e415c02004-03-12 05:54:04 +00001973}
1974
Chris Lattnerb50d1352003-10-05 00:17:43 +00001975Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
Chris Lattner302116a2007-01-31 04:40:28 +00001976 Value* const *Idxs,
1977 unsigned NumIdx) {
Gabor Greif697e94c2008-05-15 10:04:30 +00001978 assert(GetElementPtrInst::getIndexedType(C->getType(),
1979 Idxs, Idxs+NumIdx, true)
1980 && "GEP indices invalid!");
Chris Lattner04b60fe2004-02-16 20:46:13 +00001981
Chris Lattner302116a2007-01-31 04:40:28 +00001982 if (Constant *FC = ConstantFoldGetElementPtr(C, (Constant**)Idxs, NumIdx))
Chris Lattneracdbe712003-04-17 19:24:48 +00001983 return FC; // Fold a few common cases...
Chris Lattner04b60fe2004-02-16 20:46:13 +00001984
Chris Lattnerb50d1352003-10-05 00:17:43 +00001985 assert(isa<PointerType>(C->getType()) &&
Chris Lattner98fa07b2003-05-23 20:03:32 +00001986 "Non-pointer type for constant GetElementPtr expression");
Vikram S. Adve4c485332002-07-15 18:19:33 +00001987 // Look up the constant in the table first to ensure uniqueness
Chris Lattner13128ab2004-10-11 22:52:25 +00001988 std::vector<Constant*> ArgVec;
Chris Lattner302116a2007-01-31 04:40:28 +00001989 ArgVec.reserve(NumIdx+1);
Chris Lattner13128ab2004-10-11 22:52:25 +00001990 ArgVec.push_back(C);
Chris Lattner302116a2007-01-31 04:40:28 +00001991 for (unsigned i = 0; i != NumIdx; ++i)
1992 ArgVec.push_back(cast<Constant>(Idxs[i]));
1993 const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001994 return ExprConstants->getOrCreate(ReqTy, Key);
Vikram S. Adve4c485332002-07-15 18:19:33 +00001995}
1996
Chris Lattner302116a2007-01-31 04:40:28 +00001997Constant *ConstantExpr::getGetElementPtr(Constant *C, Value* const *Idxs,
1998 unsigned NumIdx) {
Chris Lattnerb50d1352003-10-05 00:17:43 +00001999 // Get the result type of the getelementptr!
Chris Lattner302116a2007-01-31 04:40:28 +00002000 const Type *Ty =
David Greenec656cbb2007-09-04 15:46:09 +00002001 GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx, true);
Chris Lattnerb50d1352003-10-05 00:17:43 +00002002 assert(Ty && "GEP indices invalid!");
Christopher Lamb54dd24c2007-12-11 08:59:05 +00002003 unsigned As = cast<PointerType>(C->getType())->getAddressSpace();
2004 return getGetElementPtrTy(PointerType::get(Ty, As), C, Idxs, NumIdx);
Chris Lattner13128ab2004-10-11 22:52:25 +00002005}
2006
Chris Lattner302116a2007-01-31 04:40:28 +00002007Constant *ConstantExpr::getGetElementPtr(Constant *C, Constant* const *Idxs,
2008 unsigned NumIdx) {
2009 return getGetElementPtr(C, (Value* const *)Idxs, NumIdx);
Chris Lattnerb50d1352003-10-05 00:17:43 +00002010}
2011
Chris Lattner302116a2007-01-31 04:40:28 +00002012
Reid Spenceree3c9912006-12-04 05:19:50 +00002013Constant *
2014ConstantExpr::getICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2015 assert(LHS->getType() == RHS->getType());
2016 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
2017 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
2018
Reid Spencer266e42b2006-12-23 06:05:41 +00002019 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
Reid Spenceree3c9912006-12-04 05:19:50 +00002020 return FC; // Fold a few common cases...
2021
2022 // Look up the constant in the table first to ensure uniqueness
2023 std::vector<Constant*> ArgVec;
2024 ArgVec.push_back(LHS);
2025 ArgVec.push_back(RHS);
Reid Spencerb1537492006-12-24 18:42:29 +00002026 // Get the key type with both the opcode and predicate
Reid Spenceree3c9912006-12-04 05:19:50 +00002027 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
Reid Spencer542964f2007-01-11 18:21:29 +00002028 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
Reid Spenceree3c9912006-12-04 05:19:50 +00002029}
2030
2031Constant *
2032ConstantExpr::getFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2033 assert(LHS->getType() == RHS->getType());
2034 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
2035
Reid Spencer266e42b2006-12-23 06:05:41 +00002036 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
Reid Spenceree3c9912006-12-04 05:19:50 +00002037 return FC; // Fold a few common cases...
2038
2039 // Look up the constant in the table first to ensure uniqueness
2040 std::vector<Constant*> ArgVec;
2041 ArgVec.push_back(LHS);
2042 ArgVec.push_back(RHS);
Reid Spencerb1537492006-12-24 18:42:29 +00002043 // Get the key type with both the opcode and predicate
Reid Spenceree3c9912006-12-04 05:19:50 +00002044 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
Reid Spencer542964f2007-01-11 18:21:29 +00002045 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
Reid Spenceree3c9912006-12-04 05:19:50 +00002046}
2047
Nate Begemand2195702008-05-12 19:01:56 +00002048Constant *
2049ConstantExpr::getVICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2050 assert(isa<VectorType>(LHS->getType()) &&
2051 "Tried to create vicmp operation on non-vector type!");
2052 assert(LHS->getType() == RHS->getType());
2053 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
2054 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid VICmp Predicate");
2055
Nate Begemanac7f3d92008-05-12 19:23:22 +00002056 const VectorType *VTy = cast<VectorType>(LHS->getType());
Nate Begemand2195702008-05-12 19:01:56 +00002057 const Type *EltTy = VTy->getElementType();
2058 unsigned NumElts = VTy->getNumElements();
2059
2060 SmallVector<Constant *, 8> Elts;
2061 for (unsigned i = 0; i != NumElts; ++i) {
2062 Constant *FC = ConstantFoldCompareInstruction(pred, LHS->getOperand(i),
2063 RHS->getOperand(i));
2064 if (FC) {
2065 uint64_t Val = cast<ConstantInt>(FC)->getZExtValue();
2066 if (Val != 0ULL)
2067 Elts.push_back(ConstantInt::getAllOnesValue(EltTy));
2068 else
2069 Elts.push_back(ConstantInt::get(EltTy, 0ULL));
2070 }
2071 }
2072 if (Elts.size() == NumElts)
2073 return ConstantVector::get(&Elts[0], Elts.size());
2074
2075 // Look up the constant in the table first to ensure uniqueness
2076 std::vector<Constant*> ArgVec;
2077 ArgVec.push_back(LHS);
2078 ArgVec.push_back(RHS);
2079 // Get the key type with both the opcode and predicate
2080 const ExprMapKeyType Key(Instruction::VICmp, ArgVec, pred);
2081 return ExprConstants->getOrCreate(LHS->getType(), Key);
2082}
2083
2084Constant *
2085ConstantExpr::getVFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2086 assert(isa<VectorType>(LHS->getType()) &&
2087 "Tried to create vfcmp operation on non-vector type!");
2088 assert(LHS->getType() == RHS->getType());
2089 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid VFCmp Predicate");
2090
2091 const VectorType *VTy = cast<VectorType>(LHS->getType());
2092 unsigned NumElts = VTy->getNumElements();
2093 const Type *EltTy = VTy->getElementType();
2094 const Type *REltTy = IntegerType::get(EltTy->getPrimitiveSizeInBits());
2095 const Type *ResultTy = VectorType::get(REltTy, NumElts);
2096
2097 SmallVector<Constant *, 8> Elts;
2098 for (unsigned i = 0; i != NumElts; ++i) {
2099 Constant *FC = ConstantFoldCompareInstruction(pred, LHS->getOperand(i),
2100 RHS->getOperand(i));
2101 if (FC) {
2102 uint64_t Val = cast<ConstantInt>(FC)->getZExtValue();
2103 if (Val != 0ULL)
2104 Elts.push_back(ConstantInt::getAllOnesValue(REltTy));
2105 else
2106 Elts.push_back(ConstantInt::get(REltTy, 0ULL));
2107 }
2108 }
2109 if (Elts.size() == NumElts)
2110 return ConstantVector::get(&Elts[0], Elts.size());
2111
2112 // Look up the constant in the table first to ensure uniqueness
2113 std::vector<Constant*> ArgVec;
2114 ArgVec.push_back(LHS);
2115 ArgVec.push_back(RHS);
2116 // Get the key type with both the opcode and predicate
2117 const ExprMapKeyType Key(Instruction::VFCmp, ArgVec, pred);
2118 return ExprConstants->getOrCreate(ResultTy, Key);
2119}
2120
Robert Bocchino23004482006-01-10 19:05:34 +00002121Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
2122 Constant *Idx) {
Robert Bocchinode7f1c92006-01-10 20:03:46 +00002123 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
2124 return FC; // Fold a few common cases...
Robert Bocchino23004482006-01-10 19:05:34 +00002125 // Look up the constant in the table first to ensure uniqueness
2126 std::vector<Constant*> ArgVec(1, Val);
2127 ArgVec.push_back(Idx);
Reid Spenceree3c9912006-12-04 05:19:50 +00002128 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
Chris Lattner69edc982006-09-28 00:35:06 +00002129 return ExprConstants->getOrCreate(ReqTy, Key);
Robert Bocchino23004482006-01-10 19:05:34 +00002130}
2131
2132Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00002133 assert(isa<VectorType>(Val->getType()) &&
Reid Spencer09575ba2007-02-15 03:39:18 +00002134 "Tried to create extractelement operation on non-vector type!");
Reid Spencer8d9336d2006-12-31 05:26:44 +00002135 assert(Idx->getType() == Type::Int32Ty &&
Reid Spencer2546b762007-01-26 07:37:34 +00002136 "Extractelement index must be i32 type!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00002137 return getExtractElementTy(cast<VectorType>(Val->getType())->getElementType(),
Robert Bocchino23004482006-01-10 19:05:34 +00002138 Val, Idx);
2139}
Chris Lattnerb50d1352003-10-05 00:17:43 +00002140
Robert Bocchinoca27f032006-01-17 20:07:22 +00002141Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
2142 Constant *Elt, Constant *Idx) {
2143 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
2144 return FC; // Fold a few common cases...
2145 // Look up the constant in the table first to ensure uniqueness
2146 std::vector<Constant*> ArgVec(1, Val);
2147 ArgVec.push_back(Elt);
2148 ArgVec.push_back(Idx);
Reid Spenceree3c9912006-12-04 05:19:50 +00002149 const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
Chris Lattner69edc982006-09-28 00:35:06 +00002150 return ExprConstants->getOrCreate(ReqTy, Key);
Robert Bocchinoca27f032006-01-17 20:07:22 +00002151}
2152
2153Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
2154 Constant *Idx) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00002155 assert(isa<VectorType>(Val->getType()) &&
Reid Spencer09575ba2007-02-15 03:39:18 +00002156 "Tried to create insertelement operation on non-vector type!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00002157 assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType()
Robert Bocchinoca27f032006-01-17 20:07:22 +00002158 && "Insertelement types must match!");
Reid Spencer8d9336d2006-12-31 05:26:44 +00002159 assert(Idx->getType() == Type::Int32Ty &&
Reid Spencer2546b762007-01-26 07:37:34 +00002160 "Insertelement index must be i32 type!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00002161 return getInsertElementTy(cast<VectorType>(Val->getType())->getElementType(),
Robert Bocchinoca27f032006-01-17 20:07:22 +00002162 Val, Elt, Idx);
2163}
2164
Chris Lattnerbbe0a422006-04-08 01:18:18 +00002165Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
2166 Constant *V2, Constant *Mask) {
2167 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
2168 return FC; // Fold a few common cases...
2169 // Look up the constant in the table first to ensure uniqueness
2170 std::vector<Constant*> ArgVec(1, V1);
2171 ArgVec.push_back(V2);
2172 ArgVec.push_back(Mask);
Reid Spenceree3c9912006-12-04 05:19:50 +00002173 const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
Chris Lattner69edc982006-09-28 00:35:06 +00002174 return ExprConstants->getOrCreate(ReqTy, Key);
Chris Lattnerbbe0a422006-04-08 01:18:18 +00002175}
2176
2177Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
2178 Constant *Mask) {
2179 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
2180 "Invalid shuffle vector constant expr operands!");
2181 return getShuffleVectorTy(V1->getType(), V1, V2, Mask);
2182}
2183
Reid Spencer2eadb532007-01-21 00:29:26 +00002184Constant *ConstantExpr::getZeroValueForNegationExpr(const Type *Ty) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00002185 if (const VectorType *PTy = dyn_cast<VectorType>(Ty))
Reid Spencer6598ca82007-01-21 02:29:10 +00002186 if (PTy->getElementType()->isFloatingPoint()) {
2187 std::vector<Constant*> zeros(PTy->getNumElements(),
Dale Johannesen98d3a082007-09-14 22:26:36 +00002188 ConstantFP::getNegativeZero(PTy->getElementType()));
Reid Spencerd84d35b2007-02-15 02:26:10 +00002189 return ConstantVector::get(PTy, zeros);
Reid Spencer6598ca82007-01-21 02:29:10 +00002190 }
Reid Spencer2eadb532007-01-21 00:29:26 +00002191
Dale Johannesen98d3a082007-09-14 22:26:36 +00002192 if (Ty->isFloatingPoint())
2193 return ConstantFP::getNegativeZero(Ty);
Reid Spencer2eadb532007-01-21 00:29:26 +00002194
2195 return Constant::getNullValue(Ty);
2196}
2197
Vikram S. Adve4c485332002-07-15 18:19:33 +00002198// destroyConstant - Remove the constant from the constant table...
2199//
2200void ConstantExpr::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00002201 ExprConstants->remove(this);
Vikram S. Adve4c485332002-07-15 18:19:33 +00002202 destroyConstantImpl();
Vikram S. Adve4e537b22002-07-14 23:13:17 +00002203}
2204
Chris Lattner3cd8c562002-07-30 18:54:25 +00002205const char *ConstantExpr::getOpcodeName() const {
2206 return Instruction::getOpcodeName(getOpcode());
Vikram S. Adve4e537b22002-07-14 23:13:17 +00002207}
Reid Spencer1ebe1ab2004-07-17 23:48:33 +00002208
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002209//===----------------------------------------------------------------------===//
2210// replaceUsesOfWithOnConstant implementations
2211
Chris Lattner913849b2007-08-21 00:55:23 +00002212/// replaceUsesOfWithOnConstant - Update this constant array to change uses of
2213/// 'From' to be uses of 'To'. This must update the uniquing data structures
2214/// etc.
2215///
2216/// Note that we intentionally replace all uses of From with To here. Consider
2217/// a large array that uses 'From' 1000 times. By handling this case all here,
2218/// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
2219/// single invocation handles all 1000 uses. Handling them one at a time would
2220/// work, but would be really slow because it would have to unique each updated
2221/// array instance.
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002222void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
Chris Lattner7a1450d2005-10-04 18:13:04 +00002223 Use *U) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002224 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
Chris Lattner8760ec72005-10-04 01:17:50 +00002225 Constant *ToC = cast<Constant>(To);
Chris Lattnerdff59112005-10-04 18:47:09 +00002226
Jim Laskeyc03caef2006-07-17 17:38:29 +00002227 std::pair<ArrayConstantsTy::MapKey, Constant*> Lookup;
Chris Lattnerb64419a2005-10-03 22:51:37 +00002228 Lookup.first.first = getType();
2229 Lookup.second = this;
Chris Lattnerdff59112005-10-04 18:47:09 +00002230
Chris Lattnerb64419a2005-10-03 22:51:37 +00002231 std::vector<Constant*> &Values = Lookup.first.second;
2232 Values.reserve(getNumOperands()); // Build replacement array.
Chris Lattnerdff59112005-10-04 18:47:09 +00002233
Chris Lattner8760ec72005-10-04 01:17:50 +00002234 // Fill values with the modified operands of the constant array. Also,
2235 // compute whether this turns into an all-zeros array.
Chris Lattnerdff59112005-10-04 18:47:09 +00002236 bool isAllZeros = false;
Chris Lattner913849b2007-08-21 00:55:23 +00002237 unsigned NumUpdated = 0;
Chris Lattnerdff59112005-10-04 18:47:09 +00002238 if (!ToC->isNullValue()) {
Chris Lattner913849b2007-08-21 00:55:23 +00002239 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2240 Constant *Val = cast<Constant>(O->get());
2241 if (Val == From) {
2242 Val = ToC;
2243 ++NumUpdated;
2244 }
2245 Values.push_back(Val);
2246 }
Chris Lattnerdff59112005-10-04 18:47:09 +00002247 } else {
2248 isAllZeros = true;
2249 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2250 Constant *Val = cast<Constant>(O->get());
Chris Lattner913849b2007-08-21 00:55:23 +00002251 if (Val == From) {
2252 Val = ToC;
2253 ++NumUpdated;
2254 }
Chris Lattnerdff59112005-10-04 18:47:09 +00002255 Values.push_back(Val);
2256 if (isAllZeros) isAllZeros = Val->isNullValue();
2257 }
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002258 }
2259
Chris Lattnerb64419a2005-10-03 22:51:37 +00002260 Constant *Replacement = 0;
2261 if (isAllZeros) {
2262 Replacement = ConstantAggregateZero::get(getType());
2263 } else {
2264 // Check to see if we have this array type already.
2265 bool Exists;
Jim Laskeyc03caef2006-07-17 17:38:29 +00002266 ArrayConstantsTy::MapTy::iterator I =
Chris Lattner69edc982006-09-28 00:35:06 +00002267 ArrayConstants->InsertOrGetItem(Lookup, Exists);
Chris Lattnerb64419a2005-10-03 22:51:37 +00002268
2269 if (Exists) {
2270 Replacement = I->second;
2271 } else {
2272 // Okay, the new shape doesn't exist in the system yet. Instead of
2273 // creating a new constant array, inserting it, replaceallusesof'ing the
2274 // old with the new, then deleting the old... just update the current one
2275 // in place!
Chris Lattner69edc982006-09-28 00:35:06 +00002276 ArrayConstants->MoveConstantToNewSlot(this, I);
Chris Lattnerb64419a2005-10-03 22:51:37 +00002277
Chris Lattner913849b2007-08-21 00:55:23 +00002278 // Update to the new value. Optimize for the case when we have a single
2279 // operand that we're changing, but handle bulk updates efficiently.
2280 if (NumUpdated == 1) {
2281 unsigned OperandToUpdate = U-OperandList;
2282 assert(getOperand(OperandToUpdate) == From &&
2283 "ReplaceAllUsesWith broken!");
2284 setOperand(OperandToUpdate, ToC);
2285 } else {
2286 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2287 if (getOperand(i) == From)
2288 setOperand(i, ToC);
2289 }
Chris Lattnerb64419a2005-10-03 22:51:37 +00002290 return;
2291 }
2292 }
2293
2294 // Otherwise, I do need to replace this with an existing value.
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002295 assert(Replacement != this && "I didn't contain From!");
2296
Chris Lattner7a1450d2005-10-04 18:13:04 +00002297 // Everyone using this now uses the replacement.
2298 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002299
2300 // Delete the old constant!
2301 destroyConstant();
2302}
2303
2304void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
Chris Lattner7a1450d2005-10-04 18:13:04 +00002305 Use *U) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002306 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
Chris Lattner8760ec72005-10-04 01:17:50 +00002307 Constant *ToC = cast<Constant>(To);
2308
Chris Lattnerdff59112005-10-04 18:47:09 +00002309 unsigned OperandToUpdate = U-OperandList;
2310 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
2311
Jim Laskeyc03caef2006-07-17 17:38:29 +00002312 std::pair<StructConstantsTy::MapKey, Constant*> Lookup;
Chris Lattner8760ec72005-10-04 01:17:50 +00002313 Lookup.first.first = getType();
2314 Lookup.second = this;
2315 std::vector<Constant*> &Values = Lookup.first.second;
2316 Values.reserve(getNumOperands()); // Build replacement struct.
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002317
Chris Lattnerdff59112005-10-04 18:47:09 +00002318
Chris Lattner8760ec72005-10-04 01:17:50 +00002319 // Fill values with the modified operands of the constant struct. Also,
2320 // compute whether this turns into an all-zeros struct.
Chris Lattnerdff59112005-10-04 18:47:09 +00002321 bool isAllZeros = false;
2322 if (!ToC->isNullValue()) {
2323 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
2324 Values.push_back(cast<Constant>(O->get()));
2325 } else {
2326 isAllZeros = true;
2327 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2328 Constant *Val = cast<Constant>(O->get());
2329 Values.push_back(Val);
2330 if (isAllZeros) isAllZeros = Val->isNullValue();
2331 }
Chris Lattner8760ec72005-10-04 01:17:50 +00002332 }
Chris Lattnerdff59112005-10-04 18:47:09 +00002333 Values[OperandToUpdate] = ToC;
2334
Chris Lattner8760ec72005-10-04 01:17:50 +00002335 Constant *Replacement = 0;
2336 if (isAllZeros) {
2337 Replacement = ConstantAggregateZero::get(getType());
2338 } else {
2339 // Check to see if we have this array type already.
2340 bool Exists;
Jim Laskeyc03caef2006-07-17 17:38:29 +00002341 StructConstantsTy::MapTy::iterator I =
Chris Lattner69edc982006-09-28 00:35:06 +00002342 StructConstants->InsertOrGetItem(Lookup, Exists);
Chris Lattner8760ec72005-10-04 01:17:50 +00002343
2344 if (Exists) {
2345 Replacement = I->second;
2346 } else {
2347 // Okay, the new shape doesn't exist in the system yet. Instead of
2348 // creating a new constant struct, inserting it, replaceallusesof'ing the
2349 // old with the new, then deleting the old... just update the current one
2350 // in place!
Chris Lattner69edc982006-09-28 00:35:06 +00002351 StructConstants->MoveConstantToNewSlot(this, I);
Chris Lattner8760ec72005-10-04 01:17:50 +00002352
Chris Lattnerdff59112005-10-04 18:47:09 +00002353 // Update to the new value.
2354 setOperand(OperandToUpdate, ToC);
Chris Lattner8760ec72005-10-04 01:17:50 +00002355 return;
2356 }
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002357 }
2358
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002359 assert(Replacement != this && "I didn't contain From!");
2360
Chris Lattner7a1450d2005-10-04 18:13:04 +00002361 // Everyone using this now uses the replacement.
2362 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002363
2364 // Delete the old constant!
2365 destroyConstant();
2366}
2367
Reid Spencerd84d35b2007-02-15 02:26:10 +00002368void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
Chris Lattner7a1450d2005-10-04 18:13:04 +00002369 Use *U) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002370 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2371
2372 std::vector<Constant*> Values;
2373 Values.reserve(getNumOperands()); // Build replacement array...
2374 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2375 Constant *Val = getOperand(i);
2376 if (Val == From) Val = cast<Constant>(To);
2377 Values.push_back(Val);
2378 }
2379
Reid Spencerd84d35b2007-02-15 02:26:10 +00002380 Constant *Replacement = ConstantVector::get(getType(), Values);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002381 assert(Replacement != this && "I didn't contain From!");
2382
Chris Lattner7a1450d2005-10-04 18:13:04 +00002383 // Everyone using this now uses the replacement.
2384 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002385
2386 // Delete the old constant!
2387 destroyConstant();
2388}
2389
2390void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
Chris Lattner7a1450d2005-10-04 18:13:04 +00002391 Use *U) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002392 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2393 Constant *To = cast<Constant>(ToV);
2394
2395 Constant *Replacement = 0;
2396 if (getOpcode() == Instruction::GetElementPtr) {
Chris Lattnerb5d70302007-02-19 20:01:23 +00002397 SmallVector<Constant*, 8> Indices;
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002398 Constant *Pointer = getOperand(0);
2399 Indices.reserve(getNumOperands()-1);
2400 if (Pointer == From) Pointer = To;
2401
2402 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2403 Constant *Val = getOperand(i);
2404 if (Val == From) Val = To;
2405 Indices.push_back(Val);
2406 }
Chris Lattnerb5d70302007-02-19 20:01:23 +00002407 Replacement = ConstantExpr::getGetElementPtr(Pointer,
2408 &Indices[0], Indices.size());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002409 } else if (isCast()) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002410 assert(getOperand(0) == From && "Cast only has one use!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002411 Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002412 } else if (getOpcode() == Instruction::Select) {
2413 Constant *C1 = getOperand(0);
2414 Constant *C2 = getOperand(1);
2415 Constant *C3 = getOperand(2);
2416 if (C1 == From) C1 = To;
2417 if (C2 == From) C2 = To;
2418 if (C3 == From) C3 = To;
2419 Replacement = ConstantExpr::getSelect(C1, C2, C3);
Robert Bocchino23004482006-01-10 19:05:34 +00002420 } else if (getOpcode() == Instruction::ExtractElement) {
2421 Constant *C1 = getOperand(0);
2422 Constant *C2 = getOperand(1);
2423 if (C1 == From) C1 = To;
2424 if (C2 == From) C2 = To;
2425 Replacement = ConstantExpr::getExtractElement(C1, C2);
Chris Lattnera93b4b52006-04-08 05:09:48 +00002426 } else if (getOpcode() == Instruction::InsertElement) {
2427 Constant *C1 = getOperand(0);
2428 Constant *C2 = getOperand(1);
2429 Constant *C3 = getOperand(1);
2430 if (C1 == From) C1 = To;
2431 if (C2 == From) C2 = To;
2432 if (C3 == From) C3 = To;
2433 Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2434 } else if (getOpcode() == Instruction::ShuffleVector) {
2435 Constant *C1 = getOperand(0);
2436 Constant *C2 = getOperand(1);
2437 Constant *C3 = getOperand(2);
2438 if (C1 == From) C1 = To;
2439 if (C2 == From) C2 = To;
2440 if (C3 == From) C3 = To;
2441 Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
Reid Spenceree3c9912006-12-04 05:19:50 +00002442 } else if (isCompare()) {
2443 Constant *C1 = getOperand(0);
2444 Constant *C2 = getOperand(1);
2445 if (C1 == From) C1 = To;
2446 if (C2 == From) C2 = To;
2447 if (getOpcode() == Instruction::ICmp)
2448 Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
2449 else
2450 Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002451 } else if (getNumOperands() == 2) {
2452 Constant *C1 = getOperand(0);
2453 Constant *C2 = getOperand(1);
2454 if (C1 == From) C1 = To;
2455 if (C2 == From) C2 = To;
2456 Replacement = ConstantExpr::get(getOpcode(), C1, C2);
2457 } else {
2458 assert(0 && "Unknown ConstantExpr type!");
2459 return;
2460 }
2461
2462 assert(Replacement != this && "I didn't contain From!");
2463
Chris Lattner7a1450d2005-10-04 18:13:04 +00002464 // Everyone using this now uses the replacement.
2465 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002466
2467 // Delete the old constant!
2468 destroyConstant();
2469}
2470
2471
Jim Laskey2698f0d2006-03-08 18:11:07 +00002472/// getStringValue - Turn an LLVM constant pointer that eventually points to a
2473/// global into a string value. Return an empty string if we can't do it.
Evan Cheng38280c02006-03-10 23:52:03 +00002474/// Parameter Chop determines if the result is chopped at the first null
2475/// terminator.
Jim Laskey2698f0d2006-03-08 18:11:07 +00002476///
Evan Cheng38280c02006-03-10 23:52:03 +00002477std::string Constant::getStringValue(bool Chop, unsigned Offset) {
Jim Laskey2698f0d2006-03-08 18:11:07 +00002478 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(this)) {
2479 if (GV->hasInitializer() && isa<ConstantArray>(GV->getInitializer())) {
2480 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
2481 if (Init->isString()) {
2482 std::string Result = Init->getAsString();
2483 if (Offset < Result.size()) {
2484 // If we are pointing INTO The string, erase the beginning...
2485 Result.erase(Result.begin(), Result.begin()+Offset);
2486
2487 // Take off the null terminator, and any string fragments after it.
Evan Cheng38280c02006-03-10 23:52:03 +00002488 if (Chop) {
2489 std::string::size_type NullPos = Result.find_first_of((char)0);
2490 if (NullPos != std::string::npos)
2491 Result.erase(Result.begin()+NullPos, Result.end());
2492 }
Jim Laskey2698f0d2006-03-08 18:11:07 +00002493 return Result;
2494 }
2495 }
2496 }
Chris Lattner6ab19ed2007-11-01 02:30:35 +00002497 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(this)) {
2498 if (CE->getOpcode() == Instruction::GetElementPtr) {
2499 // Turn a gep into the specified offset.
2500 if (CE->getNumOperands() == 3 &&
2501 cast<Constant>(CE->getOperand(1))->isNullValue() &&
2502 isa<ConstantInt>(CE->getOperand(2))) {
2503 Offset += cast<ConstantInt>(CE->getOperand(2))->getZExtValue();
2504 return CE->getOperand(0)->getStringValue(Chop, Offset);
Jim Laskey2698f0d2006-03-08 18:11:07 +00002505 }
2506 }
2507 }
2508 return "";
2509}