blob: 36ba7c0220c035d1a2bb05732a5e4cd965f74368 [file] [log] [blame]
Chris Lattner2b383d2e2003-05-13 21:37:02 +00001//===-- Constants.cpp - Implement Constant nodes --------------------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner2f7c9632001-06-06 20:29:01 +00009//
Chris Lattner3462ae32001-12-03 22:26:30 +000010// This file implements the Constant* classes...
Chris Lattner2f7c9632001-06-06 20:29:01 +000011//
12//===----------------------------------------------------------------------===//
13
Chris Lattnerca142372002-04-28 19:55:58 +000014#include "llvm/Constants.h"
Chris Lattner33e93b82007-02-27 03:05:06 +000015#include "ConstantFold.h"
Chris Lattner2f7c9632001-06-06 20:29:01 +000016#include "llvm/DerivedTypes.h"
Reid Spencer1ebe1ab2004-07-17 23:48:33 +000017#include "llvm/GlobalValue.h"
Misha Brukman63b38bd2004-07-29 17:30:56 +000018#include "llvm/Instructions.h"
Chris Lattnerd7a73302001-10-13 06:57:33 +000019#include "llvm/Module.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000020#include "llvm/ADT/StringExtras.h"
Chris Lattner3d27be12006-08-27 12:54:02 +000021#include "llvm/Support/Compiler.h"
Bill Wendling6a462f12006-11-17 08:03:48 +000022#include "llvm/Support/Debug.h"
Chris Lattner69edc982006-09-28 00:35:06 +000023#include "llvm/Support/ManagedStatic.h"
Bill Wendling6a462f12006-11-17 08:03:48 +000024#include "llvm/Support/MathExtras.h"
Chris Lattnera80bf0b2007-02-20 06:39:57 +000025#include "llvm/ADT/DenseMap.h"
Chris Lattnerb5d70302007-02-19 20:01:23 +000026#include "llvm/ADT/SmallVector.h"
Chris Lattner2f7c9632001-06-06 20:29:01 +000027#include <algorithm>
Reid Spencer3aaaa0b2007-02-05 20:47:22 +000028#include <map>
Chris Lattner189d19f2003-11-21 20:23:48 +000029using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000030
Chris Lattner2f7c9632001-06-06 20:29:01 +000031//===----------------------------------------------------------------------===//
Chris Lattner3462ae32001-12-03 22:26:30 +000032// Constant Class
Chris Lattner2f7c9632001-06-06 20:29:01 +000033//===----------------------------------------------------------------------===//
34
Chris Lattner3462ae32001-12-03 22:26:30 +000035void Constant::destroyConstantImpl() {
36 // When a Constant is destroyed, there may be lingering
Chris Lattnerd7a73302001-10-13 06:57:33 +000037 // references to the constant by other constants in the constant pool. These
Misha Brukmanbe372b92003-08-21 22:14:26 +000038 // constants are implicitly dependent on the module that is being deleted,
Chris Lattnerd7a73302001-10-13 06:57:33 +000039 // but they don't know that. Because we only find out when the CPV is
40 // deleted, we must now notify all of our users (that should only be
Chris Lattner3462ae32001-12-03 22:26:30 +000041 // Constants) that they are, in fact, invalid now and should be deleted.
Chris Lattnerd7a73302001-10-13 06:57:33 +000042 //
43 while (!use_empty()) {
44 Value *V = use_back();
45#ifndef NDEBUG // Only in -g mode...
Chris Lattnerd9f4ac662002-07-18 00:14:50 +000046 if (!isa<Constant>(V))
Bill Wendling6a462f12006-11-17 08:03:48 +000047 DOUT << "While deleting: " << *this
48 << "\n\nUse still stuck around after Def is destroyed: "
49 << *V << "\n\n";
Chris Lattnerd7a73302001-10-13 06:57:33 +000050#endif
Vikram S. Adve4e537b22002-07-14 23:13:17 +000051 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
Reid Spencer1ebe1ab2004-07-17 23:48:33 +000052 Constant *CV = cast<Constant>(V);
53 CV->destroyConstant();
Chris Lattnerd7a73302001-10-13 06:57:33 +000054
55 // The constant should remove itself from our use list...
Vikram S. Adve4e537b22002-07-14 23:13:17 +000056 assert((use_empty() || use_back() != V) && "Constant not removed!");
Chris Lattnerd7a73302001-10-13 06:57:33 +000057 }
58
59 // Value has no outstanding references it is safe to delete it now...
60 delete this;
Chris Lattner38569342001-10-01 20:11:19 +000061}
Chris Lattner2f7c9632001-06-06 20:29:01 +000062
Chris Lattner23dd1f62006-10-20 00:27:06 +000063/// canTrap - Return true if evaluation of this constant could trap. This is
64/// true for things like constant expressions that could divide by zero.
65bool Constant::canTrap() const {
66 assert(getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
67 // The only thing that could possibly trap are constant exprs.
68 const ConstantExpr *CE = dyn_cast<ConstantExpr>(this);
69 if (!CE) return false;
70
71 // ConstantExpr traps if any operands can trap.
72 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
73 if (getOperand(i)->canTrap())
74 return true;
75
76 // Otherwise, only specific operations can trap.
77 switch (CE->getOpcode()) {
78 default:
79 return false;
Reid Spencer7e80b0b2006-10-26 06:15:43 +000080 case Instruction::UDiv:
81 case Instruction::SDiv:
82 case Instruction::FDiv:
Reid Spencer7eb55b32006-11-02 01:53:59 +000083 case Instruction::URem:
84 case Instruction::SRem:
85 case Instruction::FRem:
Chris Lattner23dd1f62006-10-20 00:27:06 +000086 // Div and rem can trap if the RHS is not known to be non-zero.
87 if (!isa<ConstantInt>(getOperand(1)) || getOperand(1)->isNullValue())
88 return true;
89 return false;
90 }
91}
92
Evan Chengf9e003b2007-03-08 00:59:12 +000093/// ContaintsRelocations - Return true if the constant value contains
94/// relocations which cannot be resolved at compile time.
95bool Constant::ContainsRelocations() const {
96 if (isa<GlobalValue>(this))
97 return true;
98 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
99 if (getOperand(i)->ContainsRelocations())
100 return true;
101 return false;
102}
103
Chris Lattnerb1585a92002-08-13 17:50:20 +0000104// Static constructor to create a '0' constant of arbitrary type...
105Constant *Constant::getNullValue(const Type *Ty) {
Chris Lattner6b727592004-06-17 18:19:28 +0000106 switch (Ty->getTypeID()) {
Chris Lattnerdbcb0d32007-02-20 05:46:39 +0000107 case Type::IntegerTyID:
108 return ConstantInt::get(Ty, 0);
109 case Type::FloatTyID:
110 case Type::DoubleTyID:
Dale Johannesenbdad8092007-08-09 22:51:36 +0000111 case Type::X86_FP80TyID:
112 case Type::PPC_FP128TyID:
113 case Type::FP128TyID:
Chris Lattnerdbcb0d32007-02-20 05:46:39 +0000114 return ConstantFP::get(Ty, 0.0);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000115 case Type::PointerTyID:
Chris Lattnerb1585a92002-08-13 17:50:20 +0000116 return ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattner9fba3da2004-02-15 05:53:04 +0000117 case Type::StructTyID:
118 case Type::ArrayTyID:
Reid Spencerd84d35b2007-02-15 02:26:10 +0000119 case Type::VectorTyID:
Chris Lattner9fba3da2004-02-15 05:53:04 +0000120 return ConstantAggregateZero::get(Ty);
Chris Lattnerb1585a92002-08-13 17:50:20 +0000121 default:
Reid Spencercf394bf2004-07-04 11:51:24 +0000122 // Function, Label, or Opaque type?
123 assert(!"Cannot create a null constant of that type!");
Chris Lattnerb1585a92002-08-13 17:50:20 +0000124 return 0;
125 }
126}
127
Chris Lattner72e39582007-06-15 06:10:53 +0000128Constant *Constant::getAllOnesValue(const Type *Ty) {
129 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty))
130 return ConstantInt::get(APInt::getAllOnesValue(ITy->getBitWidth()));
131 return ConstantVector::getAllOnesValue(cast<VectorType>(Ty));
132}
Chris Lattnerb1585a92002-08-13 17:50:20 +0000133
134// Static constructor to create an integral constant with all bits set
Zhou Sheng75b871f2007-01-11 12:24:14 +0000135ConstantInt *ConstantInt::getAllOnesValue(const Type *Ty) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000136 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty))
Reid Spencerd1bbfa52007-03-01 19:30:34 +0000137 return ConstantInt::get(APInt::getAllOnesValue(ITy->getBitWidth()));
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000138 return 0;
Chris Lattnerb1585a92002-08-13 17:50:20 +0000139}
140
Dan Gohman30978072007-05-24 14:36:04 +0000141/// @returns the value for a vector integer constant of the given type that
Chris Lattnerecab54c2007-01-04 01:49:26 +0000142/// has all its bits set to true.
143/// @brief Get the all ones value
Reid Spencerd84d35b2007-02-15 02:26:10 +0000144ConstantVector *ConstantVector::getAllOnesValue(const VectorType *Ty) {
Chris Lattnerecab54c2007-01-04 01:49:26 +0000145 std::vector<Constant*> Elts;
146 Elts.resize(Ty->getNumElements(),
Zhou Sheng75b871f2007-01-11 12:24:14 +0000147 ConstantInt::getAllOnesValue(Ty->getElementType()));
Dan Gohman30978072007-05-24 14:36:04 +0000148 assert(Elts[0] && "Not a vector integer type!");
Reid Spencerd84d35b2007-02-15 02:26:10 +0000149 return cast<ConstantVector>(ConstantVector::get(Elts));
Chris Lattnerecab54c2007-01-04 01:49:26 +0000150}
151
152
Chris Lattner2f7c9632001-06-06 20:29:01 +0000153//===----------------------------------------------------------------------===//
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000154// ConstantInt
Chris Lattner2f7c9632001-06-06 20:29:01 +0000155//===----------------------------------------------------------------------===//
156
Reid Spencerb31bffe2007-02-26 23:54:03 +0000157ConstantInt::ConstantInt(const IntegerType *Ty, const APInt& V)
Chris Lattner5db2f472007-02-20 05:55:46 +0000158 : Constant(Ty, ConstantIntVal, 0, 0), Val(V) {
Reid Spencerb31bffe2007-02-26 23:54:03 +0000159 assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
Chris Lattner2f7c9632001-06-06 20:29:01 +0000160}
161
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000162ConstantInt *ConstantInt::TheTrueVal = 0;
163ConstantInt *ConstantInt::TheFalseVal = 0;
164
165namespace llvm {
166 void CleanupTrueFalse(void *) {
167 ConstantInt::ResetTrueFalse();
168 }
169}
170
171static ManagedCleanup<llvm::CleanupTrueFalse> TrueFalseCleanup;
172
173ConstantInt *ConstantInt::CreateTrueFalseVals(bool WhichOne) {
174 assert(TheTrueVal == 0 && TheFalseVal == 0);
175 TheTrueVal = get(Type::Int1Ty, 1);
176 TheFalseVal = get(Type::Int1Ty, 0);
177
178 // Ensure that llvm_shutdown nulls out TheTrueVal/TheFalseVal.
179 TrueFalseCleanup.Register();
180
181 return WhichOne ? TheTrueVal : TheFalseVal;
182}
183
184
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000185namespace {
Reid Spencerb31bffe2007-02-26 23:54:03 +0000186 struct DenseMapAPIntKeyInfo {
187 struct KeyTy {
188 APInt val;
189 const Type* type;
190 KeyTy(const APInt& V, const Type* Ty) : val(V), type(Ty) {}
191 KeyTy(const KeyTy& that) : val(that.val), type(that.type) {}
192 bool operator==(const KeyTy& that) const {
193 return type == that.type && this->val == that.val;
194 }
195 bool operator!=(const KeyTy& that) const {
196 return !this->operator==(that);
197 }
198 };
199 static inline KeyTy getEmptyKey() { return KeyTy(APInt(1,0), 0); }
200 static inline KeyTy getTombstoneKey() { return KeyTy(APInt(1,1), 0); }
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000201 static unsigned getHashValue(const KeyTy &Key) {
Reid Spencerb31bffe2007-02-26 23:54:03 +0000202 return DenseMapKeyInfo<void*>::getHashValue(Key.type) ^
203 Key.val.getHashValue();
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000204 }
Dale Johannesena719a602007-08-24 00:56:33 +0000205 static bool isPod() { return false; }
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000206 };
207}
208
209
Reid Spencerb31bffe2007-02-26 23:54:03 +0000210typedef DenseMap<DenseMapAPIntKeyInfo::KeyTy, ConstantInt*,
211 DenseMapAPIntKeyInfo> IntMapTy;
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000212static ManagedStatic<IntMapTy> IntConstants;
213
Reid Spencer362fb292007-03-19 20:39:08 +0000214ConstantInt *ConstantInt::get(const Type *Ty, uint64_t V, bool isSigned) {
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000215 const IntegerType *ITy = cast<IntegerType>(Ty);
Reid Spencer362fb292007-03-19 20:39:08 +0000216 return get(APInt(ITy->getBitWidth(), V, isSigned));
Reid Spencerb31bffe2007-02-26 23:54:03 +0000217}
218
Reid Spencerd1bbfa52007-03-01 19:30:34 +0000219// Get a ConstantInt from an APInt. Note that the value stored in the DenseMap
220// as the key, is a DensMapAPIntKeyInfo::KeyTy which has provided the
Reid Spencerb31bffe2007-02-26 23:54:03 +0000221// operator== and operator!= to ensure that the DenseMap doesn't attempt to
222// compare APInt's of different widths, which would violate an APInt class
223// invariant which generates an assertion.
Reid Spencerd1bbfa52007-03-01 19:30:34 +0000224ConstantInt *ConstantInt::get(const APInt& V) {
225 // Get the corresponding integer type for the bit width of the value.
226 const IntegerType *ITy = IntegerType::get(V.getBitWidth());
Reid Spencerb31bffe2007-02-26 23:54:03 +0000227 // get an existing value or the insertion position
Reid Spencerd1bbfa52007-03-01 19:30:34 +0000228 DenseMapAPIntKeyInfo::KeyTy Key(V, ITy);
Reid Spencerb31bffe2007-02-26 23:54:03 +0000229 ConstantInt *&Slot = (*IntConstants)[Key];
230 // if it exists, return it.
231 if (Slot)
232 return Slot;
233 // otherwise create a new one, insert it, and return it.
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000234 return Slot = new ConstantInt(ITy, V);
235}
236
237//===----------------------------------------------------------------------===//
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000238// ConstantFP
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000239//===----------------------------------------------------------------------===//
240
241
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000242ConstantFP::ConstantFP(const Type *Ty, double V)
Dale Johannesena719a602007-08-24 00:56:33 +0000243 : Constant(Ty, ConstantFPVal, 0, 0), Val(APFloat(V)) {
Chris Lattner2f7c9632001-06-06 20:29:01 +0000244}
245
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000246bool ConstantFP::isNullValue() const {
Dale Johannesena719a602007-08-24 00:56:33 +0000247 return Val.isZero() && !Val.isNegative();
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000248}
249
250bool ConstantFP::isExactlyValue(double V) const {
Dale Johannesena719a602007-08-24 00:56:33 +0000251 return Val == APFloat(V);
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000252}
253
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000254namespace {
Dale Johannesena719a602007-08-24 00:56:33 +0000255 struct DenseMapAPFloatKeyInfo {
Dale Johannesen918c33c2007-08-24 05:08:11 +0000256 static inline APFloat getEmptyKey() {
257 return APFloat(APFloat::Bogus,1);
Reid Spencerb31bffe2007-02-26 23:54:03 +0000258 }
Dale Johannesen918c33c2007-08-24 05:08:11 +0000259 static inline APFloat getTombstoneKey() {
260 return APFloat(APFloat::Bogus,2);
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000261 }
Dale Johannesen918c33c2007-08-24 05:08:11 +0000262 static unsigned getHashValue(const APFloat &Key) {
263 return Key.getHashValue();
Dale Johannesena719a602007-08-24 00:56:33 +0000264 }
265 static bool isPod() { return false; }
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000266 };
267}
268
269//---- ConstantFP::get() implementation...
270//
Dale Johannesen918c33c2007-08-24 05:08:11 +0000271typedef DenseMap<APFloat, ConstantFP*,
Dale Johannesena719a602007-08-24 00:56:33 +0000272 DenseMapAPFloatKeyInfo> FPMapTy;
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000273
Dale Johannesena719a602007-08-24 00:56:33 +0000274static ManagedStatic<FPMapTy> FPConstants;
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000275
276ConstantFP *ConstantFP::get(const Type *Ty, double V) {
277 if (Ty == Type::FloatTy) {
Dale Johannesen918c33c2007-08-24 05:08:11 +0000278 APFloat Key(APFloat((float)V));
Dale Johannesena719a602007-08-24 00:56:33 +0000279 ConstantFP *&Slot = (*FPConstants)[Key];
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000280 if (Slot) return Slot;
281 return Slot = new ConstantFP(Ty, (float)V);
Dale Johannesena719a602007-08-24 00:56:33 +0000282 } else if (Ty == Type::DoubleTy) {
283 // Without the redundant cast, the following is taken to be
284 // a function declaration. What a language.
Dale Johannesen918c33c2007-08-24 05:08:11 +0000285 APFloat Key(APFloat((double)V));
Dale Johannesena719a602007-08-24 00:56:33 +0000286 ConstantFP *&Slot = (*FPConstants)[Key];
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000287 if (Slot) return Slot;
Evan Cheng71b87232007-02-20 21:30:56 +0000288 return Slot = new ConstantFP(Ty, V);
Dale Johannesenbdad8092007-08-09 22:51:36 +0000289 } else if (Ty == Type::X86_FP80Ty ||
290 Ty == Type::PPC_FP128Ty || Ty == Type::FP128Ty) {
291 assert(0 && "Long double constants not handled yet.");
292 } else {
293 assert(0 && "Unknown FP Type!");
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000294 }
295}
296
297
298//===----------------------------------------------------------------------===//
299// ConstantXXX Classes
300//===----------------------------------------------------------------------===//
301
302
Chris Lattner3462ae32001-12-03 22:26:30 +0000303ConstantArray::ConstantArray(const ArrayType *T,
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000304 const std::vector<Constant*> &V)
Chris Lattnere7e139e2005-09-27 06:09:08 +0000305 : Constant(T, ConstantArrayVal, new Use[V.size()], V.size()) {
Alkis Evlogimenos0507ffe2004-09-15 02:32:15 +0000306 assert(V.size() == T->getNumElements() &&
307 "Invalid initializer vector for constant array");
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000308 Use *OL = OperandList;
Chris Lattner0144fad2005-10-03 21:56:24 +0000309 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
310 I != E; ++I, ++OL) {
Chris Lattner20a24452005-10-07 05:23:36 +0000311 Constant *C = *I;
312 assert((C->getType() == T->getElementType() ||
Alkis Evlogimenoscb031d92004-09-10 04:16:59 +0000313 (T->isAbstract() &&
Chris Lattner20a24452005-10-07 05:23:36 +0000314 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
Alkis Evlogimenoscb031d92004-09-10 04:16:59 +0000315 "Initializer for array element doesn't match array element type!");
Chris Lattner20a24452005-10-07 05:23:36 +0000316 OL->init(C, this);
Chris Lattner2f7c9632001-06-06 20:29:01 +0000317 }
318}
319
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000320ConstantArray::~ConstantArray() {
321 delete [] OperandList;
322}
323
Chris Lattner3462ae32001-12-03 22:26:30 +0000324ConstantStruct::ConstantStruct(const StructType *T,
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000325 const std::vector<Constant*> &V)
Chris Lattnere7e139e2005-09-27 06:09:08 +0000326 : Constant(T, ConstantStructVal, new Use[V.size()], V.size()) {
Chris Lattnerac6db752004-02-09 04:37:31 +0000327 assert(V.size() == T->getNumElements() &&
Vikram S. Adve4e537b22002-07-14 23:13:17 +0000328 "Invalid initializer vector for constant structure");
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000329 Use *OL = OperandList;
Chris Lattner0144fad2005-10-03 21:56:24 +0000330 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
331 I != E; ++I, ++OL) {
Chris Lattner20a24452005-10-07 05:23:36 +0000332 Constant *C = *I;
333 assert((C->getType() == T->getElementType(I-V.begin()) ||
Chris Lattner0144fad2005-10-03 21:56:24 +0000334 ((T->getElementType(I-V.begin())->isAbstract() ||
Chris Lattner20a24452005-10-07 05:23:36 +0000335 C->getType()->isAbstract()) &&
Chris Lattner0144fad2005-10-03 21:56:24 +0000336 T->getElementType(I-V.begin())->getTypeID() ==
Chris Lattner20a24452005-10-07 05:23:36 +0000337 C->getType()->getTypeID())) &&
Chris Lattner93c8f142003-06-02 17:42:47 +0000338 "Initializer for struct element doesn't match struct element type!");
Chris Lattner20a24452005-10-07 05:23:36 +0000339 OL->init(C, this);
Chris Lattner2f7c9632001-06-06 20:29:01 +0000340 }
341}
342
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000343ConstantStruct::~ConstantStruct() {
344 delete [] OperandList;
345}
346
347
Reid Spencerd84d35b2007-02-15 02:26:10 +0000348ConstantVector::ConstantVector(const VectorType *T,
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000349 const std::vector<Constant*> &V)
Reid Spencerd84d35b2007-02-15 02:26:10 +0000350 : Constant(T, ConstantVectorVal, new Use[V.size()], V.size()) {
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000351 Use *OL = OperandList;
Chris Lattner0144fad2005-10-03 21:56:24 +0000352 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
353 I != E; ++I, ++OL) {
Chris Lattner20a24452005-10-07 05:23:36 +0000354 Constant *C = *I;
355 assert((C->getType() == T->getElementType() ||
Alkis Evlogimenoscb031d92004-09-10 04:16:59 +0000356 (T->isAbstract() &&
Chris Lattner20a24452005-10-07 05:23:36 +0000357 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
Dan Gohman30978072007-05-24 14:36:04 +0000358 "Initializer for vector element doesn't match vector element type!");
Chris Lattner20a24452005-10-07 05:23:36 +0000359 OL->init(C, this);
Brian Gaeke02209042004-08-20 06:00:58 +0000360 }
361}
362
Reid Spencerd84d35b2007-02-15 02:26:10 +0000363ConstantVector::~ConstantVector() {
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000364 delete [] OperandList;
Vikram S. Adve4e537b22002-07-14 23:13:17 +0000365}
366
Reid Spencer10fbf0e2006-12-03 05:48:19 +0000367// We declare several classes private to this file, so use an anonymous
368// namespace
369namespace {
370
371/// UnaryConstantExpr - This class is private to Constants.cpp, and is used
372/// behind the scenes to implement unary constant exprs.
373class VISIBILITY_HIDDEN UnaryConstantExpr : public ConstantExpr {
374 Use Op;
375public:
376 UnaryConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
377 : ConstantExpr(Ty, Opcode, &Op, 1), Op(C, this) {}
378};
379
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000380/// BinaryConstantExpr - This class is private to Constants.cpp, and is used
381/// behind the scenes to implement binary constant exprs.
Chris Lattner02157b02006-06-28 21:38:54 +0000382class VISIBILITY_HIDDEN BinaryConstantExpr : public ConstantExpr {
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000383 Use Ops[2];
384public:
385 BinaryConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
Reid Spencer266e42b2006-12-23 06:05:41 +0000386 : ConstantExpr(C1->getType(), Opcode, Ops, 2) {
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000387 Ops[0].init(C1, this);
388 Ops[1].init(C2, this);
389 }
390};
Vikram S. Adve4e537b22002-07-14 23:13:17 +0000391
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000392/// SelectConstantExpr - This class is private to Constants.cpp, and is used
393/// behind the scenes to implement select constant exprs.
Chris Lattner02157b02006-06-28 21:38:54 +0000394class VISIBILITY_HIDDEN SelectConstantExpr : public ConstantExpr {
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000395 Use Ops[3];
396public:
397 SelectConstantExpr(Constant *C1, Constant *C2, Constant *C3)
398 : ConstantExpr(C2->getType(), Instruction::Select, Ops, 3) {
399 Ops[0].init(C1, this);
400 Ops[1].init(C2, this);
401 Ops[2].init(C3, this);
402 }
403};
404
Robert Bocchinoca27f032006-01-17 20:07:22 +0000405/// ExtractElementConstantExpr - This class is private to
406/// Constants.cpp, and is used behind the scenes to implement
407/// extractelement constant exprs.
Chris Lattner02157b02006-06-28 21:38:54 +0000408class VISIBILITY_HIDDEN ExtractElementConstantExpr : public ConstantExpr {
Robert Bocchino23004482006-01-10 19:05:34 +0000409 Use Ops[2];
410public:
411 ExtractElementConstantExpr(Constant *C1, Constant *C2)
Reid Spencerd84d35b2007-02-15 02:26:10 +0000412 : ConstantExpr(cast<VectorType>(C1->getType())->getElementType(),
Robert Bocchino23004482006-01-10 19:05:34 +0000413 Instruction::ExtractElement, Ops, 2) {
414 Ops[0].init(C1, this);
415 Ops[1].init(C2, this);
416 }
417};
418
Robert Bocchinoca27f032006-01-17 20:07:22 +0000419/// InsertElementConstantExpr - This class is private to
420/// Constants.cpp, and is used behind the scenes to implement
421/// insertelement constant exprs.
Chris Lattner02157b02006-06-28 21:38:54 +0000422class VISIBILITY_HIDDEN InsertElementConstantExpr : public ConstantExpr {
Robert Bocchinoca27f032006-01-17 20:07:22 +0000423 Use Ops[3];
424public:
425 InsertElementConstantExpr(Constant *C1, Constant *C2, Constant *C3)
426 : ConstantExpr(C1->getType(), Instruction::InsertElement,
427 Ops, 3) {
428 Ops[0].init(C1, this);
429 Ops[1].init(C2, this);
430 Ops[2].init(C3, this);
431 }
432};
433
Chris Lattnerbbe0a422006-04-08 01:18:18 +0000434/// ShuffleVectorConstantExpr - This class is private to
435/// Constants.cpp, and is used behind the scenes to implement
436/// shufflevector constant exprs.
Chris Lattner02157b02006-06-28 21:38:54 +0000437class VISIBILITY_HIDDEN ShuffleVectorConstantExpr : public ConstantExpr {
Chris Lattnerbbe0a422006-04-08 01:18:18 +0000438 Use Ops[3];
439public:
440 ShuffleVectorConstantExpr(Constant *C1, Constant *C2, Constant *C3)
441 : ConstantExpr(C1->getType(), Instruction::ShuffleVector,
442 Ops, 3) {
443 Ops[0].init(C1, this);
444 Ops[1].init(C2, this);
445 Ops[2].init(C3, this);
446 }
447};
448
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000449/// GetElementPtrConstantExpr - This class is private to Constants.cpp, and is
450/// used behind the scenes to implement getelementpr constant exprs.
Chris Lattner02157b02006-06-28 21:38:54 +0000451struct VISIBILITY_HIDDEN GetElementPtrConstantExpr : public ConstantExpr {
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000452 GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
453 const Type *DestTy)
454 : ConstantExpr(DestTy, Instruction::GetElementPtr,
455 new Use[IdxList.size()+1], IdxList.size()+1) {
456 OperandList[0].init(C, this);
457 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
458 OperandList[i+1].init(IdxList[i], this);
459 }
460 ~GetElementPtrConstantExpr() {
Misha Brukmanb1c93172005-04-21 23:48:37 +0000461 delete [] OperandList;
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000462 }
463};
Reid Spencer10fbf0e2006-12-03 05:48:19 +0000464
465// CompareConstantExpr - This class is private to Constants.cpp, and is used
466// behind the scenes to implement ICmp and FCmp constant expressions. This is
467// needed in order to store the predicate value for these instructions.
468struct VISIBILITY_HIDDEN CompareConstantExpr : public ConstantExpr {
469 unsigned short predicate;
470 Use Ops[2];
471 CompareConstantExpr(Instruction::OtherOps opc, unsigned short pred,
472 Constant* LHS, Constant* RHS)
Reid Spencer542964f2007-01-11 18:21:29 +0000473 : ConstantExpr(Type::Int1Ty, opc, Ops, 2), predicate(pred) {
Reid Spencer10fbf0e2006-12-03 05:48:19 +0000474 OperandList[0].init(LHS, this);
475 OperandList[1].init(RHS, this);
476 }
477};
478
479} // end anonymous namespace
Vikram S. Adve4e537b22002-07-14 23:13:17 +0000480
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000481
482// Utility function for determining if a ConstantExpr is a CastOp or not. This
483// can't be inline because we don't want to #include Instruction.h into
484// Constant.h
485bool ConstantExpr::isCast() const {
486 return Instruction::isCast(getOpcode());
487}
488
Reid Spenceree3c9912006-12-04 05:19:50 +0000489bool ConstantExpr::isCompare() const {
490 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
491}
492
Chris Lattner817175f2004-03-29 02:37:53 +0000493/// ConstantExpr::get* - Return some common constants without having to
494/// specify the full Instruction::OPCODE identifier.
495///
496Constant *ConstantExpr::getNeg(Constant *C) {
Reid Spencer2eadb532007-01-21 00:29:26 +0000497 return get(Instruction::Sub,
498 ConstantExpr::getZeroValueForNegationExpr(C->getType()),
499 C);
Chris Lattner817175f2004-03-29 02:37:53 +0000500}
501Constant *ConstantExpr::getNot(Constant *C) {
Zhou Sheng75b871f2007-01-11 12:24:14 +0000502 assert(isa<ConstantInt>(C) && "Cannot NOT a nonintegral type!");
Chris Lattner817175f2004-03-29 02:37:53 +0000503 return get(Instruction::Xor, C,
Zhou Sheng75b871f2007-01-11 12:24:14 +0000504 ConstantInt::getAllOnesValue(C->getType()));
Chris Lattner817175f2004-03-29 02:37:53 +0000505}
506Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2) {
507 return get(Instruction::Add, C1, C2);
508}
509Constant *ConstantExpr::getSub(Constant *C1, Constant *C2) {
510 return get(Instruction::Sub, C1, C2);
511}
512Constant *ConstantExpr::getMul(Constant *C1, Constant *C2) {
513 return get(Instruction::Mul, C1, C2);
514}
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000515Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2) {
516 return get(Instruction::UDiv, C1, C2);
517}
518Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2) {
519 return get(Instruction::SDiv, C1, C2);
520}
521Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
522 return get(Instruction::FDiv, C1, C2);
Chris Lattner817175f2004-03-29 02:37:53 +0000523}
Reid Spencer7eb55b32006-11-02 01:53:59 +0000524Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
525 return get(Instruction::URem, C1, C2);
526}
527Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
528 return get(Instruction::SRem, C1, C2);
529}
530Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
531 return get(Instruction::FRem, C1, C2);
Chris Lattner817175f2004-03-29 02:37:53 +0000532}
533Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
534 return get(Instruction::And, C1, C2);
535}
536Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
537 return get(Instruction::Or, C1, C2);
538}
539Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
540 return get(Instruction::Xor, C1, C2);
541}
Reid Spencer10fbf0e2006-12-03 05:48:19 +0000542unsigned ConstantExpr::getPredicate() const {
543 assert(getOpcode() == Instruction::FCmp || getOpcode() == Instruction::ICmp);
544 return dynamic_cast<const CompareConstantExpr*>(this)->predicate;
545}
Chris Lattner817175f2004-03-29 02:37:53 +0000546Constant *ConstantExpr::getShl(Constant *C1, Constant *C2) {
547 return get(Instruction::Shl, C1, C2);
548}
Reid Spencerfdff9382006-11-08 06:47:33 +0000549Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2) {
550 return get(Instruction::LShr, C1, C2);
Chris Lattner817175f2004-03-29 02:37:53 +0000551}
Reid Spencerfdff9382006-11-08 06:47:33 +0000552Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2) {
553 return get(Instruction::AShr, C1, C2);
Chris Lattnerdb8bdba2004-05-25 05:32:43 +0000554}
Chris Lattner60e0dd72001-10-03 06:12:09 +0000555
Chris Lattner7c1018a2006-07-14 19:37:40 +0000556/// getWithOperandReplaced - Return a constant expression identical to this
557/// one, but with the specified operand set to the specified value.
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000558Constant *
559ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
Chris Lattner7c1018a2006-07-14 19:37:40 +0000560 assert(OpNo < getNumOperands() && "Operand num is out of range!");
561 assert(Op->getType() == getOperand(OpNo)->getType() &&
562 "Replacing operand with value of different type!");
Chris Lattner227816342006-07-14 22:20:01 +0000563 if (getOperand(OpNo) == Op)
564 return const_cast<ConstantExpr*>(this);
Chris Lattner7c1018a2006-07-14 19:37:40 +0000565
Chris Lattner227816342006-07-14 22:20:01 +0000566 Constant *Op0, *Op1, *Op2;
Chris Lattner7c1018a2006-07-14 19:37:40 +0000567 switch (getOpcode()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000568 case Instruction::Trunc:
569 case Instruction::ZExt:
570 case Instruction::SExt:
571 case Instruction::FPTrunc:
572 case Instruction::FPExt:
573 case Instruction::UIToFP:
574 case Instruction::SIToFP:
575 case Instruction::FPToUI:
576 case Instruction::FPToSI:
577 case Instruction::PtrToInt:
578 case Instruction::IntToPtr:
579 case Instruction::BitCast:
580 return ConstantExpr::getCast(getOpcode(), Op, getType());
Chris Lattner227816342006-07-14 22:20:01 +0000581 case Instruction::Select:
582 Op0 = (OpNo == 0) ? Op : getOperand(0);
583 Op1 = (OpNo == 1) ? Op : getOperand(1);
584 Op2 = (OpNo == 2) ? Op : getOperand(2);
585 return ConstantExpr::getSelect(Op0, Op1, Op2);
586 case Instruction::InsertElement:
587 Op0 = (OpNo == 0) ? Op : getOperand(0);
588 Op1 = (OpNo == 1) ? Op : getOperand(1);
589 Op2 = (OpNo == 2) ? Op : getOperand(2);
590 return ConstantExpr::getInsertElement(Op0, Op1, Op2);
591 case Instruction::ExtractElement:
592 Op0 = (OpNo == 0) ? Op : getOperand(0);
593 Op1 = (OpNo == 1) ? Op : getOperand(1);
594 return ConstantExpr::getExtractElement(Op0, Op1);
595 case Instruction::ShuffleVector:
596 Op0 = (OpNo == 0) ? Op : getOperand(0);
597 Op1 = (OpNo == 1) ? Op : getOperand(1);
598 Op2 = (OpNo == 2) ? Op : getOperand(2);
599 return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Chris Lattner7c1018a2006-07-14 19:37:40 +0000600 case Instruction::GetElementPtr: {
Chris Lattnerb5d70302007-02-19 20:01:23 +0000601 SmallVector<Constant*, 8> Ops;
602 Ops.resize(getNumOperands());
Chris Lattner7c1018a2006-07-14 19:37:40 +0000603 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
Chris Lattnerb5d70302007-02-19 20:01:23 +0000604 Ops[i] = getOperand(i);
Chris Lattner7c1018a2006-07-14 19:37:40 +0000605 if (OpNo == 0)
Chris Lattnerb5d70302007-02-19 20:01:23 +0000606 return ConstantExpr::getGetElementPtr(Op, &Ops[0], Ops.size());
Chris Lattner7c1018a2006-07-14 19:37:40 +0000607 Ops[OpNo-1] = Op;
Chris Lattnerb5d70302007-02-19 20:01:23 +0000608 return ConstantExpr::getGetElementPtr(getOperand(0), &Ops[0], Ops.size());
Chris Lattner7c1018a2006-07-14 19:37:40 +0000609 }
Chris Lattner7c1018a2006-07-14 19:37:40 +0000610 default:
611 assert(getNumOperands() == 2 && "Must be binary operator?");
Chris Lattner227816342006-07-14 22:20:01 +0000612 Op0 = (OpNo == 0) ? Op : getOperand(0);
613 Op1 = (OpNo == 1) ? Op : getOperand(1);
614 return ConstantExpr::get(getOpcode(), Op0, Op1);
615 }
616}
617
618/// getWithOperands - This returns the current constant expression with the
619/// operands replaced with the specified values. The specified operands must
620/// match count and type with the existing ones.
621Constant *ConstantExpr::
622getWithOperands(const std::vector<Constant*> &Ops) const {
623 assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
624 bool AnyChange = false;
625 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
626 assert(Ops[i]->getType() == getOperand(i)->getType() &&
627 "Operand type mismatch!");
628 AnyChange |= Ops[i] != getOperand(i);
629 }
630 if (!AnyChange) // No operands changed, return self.
631 return const_cast<ConstantExpr*>(this);
632
633 switch (getOpcode()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000634 case Instruction::Trunc:
635 case Instruction::ZExt:
636 case Instruction::SExt:
637 case Instruction::FPTrunc:
638 case Instruction::FPExt:
639 case Instruction::UIToFP:
640 case Instruction::SIToFP:
641 case Instruction::FPToUI:
642 case Instruction::FPToSI:
643 case Instruction::PtrToInt:
644 case Instruction::IntToPtr:
645 case Instruction::BitCast:
646 return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
Chris Lattner227816342006-07-14 22:20:01 +0000647 case Instruction::Select:
648 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
649 case Instruction::InsertElement:
650 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
651 case Instruction::ExtractElement:
652 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
653 case Instruction::ShuffleVector:
654 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
Chris Lattnerb5d70302007-02-19 20:01:23 +0000655 case Instruction::GetElementPtr:
656 return ConstantExpr::getGetElementPtr(Ops[0], &Ops[1], Ops.size()-1);
Reid Spencer266e42b2006-12-23 06:05:41 +0000657 case Instruction::ICmp:
658 case Instruction::FCmp:
659 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
Chris Lattner227816342006-07-14 22:20:01 +0000660 default:
661 assert(getNumOperands() == 2 && "Must be binary operator?");
662 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1]);
Chris Lattner7c1018a2006-07-14 19:37:40 +0000663 }
664}
665
Chris Lattner2f7c9632001-06-06 20:29:01 +0000666
667//===----------------------------------------------------------------------===//
Chris Lattner2f7c9632001-06-06 20:29:01 +0000668// isValueValidForType implementations
669
Reid Spencere7334722006-12-19 01:28:19 +0000670bool ConstantInt::isValueValidForType(const Type *Ty, uint64_t Val) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000671 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000672 if (Ty == Type::Int1Ty)
673 return Val == 0 || Val == 1;
Reid Spencerd7a00d72007-02-05 23:47:56 +0000674 if (NumBits >= 64)
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000675 return true; // always true, has to fit in largest type
676 uint64_t Max = (1ll << NumBits) - 1;
677 return Val <= Max;
Reid Spencere7334722006-12-19 01:28:19 +0000678}
679
Reid Spencere0fc4df2006-10-20 07:07:24 +0000680bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000681 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000682 if (Ty == Type::Int1Ty)
Reid Spencera94d3942007-01-19 21:13:56 +0000683 return Val == 0 || Val == 1 || Val == -1;
Reid Spencerd7a00d72007-02-05 23:47:56 +0000684 if (NumBits >= 64)
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000685 return true; // always true, has to fit in largest type
686 int64_t Min = -(1ll << (NumBits-1));
687 int64_t Max = (1ll << (NumBits-1)) - 1;
688 return (Val >= Min && Val <= Max);
Chris Lattner2f7c9632001-06-06 20:29:01 +0000689}
690
Chris Lattner3462ae32001-12-03 22:26:30 +0000691bool ConstantFP::isValueValidForType(const Type *Ty, double Val) {
Chris Lattner6b727592004-06-17 18:19:28 +0000692 switch (Ty->getTypeID()) {
Chris Lattner2f7c9632001-06-06 20:29:01 +0000693 default:
694 return false; // These can't be represented as floating point!
695
Dale Johannesenbdad8092007-08-09 22:51:36 +0000696 // TODO: Figure out how to test if we can use a shorter type instead!
Chris Lattner2f7c9632001-06-06 20:29:01 +0000697 case Type::FloatTyID:
Chris Lattner2f7c9632001-06-06 20:29:01 +0000698 case Type::DoubleTyID:
Dale Johannesenbdad8092007-08-09 22:51:36 +0000699 case Type::X86_FP80TyID:
700 case Type::PPC_FP128TyID:
701 case Type::FP128TyID:
702 return true;
Chris Lattner2f7c9632001-06-06 20:29:01 +0000703 }
Chris Lattneraa2372562006-05-24 17:04:05 +0000704}
Chris Lattner9655e542001-07-20 19:16:02 +0000705
Chris Lattner49d855c2001-09-07 16:46:31 +0000706//===----------------------------------------------------------------------===//
Chris Lattner49d855c2001-09-07 16:46:31 +0000707// Factory Function Implementation
708
Chris Lattner98fa07b2003-05-23 20:03:32 +0000709// ConstantCreator - A class that is used to create constants by
710// ValueMap*. This class should be partially specialized if there is
711// something strange that needs to be done to interface to the ctor for the
712// constant.
713//
Chris Lattner189d19f2003-11-21 20:23:48 +0000714namespace llvm {
715 template<class ConstantClass, class TypeClass, class ValType>
Chris Lattner02157b02006-06-28 21:38:54 +0000716 struct VISIBILITY_HIDDEN ConstantCreator {
Chris Lattner189d19f2003-11-21 20:23:48 +0000717 static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
718 return new ConstantClass(Ty, V);
719 }
720 };
Misha Brukmanb1c93172005-04-21 23:48:37 +0000721
Chris Lattner189d19f2003-11-21 20:23:48 +0000722 template<class ConstantClass, class TypeClass>
Chris Lattner02157b02006-06-28 21:38:54 +0000723 struct VISIBILITY_HIDDEN ConvertConstantType {
Chris Lattner189d19f2003-11-21 20:23:48 +0000724 static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
725 assert(0 && "This type cannot be converted!\n");
726 abort();
727 }
728 };
Chris Lattnerb50d1352003-10-05 00:17:43 +0000729
Chris Lattner935aa922005-10-04 17:48:46 +0000730 template<class ValType, class TypeClass, class ConstantClass,
731 bool HasLargeKey = false /*true for arrays and structs*/ >
Chris Lattner02157b02006-06-28 21:38:54 +0000732 class VISIBILITY_HIDDEN ValueMap : public AbstractTypeUser {
Chris Lattnerb64419a2005-10-03 22:51:37 +0000733 public:
Jim Laskeyc03caef2006-07-17 17:38:29 +0000734 typedef std::pair<const Type*, ValType> MapKey;
735 typedef std::map<MapKey, Constant *> MapTy;
736 typedef std::map<Constant*, typename MapTy::iterator> InverseMapTy;
737 typedef std::map<const Type*, typename MapTy::iterator> AbstractTypeMapTy;
Chris Lattnerb64419a2005-10-03 22:51:37 +0000738 private:
Chris Lattner5bbf60a52005-10-04 16:52:46 +0000739 /// Map - This is the main map from the element descriptor to the Constants.
740 /// This is the primary way we avoid creating two of the same shape
741 /// constant.
Chris Lattnerb50d1352003-10-05 00:17:43 +0000742 MapTy Map;
Chris Lattner935aa922005-10-04 17:48:46 +0000743
744 /// InverseMap - If "HasLargeKey" is true, this contains an inverse mapping
745 /// from the constants to their element in Map. This is important for
746 /// removal of constants from the array, which would otherwise have to scan
747 /// through the map with very large keys.
Jim Laskeyc03caef2006-07-17 17:38:29 +0000748 InverseMapTy InverseMap;
Chris Lattnerb50d1352003-10-05 00:17:43 +0000749
Jim Laskeyc03caef2006-07-17 17:38:29 +0000750 /// AbstractTypeMap - Map for abstract type constants.
751 ///
Chris Lattnerb50d1352003-10-05 00:17:43 +0000752 AbstractTypeMapTy AbstractTypeMap;
Chris Lattner99a669b2004-11-19 16:39:44 +0000753
Chris Lattner98fa07b2003-05-23 20:03:32 +0000754 public:
Jim Laskeyc03caef2006-07-17 17:38:29 +0000755 typename MapTy::iterator map_end() { return Map.end(); }
Chris Lattnerb64419a2005-10-03 22:51:37 +0000756
757 /// InsertOrGetItem - Return an iterator for the specified element.
758 /// If the element exists in the map, the returned iterator points to the
759 /// entry and Exists=true. If not, the iterator points to the newly
760 /// inserted entry and returns Exists=false. Newly inserted entries have
761 /// I->second == 0, and should be filled in.
Jim Laskeyc03caef2006-07-17 17:38:29 +0000762 typename MapTy::iterator InsertOrGetItem(std::pair<MapKey, Constant *>
763 &InsertVal,
Chris Lattnerb64419a2005-10-03 22:51:37 +0000764 bool &Exists) {
Jim Laskeyc03caef2006-07-17 17:38:29 +0000765 std::pair<typename MapTy::iterator, bool> IP = Map.insert(InsertVal);
Chris Lattnerb64419a2005-10-03 22:51:37 +0000766 Exists = !IP.second;
767 return IP.first;
768 }
Chris Lattner5bbf60a52005-10-04 16:52:46 +0000769
Chris Lattner935aa922005-10-04 17:48:46 +0000770private:
Jim Laskeyc03caef2006-07-17 17:38:29 +0000771 typename MapTy::iterator FindExistingElement(ConstantClass *CP) {
Chris Lattner935aa922005-10-04 17:48:46 +0000772 if (HasLargeKey) {
Jim Laskeyc03caef2006-07-17 17:38:29 +0000773 typename InverseMapTy::iterator IMI = InverseMap.find(CP);
Chris Lattner935aa922005-10-04 17:48:46 +0000774 assert(IMI != InverseMap.end() && IMI->second != Map.end() &&
775 IMI->second->second == CP &&
776 "InverseMap corrupt!");
777 return IMI->second;
778 }
779
Jim Laskeyc03caef2006-07-17 17:38:29 +0000780 typename MapTy::iterator I =
Chris Lattner935aa922005-10-04 17:48:46 +0000781 Map.find(MapKey((TypeClass*)CP->getRawType(), getValType(CP)));
Chris Lattner5bbf60a52005-10-04 16:52:46 +0000782 if (I == Map.end() || I->second != CP) {
783 // FIXME: This should not use a linear scan. If this gets to be a
784 // performance problem, someone should look at this.
785 for (I = Map.begin(); I != Map.end() && I->second != CP; ++I)
786 /* empty */;
787 }
Chris Lattner935aa922005-10-04 17:48:46 +0000788 return I;
789 }
790public:
791
Chris Lattnerb64419a2005-10-03 22:51:37 +0000792 /// getOrCreate - Return the specified constant from the map, creating it if
793 /// necessary.
Chris Lattner98fa07b2003-05-23 20:03:32 +0000794 ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
Chris Lattnerb50d1352003-10-05 00:17:43 +0000795 MapKey Lookup(Ty, V);
Jim Laskeyc03caef2006-07-17 17:38:29 +0000796 typename MapTy::iterator I = Map.lower_bound(Lookup);
Reid Spencere0fc4df2006-10-20 07:07:24 +0000797 // Is it in the map?
Chris Lattner98fa07b2003-05-23 20:03:32 +0000798 if (I != Map.end() && I->first == Lookup)
Reid Spencere0fc4df2006-10-20 07:07:24 +0000799 return static_cast<ConstantClass *>(I->second);
Chris Lattner98fa07b2003-05-23 20:03:32 +0000800
801 // If no preexisting value, create one now...
802 ConstantClass *Result =
803 ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
804
Chris Lattnerb50d1352003-10-05 00:17:43 +0000805 /// FIXME: why does this assert fail when loading 176.gcc?
806 //assert(Result->getType() == Ty && "Type specified is not correct!");
807 I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
808
Chris Lattner935aa922005-10-04 17:48:46 +0000809 if (HasLargeKey) // Remember the reverse mapping if needed.
810 InverseMap.insert(std::make_pair(Result, I));
811
Chris Lattnerb50d1352003-10-05 00:17:43 +0000812 // If the type of the constant is abstract, make sure that an entry exists
813 // for it in the AbstractTypeMap.
814 if (Ty->isAbstract()) {
815 typename AbstractTypeMapTy::iterator TI =
816 AbstractTypeMap.lower_bound(Ty);
817
818 if (TI == AbstractTypeMap.end() || TI->first != Ty) {
819 // Add ourselves to the ATU list of the type.
820 cast<DerivedType>(Ty)->addAbstractTypeUser(this);
821
822 AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
823 }
824 }
Chris Lattner98fa07b2003-05-23 20:03:32 +0000825 return Result;
826 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000827
Chris Lattner98fa07b2003-05-23 20:03:32 +0000828 void remove(ConstantClass *CP) {
Jim Laskeyc03caef2006-07-17 17:38:29 +0000829 typename MapTy::iterator I = FindExistingElement(CP);
Chris Lattnerb50d1352003-10-05 00:17:43 +0000830 assert(I != Map.end() && "Constant not found in constant table!");
Chris Lattner3e650af2004-08-04 04:48:01 +0000831 assert(I->second == CP && "Didn't find correct element?");
Chris Lattnerb50d1352003-10-05 00:17:43 +0000832
Chris Lattner935aa922005-10-04 17:48:46 +0000833 if (HasLargeKey) // Remember the reverse mapping if needed.
834 InverseMap.erase(CP);
835
Chris Lattnerb50d1352003-10-05 00:17:43 +0000836 // Now that we found the entry, make sure this isn't the entry that
837 // the AbstractTypeMap points to.
Jim Laskeyc03caef2006-07-17 17:38:29 +0000838 const TypeClass *Ty = static_cast<const TypeClass *>(I->first.first);
Chris Lattnerb50d1352003-10-05 00:17:43 +0000839 if (Ty->isAbstract()) {
840 assert(AbstractTypeMap.count(Ty) &&
841 "Abstract type not in AbstractTypeMap?");
Jim Laskeyc03caef2006-07-17 17:38:29 +0000842 typename MapTy::iterator &ATMEntryIt = AbstractTypeMap[Ty];
Chris Lattnerb50d1352003-10-05 00:17:43 +0000843 if (ATMEntryIt == I) {
844 // Yes, we are removing the representative entry for this type.
845 // See if there are any other entries of the same type.
Jim Laskeyc03caef2006-07-17 17:38:29 +0000846 typename MapTy::iterator TmpIt = ATMEntryIt;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000847
Chris Lattnerb50d1352003-10-05 00:17:43 +0000848 // First check the entry before this one...
849 if (TmpIt != Map.begin()) {
850 --TmpIt;
851 if (TmpIt->first.first != Ty) // Not the same type, move back...
852 ++TmpIt;
853 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000854
Chris Lattnerb50d1352003-10-05 00:17:43 +0000855 // If we didn't find the same type, try to move forward...
856 if (TmpIt == ATMEntryIt) {
857 ++TmpIt;
858 if (TmpIt == Map.end() || TmpIt->first.first != Ty)
859 --TmpIt; // No entry afterwards with the same type
860 }
861
862 // If there is another entry in the map of the same abstract type,
863 // update the AbstractTypeMap entry now.
864 if (TmpIt != ATMEntryIt) {
865 ATMEntryIt = TmpIt;
866 } else {
867 // Otherwise, we are removing the last instance of this type
868 // from the table. Remove from the ATM, and from user list.
869 cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
870 AbstractTypeMap.erase(Ty);
871 }
Chris Lattner98fa07b2003-05-23 20:03:32 +0000872 }
Chris Lattnerb50d1352003-10-05 00:17:43 +0000873 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000874
Chris Lattnerb50d1352003-10-05 00:17:43 +0000875 Map.erase(I);
876 }
877
Chris Lattner3b793c62005-10-04 21:35:50 +0000878
879 /// MoveConstantToNewSlot - If we are about to change C to be the element
880 /// specified by I, update our internal data structures to reflect this
881 /// fact.
Jim Laskeyc03caef2006-07-17 17:38:29 +0000882 void MoveConstantToNewSlot(ConstantClass *C, typename MapTy::iterator I) {
Chris Lattner3b793c62005-10-04 21:35:50 +0000883 // First, remove the old location of the specified constant in the map.
Jim Laskeyc03caef2006-07-17 17:38:29 +0000884 typename MapTy::iterator OldI = FindExistingElement(C);
Chris Lattner3b793c62005-10-04 21:35:50 +0000885 assert(OldI != Map.end() && "Constant not found in constant table!");
886 assert(OldI->second == C && "Didn't find correct element?");
887
888 // If this constant is the representative element for its abstract type,
889 // update the AbstractTypeMap so that the representative element is I.
890 if (C->getType()->isAbstract()) {
891 typename AbstractTypeMapTy::iterator ATI =
892 AbstractTypeMap.find(C->getType());
893 assert(ATI != AbstractTypeMap.end() &&
894 "Abstract type not in AbstractTypeMap?");
895 if (ATI->second == OldI)
896 ATI->second = I;
897 }
898
899 // Remove the old entry from the map.
900 Map.erase(OldI);
901
902 // Update the inverse map so that we know that this constant is now
903 // located at descriptor I.
904 if (HasLargeKey) {
905 assert(I->second == C && "Bad inversemap entry!");
906 InverseMap[C] = I;
907 }
908 }
909
Chris Lattnerb50d1352003-10-05 00:17:43 +0000910 void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
Misha Brukmanb1c93172005-04-21 23:48:37 +0000911 typename AbstractTypeMapTy::iterator I =
Jim Laskeyc03caef2006-07-17 17:38:29 +0000912 AbstractTypeMap.find(cast<Type>(OldTy));
Chris Lattnerb50d1352003-10-05 00:17:43 +0000913
914 assert(I != AbstractTypeMap.end() &&
915 "Abstract type not in AbstractTypeMap?");
916
917 // Convert a constant at a time until the last one is gone. The last one
918 // leaving will remove() itself, causing the AbstractTypeMapEntry to be
919 // eliminated eventually.
920 do {
921 ConvertConstantType<ConstantClass,
Jim Laskeyc03caef2006-07-17 17:38:29 +0000922 TypeClass>::convert(
923 static_cast<ConstantClass *>(I->second->second),
Chris Lattnerb50d1352003-10-05 00:17:43 +0000924 cast<TypeClass>(NewTy));
925
Jim Laskeyc03caef2006-07-17 17:38:29 +0000926 I = AbstractTypeMap.find(cast<Type>(OldTy));
Chris Lattnerb50d1352003-10-05 00:17:43 +0000927 } while (I != AbstractTypeMap.end());
928 }
929
930 // If the type became concrete without being refined to any other existing
931 // type, we just remove ourselves from the ATU list.
932 void typeBecameConcrete(const DerivedType *AbsTy) {
933 AbsTy->removeAbstractTypeUser(this);
934 }
935
936 void dump() const {
Bill Wendling6a462f12006-11-17 08:03:48 +0000937 DOUT << "Constant.cpp: ValueMap\n";
Chris Lattner98fa07b2003-05-23 20:03:32 +0000938 }
939 };
940}
941
Chris Lattnera84df0a22006-09-28 23:36:21 +0000942
Chris Lattner28173502007-02-20 06:11:36 +0000943
Chris Lattner9fba3da2004-02-15 05:53:04 +0000944//---- ConstantAggregateZero::get() implementation...
945//
946namespace llvm {
947 // ConstantAggregateZero does not take extra "value" argument...
948 template<class ValType>
949 struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
950 static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
951 return new ConstantAggregateZero(Ty);
952 }
953 };
954
955 template<>
956 struct ConvertConstantType<ConstantAggregateZero, Type> {
957 static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
958 // Make everyone now use a constant of the new type...
959 Constant *New = ConstantAggregateZero::get(NewTy);
960 assert(New != OldC && "Didn't replace constant??");
961 OldC->uncheckedReplaceAllUsesWith(New);
962 OldC->destroyConstant(); // This constant is now dead, destroy it.
963 }
964 };
965}
966
Chris Lattner69edc982006-09-28 00:35:06 +0000967static ManagedStatic<ValueMap<char, Type,
968 ConstantAggregateZero> > AggZeroConstants;
Chris Lattner9fba3da2004-02-15 05:53:04 +0000969
Chris Lattner3e650af2004-08-04 04:48:01 +0000970static char getValType(ConstantAggregateZero *CPZ) { return 0; }
971
Chris Lattner9fba3da2004-02-15 05:53:04 +0000972Constant *ConstantAggregateZero::get(const Type *Ty) {
Reid Spencerd84d35b2007-02-15 02:26:10 +0000973 assert((isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) &&
Chris Lattnerbfd0b6d2006-06-10 04:16:23 +0000974 "Cannot create an aggregate zero of non-aggregate type!");
Chris Lattner69edc982006-09-28 00:35:06 +0000975 return AggZeroConstants->getOrCreate(Ty, 0);
Chris Lattner9fba3da2004-02-15 05:53:04 +0000976}
977
978// destroyConstant - Remove the constant from the constant table...
979//
980void ConstantAggregateZero::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +0000981 AggZeroConstants->remove(this);
Chris Lattner9fba3da2004-02-15 05:53:04 +0000982 destroyConstantImpl();
983}
984
Chris Lattner3462ae32001-12-03 22:26:30 +0000985//---- ConstantArray::get() implementation...
Chris Lattner49d855c2001-09-07 16:46:31 +0000986//
Chris Lattner189d19f2003-11-21 20:23:48 +0000987namespace llvm {
988 template<>
989 struct ConvertConstantType<ConstantArray, ArrayType> {
990 static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
991 // Make everyone now use a constant of the new type...
992 std::vector<Constant*> C;
993 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
994 C.push_back(cast<Constant>(OldC->getOperand(i)));
995 Constant *New = ConstantArray::get(NewTy, C);
996 assert(New != OldC && "Didn't replace constant??");
997 OldC->uncheckedReplaceAllUsesWith(New);
998 OldC->destroyConstant(); // This constant is now dead, destroy it.
999 }
1000 };
1001}
Chris Lattnerb50d1352003-10-05 00:17:43 +00001002
Chris Lattner3e650af2004-08-04 04:48:01 +00001003static std::vector<Constant*> getValType(ConstantArray *CA) {
1004 std::vector<Constant*> Elements;
1005 Elements.reserve(CA->getNumOperands());
1006 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1007 Elements.push_back(cast<Constant>(CA->getOperand(i)));
1008 return Elements;
1009}
1010
Chris Lattnerb64419a2005-10-03 22:51:37 +00001011typedef ValueMap<std::vector<Constant*>, ArrayType,
Chris Lattner935aa922005-10-04 17:48:46 +00001012 ConstantArray, true /*largekey*/> ArrayConstantsTy;
Chris Lattner69edc982006-09-28 00:35:06 +00001013static ManagedStatic<ArrayConstantsTy> ArrayConstants;
Chris Lattner49d855c2001-09-07 16:46:31 +00001014
Chris Lattner015e8212004-02-15 04:14:47 +00001015Constant *ConstantArray::get(const ArrayType *Ty,
Chris Lattner9fba3da2004-02-15 05:53:04 +00001016 const std::vector<Constant*> &V) {
1017 // If this is an all-zero array, return a ConstantAggregateZero object
1018 if (!V.empty()) {
1019 Constant *C = V[0];
1020 if (!C->isNullValue())
Chris Lattner69edc982006-09-28 00:35:06 +00001021 return ArrayConstants->getOrCreate(Ty, V);
Chris Lattner9fba3da2004-02-15 05:53:04 +00001022 for (unsigned i = 1, e = V.size(); i != e; ++i)
1023 if (V[i] != C)
Chris Lattner69edc982006-09-28 00:35:06 +00001024 return ArrayConstants->getOrCreate(Ty, V);
Chris Lattner9fba3da2004-02-15 05:53:04 +00001025 }
1026 return ConstantAggregateZero::get(Ty);
Chris Lattner49d855c2001-09-07 16:46:31 +00001027}
1028
Chris Lattner98fa07b2003-05-23 20:03:32 +00001029// destroyConstant - Remove the constant from the constant table...
1030//
1031void ConstantArray::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00001032 ArrayConstants->remove(this);
Chris Lattner98fa07b2003-05-23 20:03:32 +00001033 destroyConstantImpl();
1034}
1035
Reid Spencer6f614532006-05-30 08:23:18 +00001036/// ConstantArray::get(const string&) - Return an array that is initialized to
1037/// contain the specified string. If length is zero then a null terminator is
1038/// added to the specified string so that it may be used in a natural way.
1039/// Otherwise, the length parameter specifies how much of the string to use
1040/// and it won't be null terminated.
1041///
Reid Spencer82ebaba2006-05-30 18:15:07 +00001042Constant *ConstantArray::get(const std::string &Str, bool AddNull) {
Chris Lattner7f74a562002-01-20 22:54:45 +00001043 std::vector<Constant*> ElementVals;
Reid Spencer82ebaba2006-05-30 18:15:07 +00001044 for (unsigned i = 0; i < Str.length(); ++i)
Reid Spencer8d9336d2006-12-31 05:26:44 +00001045 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, Str[i]));
Chris Lattner8f80fe02001-10-14 23:54:12 +00001046
1047 // Add a null terminator to the string...
Reid Spencer82ebaba2006-05-30 18:15:07 +00001048 if (AddNull) {
Reid Spencer8d9336d2006-12-31 05:26:44 +00001049 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, 0));
Reid Spencer6f614532006-05-30 08:23:18 +00001050 }
Chris Lattner8f80fe02001-10-14 23:54:12 +00001051
Reid Spencer8d9336d2006-12-31 05:26:44 +00001052 ArrayType *ATy = ArrayType::get(Type::Int8Ty, ElementVals.size());
Chris Lattner3462ae32001-12-03 22:26:30 +00001053 return ConstantArray::get(ATy, ElementVals);
Vikram S. Adve34410432001-10-14 23:17:20 +00001054}
1055
Reid Spencer2546b762007-01-26 07:37:34 +00001056/// isString - This method returns true if the array is an array of i8, and
1057/// if the elements of the array are all ConstantInt's.
Chris Lattnere8dfcca2004-01-14 17:06:38 +00001058bool ConstantArray::isString() const {
Reid Spencer2546b762007-01-26 07:37:34 +00001059 // Check the element type for i8...
Reid Spencer8d9336d2006-12-31 05:26:44 +00001060 if (getType()->getElementType() != Type::Int8Ty)
Chris Lattnere8dfcca2004-01-14 17:06:38 +00001061 return false;
1062 // Check the elements to make sure they are all integers, not constant
1063 // expressions.
1064 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1065 if (!isa<ConstantInt>(getOperand(i)))
1066 return false;
1067 return true;
1068}
1069
Evan Cheng3763c5b2006-10-26 19:15:05 +00001070/// isCString - This method returns true if the array is a string (see
1071/// isString) and it ends in a null byte \0 and does not contains any other
1072/// null bytes except its terminator.
1073bool ConstantArray::isCString() const {
Reid Spencer2546b762007-01-26 07:37:34 +00001074 // Check the element type for i8...
Reid Spencer8d9336d2006-12-31 05:26:44 +00001075 if (getType()->getElementType() != Type::Int8Ty)
Evan Chenge974da62006-10-26 21:48:03 +00001076 return false;
1077 Constant *Zero = Constant::getNullValue(getOperand(0)->getType());
1078 // Last element must be a null.
1079 if (getOperand(getNumOperands()-1) != Zero)
1080 return false;
1081 // Other elements must be non-null integers.
1082 for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
1083 if (!isa<ConstantInt>(getOperand(i)))
Evan Cheng3763c5b2006-10-26 19:15:05 +00001084 return false;
Evan Chenge974da62006-10-26 21:48:03 +00001085 if (getOperand(i) == Zero)
1086 return false;
1087 }
Evan Cheng3763c5b2006-10-26 19:15:05 +00001088 return true;
1089}
1090
1091
Reid Spencer2546b762007-01-26 07:37:34 +00001092// getAsString - If the sub-element type of this array is i8
Chris Lattner81fabb02002-08-26 17:53:56 +00001093// then this method converts the array to an std::string and returns it.
1094// Otherwise, it asserts out.
1095//
1096std::string ConstantArray::getAsString() const {
Chris Lattnere8dfcca2004-01-14 17:06:38 +00001097 assert(isString() && "Not a string!");
Chris Lattner81fabb02002-08-26 17:53:56 +00001098 std::string Result;
Chris Lattner6077c312003-07-23 15:22:26 +00001099 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
Reid Spencere0fc4df2006-10-20 07:07:24 +00001100 Result += (char)cast<ConstantInt>(getOperand(i))->getZExtValue();
Chris Lattner81fabb02002-08-26 17:53:56 +00001101 return Result;
1102}
1103
1104
Chris Lattner3462ae32001-12-03 22:26:30 +00001105//---- ConstantStruct::get() implementation...
Chris Lattner49d855c2001-09-07 16:46:31 +00001106//
Chris Lattnerb50d1352003-10-05 00:17:43 +00001107
Chris Lattner189d19f2003-11-21 20:23:48 +00001108namespace llvm {
1109 template<>
1110 struct ConvertConstantType<ConstantStruct, StructType> {
1111 static void convert(ConstantStruct *OldC, const StructType *NewTy) {
1112 // Make everyone now use a constant of the new type...
1113 std::vector<Constant*> C;
1114 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1115 C.push_back(cast<Constant>(OldC->getOperand(i)));
1116 Constant *New = ConstantStruct::get(NewTy, C);
1117 assert(New != OldC && "Didn't replace constant??");
Misha Brukmanb1c93172005-04-21 23:48:37 +00001118
Chris Lattner189d19f2003-11-21 20:23:48 +00001119 OldC->uncheckedReplaceAllUsesWith(New);
1120 OldC->destroyConstant(); // This constant is now dead, destroy it.
1121 }
1122 };
1123}
Chris Lattnerb50d1352003-10-05 00:17:43 +00001124
Chris Lattner8760ec72005-10-04 01:17:50 +00001125typedef ValueMap<std::vector<Constant*>, StructType,
Chris Lattner935aa922005-10-04 17:48:46 +00001126 ConstantStruct, true /*largekey*/> StructConstantsTy;
Chris Lattner69edc982006-09-28 00:35:06 +00001127static ManagedStatic<StructConstantsTy> StructConstants;
Chris Lattner49d855c2001-09-07 16:46:31 +00001128
Chris Lattner3e650af2004-08-04 04:48:01 +00001129static std::vector<Constant*> getValType(ConstantStruct *CS) {
1130 std::vector<Constant*> Elements;
1131 Elements.reserve(CS->getNumOperands());
1132 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1133 Elements.push_back(cast<Constant>(CS->getOperand(i)));
1134 return Elements;
1135}
1136
Chris Lattner015e8212004-02-15 04:14:47 +00001137Constant *ConstantStruct::get(const StructType *Ty,
1138 const std::vector<Constant*> &V) {
Chris Lattner9fba3da2004-02-15 05:53:04 +00001139 // Create a ConstantAggregateZero value if all elements are zeros...
1140 for (unsigned i = 0, e = V.size(); i != e; ++i)
1141 if (!V[i]->isNullValue())
Chris Lattner69edc982006-09-28 00:35:06 +00001142 return StructConstants->getOrCreate(Ty, V);
Chris Lattner9fba3da2004-02-15 05:53:04 +00001143
1144 return ConstantAggregateZero::get(Ty);
Chris Lattner49d855c2001-09-07 16:46:31 +00001145}
Chris Lattner883ad0b2001-10-03 15:39:36 +00001146
Andrew Lenharthdcb3c972006-12-08 18:06:16 +00001147Constant *ConstantStruct::get(const std::vector<Constant*> &V, bool packed) {
Chris Lattnerd6108ca2004-07-12 20:35:11 +00001148 std::vector<const Type*> StructEls;
1149 StructEls.reserve(V.size());
1150 for (unsigned i = 0, e = V.size(); i != e; ++i)
1151 StructEls.push_back(V[i]->getType());
Andrew Lenharthdcb3c972006-12-08 18:06:16 +00001152 return get(StructType::get(StructEls, packed), V);
Chris Lattnerd6108ca2004-07-12 20:35:11 +00001153}
1154
Chris Lattnerd7a73302001-10-13 06:57:33 +00001155// destroyConstant - Remove the constant from the constant table...
Chris Lattner883ad0b2001-10-03 15:39:36 +00001156//
Chris Lattner3462ae32001-12-03 22:26:30 +00001157void ConstantStruct::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00001158 StructConstants->remove(this);
Chris Lattnerd7a73302001-10-13 06:57:33 +00001159 destroyConstantImpl();
1160}
Chris Lattner883ad0b2001-10-03 15:39:36 +00001161
Reid Spencerd84d35b2007-02-15 02:26:10 +00001162//---- ConstantVector::get() implementation...
Brian Gaeke02209042004-08-20 06:00:58 +00001163//
1164namespace llvm {
1165 template<>
Reid Spencerd84d35b2007-02-15 02:26:10 +00001166 struct ConvertConstantType<ConstantVector, VectorType> {
1167 static void convert(ConstantVector *OldC, const VectorType *NewTy) {
Brian Gaeke02209042004-08-20 06:00:58 +00001168 // Make everyone now use a constant of the new type...
1169 std::vector<Constant*> C;
1170 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1171 C.push_back(cast<Constant>(OldC->getOperand(i)));
Reid Spencerd84d35b2007-02-15 02:26:10 +00001172 Constant *New = ConstantVector::get(NewTy, C);
Brian Gaeke02209042004-08-20 06:00:58 +00001173 assert(New != OldC && "Didn't replace constant??");
1174 OldC->uncheckedReplaceAllUsesWith(New);
1175 OldC->destroyConstant(); // This constant is now dead, destroy it.
1176 }
1177 };
1178}
1179
Reid Spencerd84d35b2007-02-15 02:26:10 +00001180static std::vector<Constant*> getValType(ConstantVector *CP) {
Brian Gaeke02209042004-08-20 06:00:58 +00001181 std::vector<Constant*> Elements;
1182 Elements.reserve(CP->getNumOperands());
1183 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1184 Elements.push_back(CP->getOperand(i));
1185 return Elements;
1186}
1187
Reid Spencerd84d35b2007-02-15 02:26:10 +00001188static ManagedStatic<ValueMap<std::vector<Constant*>, VectorType,
Reid Spencer09575ba2007-02-15 03:39:18 +00001189 ConstantVector> > VectorConstants;
Brian Gaeke02209042004-08-20 06:00:58 +00001190
Reid Spencerd84d35b2007-02-15 02:26:10 +00001191Constant *ConstantVector::get(const VectorType *Ty,
Brian Gaeke02209042004-08-20 06:00:58 +00001192 const std::vector<Constant*> &V) {
Dan Gohman30978072007-05-24 14:36:04 +00001193 // If this is an all-zero vector, return a ConstantAggregateZero object
Brian Gaeke02209042004-08-20 06:00:58 +00001194 if (!V.empty()) {
1195 Constant *C = V[0];
1196 if (!C->isNullValue())
Reid Spencer09575ba2007-02-15 03:39:18 +00001197 return VectorConstants->getOrCreate(Ty, V);
Brian Gaeke02209042004-08-20 06:00:58 +00001198 for (unsigned i = 1, e = V.size(); i != e; ++i)
1199 if (V[i] != C)
Reid Spencer09575ba2007-02-15 03:39:18 +00001200 return VectorConstants->getOrCreate(Ty, V);
Brian Gaeke02209042004-08-20 06:00:58 +00001201 }
1202 return ConstantAggregateZero::get(Ty);
1203}
1204
Reid Spencerd84d35b2007-02-15 02:26:10 +00001205Constant *ConstantVector::get(const std::vector<Constant*> &V) {
Brian Gaeke02209042004-08-20 06:00:58 +00001206 assert(!V.empty() && "Cannot infer type if V is empty");
Reid Spencerd84d35b2007-02-15 02:26:10 +00001207 return get(VectorType::get(V.front()->getType(),V.size()), V);
Brian Gaeke02209042004-08-20 06:00:58 +00001208}
1209
1210// destroyConstant - Remove the constant from the constant table...
1211//
Reid Spencerd84d35b2007-02-15 02:26:10 +00001212void ConstantVector::destroyConstant() {
Reid Spencer09575ba2007-02-15 03:39:18 +00001213 VectorConstants->remove(this);
Brian Gaeke02209042004-08-20 06:00:58 +00001214 destroyConstantImpl();
1215}
1216
Dan Gohman30978072007-05-24 14:36:04 +00001217/// This function will return true iff every element in this vector constant
Jim Laskeyf0478822007-01-12 22:39:14 +00001218/// is set to all ones.
1219/// @returns true iff this constant's emements are all set to all ones.
1220/// @brief Determine if the value is all ones.
Reid Spencerd84d35b2007-02-15 02:26:10 +00001221bool ConstantVector::isAllOnesValue() const {
Jim Laskeyf0478822007-01-12 22:39:14 +00001222 // Check out first element.
1223 const Constant *Elt = getOperand(0);
1224 const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1225 if (!CI || !CI->isAllOnesValue()) return false;
1226 // Then make sure all remaining elements point to the same value.
1227 for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
1228 if (getOperand(I) != Elt) return false;
1229 }
1230 return true;
1231}
1232
Chris Lattner3462ae32001-12-03 22:26:30 +00001233//---- ConstantPointerNull::get() implementation...
Chris Lattnerd7a73302001-10-13 06:57:33 +00001234//
Chris Lattner98fa07b2003-05-23 20:03:32 +00001235
Chris Lattner189d19f2003-11-21 20:23:48 +00001236namespace llvm {
1237 // ConstantPointerNull does not take extra "value" argument...
1238 template<class ValType>
1239 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1240 static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1241 return new ConstantPointerNull(Ty);
1242 }
1243 };
Chris Lattner98fa07b2003-05-23 20:03:32 +00001244
Chris Lattner189d19f2003-11-21 20:23:48 +00001245 template<>
1246 struct ConvertConstantType<ConstantPointerNull, PointerType> {
1247 static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1248 // Make everyone now use a constant of the new type...
1249 Constant *New = ConstantPointerNull::get(NewTy);
1250 assert(New != OldC && "Didn't replace constant??");
1251 OldC->uncheckedReplaceAllUsesWith(New);
1252 OldC->destroyConstant(); // This constant is now dead, destroy it.
1253 }
1254 };
1255}
Chris Lattnerb50d1352003-10-05 00:17:43 +00001256
Chris Lattner69edc982006-09-28 00:35:06 +00001257static ManagedStatic<ValueMap<char, PointerType,
1258 ConstantPointerNull> > NullPtrConstants;
Chris Lattnerd7a73302001-10-13 06:57:33 +00001259
Chris Lattner3e650af2004-08-04 04:48:01 +00001260static char getValType(ConstantPointerNull *) {
1261 return 0;
1262}
1263
1264
Chris Lattner3462ae32001-12-03 22:26:30 +00001265ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
Chris Lattner69edc982006-09-28 00:35:06 +00001266 return NullPtrConstants->getOrCreate(Ty, 0);
Chris Lattner883ad0b2001-10-03 15:39:36 +00001267}
1268
Chris Lattner0c6e0b92002-08-18 00:40:04 +00001269// destroyConstant - Remove the constant from the constant table...
1270//
1271void ConstantPointerNull::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00001272 NullPtrConstants->remove(this);
Chris Lattner0c6e0b92002-08-18 00:40:04 +00001273 destroyConstantImpl();
1274}
1275
1276
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001277//---- UndefValue::get() implementation...
1278//
1279
1280namespace llvm {
1281 // UndefValue does not take extra "value" argument...
1282 template<class ValType>
1283 struct ConstantCreator<UndefValue, Type, ValType> {
1284 static UndefValue *create(const Type *Ty, const ValType &V) {
1285 return new UndefValue(Ty);
1286 }
1287 };
1288
1289 template<>
1290 struct ConvertConstantType<UndefValue, Type> {
1291 static void convert(UndefValue *OldC, const Type *NewTy) {
1292 // Make everyone now use a constant of the new type.
1293 Constant *New = UndefValue::get(NewTy);
1294 assert(New != OldC && "Didn't replace constant??");
1295 OldC->uncheckedReplaceAllUsesWith(New);
1296 OldC->destroyConstant(); // This constant is now dead, destroy it.
1297 }
1298 };
1299}
1300
Chris Lattner69edc982006-09-28 00:35:06 +00001301static ManagedStatic<ValueMap<char, Type, UndefValue> > UndefValueConstants;
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001302
1303static char getValType(UndefValue *) {
1304 return 0;
1305}
1306
1307
1308UndefValue *UndefValue::get(const Type *Ty) {
Chris Lattner69edc982006-09-28 00:35:06 +00001309 return UndefValueConstants->getOrCreate(Ty, 0);
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001310}
1311
1312// destroyConstant - Remove the constant from the constant table.
1313//
1314void UndefValue::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00001315 UndefValueConstants->remove(this);
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001316 destroyConstantImpl();
1317}
1318
1319
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001320//---- ConstantExpr::get() implementations...
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001321//
Reid Spencer8d9336d2006-12-31 05:26:44 +00001322
Reid Spenceree3c9912006-12-04 05:19:50 +00001323struct ExprMapKeyType {
1324 explicit ExprMapKeyType(unsigned opc, std::vector<Constant*> ops,
Reid Spencerdba6aa42006-12-04 18:38:05 +00001325 unsigned short pred = 0) : opcode(opc), predicate(pred), operands(ops) { }
1326 uint16_t opcode;
1327 uint16_t predicate;
Reid Spenceree3c9912006-12-04 05:19:50 +00001328 std::vector<Constant*> operands;
Reid Spenceree3c9912006-12-04 05:19:50 +00001329 bool operator==(const ExprMapKeyType& that) const {
1330 return this->opcode == that.opcode &&
1331 this->predicate == that.predicate &&
1332 this->operands == that.operands;
1333 }
1334 bool operator<(const ExprMapKeyType & that) const {
1335 return this->opcode < that.opcode ||
1336 (this->opcode == that.opcode && this->predicate < that.predicate) ||
1337 (this->opcode == that.opcode && this->predicate == that.predicate &&
1338 this->operands < that.operands);
1339 }
1340
1341 bool operator!=(const ExprMapKeyType& that) const {
1342 return !(*this == that);
1343 }
1344};
Chris Lattner98fa07b2003-05-23 20:03:32 +00001345
Chris Lattner189d19f2003-11-21 20:23:48 +00001346namespace llvm {
1347 template<>
1348 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
Reid Spencer10fbf0e2006-12-03 05:48:19 +00001349 static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V,
1350 unsigned short pred = 0) {
Reid Spenceree3c9912006-12-04 05:19:50 +00001351 if (Instruction::isCast(V.opcode))
1352 return new UnaryConstantExpr(V.opcode, V.operands[0], Ty);
1353 if ((V.opcode >= Instruction::BinaryOpsBegin &&
Reid Spencer2341c222007-02-02 02:16:23 +00001354 V.opcode < Instruction::BinaryOpsEnd))
Reid Spenceree3c9912006-12-04 05:19:50 +00001355 return new BinaryConstantExpr(V.opcode, V.operands[0], V.operands[1]);
1356 if (V.opcode == Instruction::Select)
1357 return new SelectConstantExpr(V.operands[0], V.operands[1],
1358 V.operands[2]);
1359 if (V.opcode == Instruction::ExtractElement)
1360 return new ExtractElementConstantExpr(V.operands[0], V.operands[1]);
1361 if (V.opcode == Instruction::InsertElement)
1362 return new InsertElementConstantExpr(V.operands[0], V.operands[1],
1363 V.operands[2]);
1364 if (V.opcode == Instruction::ShuffleVector)
1365 return new ShuffleVectorConstantExpr(V.operands[0], V.operands[1],
1366 V.operands[2]);
1367 if (V.opcode == Instruction::GetElementPtr) {
1368 std::vector<Constant*> IdxList(V.operands.begin()+1, V.operands.end());
1369 return new GetElementPtrConstantExpr(V.operands[0], IdxList, Ty);
1370 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001371
Reid Spenceree3c9912006-12-04 05:19:50 +00001372 // The compare instructions are weird. We have to encode the predicate
1373 // value and it is combined with the instruction opcode by multiplying
1374 // the opcode by one hundred. We must decode this to get the predicate.
1375 if (V.opcode == Instruction::ICmp)
1376 return new CompareConstantExpr(Instruction::ICmp, V.predicate,
1377 V.operands[0], V.operands[1]);
1378 if (V.opcode == Instruction::FCmp)
1379 return new CompareConstantExpr(Instruction::FCmp, V.predicate,
1380 V.operands[0], V.operands[1]);
1381 assert(0 && "Invalid ConstantExpr!");
Jeff Cohen9f469632006-12-15 21:47:01 +00001382 return 0;
Chris Lattnerb50d1352003-10-05 00:17:43 +00001383 }
Chris Lattner189d19f2003-11-21 20:23:48 +00001384 };
Chris Lattnerb50d1352003-10-05 00:17:43 +00001385
Chris Lattner189d19f2003-11-21 20:23:48 +00001386 template<>
1387 struct ConvertConstantType<ConstantExpr, Type> {
1388 static void convert(ConstantExpr *OldC, const Type *NewTy) {
1389 Constant *New;
1390 switch (OldC->getOpcode()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001391 case Instruction::Trunc:
1392 case Instruction::ZExt:
1393 case Instruction::SExt:
1394 case Instruction::FPTrunc:
1395 case Instruction::FPExt:
1396 case Instruction::UIToFP:
1397 case Instruction::SIToFP:
1398 case Instruction::FPToUI:
1399 case Instruction::FPToSI:
1400 case Instruction::PtrToInt:
1401 case Instruction::IntToPtr:
1402 case Instruction::BitCast:
Reid Spencerbb65ebf2006-12-12 23:36:14 +00001403 New = ConstantExpr::getCast(OldC->getOpcode(), OldC->getOperand(0),
1404 NewTy);
Chris Lattner189d19f2003-11-21 20:23:48 +00001405 break;
Chris Lattner6e415c02004-03-12 05:54:04 +00001406 case Instruction::Select:
1407 New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1408 OldC->getOperand(1),
1409 OldC->getOperand(2));
1410 break;
Chris Lattner189d19f2003-11-21 20:23:48 +00001411 default:
1412 assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
Reid Spencer7eb55b32006-11-02 01:53:59 +00001413 OldC->getOpcode() < Instruction::BinaryOpsEnd);
Chris Lattner189d19f2003-11-21 20:23:48 +00001414 New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1415 OldC->getOperand(1));
1416 break;
1417 case Instruction::GetElementPtr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00001418 // Make everyone now use a constant of the new type...
Chris Lattner13128ab2004-10-11 22:52:25 +00001419 std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
Chris Lattner302116a2007-01-31 04:40:28 +00001420 New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0),
1421 &Idx[0], Idx.size());
Chris Lattner189d19f2003-11-21 20:23:48 +00001422 break;
1423 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001424
Chris Lattner189d19f2003-11-21 20:23:48 +00001425 assert(New != OldC && "Didn't replace constant??");
1426 OldC->uncheckedReplaceAllUsesWith(New);
1427 OldC->destroyConstant(); // This constant is now dead, destroy it.
1428 }
1429 };
1430} // end namespace llvm
Chris Lattnerb50d1352003-10-05 00:17:43 +00001431
1432
Chris Lattner3e650af2004-08-04 04:48:01 +00001433static ExprMapKeyType getValType(ConstantExpr *CE) {
1434 std::vector<Constant*> Operands;
1435 Operands.reserve(CE->getNumOperands());
1436 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
1437 Operands.push_back(cast<Constant>(CE->getOperand(i)));
Reid Spenceree3c9912006-12-04 05:19:50 +00001438 return ExprMapKeyType(CE->getOpcode(), Operands,
1439 CE->isCompare() ? CE->getPredicate() : 0);
Chris Lattner3e650af2004-08-04 04:48:01 +00001440}
1441
Chris Lattner69edc982006-09-28 00:35:06 +00001442static ManagedStatic<ValueMap<ExprMapKeyType, Type,
1443 ConstantExpr> > ExprConstants;
Vikram S. Adve4c485332002-07-15 18:19:33 +00001444
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001445/// This is a utility function to handle folding of casts and lookup of the
1446/// cast in the ExprConstants map. It is usedby the various get* methods below.
1447static inline Constant *getFoldedCast(
1448 Instruction::CastOps opc, Constant *C, const Type *Ty) {
Chris Lattner815ae2b2003-10-07 22:19:19 +00001449 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001450 // Fold a few common cases
1451 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
1452 return FC;
Chris Lattneracdbe712003-04-17 19:24:48 +00001453
Vikram S. Adve4c485332002-07-15 18:19:33 +00001454 // Look up the constant in the table first to ensure uniqueness
Chris Lattner2b383d2e2003-05-13 21:37:02 +00001455 std::vector<Constant*> argVec(1, C);
Reid Spenceree3c9912006-12-04 05:19:50 +00001456 ExprMapKeyType Key(opc, argVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001457 return ExprConstants->getOrCreate(Ty, Key);
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001458}
Reid Spencerf37dc652006-12-05 19:14:13 +00001459
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001460Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
1461 Instruction::CastOps opc = Instruction::CastOps(oc);
1462 assert(Instruction::isCast(opc) && "opcode out of range");
1463 assert(C && Ty && "Null arguments to getCast");
1464 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1465
1466 switch (opc) {
1467 default:
1468 assert(0 && "Invalid cast opcode");
1469 break;
1470 case Instruction::Trunc: return getTrunc(C, Ty);
Reid Spencerbb65ebf2006-12-12 23:36:14 +00001471 case Instruction::ZExt: return getZExt(C, Ty);
1472 case Instruction::SExt: return getSExt(C, Ty);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001473 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
1474 case Instruction::FPExt: return getFPExtend(C, Ty);
1475 case Instruction::UIToFP: return getUIToFP(C, Ty);
1476 case Instruction::SIToFP: return getSIToFP(C, Ty);
1477 case Instruction::FPToUI: return getFPToUI(C, Ty);
1478 case Instruction::FPToSI: return getFPToSI(C, Ty);
1479 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1480 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1481 case Instruction::BitCast: return getBitCast(C, Ty);
Chris Lattner1ece6f82005-01-01 15:59:57 +00001482 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001483 return 0;
Reid Spencerf37dc652006-12-05 19:14:13 +00001484}
1485
Reid Spencer5c140882006-12-04 20:17:56 +00001486Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
1487 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1488 return getCast(Instruction::BitCast, C, Ty);
1489 return getCast(Instruction::ZExt, C, Ty);
1490}
1491
1492Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
1493 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1494 return getCast(Instruction::BitCast, C, Ty);
1495 return getCast(Instruction::SExt, C, Ty);
1496}
1497
1498Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
1499 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1500 return getCast(Instruction::BitCast, C, Ty);
1501 return getCast(Instruction::Trunc, C, Ty);
1502}
1503
Reid Spencerbc245a02006-12-05 03:25:26 +00001504Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
1505 assert(isa<PointerType>(S->getType()) && "Invalid cast");
Chris Lattner03c49532007-01-15 02:27:26 +00001506 assert((Ty->isInteger() || isa<PointerType>(Ty)) && "Invalid cast");
Reid Spencerbc245a02006-12-05 03:25:26 +00001507
Chris Lattner03c49532007-01-15 02:27:26 +00001508 if (Ty->isInteger())
Reid Spencerbc245a02006-12-05 03:25:26 +00001509 return getCast(Instruction::PtrToInt, S, Ty);
1510 return getCast(Instruction::BitCast, S, Ty);
1511}
1512
Reid Spencer56521c42006-12-12 00:51:07 +00001513Constant *ConstantExpr::getIntegerCast(Constant *C, const Type *Ty,
1514 bool isSigned) {
Chris Lattner03c49532007-01-15 02:27:26 +00001515 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
Reid Spencer56521c42006-12-12 00:51:07 +00001516 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1517 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1518 Instruction::CastOps opcode =
1519 (SrcBits == DstBits ? Instruction::BitCast :
1520 (SrcBits > DstBits ? Instruction::Trunc :
1521 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1522 return getCast(opcode, C, Ty);
1523}
1524
1525Constant *ConstantExpr::getFPCast(Constant *C, const Type *Ty) {
1526 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1527 "Invalid cast");
1528 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1529 unsigned DstBits = Ty->getPrimitiveSizeInBits();
Reid Spencerca104e82006-12-12 05:38:50 +00001530 if (SrcBits == DstBits)
1531 return C; // Avoid a useless cast
Reid Spencer56521c42006-12-12 00:51:07 +00001532 Instruction::CastOps opcode =
Reid Spencerca104e82006-12-12 05:38:50 +00001533 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
Reid Spencer56521c42006-12-12 00:51:07 +00001534 return getCast(opcode, C, Ty);
1535}
1536
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001537Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
Chris Lattner03c49532007-01-15 02:27:26 +00001538 assert(C->getType()->isInteger() && "Trunc operand must be integer");
1539 assert(Ty->isInteger() && "Trunc produces only integral");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001540 assert(C->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()&&
1541 "SrcTy must be larger than DestTy for Trunc!");
1542
1543 return getFoldedCast(Instruction::Trunc, C, Ty);
1544}
1545
Reid Spencerbb65ebf2006-12-12 23:36:14 +00001546Constant *ConstantExpr::getSExt(Constant *C, const Type *Ty) {
Chris Lattner03c49532007-01-15 02:27:26 +00001547 assert(C->getType()->isInteger() && "SEXt operand must be integral");
1548 assert(Ty->isInteger() && "SExt produces only integer");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001549 assert(C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1550 "SrcTy must be smaller than DestTy for SExt!");
1551
1552 return getFoldedCast(Instruction::SExt, C, Ty);
Chris Lattnerdd284742004-04-04 23:20:30 +00001553}
1554
Reid Spencerbb65ebf2006-12-12 23:36:14 +00001555Constant *ConstantExpr::getZExt(Constant *C, const Type *Ty) {
Chris Lattner03c49532007-01-15 02:27:26 +00001556 assert(C->getType()->isInteger() && "ZEXt operand must be integral");
1557 assert(Ty->isInteger() && "ZExt produces only integer");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001558 assert(C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1559 "SrcTy must be smaller than DestTy for ZExt!");
1560
1561 return getFoldedCast(Instruction::ZExt, C, Ty);
1562}
1563
1564Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
1565 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1566 C->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()&&
1567 "This is an illegal floating point truncation!");
1568 return getFoldedCast(Instruction::FPTrunc, C, Ty);
1569}
1570
1571Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
1572 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1573 C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1574 "This is an illegal floating point extension!");
1575 return getFoldedCast(Instruction::FPExt, C, Ty);
1576}
1577
1578Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
Chris Lattner03c49532007-01-15 02:27:26 +00001579 assert(C->getType()->isInteger() && Ty->isFloatingPoint() &&
Reid Spencer2546b762007-01-26 07:37:34 +00001580 "This is an illegal i32 to floating point cast!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001581 return getFoldedCast(Instruction::UIToFP, C, Ty);
1582}
1583
1584Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
Chris Lattner03c49532007-01-15 02:27:26 +00001585 assert(C->getType()->isInteger() && Ty->isFloatingPoint() &&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001586 "This is an illegal sint to floating point cast!");
1587 return getFoldedCast(Instruction::SIToFP, C, Ty);
1588}
1589
1590Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
Chris Lattner03c49532007-01-15 02:27:26 +00001591 assert(C->getType()->isFloatingPoint() && Ty->isInteger() &&
Reid Spencer2546b762007-01-26 07:37:34 +00001592 "This is an illegal floating point to i32 cast!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001593 return getFoldedCast(Instruction::FPToUI, C, Ty);
1594}
1595
1596Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
Chris Lattner03c49532007-01-15 02:27:26 +00001597 assert(C->getType()->isFloatingPoint() && Ty->isInteger() &&
Reid Spencer2546b762007-01-26 07:37:34 +00001598 "This is an illegal floating point to i32 cast!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001599 return getFoldedCast(Instruction::FPToSI, C, Ty);
1600}
1601
1602Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
1603 assert(isa<PointerType>(C->getType()) && "PtrToInt source must be pointer");
Chris Lattner03c49532007-01-15 02:27:26 +00001604 assert(DstTy->isInteger() && "PtrToInt destination must be integral");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001605 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
1606}
1607
1608Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
Chris Lattner03c49532007-01-15 02:27:26 +00001609 assert(C->getType()->isInteger() && "IntToPtr source must be integral");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001610 assert(isa<PointerType>(DstTy) && "IntToPtr destination must be a pointer");
1611 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
1612}
1613
1614Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
1615 // BitCast implies a no-op cast of type only. No bits change. However, you
1616 // can't cast pointers to anything but pointers.
1617 const Type *SrcTy = C->getType();
1618 assert((isa<PointerType>(SrcTy) == isa<PointerType>(DstTy)) &&
Reid Spencer5c140882006-12-04 20:17:56 +00001619 "BitCast cannot cast pointer to non-pointer and vice versa");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001620
1621 // Now we know we're not dealing with mismatched pointer casts (ptr->nonptr
1622 // or nonptr->ptr). For all the other types, the cast is okay if source and
1623 // destination bit widths are identical.
1624 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1625 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
Reid Spencer5c140882006-12-04 20:17:56 +00001626 assert(SrcBitSize == DstBitSize && "BitCast requies types of same width");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001627 return getFoldedCast(Instruction::BitCast, C, DstTy);
Chris Lattnerdd284742004-04-04 23:20:30 +00001628}
1629
Alkis Evlogimenosda5de052004-10-24 01:41:10 +00001630Constant *ConstantExpr::getSizeOf(const Type *Ty) {
Chris Lattneracc4e542004-12-13 19:48:51 +00001631 // sizeof is implemented as: (ulong) gep (Ty*)null, 1
Chris Lattnerb5d70302007-02-19 20:01:23 +00001632 Constant *GEPIdx = ConstantInt::get(Type::Int32Ty, 1);
1633 Constant *GEP =
1634 getGetElementPtr(getNullValue(PointerType::get(Ty)), &GEPIdx, 1);
1635 return getCast(Instruction::PtrToInt, GEP, Type::Int64Ty);
Alkis Evlogimenos9160d5f2005-03-19 11:40:31 +00001636}
1637
Chris Lattnerb50d1352003-10-05 00:17:43 +00001638Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
Reid Spencera009d0d2006-12-04 21:35:24 +00001639 Constant *C1, Constant *C2) {
Chris Lattner38a9bcd2003-05-21 17:49:25 +00001640 // Check the operands for consistency first
Reid Spencer7eb55b32006-11-02 01:53:59 +00001641 assert(Opcode >= Instruction::BinaryOpsBegin &&
1642 Opcode < Instruction::BinaryOpsEnd &&
Chris Lattner38a9bcd2003-05-21 17:49:25 +00001643 "Invalid opcode in binary constant expression");
1644 assert(C1->getType() == C2->getType() &&
1645 "Operand types in binary constant expression should match");
Chris Lattnerb50d1352003-10-05 00:17:43 +00001646
Reid Spencer542964f2007-01-11 18:21:29 +00001647 if (ReqTy == C1->getType() || ReqTy == Type::Int1Ty)
Chris Lattnerb50d1352003-10-05 00:17:43 +00001648 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1649 return FC; // Fold a few common cases...
Chris Lattneracdbe712003-04-17 19:24:48 +00001650
Chris Lattner2b383d2e2003-05-13 21:37:02 +00001651 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
Reid Spencera009d0d2006-12-04 21:35:24 +00001652 ExprMapKeyType Key(Opcode, argVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001653 return ExprConstants->getOrCreate(ReqTy, Key);
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001654}
1655
Reid Spencer266e42b2006-12-23 06:05:41 +00001656Constant *ConstantExpr::getCompareTy(unsigned short predicate,
Reid Spencera009d0d2006-12-04 21:35:24 +00001657 Constant *C1, Constant *C2) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001658 switch (predicate) {
1659 default: assert(0 && "Invalid CmpInst predicate");
1660 case FCmpInst::FCMP_FALSE: case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_OGT:
1661 case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OLE:
1662 case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_ORD: case FCmpInst::FCMP_UNO:
1663 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UGT: case FCmpInst::FCMP_UGE:
1664 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_ULE: case FCmpInst::FCMP_UNE:
1665 case FCmpInst::FCMP_TRUE:
1666 return getFCmp(predicate, C1, C2);
1667 case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_UGT:
1668 case ICmpInst::ICMP_UGE: case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE:
1669 case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_SGE: case ICmpInst::ICMP_SLT:
1670 case ICmpInst::ICMP_SLE:
1671 return getICmp(predicate, C1, C2);
1672 }
Reid Spencera009d0d2006-12-04 21:35:24 +00001673}
1674
1675Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001676#ifndef NDEBUG
1677 switch (Opcode) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00001678 case Instruction::Add:
1679 case Instruction::Sub:
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001680 case Instruction::Mul:
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001681 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Chris Lattner03c49532007-01-15 02:27:26 +00001682 assert((C1->getType()->isInteger() || C1->getType()->isFloatingPoint() ||
Reid Spencerd84d35b2007-02-15 02:26:10 +00001683 isa<VectorType>(C1->getType())) &&
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001684 "Tried to create an arithmetic operation on a non-arithmetic type!");
1685 break;
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001686 case Instruction::UDiv:
1687 case Instruction::SDiv:
1688 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00001689 assert((C1->getType()->isInteger() || (isa<VectorType>(C1->getType()) &&
1690 cast<VectorType>(C1->getType())->getElementType()->isInteger())) &&
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001691 "Tried to create an arithmetic operation on a non-arithmetic type!");
1692 break;
1693 case Instruction::FDiv:
1694 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00001695 assert((C1->getType()->isFloatingPoint() || (isa<VectorType>(C1->getType())
1696 && cast<VectorType>(C1->getType())->getElementType()->isFloatingPoint()))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001697 && "Tried to create an arithmetic operation on a non-arithmetic type!");
1698 break;
Reid Spencer7eb55b32006-11-02 01:53:59 +00001699 case Instruction::URem:
1700 case Instruction::SRem:
1701 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00001702 assert((C1->getType()->isInteger() || (isa<VectorType>(C1->getType()) &&
1703 cast<VectorType>(C1->getType())->getElementType()->isInteger())) &&
Reid Spencer7eb55b32006-11-02 01:53:59 +00001704 "Tried to create an arithmetic operation on a non-arithmetic type!");
1705 break;
1706 case Instruction::FRem:
1707 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00001708 assert((C1->getType()->isFloatingPoint() || (isa<VectorType>(C1->getType())
1709 && cast<VectorType>(C1->getType())->getElementType()->isFloatingPoint()))
Reid Spencer7eb55b32006-11-02 01:53:59 +00001710 && "Tried to create an arithmetic operation on a non-arithmetic type!");
1711 break;
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001712 case Instruction::And:
1713 case Instruction::Or:
1714 case Instruction::Xor:
1715 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00001716 assert((C1->getType()->isInteger() || isa<VectorType>(C1->getType())) &&
Misha Brukman3852f652005-01-27 06:46:38 +00001717 "Tried to create a logical operation on a non-integral type!");
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001718 break;
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001719 case Instruction::Shl:
Reid Spencerfdff9382006-11-08 06:47:33 +00001720 case Instruction::LShr:
1721 case Instruction::AShr:
Reid Spencer2341c222007-02-02 02:16:23 +00001722 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Chris Lattner03c49532007-01-15 02:27:26 +00001723 assert(C1->getType()->isInteger() &&
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001724 "Tried to create a shift operation on a non-integer type!");
1725 break;
1726 default:
1727 break;
1728 }
1729#endif
1730
Reid Spencera009d0d2006-12-04 21:35:24 +00001731 return getTy(C1->getType(), Opcode, C1, C2);
1732}
1733
Reid Spencer266e42b2006-12-23 06:05:41 +00001734Constant *ConstantExpr::getCompare(unsigned short pred,
Reid Spencera009d0d2006-12-04 21:35:24 +00001735 Constant *C1, Constant *C2) {
1736 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Reid Spencer266e42b2006-12-23 06:05:41 +00001737 return getCompareTy(pred, C1, C2);
Chris Lattner29ca2c62004-08-04 18:50:09 +00001738}
1739
Chris Lattner6e415c02004-03-12 05:54:04 +00001740Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
1741 Constant *V1, Constant *V2) {
Reid Spencer2546b762007-01-26 07:37:34 +00001742 assert(C->getType() == Type::Int1Ty && "Select condition must be i1!");
Chris Lattner6e415c02004-03-12 05:54:04 +00001743 assert(V1->getType() == V2->getType() && "Select value types must match!");
1744 assert(V1->getType()->isFirstClassType() && "Cannot select aggregate type!");
1745
1746 if (ReqTy == V1->getType())
1747 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1748 return SC; // Fold common cases
1749
1750 std::vector<Constant*> argVec(3, C);
1751 argVec[1] = V1;
1752 argVec[2] = V2;
Reid Spenceree3c9912006-12-04 05:19:50 +00001753 ExprMapKeyType Key(Instruction::Select, argVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001754 return ExprConstants->getOrCreate(ReqTy, Key);
Chris Lattner6e415c02004-03-12 05:54:04 +00001755}
1756
Chris Lattnerb50d1352003-10-05 00:17:43 +00001757Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
Chris Lattner302116a2007-01-31 04:40:28 +00001758 Value* const *Idxs,
1759 unsigned NumIdx) {
1760 assert(GetElementPtrInst::getIndexedType(C->getType(), Idxs, NumIdx, true) &&
Chris Lattner04b60fe2004-02-16 20:46:13 +00001761 "GEP indices invalid!");
1762
Chris Lattner302116a2007-01-31 04:40:28 +00001763 if (Constant *FC = ConstantFoldGetElementPtr(C, (Constant**)Idxs, NumIdx))
Chris Lattneracdbe712003-04-17 19:24:48 +00001764 return FC; // Fold a few common cases...
Chris Lattner04b60fe2004-02-16 20:46:13 +00001765
Chris Lattnerb50d1352003-10-05 00:17:43 +00001766 assert(isa<PointerType>(C->getType()) &&
Chris Lattner98fa07b2003-05-23 20:03:32 +00001767 "Non-pointer type for constant GetElementPtr expression");
Vikram S. Adve4c485332002-07-15 18:19:33 +00001768 // Look up the constant in the table first to ensure uniqueness
Chris Lattner13128ab2004-10-11 22:52:25 +00001769 std::vector<Constant*> ArgVec;
Chris Lattner302116a2007-01-31 04:40:28 +00001770 ArgVec.reserve(NumIdx+1);
Chris Lattner13128ab2004-10-11 22:52:25 +00001771 ArgVec.push_back(C);
Chris Lattner302116a2007-01-31 04:40:28 +00001772 for (unsigned i = 0; i != NumIdx; ++i)
1773 ArgVec.push_back(cast<Constant>(Idxs[i]));
1774 const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001775 return ExprConstants->getOrCreate(ReqTy, Key);
Vikram S. Adve4c485332002-07-15 18:19:33 +00001776}
1777
Chris Lattner302116a2007-01-31 04:40:28 +00001778Constant *ConstantExpr::getGetElementPtr(Constant *C, Value* const *Idxs,
1779 unsigned NumIdx) {
Chris Lattnerb50d1352003-10-05 00:17:43 +00001780 // Get the result type of the getelementptr!
Chris Lattner302116a2007-01-31 04:40:28 +00001781 const Type *Ty =
1782 GetElementPtrInst::getIndexedType(C->getType(), Idxs, NumIdx, true);
Chris Lattnerb50d1352003-10-05 00:17:43 +00001783 assert(Ty && "GEP indices invalid!");
Chris Lattner302116a2007-01-31 04:40:28 +00001784 return getGetElementPtrTy(PointerType::get(Ty), C, Idxs, NumIdx);
Chris Lattner13128ab2004-10-11 22:52:25 +00001785}
1786
Chris Lattner302116a2007-01-31 04:40:28 +00001787Constant *ConstantExpr::getGetElementPtr(Constant *C, Constant* const *Idxs,
1788 unsigned NumIdx) {
1789 return getGetElementPtr(C, (Value* const *)Idxs, NumIdx);
Chris Lattnerb50d1352003-10-05 00:17:43 +00001790}
1791
Chris Lattner302116a2007-01-31 04:40:28 +00001792
Reid Spenceree3c9912006-12-04 05:19:50 +00001793Constant *
1794ConstantExpr::getICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1795 assert(LHS->getType() == RHS->getType());
1796 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
1797 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
1798
Reid Spencer266e42b2006-12-23 06:05:41 +00001799 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
Reid Spenceree3c9912006-12-04 05:19:50 +00001800 return FC; // Fold a few common cases...
1801
1802 // Look up the constant in the table first to ensure uniqueness
1803 std::vector<Constant*> ArgVec;
1804 ArgVec.push_back(LHS);
1805 ArgVec.push_back(RHS);
Reid Spencerb1537492006-12-24 18:42:29 +00001806 // Get the key type with both the opcode and predicate
Reid Spenceree3c9912006-12-04 05:19:50 +00001807 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
Reid Spencer542964f2007-01-11 18:21:29 +00001808 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
Reid Spenceree3c9912006-12-04 05:19:50 +00001809}
1810
1811Constant *
1812ConstantExpr::getFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1813 assert(LHS->getType() == RHS->getType());
1814 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
1815
Reid Spencer266e42b2006-12-23 06:05:41 +00001816 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
Reid Spenceree3c9912006-12-04 05:19:50 +00001817 return FC; // Fold a few common cases...
1818
1819 // Look up the constant in the table first to ensure uniqueness
1820 std::vector<Constant*> ArgVec;
1821 ArgVec.push_back(LHS);
1822 ArgVec.push_back(RHS);
Reid Spencerb1537492006-12-24 18:42:29 +00001823 // Get the key type with both the opcode and predicate
Reid Spenceree3c9912006-12-04 05:19:50 +00001824 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
Reid Spencer542964f2007-01-11 18:21:29 +00001825 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
Reid Spenceree3c9912006-12-04 05:19:50 +00001826}
1827
Robert Bocchino23004482006-01-10 19:05:34 +00001828Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
1829 Constant *Idx) {
Robert Bocchinode7f1c92006-01-10 20:03:46 +00001830 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
1831 return FC; // Fold a few common cases...
Robert Bocchino23004482006-01-10 19:05:34 +00001832 // Look up the constant in the table first to ensure uniqueness
1833 std::vector<Constant*> ArgVec(1, Val);
1834 ArgVec.push_back(Idx);
Reid Spenceree3c9912006-12-04 05:19:50 +00001835 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001836 return ExprConstants->getOrCreate(ReqTy, Key);
Robert Bocchino23004482006-01-10 19:05:34 +00001837}
1838
1839Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001840 assert(isa<VectorType>(Val->getType()) &&
Reid Spencer09575ba2007-02-15 03:39:18 +00001841 "Tried to create extractelement operation on non-vector type!");
Reid Spencer8d9336d2006-12-31 05:26:44 +00001842 assert(Idx->getType() == Type::Int32Ty &&
Reid Spencer2546b762007-01-26 07:37:34 +00001843 "Extractelement index must be i32 type!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00001844 return getExtractElementTy(cast<VectorType>(Val->getType())->getElementType(),
Robert Bocchino23004482006-01-10 19:05:34 +00001845 Val, Idx);
1846}
Chris Lattnerb50d1352003-10-05 00:17:43 +00001847
Robert Bocchinoca27f032006-01-17 20:07:22 +00001848Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
1849 Constant *Elt, Constant *Idx) {
1850 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
1851 return FC; // Fold a few common cases...
1852 // Look up the constant in the table first to ensure uniqueness
1853 std::vector<Constant*> ArgVec(1, Val);
1854 ArgVec.push_back(Elt);
1855 ArgVec.push_back(Idx);
Reid Spenceree3c9912006-12-04 05:19:50 +00001856 const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001857 return ExprConstants->getOrCreate(ReqTy, Key);
Robert Bocchinoca27f032006-01-17 20:07:22 +00001858}
1859
1860Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
1861 Constant *Idx) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001862 assert(isa<VectorType>(Val->getType()) &&
Reid Spencer09575ba2007-02-15 03:39:18 +00001863 "Tried to create insertelement operation on non-vector type!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00001864 assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType()
Robert Bocchinoca27f032006-01-17 20:07:22 +00001865 && "Insertelement types must match!");
Reid Spencer8d9336d2006-12-31 05:26:44 +00001866 assert(Idx->getType() == Type::Int32Ty &&
Reid Spencer2546b762007-01-26 07:37:34 +00001867 "Insertelement index must be i32 type!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00001868 return getInsertElementTy(cast<VectorType>(Val->getType())->getElementType(),
Robert Bocchinoca27f032006-01-17 20:07:22 +00001869 Val, Elt, Idx);
1870}
1871
Chris Lattnerbbe0a422006-04-08 01:18:18 +00001872Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
1873 Constant *V2, Constant *Mask) {
1874 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
1875 return FC; // Fold a few common cases...
1876 // Look up the constant in the table first to ensure uniqueness
1877 std::vector<Constant*> ArgVec(1, V1);
1878 ArgVec.push_back(V2);
1879 ArgVec.push_back(Mask);
Reid Spenceree3c9912006-12-04 05:19:50 +00001880 const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001881 return ExprConstants->getOrCreate(ReqTy, Key);
Chris Lattnerbbe0a422006-04-08 01:18:18 +00001882}
1883
1884Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
1885 Constant *Mask) {
1886 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
1887 "Invalid shuffle vector constant expr operands!");
1888 return getShuffleVectorTy(V1->getType(), V1, V2, Mask);
1889}
1890
Reid Spencer2eadb532007-01-21 00:29:26 +00001891Constant *ConstantExpr::getZeroValueForNegationExpr(const Type *Ty) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001892 if (const VectorType *PTy = dyn_cast<VectorType>(Ty))
Reid Spencer6598ca82007-01-21 02:29:10 +00001893 if (PTy->getElementType()->isFloatingPoint()) {
1894 std::vector<Constant*> zeros(PTy->getNumElements(),
1895 ConstantFP::get(PTy->getElementType(),-0.0));
Reid Spencerd84d35b2007-02-15 02:26:10 +00001896 return ConstantVector::get(PTy, zeros);
Reid Spencer6598ca82007-01-21 02:29:10 +00001897 }
Reid Spencer2eadb532007-01-21 00:29:26 +00001898
1899 if (Ty->isFloatingPoint())
1900 return ConstantFP::get(Ty, -0.0);
1901
1902 return Constant::getNullValue(Ty);
1903}
1904
Vikram S. Adve4c485332002-07-15 18:19:33 +00001905// destroyConstant - Remove the constant from the constant table...
1906//
1907void ConstantExpr::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00001908 ExprConstants->remove(this);
Vikram S. Adve4c485332002-07-15 18:19:33 +00001909 destroyConstantImpl();
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001910}
1911
Chris Lattner3cd8c562002-07-30 18:54:25 +00001912const char *ConstantExpr::getOpcodeName() const {
1913 return Instruction::getOpcodeName(getOpcode());
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001914}
Reid Spencer1ebe1ab2004-07-17 23:48:33 +00001915
Chris Lattnerc4062ba2005-10-03 21:58:36 +00001916//===----------------------------------------------------------------------===//
1917// replaceUsesOfWithOnConstant implementations
1918
Chris Lattner913849b2007-08-21 00:55:23 +00001919/// replaceUsesOfWithOnConstant - Update this constant array to change uses of
1920/// 'From' to be uses of 'To'. This must update the uniquing data structures
1921/// etc.
1922///
1923/// Note that we intentionally replace all uses of From with To here. Consider
1924/// a large array that uses 'From' 1000 times. By handling this case all here,
1925/// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
1926/// single invocation handles all 1000 uses. Handling them one at a time would
1927/// work, but would be really slow because it would have to unique each updated
1928/// array instance.
Chris Lattnerc4062ba2005-10-03 21:58:36 +00001929void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
Chris Lattner7a1450d2005-10-04 18:13:04 +00001930 Use *U) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00001931 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
Chris Lattner8760ec72005-10-04 01:17:50 +00001932 Constant *ToC = cast<Constant>(To);
Chris Lattnerdff59112005-10-04 18:47:09 +00001933
Jim Laskeyc03caef2006-07-17 17:38:29 +00001934 std::pair<ArrayConstantsTy::MapKey, Constant*> Lookup;
Chris Lattnerb64419a2005-10-03 22:51:37 +00001935 Lookup.first.first = getType();
1936 Lookup.second = this;
Chris Lattnerdff59112005-10-04 18:47:09 +00001937
Chris Lattnerb64419a2005-10-03 22:51:37 +00001938 std::vector<Constant*> &Values = Lookup.first.second;
1939 Values.reserve(getNumOperands()); // Build replacement array.
Chris Lattnerdff59112005-10-04 18:47:09 +00001940
Chris Lattner8760ec72005-10-04 01:17:50 +00001941 // Fill values with the modified operands of the constant array. Also,
1942 // compute whether this turns into an all-zeros array.
Chris Lattnerdff59112005-10-04 18:47:09 +00001943 bool isAllZeros = false;
Chris Lattner913849b2007-08-21 00:55:23 +00001944 unsigned NumUpdated = 0;
Chris Lattnerdff59112005-10-04 18:47:09 +00001945 if (!ToC->isNullValue()) {
Chris Lattner913849b2007-08-21 00:55:23 +00001946 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1947 Constant *Val = cast<Constant>(O->get());
1948 if (Val == From) {
1949 Val = ToC;
1950 ++NumUpdated;
1951 }
1952 Values.push_back(Val);
1953 }
Chris Lattnerdff59112005-10-04 18:47:09 +00001954 } else {
1955 isAllZeros = true;
1956 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1957 Constant *Val = cast<Constant>(O->get());
Chris Lattner913849b2007-08-21 00:55:23 +00001958 if (Val == From) {
1959 Val = ToC;
1960 ++NumUpdated;
1961 }
Chris Lattnerdff59112005-10-04 18:47:09 +00001962 Values.push_back(Val);
1963 if (isAllZeros) isAllZeros = Val->isNullValue();
1964 }
Chris Lattnerc4062ba2005-10-03 21:58:36 +00001965 }
1966
Chris Lattnerb64419a2005-10-03 22:51:37 +00001967 Constant *Replacement = 0;
1968 if (isAllZeros) {
1969 Replacement = ConstantAggregateZero::get(getType());
1970 } else {
1971 // Check to see if we have this array type already.
1972 bool Exists;
Jim Laskeyc03caef2006-07-17 17:38:29 +00001973 ArrayConstantsTy::MapTy::iterator I =
Chris Lattner69edc982006-09-28 00:35:06 +00001974 ArrayConstants->InsertOrGetItem(Lookup, Exists);
Chris Lattnerb64419a2005-10-03 22:51:37 +00001975
1976 if (Exists) {
1977 Replacement = I->second;
1978 } else {
1979 // Okay, the new shape doesn't exist in the system yet. Instead of
1980 // creating a new constant array, inserting it, replaceallusesof'ing the
1981 // old with the new, then deleting the old... just update the current one
1982 // in place!
Chris Lattner69edc982006-09-28 00:35:06 +00001983 ArrayConstants->MoveConstantToNewSlot(this, I);
Chris Lattnerb64419a2005-10-03 22:51:37 +00001984
Chris Lattner913849b2007-08-21 00:55:23 +00001985 // Update to the new value. Optimize for the case when we have a single
1986 // operand that we're changing, but handle bulk updates efficiently.
1987 if (NumUpdated == 1) {
1988 unsigned OperandToUpdate = U-OperandList;
1989 assert(getOperand(OperandToUpdate) == From &&
1990 "ReplaceAllUsesWith broken!");
1991 setOperand(OperandToUpdate, ToC);
1992 } else {
1993 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1994 if (getOperand(i) == From)
1995 setOperand(i, ToC);
1996 }
Chris Lattnerb64419a2005-10-03 22:51:37 +00001997 return;
1998 }
1999 }
2000
2001 // Otherwise, I do need to replace this with an existing value.
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002002 assert(Replacement != this && "I didn't contain From!");
2003
Chris Lattner7a1450d2005-10-04 18:13:04 +00002004 // Everyone using this now uses the replacement.
2005 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002006
2007 // Delete the old constant!
2008 destroyConstant();
2009}
2010
2011void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
Chris Lattner7a1450d2005-10-04 18:13:04 +00002012 Use *U) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002013 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
Chris Lattner8760ec72005-10-04 01:17:50 +00002014 Constant *ToC = cast<Constant>(To);
2015
Chris Lattnerdff59112005-10-04 18:47:09 +00002016 unsigned OperandToUpdate = U-OperandList;
2017 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
2018
Jim Laskeyc03caef2006-07-17 17:38:29 +00002019 std::pair<StructConstantsTy::MapKey, Constant*> Lookup;
Chris Lattner8760ec72005-10-04 01:17:50 +00002020 Lookup.first.first = getType();
2021 Lookup.second = this;
2022 std::vector<Constant*> &Values = Lookup.first.second;
2023 Values.reserve(getNumOperands()); // Build replacement struct.
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002024
Chris Lattnerdff59112005-10-04 18:47:09 +00002025
Chris Lattner8760ec72005-10-04 01:17:50 +00002026 // Fill values with the modified operands of the constant struct. Also,
2027 // compute whether this turns into an all-zeros struct.
Chris Lattnerdff59112005-10-04 18:47:09 +00002028 bool isAllZeros = false;
2029 if (!ToC->isNullValue()) {
2030 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
2031 Values.push_back(cast<Constant>(O->get()));
2032 } else {
2033 isAllZeros = true;
2034 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2035 Constant *Val = cast<Constant>(O->get());
2036 Values.push_back(Val);
2037 if (isAllZeros) isAllZeros = Val->isNullValue();
2038 }
Chris Lattner8760ec72005-10-04 01:17:50 +00002039 }
Chris Lattnerdff59112005-10-04 18:47:09 +00002040 Values[OperandToUpdate] = ToC;
2041
Chris Lattner8760ec72005-10-04 01:17:50 +00002042 Constant *Replacement = 0;
2043 if (isAllZeros) {
2044 Replacement = ConstantAggregateZero::get(getType());
2045 } else {
2046 // Check to see if we have this array type already.
2047 bool Exists;
Jim Laskeyc03caef2006-07-17 17:38:29 +00002048 StructConstantsTy::MapTy::iterator I =
Chris Lattner69edc982006-09-28 00:35:06 +00002049 StructConstants->InsertOrGetItem(Lookup, Exists);
Chris Lattner8760ec72005-10-04 01:17:50 +00002050
2051 if (Exists) {
2052 Replacement = I->second;
2053 } else {
2054 // Okay, the new shape doesn't exist in the system yet. Instead of
2055 // creating a new constant struct, inserting it, replaceallusesof'ing the
2056 // old with the new, then deleting the old... just update the current one
2057 // in place!
Chris Lattner69edc982006-09-28 00:35:06 +00002058 StructConstants->MoveConstantToNewSlot(this, I);
Chris Lattner8760ec72005-10-04 01:17:50 +00002059
Chris Lattnerdff59112005-10-04 18:47:09 +00002060 // Update to the new value.
2061 setOperand(OperandToUpdate, ToC);
Chris Lattner8760ec72005-10-04 01:17:50 +00002062 return;
2063 }
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002064 }
2065
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002066 assert(Replacement != this && "I didn't contain From!");
2067
Chris Lattner7a1450d2005-10-04 18:13:04 +00002068 // Everyone using this now uses the replacement.
2069 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002070
2071 // Delete the old constant!
2072 destroyConstant();
2073}
2074
Reid Spencerd84d35b2007-02-15 02:26:10 +00002075void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
Chris Lattner7a1450d2005-10-04 18:13:04 +00002076 Use *U) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002077 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2078
2079 std::vector<Constant*> Values;
2080 Values.reserve(getNumOperands()); // Build replacement array...
2081 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2082 Constant *Val = getOperand(i);
2083 if (Val == From) Val = cast<Constant>(To);
2084 Values.push_back(Val);
2085 }
2086
Reid Spencerd84d35b2007-02-15 02:26:10 +00002087 Constant *Replacement = ConstantVector::get(getType(), Values);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002088 assert(Replacement != this && "I didn't contain From!");
2089
Chris Lattner7a1450d2005-10-04 18:13:04 +00002090 // Everyone using this now uses the replacement.
2091 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002092
2093 // Delete the old constant!
2094 destroyConstant();
2095}
2096
2097void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
Chris Lattner7a1450d2005-10-04 18:13:04 +00002098 Use *U) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002099 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2100 Constant *To = cast<Constant>(ToV);
2101
2102 Constant *Replacement = 0;
2103 if (getOpcode() == Instruction::GetElementPtr) {
Chris Lattnerb5d70302007-02-19 20:01:23 +00002104 SmallVector<Constant*, 8> Indices;
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002105 Constant *Pointer = getOperand(0);
2106 Indices.reserve(getNumOperands()-1);
2107 if (Pointer == From) Pointer = To;
2108
2109 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2110 Constant *Val = getOperand(i);
2111 if (Val == From) Val = To;
2112 Indices.push_back(Val);
2113 }
Chris Lattnerb5d70302007-02-19 20:01:23 +00002114 Replacement = ConstantExpr::getGetElementPtr(Pointer,
2115 &Indices[0], Indices.size());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002116 } else if (isCast()) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002117 assert(getOperand(0) == From && "Cast only has one use!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002118 Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002119 } else if (getOpcode() == Instruction::Select) {
2120 Constant *C1 = getOperand(0);
2121 Constant *C2 = getOperand(1);
2122 Constant *C3 = getOperand(2);
2123 if (C1 == From) C1 = To;
2124 if (C2 == From) C2 = To;
2125 if (C3 == From) C3 = To;
2126 Replacement = ConstantExpr::getSelect(C1, C2, C3);
Robert Bocchino23004482006-01-10 19:05:34 +00002127 } else if (getOpcode() == Instruction::ExtractElement) {
2128 Constant *C1 = getOperand(0);
2129 Constant *C2 = getOperand(1);
2130 if (C1 == From) C1 = To;
2131 if (C2 == From) C2 = To;
2132 Replacement = ConstantExpr::getExtractElement(C1, C2);
Chris Lattnera93b4b52006-04-08 05:09:48 +00002133 } else if (getOpcode() == Instruction::InsertElement) {
2134 Constant *C1 = getOperand(0);
2135 Constant *C2 = getOperand(1);
2136 Constant *C3 = getOperand(1);
2137 if (C1 == From) C1 = To;
2138 if (C2 == From) C2 = To;
2139 if (C3 == From) C3 = To;
2140 Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2141 } else if (getOpcode() == Instruction::ShuffleVector) {
2142 Constant *C1 = getOperand(0);
2143 Constant *C2 = getOperand(1);
2144 Constant *C3 = getOperand(2);
2145 if (C1 == From) C1 = To;
2146 if (C2 == From) C2 = To;
2147 if (C3 == From) C3 = To;
2148 Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
Reid Spenceree3c9912006-12-04 05:19:50 +00002149 } else if (isCompare()) {
2150 Constant *C1 = getOperand(0);
2151 Constant *C2 = getOperand(1);
2152 if (C1 == From) C1 = To;
2153 if (C2 == From) C2 = To;
2154 if (getOpcode() == Instruction::ICmp)
2155 Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
2156 else
2157 Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002158 } else if (getNumOperands() == 2) {
2159 Constant *C1 = getOperand(0);
2160 Constant *C2 = getOperand(1);
2161 if (C1 == From) C1 = To;
2162 if (C2 == From) C2 = To;
2163 Replacement = ConstantExpr::get(getOpcode(), C1, C2);
2164 } else {
2165 assert(0 && "Unknown ConstantExpr type!");
2166 return;
2167 }
2168
2169 assert(Replacement != this && "I didn't contain From!");
2170
Chris Lattner7a1450d2005-10-04 18:13:04 +00002171 // Everyone using this now uses the replacement.
2172 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002173
2174 // Delete the old constant!
2175 destroyConstant();
2176}
2177
2178
Jim Laskey2698f0d2006-03-08 18:11:07 +00002179/// getStringValue - Turn an LLVM constant pointer that eventually points to a
2180/// global into a string value. Return an empty string if we can't do it.
Evan Cheng38280c02006-03-10 23:52:03 +00002181/// Parameter Chop determines if the result is chopped at the first null
2182/// terminator.
Jim Laskey2698f0d2006-03-08 18:11:07 +00002183///
Evan Cheng38280c02006-03-10 23:52:03 +00002184std::string Constant::getStringValue(bool Chop, unsigned Offset) {
Jim Laskey2698f0d2006-03-08 18:11:07 +00002185 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(this)) {
2186 if (GV->hasInitializer() && isa<ConstantArray>(GV->getInitializer())) {
2187 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
2188 if (Init->isString()) {
2189 std::string Result = Init->getAsString();
2190 if (Offset < Result.size()) {
2191 // If we are pointing INTO The string, erase the beginning...
2192 Result.erase(Result.begin(), Result.begin()+Offset);
2193
2194 // Take off the null terminator, and any string fragments after it.
Evan Cheng38280c02006-03-10 23:52:03 +00002195 if (Chop) {
2196 std::string::size_type NullPos = Result.find_first_of((char)0);
2197 if (NullPos != std::string::npos)
2198 Result.erase(Result.begin()+NullPos, Result.end());
2199 }
Jim Laskey2698f0d2006-03-08 18:11:07 +00002200 return Result;
2201 }
2202 }
2203 }
2204 } else if (Constant *C = dyn_cast<Constant>(this)) {
2205 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
Evan Cheng2c5e5302006-03-11 00:13:10 +00002206 return GV->getStringValue(Chop, Offset);
Jim Laskey2698f0d2006-03-08 18:11:07 +00002207 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2208 if (CE->getOpcode() == Instruction::GetElementPtr) {
2209 // Turn a gep into the specified offset.
2210 if (CE->getNumOperands() == 3 &&
2211 cast<Constant>(CE->getOperand(1))->isNullValue() &&
2212 isa<ConstantInt>(CE->getOperand(2))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002213 Offset += cast<ConstantInt>(CE->getOperand(2))->getZExtValue();
Evan Cheng2c5e5302006-03-11 00:13:10 +00002214 return CE->getOperand(0)->getStringValue(Chop, Offset);
Jim Laskey2698f0d2006-03-08 18:11:07 +00002215 }
2216 }
2217 }
2218 }
2219 return "";
2220}