blob: 04689e4c98a2c53f196e7181ef8bd68a597e3ab8 [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 Johannesenbdea32d2007-08-24 22:09:56 +0000251 return Val.bitwiseIsEqual(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 Johannesenbdea32d2007-08-24 22:09:56 +0000256 struct KeyTy {
257 APFloat val;
258 KeyTy(const APFloat& V) : val(V){}
259 KeyTy(const KeyTy& that) : val(that.val) {}
260 bool operator==(const KeyTy& that) const {
261 return this->val.bitwiseIsEqual(that.val);
262 }
263 bool operator!=(const KeyTy& that) const {
264 return !this->operator==(that);
265 }
266 };
267 static inline KeyTy getEmptyKey() {
268 return KeyTy(APFloat(APFloat::Bogus,1));
Reid Spencerb31bffe2007-02-26 23:54:03 +0000269 }
Dale Johannesenbdea32d2007-08-24 22:09:56 +0000270 static inline KeyTy getTombstoneKey() {
271 return KeyTy(APFloat(APFloat::Bogus,2));
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000272 }
Dale Johannesenbdea32d2007-08-24 22:09:56 +0000273 static unsigned getHashValue(const KeyTy &Key) {
274 return Key.val.getHashValue();
Dale Johannesena719a602007-08-24 00:56:33 +0000275 }
276 static bool isPod() { return false; }
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000277 };
278}
279
280//---- ConstantFP::get() implementation...
281//
Dale Johannesenbdea32d2007-08-24 22:09:56 +0000282typedef DenseMap<DenseMapAPFloatKeyInfo::KeyTy, ConstantFP*,
Dale Johannesena719a602007-08-24 00:56:33 +0000283 DenseMapAPFloatKeyInfo> FPMapTy;
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000284
Dale Johannesena719a602007-08-24 00:56:33 +0000285static ManagedStatic<FPMapTy> FPConstants;
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000286
287ConstantFP *ConstantFP::get(const Type *Ty, double V) {
288 if (Ty == Type::FloatTy) {
Dale Johannesenbdea32d2007-08-24 22:09:56 +0000289 DenseMapAPFloatKeyInfo::KeyTy Key(APFloat((float)V));
Dale Johannesena719a602007-08-24 00:56:33 +0000290 ConstantFP *&Slot = (*FPConstants)[Key];
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000291 if (Slot) return Slot;
292 return Slot = new ConstantFP(Ty, (float)V);
Dale Johannesena719a602007-08-24 00:56:33 +0000293 } else if (Ty == Type::DoubleTy) {
294 // Without the redundant cast, the following is taken to be
295 // a function declaration. What a language.
Dale Johannesenbdea32d2007-08-24 22:09:56 +0000296 DenseMapAPFloatKeyInfo::KeyTy Key(APFloat((double)V));
Dale Johannesena719a602007-08-24 00:56:33 +0000297 ConstantFP *&Slot = (*FPConstants)[Key];
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000298 if (Slot) return Slot;
Evan Cheng71b87232007-02-20 21:30:56 +0000299 return Slot = new ConstantFP(Ty, V);
Dale Johannesenbdad8092007-08-09 22:51:36 +0000300 } else if (Ty == Type::X86_FP80Ty ||
301 Ty == Type::PPC_FP128Ty || Ty == Type::FP128Ty) {
302 assert(0 && "Long double constants not handled yet.");
303 } else {
304 assert(0 && "Unknown FP Type!");
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000305 }
306}
307
308
309//===----------------------------------------------------------------------===//
310// ConstantXXX Classes
311//===----------------------------------------------------------------------===//
312
313
Chris Lattner3462ae32001-12-03 22:26:30 +0000314ConstantArray::ConstantArray(const ArrayType *T,
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000315 const std::vector<Constant*> &V)
Chris Lattnere7e139e2005-09-27 06:09:08 +0000316 : Constant(T, ConstantArrayVal, new Use[V.size()], V.size()) {
Alkis Evlogimenos0507ffe2004-09-15 02:32:15 +0000317 assert(V.size() == T->getNumElements() &&
318 "Invalid initializer vector for constant array");
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000319 Use *OL = OperandList;
Chris Lattner0144fad2005-10-03 21:56:24 +0000320 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
321 I != E; ++I, ++OL) {
Chris Lattner20a24452005-10-07 05:23:36 +0000322 Constant *C = *I;
323 assert((C->getType() == T->getElementType() ||
Alkis Evlogimenoscb031d92004-09-10 04:16:59 +0000324 (T->isAbstract() &&
Chris Lattner20a24452005-10-07 05:23:36 +0000325 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
Alkis Evlogimenoscb031d92004-09-10 04:16:59 +0000326 "Initializer for array element doesn't match array element type!");
Chris Lattner20a24452005-10-07 05:23:36 +0000327 OL->init(C, this);
Chris Lattner2f7c9632001-06-06 20:29:01 +0000328 }
329}
330
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000331ConstantArray::~ConstantArray() {
332 delete [] OperandList;
333}
334
Chris Lattner3462ae32001-12-03 22:26:30 +0000335ConstantStruct::ConstantStruct(const StructType *T,
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000336 const std::vector<Constant*> &V)
Chris Lattnere7e139e2005-09-27 06:09:08 +0000337 : Constant(T, ConstantStructVal, new Use[V.size()], V.size()) {
Chris Lattnerac6db752004-02-09 04:37:31 +0000338 assert(V.size() == T->getNumElements() &&
Vikram S. Adve4e537b22002-07-14 23:13:17 +0000339 "Invalid initializer vector for constant structure");
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000340 Use *OL = OperandList;
Chris Lattner0144fad2005-10-03 21:56:24 +0000341 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
342 I != E; ++I, ++OL) {
Chris Lattner20a24452005-10-07 05:23:36 +0000343 Constant *C = *I;
344 assert((C->getType() == T->getElementType(I-V.begin()) ||
Chris Lattner0144fad2005-10-03 21:56:24 +0000345 ((T->getElementType(I-V.begin())->isAbstract() ||
Chris Lattner20a24452005-10-07 05:23:36 +0000346 C->getType()->isAbstract()) &&
Chris Lattner0144fad2005-10-03 21:56:24 +0000347 T->getElementType(I-V.begin())->getTypeID() ==
Chris Lattner20a24452005-10-07 05:23:36 +0000348 C->getType()->getTypeID())) &&
Chris Lattner93c8f142003-06-02 17:42:47 +0000349 "Initializer for struct element doesn't match struct element type!");
Chris Lattner20a24452005-10-07 05:23:36 +0000350 OL->init(C, this);
Chris Lattner2f7c9632001-06-06 20:29:01 +0000351 }
352}
353
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000354ConstantStruct::~ConstantStruct() {
355 delete [] OperandList;
356}
357
358
Reid Spencerd84d35b2007-02-15 02:26:10 +0000359ConstantVector::ConstantVector(const VectorType *T,
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000360 const std::vector<Constant*> &V)
Reid Spencerd84d35b2007-02-15 02:26:10 +0000361 : Constant(T, ConstantVectorVal, new Use[V.size()], V.size()) {
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000362 Use *OL = OperandList;
Chris Lattner0144fad2005-10-03 21:56:24 +0000363 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
364 I != E; ++I, ++OL) {
Chris Lattner20a24452005-10-07 05:23:36 +0000365 Constant *C = *I;
366 assert((C->getType() == T->getElementType() ||
Alkis Evlogimenoscb031d92004-09-10 04:16:59 +0000367 (T->isAbstract() &&
Chris Lattner20a24452005-10-07 05:23:36 +0000368 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
Dan Gohman30978072007-05-24 14:36:04 +0000369 "Initializer for vector element doesn't match vector element type!");
Chris Lattner20a24452005-10-07 05:23:36 +0000370 OL->init(C, this);
Brian Gaeke02209042004-08-20 06:00:58 +0000371 }
372}
373
Reid Spencerd84d35b2007-02-15 02:26:10 +0000374ConstantVector::~ConstantVector() {
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000375 delete [] OperandList;
Vikram S. Adve4e537b22002-07-14 23:13:17 +0000376}
377
Reid Spencer10fbf0e2006-12-03 05:48:19 +0000378// We declare several classes private to this file, so use an anonymous
379// namespace
380namespace {
381
382/// UnaryConstantExpr - This class is private to Constants.cpp, and is used
383/// behind the scenes to implement unary constant exprs.
384class VISIBILITY_HIDDEN UnaryConstantExpr : public ConstantExpr {
385 Use Op;
386public:
387 UnaryConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
388 : ConstantExpr(Ty, Opcode, &Op, 1), Op(C, this) {}
389};
390
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000391/// BinaryConstantExpr - This class is private to Constants.cpp, and is used
392/// behind the scenes to implement binary constant exprs.
Chris Lattner02157b02006-06-28 21:38:54 +0000393class VISIBILITY_HIDDEN BinaryConstantExpr : public ConstantExpr {
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000394 Use Ops[2];
395public:
396 BinaryConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
Reid Spencer266e42b2006-12-23 06:05:41 +0000397 : ConstantExpr(C1->getType(), Opcode, Ops, 2) {
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000398 Ops[0].init(C1, this);
399 Ops[1].init(C2, this);
400 }
401};
Vikram S. Adve4e537b22002-07-14 23:13:17 +0000402
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000403/// SelectConstantExpr - This class is private to Constants.cpp, and is used
404/// behind the scenes to implement select constant exprs.
Chris Lattner02157b02006-06-28 21:38:54 +0000405class VISIBILITY_HIDDEN SelectConstantExpr : public ConstantExpr {
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000406 Use Ops[3];
407public:
408 SelectConstantExpr(Constant *C1, Constant *C2, Constant *C3)
409 : ConstantExpr(C2->getType(), Instruction::Select, Ops, 3) {
410 Ops[0].init(C1, this);
411 Ops[1].init(C2, this);
412 Ops[2].init(C3, this);
413 }
414};
415
Robert Bocchinoca27f032006-01-17 20:07:22 +0000416/// ExtractElementConstantExpr - This class is private to
417/// Constants.cpp, and is used behind the scenes to implement
418/// extractelement constant exprs.
Chris Lattner02157b02006-06-28 21:38:54 +0000419class VISIBILITY_HIDDEN ExtractElementConstantExpr : public ConstantExpr {
Robert Bocchino23004482006-01-10 19:05:34 +0000420 Use Ops[2];
421public:
422 ExtractElementConstantExpr(Constant *C1, Constant *C2)
Reid Spencerd84d35b2007-02-15 02:26:10 +0000423 : ConstantExpr(cast<VectorType>(C1->getType())->getElementType(),
Robert Bocchino23004482006-01-10 19:05:34 +0000424 Instruction::ExtractElement, Ops, 2) {
425 Ops[0].init(C1, this);
426 Ops[1].init(C2, this);
427 }
428};
429
Robert Bocchinoca27f032006-01-17 20:07:22 +0000430/// InsertElementConstantExpr - This class is private to
431/// Constants.cpp, and is used behind the scenes to implement
432/// insertelement constant exprs.
Chris Lattner02157b02006-06-28 21:38:54 +0000433class VISIBILITY_HIDDEN InsertElementConstantExpr : public ConstantExpr {
Robert Bocchinoca27f032006-01-17 20:07:22 +0000434 Use Ops[3];
435public:
436 InsertElementConstantExpr(Constant *C1, Constant *C2, Constant *C3)
437 : ConstantExpr(C1->getType(), Instruction::InsertElement,
438 Ops, 3) {
439 Ops[0].init(C1, this);
440 Ops[1].init(C2, this);
441 Ops[2].init(C3, this);
442 }
443};
444
Chris Lattnerbbe0a422006-04-08 01:18:18 +0000445/// ShuffleVectorConstantExpr - This class is private to
446/// Constants.cpp, and is used behind the scenes to implement
447/// shufflevector constant exprs.
Chris Lattner02157b02006-06-28 21:38:54 +0000448class VISIBILITY_HIDDEN ShuffleVectorConstantExpr : public ConstantExpr {
Chris Lattnerbbe0a422006-04-08 01:18:18 +0000449 Use Ops[3];
450public:
451 ShuffleVectorConstantExpr(Constant *C1, Constant *C2, Constant *C3)
452 : ConstantExpr(C1->getType(), Instruction::ShuffleVector,
453 Ops, 3) {
454 Ops[0].init(C1, this);
455 Ops[1].init(C2, this);
456 Ops[2].init(C3, this);
457 }
458};
459
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000460/// GetElementPtrConstantExpr - This class is private to Constants.cpp, and is
461/// used behind the scenes to implement getelementpr constant exprs.
Chris Lattner02157b02006-06-28 21:38:54 +0000462struct VISIBILITY_HIDDEN GetElementPtrConstantExpr : public ConstantExpr {
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000463 GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
464 const Type *DestTy)
465 : ConstantExpr(DestTy, Instruction::GetElementPtr,
466 new Use[IdxList.size()+1], IdxList.size()+1) {
467 OperandList[0].init(C, this);
468 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
469 OperandList[i+1].init(IdxList[i], this);
470 }
471 ~GetElementPtrConstantExpr() {
Misha Brukmanb1c93172005-04-21 23:48:37 +0000472 delete [] OperandList;
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000473 }
474};
Reid Spencer10fbf0e2006-12-03 05:48:19 +0000475
476// CompareConstantExpr - This class is private to Constants.cpp, and is used
477// behind the scenes to implement ICmp and FCmp constant expressions. This is
478// needed in order to store the predicate value for these instructions.
479struct VISIBILITY_HIDDEN CompareConstantExpr : public ConstantExpr {
480 unsigned short predicate;
481 Use Ops[2];
482 CompareConstantExpr(Instruction::OtherOps opc, unsigned short pred,
483 Constant* LHS, Constant* RHS)
Reid Spencer542964f2007-01-11 18:21:29 +0000484 : ConstantExpr(Type::Int1Ty, opc, Ops, 2), predicate(pred) {
Reid Spencer10fbf0e2006-12-03 05:48:19 +0000485 OperandList[0].init(LHS, this);
486 OperandList[1].init(RHS, this);
487 }
488};
489
490} // end anonymous namespace
Vikram S. Adve4e537b22002-07-14 23:13:17 +0000491
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000492
493// Utility function for determining if a ConstantExpr is a CastOp or not. This
494// can't be inline because we don't want to #include Instruction.h into
495// Constant.h
496bool ConstantExpr::isCast() const {
497 return Instruction::isCast(getOpcode());
498}
499
Reid Spenceree3c9912006-12-04 05:19:50 +0000500bool ConstantExpr::isCompare() const {
501 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
502}
503
Chris Lattner817175f2004-03-29 02:37:53 +0000504/// ConstantExpr::get* - Return some common constants without having to
505/// specify the full Instruction::OPCODE identifier.
506///
507Constant *ConstantExpr::getNeg(Constant *C) {
Reid Spencer2eadb532007-01-21 00:29:26 +0000508 return get(Instruction::Sub,
509 ConstantExpr::getZeroValueForNegationExpr(C->getType()),
510 C);
Chris Lattner817175f2004-03-29 02:37:53 +0000511}
512Constant *ConstantExpr::getNot(Constant *C) {
Zhou Sheng75b871f2007-01-11 12:24:14 +0000513 assert(isa<ConstantInt>(C) && "Cannot NOT a nonintegral type!");
Chris Lattner817175f2004-03-29 02:37:53 +0000514 return get(Instruction::Xor, C,
Zhou Sheng75b871f2007-01-11 12:24:14 +0000515 ConstantInt::getAllOnesValue(C->getType()));
Chris Lattner817175f2004-03-29 02:37:53 +0000516}
517Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2) {
518 return get(Instruction::Add, C1, C2);
519}
520Constant *ConstantExpr::getSub(Constant *C1, Constant *C2) {
521 return get(Instruction::Sub, C1, C2);
522}
523Constant *ConstantExpr::getMul(Constant *C1, Constant *C2) {
524 return get(Instruction::Mul, C1, C2);
525}
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000526Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2) {
527 return get(Instruction::UDiv, C1, C2);
528}
529Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2) {
530 return get(Instruction::SDiv, C1, C2);
531}
532Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
533 return get(Instruction::FDiv, C1, C2);
Chris Lattner817175f2004-03-29 02:37:53 +0000534}
Reid Spencer7eb55b32006-11-02 01:53:59 +0000535Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
536 return get(Instruction::URem, C1, C2);
537}
538Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
539 return get(Instruction::SRem, C1, C2);
540}
541Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
542 return get(Instruction::FRem, C1, C2);
Chris Lattner817175f2004-03-29 02:37:53 +0000543}
544Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
545 return get(Instruction::And, C1, C2);
546}
547Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
548 return get(Instruction::Or, C1, C2);
549}
550Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
551 return get(Instruction::Xor, C1, C2);
552}
Reid Spencer10fbf0e2006-12-03 05:48:19 +0000553unsigned ConstantExpr::getPredicate() const {
554 assert(getOpcode() == Instruction::FCmp || getOpcode() == Instruction::ICmp);
555 return dynamic_cast<const CompareConstantExpr*>(this)->predicate;
556}
Chris Lattner817175f2004-03-29 02:37:53 +0000557Constant *ConstantExpr::getShl(Constant *C1, Constant *C2) {
558 return get(Instruction::Shl, C1, C2);
559}
Reid Spencerfdff9382006-11-08 06:47:33 +0000560Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2) {
561 return get(Instruction::LShr, C1, C2);
Chris Lattner817175f2004-03-29 02:37:53 +0000562}
Reid Spencerfdff9382006-11-08 06:47:33 +0000563Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2) {
564 return get(Instruction::AShr, C1, C2);
Chris Lattnerdb8bdba2004-05-25 05:32:43 +0000565}
Chris Lattner60e0dd72001-10-03 06:12:09 +0000566
Chris Lattner7c1018a2006-07-14 19:37:40 +0000567/// getWithOperandReplaced - Return a constant expression identical to this
568/// one, but with the specified operand set to the specified value.
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000569Constant *
570ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
Chris Lattner7c1018a2006-07-14 19:37:40 +0000571 assert(OpNo < getNumOperands() && "Operand num is out of range!");
572 assert(Op->getType() == getOperand(OpNo)->getType() &&
573 "Replacing operand with value of different type!");
Chris Lattner227816342006-07-14 22:20:01 +0000574 if (getOperand(OpNo) == Op)
575 return const_cast<ConstantExpr*>(this);
Chris Lattner7c1018a2006-07-14 19:37:40 +0000576
Chris Lattner227816342006-07-14 22:20:01 +0000577 Constant *Op0, *Op1, *Op2;
Chris Lattner7c1018a2006-07-14 19:37:40 +0000578 switch (getOpcode()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000579 case Instruction::Trunc:
580 case Instruction::ZExt:
581 case Instruction::SExt:
582 case Instruction::FPTrunc:
583 case Instruction::FPExt:
584 case Instruction::UIToFP:
585 case Instruction::SIToFP:
586 case Instruction::FPToUI:
587 case Instruction::FPToSI:
588 case Instruction::PtrToInt:
589 case Instruction::IntToPtr:
590 case Instruction::BitCast:
591 return ConstantExpr::getCast(getOpcode(), Op, getType());
Chris Lattner227816342006-07-14 22:20:01 +0000592 case Instruction::Select:
593 Op0 = (OpNo == 0) ? Op : getOperand(0);
594 Op1 = (OpNo == 1) ? Op : getOperand(1);
595 Op2 = (OpNo == 2) ? Op : getOperand(2);
596 return ConstantExpr::getSelect(Op0, Op1, Op2);
597 case Instruction::InsertElement:
598 Op0 = (OpNo == 0) ? Op : getOperand(0);
599 Op1 = (OpNo == 1) ? Op : getOperand(1);
600 Op2 = (OpNo == 2) ? Op : getOperand(2);
601 return ConstantExpr::getInsertElement(Op0, Op1, Op2);
602 case Instruction::ExtractElement:
603 Op0 = (OpNo == 0) ? Op : getOperand(0);
604 Op1 = (OpNo == 1) ? Op : getOperand(1);
605 return ConstantExpr::getExtractElement(Op0, Op1);
606 case Instruction::ShuffleVector:
607 Op0 = (OpNo == 0) ? Op : getOperand(0);
608 Op1 = (OpNo == 1) ? Op : getOperand(1);
609 Op2 = (OpNo == 2) ? Op : getOperand(2);
610 return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Chris Lattner7c1018a2006-07-14 19:37:40 +0000611 case Instruction::GetElementPtr: {
Chris Lattnerb5d70302007-02-19 20:01:23 +0000612 SmallVector<Constant*, 8> Ops;
613 Ops.resize(getNumOperands());
Chris Lattner7c1018a2006-07-14 19:37:40 +0000614 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
Chris Lattnerb5d70302007-02-19 20:01:23 +0000615 Ops[i] = getOperand(i);
Chris Lattner7c1018a2006-07-14 19:37:40 +0000616 if (OpNo == 0)
Chris Lattnerb5d70302007-02-19 20:01:23 +0000617 return ConstantExpr::getGetElementPtr(Op, &Ops[0], Ops.size());
Chris Lattner7c1018a2006-07-14 19:37:40 +0000618 Ops[OpNo-1] = Op;
Chris Lattnerb5d70302007-02-19 20:01:23 +0000619 return ConstantExpr::getGetElementPtr(getOperand(0), &Ops[0], Ops.size());
Chris Lattner7c1018a2006-07-14 19:37:40 +0000620 }
Chris Lattner7c1018a2006-07-14 19:37:40 +0000621 default:
622 assert(getNumOperands() == 2 && "Must be binary operator?");
Chris Lattner227816342006-07-14 22:20:01 +0000623 Op0 = (OpNo == 0) ? Op : getOperand(0);
624 Op1 = (OpNo == 1) ? Op : getOperand(1);
625 return ConstantExpr::get(getOpcode(), Op0, Op1);
626 }
627}
628
629/// getWithOperands - This returns the current constant expression with the
630/// operands replaced with the specified values. The specified operands must
631/// match count and type with the existing ones.
632Constant *ConstantExpr::
633getWithOperands(const std::vector<Constant*> &Ops) const {
634 assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
635 bool AnyChange = false;
636 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
637 assert(Ops[i]->getType() == getOperand(i)->getType() &&
638 "Operand type mismatch!");
639 AnyChange |= Ops[i] != getOperand(i);
640 }
641 if (!AnyChange) // No operands changed, return self.
642 return const_cast<ConstantExpr*>(this);
643
644 switch (getOpcode()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000645 case Instruction::Trunc:
646 case Instruction::ZExt:
647 case Instruction::SExt:
648 case Instruction::FPTrunc:
649 case Instruction::FPExt:
650 case Instruction::UIToFP:
651 case Instruction::SIToFP:
652 case Instruction::FPToUI:
653 case Instruction::FPToSI:
654 case Instruction::PtrToInt:
655 case Instruction::IntToPtr:
656 case Instruction::BitCast:
657 return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
Chris Lattner227816342006-07-14 22:20:01 +0000658 case Instruction::Select:
659 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
660 case Instruction::InsertElement:
661 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
662 case Instruction::ExtractElement:
663 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
664 case Instruction::ShuffleVector:
665 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
Chris Lattnerb5d70302007-02-19 20:01:23 +0000666 case Instruction::GetElementPtr:
667 return ConstantExpr::getGetElementPtr(Ops[0], &Ops[1], Ops.size()-1);
Reid Spencer266e42b2006-12-23 06:05:41 +0000668 case Instruction::ICmp:
669 case Instruction::FCmp:
670 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
Chris Lattner227816342006-07-14 22:20:01 +0000671 default:
672 assert(getNumOperands() == 2 && "Must be binary operator?");
673 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1]);
Chris Lattner7c1018a2006-07-14 19:37:40 +0000674 }
675}
676
Chris Lattner2f7c9632001-06-06 20:29:01 +0000677
678//===----------------------------------------------------------------------===//
Chris Lattner2f7c9632001-06-06 20:29:01 +0000679// isValueValidForType implementations
680
Reid Spencere7334722006-12-19 01:28:19 +0000681bool ConstantInt::isValueValidForType(const Type *Ty, uint64_t Val) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000682 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000683 if (Ty == Type::Int1Ty)
684 return Val == 0 || Val == 1;
Reid Spencerd7a00d72007-02-05 23:47:56 +0000685 if (NumBits >= 64)
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000686 return true; // always true, has to fit in largest type
687 uint64_t Max = (1ll << NumBits) - 1;
688 return Val <= Max;
Reid Spencere7334722006-12-19 01:28:19 +0000689}
690
Reid Spencere0fc4df2006-10-20 07:07:24 +0000691bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000692 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000693 if (Ty == Type::Int1Ty)
Reid Spencera94d3942007-01-19 21:13:56 +0000694 return Val == 0 || Val == 1 || Val == -1;
Reid Spencerd7a00d72007-02-05 23:47:56 +0000695 if (NumBits >= 64)
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000696 return true; // always true, has to fit in largest type
697 int64_t Min = -(1ll << (NumBits-1));
698 int64_t Max = (1ll << (NumBits-1)) - 1;
699 return (Val >= Min && Val <= Max);
Chris Lattner2f7c9632001-06-06 20:29:01 +0000700}
701
Chris Lattner3462ae32001-12-03 22:26:30 +0000702bool ConstantFP::isValueValidForType(const Type *Ty, double Val) {
Chris Lattner6b727592004-06-17 18:19:28 +0000703 switch (Ty->getTypeID()) {
Chris Lattner2f7c9632001-06-06 20:29:01 +0000704 default:
705 return false; // These can't be represented as floating point!
706
Dale Johannesenbdad8092007-08-09 22:51:36 +0000707 // TODO: Figure out how to test if we can use a shorter type instead!
Chris Lattner2f7c9632001-06-06 20:29:01 +0000708 case Type::FloatTyID:
Chris Lattner2f7c9632001-06-06 20:29:01 +0000709 case Type::DoubleTyID:
Dale Johannesenbdad8092007-08-09 22:51:36 +0000710 case Type::X86_FP80TyID:
711 case Type::PPC_FP128TyID:
712 case Type::FP128TyID:
713 return true;
Chris Lattner2f7c9632001-06-06 20:29:01 +0000714 }
Chris Lattneraa2372562006-05-24 17:04:05 +0000715}
Chris Lattner9655e542001-07-20 19:16:02 +0000716
Chris Lattner49d855c2001-09-07 16:46:31 +0000717//===----------------------------------------------------------------------===//
Chris Lattner49d855c2001-09-07 16:46:31 +0000718// Factory Function Implementation
719
Chris Lattner98fa07b2003-05-23 20:03:32 +0000720// ConstantCreator - A class that is used to create constants by
721// ValueMap*. This class should be partially specialized if there is
722// something strange that needs to be done to interface to the ctor for the
723// constant.
724//
Chris Lattner189d19f2003-11-21 20:23:48 +0000725namespace llvm {
726 template<class ConstantClass, class TypeClass, class ValType>
Chris Lattner02157b02006-06-28 21:38:54 +0000727 struct VISIBILITY_HIDDEN ConstantCreator {
Chris Lattner189d19f2003-11-21 20:23:48 +0000728 static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
729 return new ConstantClass(Ty, V);
730 }
731 };
Misha Brukmanb1c93172005-04-21 23:48:37 +0000732
Chris Lattner189d19f2003-11-21 20:23:48 +0000733 template<class ConstantClass, class TypeClass>
Chris Lattner02157b02006-06-28 21:38:54 +0000734 struct VISIBILITY_HIDDEN ConvertConstantType {
Chris Lattner189d19f2003-11-21 20:23:48 +0000735 static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
736 assert(0 && "This type cannot be converted!\n");
737 abort();
738 }
739 };
Chris Lattnerb50d1352003-10-05 00:17:43 +0000740
Chris Lattner935aa922005-10-04 17:48:46 +0000741 template<class ValType, class TypeClass, class ConstantClass,
742 bool HasLargeKey = false /*true for arrays and structs*/ >
Chris Lattner02157b02006-06-28 21:38:54 +0000743 class VISIBILITY_HIDDEN ValueMap : public AbstractTypeUser {
Chris Lattnerb64419a2005-10-03 22:51:37 +0000744 public:
Jim Laskeyc03caef2006-07-17 17:38:29 +0000745 typedef std::pair<const Type*, ValType> MapKey;
746 typedef std::map<MapKey, Constant *> MapTy;
747 typedef std::map<Constant*, typename MapTy::iterator> InverseMapTy;
748 typedef std::map<const Type*, typename MapTy::iterator> AbstractTypeMapTy;
Chris Lattnerb64419a2005-10-03 22:51:37 +0000749 private:
Chris Lattner5bbf60a52005-10-04 16:52:46 +0000750 /// Map - This is the main map from the element descriptor to the Constants.
751 /// This is the primary way we avoid creating two of the same shape
752 /// constant.
Chris Lattnerb50d1352003-10-05 00:17:43 +0000753 MapTy Map;
Chris Lattner935aa922005-10-04 17:48:46 +0000754
755 /// InverseMap - If "HasLargeKey" is true, this contains an inverse mapping
756 /// from the constants to their element in Map. This is important for
757 /// removal of constants from the array, which would otherwise have to scan
758 /// through the map with very large keys.
Jim Laskeyc03caef2006-07-17 17:38:29 +0000759 InverseMapTy InverseMap;
Chris Lattnerb50d1352003-10-05 00:17:43 +0000760
Jim Laskeyc03caef2006-07-17 17:38:29 +0000761 /// AbstractTypeMap - Map for abstract type constants.
762 ///
Chris Lattnerb50d1352003-10-05 00:17:43 +0000763 AbstractTypeMapTy AbstractTypeMap;
Chris Lattner99a669b2004-11-19 16:39:44 +0000764
Chris Lattner98fa07b2003-05-23 20:03:32 +0000765 public:
Jim Laskeyc03caef2006-07-17 17:38:29 +0000766 typename MapTy::iterator map_end() { return Map.end(); }
Chris Lattnerb64419a2005-10-03 22:51:37 +0000767
768 /// InsertOrGetItem - Return an iterator for the specified element.
769 /// If the element exists in the map, the returned iterator points to the
770 /// entry and Exists=true. If not, the iterator points to the newly
771 /// inserted entry and returns Exists=false. Newly inserted entries have
772 /// I->second == 0, and should be filled in.
Jim Laskeyc03caef2006-07-17 17:38:29 +0000773 typename MapTy::iterator InsertOrGetItem(std::pair<MapKey, Constant *>
774 &InsertVal,
Chris Lattnerb64419a2005-10-03 22:51:37 +0000775 bool &Exists) {
Jim Laskeyc03caef2006-07-17 17:38:29 +0000776 std::pair<typename MapTy::iterator, bool> IP = Map.insert(InsertVal);
Chris Lattnerb64419a2005-10-03 22:51:37 +0000777 Exists = !IP.second;
778 return IP.first;
779 }
Chris Lattner5bbf60a52005-10-04 16:52:46 +0000780
Chris Lattner935aa922005-10-04 17:48:46 +0000781private:
Jim Laskeyc03caef2006-07-17 17:38:29 +0000782 typename MapTy::iterator FindExistingElement(ConstantClass *CP) {
Chris Lattner935aa922005-10-04 17:48:46 +0000783 if (HasLargeKey) {
Jim Laskeyc03caef2006-07-17 17:38:29 +0000784 typename InverseMapTy::iterator IMI = InverseMap.find(CP);
Chris Lattner935aa922005-10-04 17:48:46 +0000785 assert(IMI != InverseMap.end() && IMI->second != Map.end() &&
786 IMI->second->second == CP &&
787 "InverseMap corrupt!");
788 return IMI->second;
789 }
790
Jim Laskeyc03caef2006-07-17 17:38:29 +0000791 typename MapTy::iterator I =
Chris Lattner935aa922005-10-04 17:48:46 +0000792 Map.find(MapKey((TypeClass*)CP->getRawType(), getValType(CP)));
Chris Lattner5bbf60a52005-10-04 16:52:46 +0000793 if (I == Map.end() || I->second != CP) {
794 // FIXME: This should not use a linear scan. If this gets to be a
795 // performance problem, someone should look at this.
796 for (I = Map.begin(); I != Map.end() && I->second != CP; ++I)
797 /* empty */;
798 }
Chris Lattner935aa922005-10-04 17:48:46 +0000799 return I;
800 }
801public:
802
Chris Lattnerb64419a2005-10-03 22:51:37 +0000803 /// getOrCreate - Return the specified constant from the map, creating it if
804 /// necessary.
Chris Lattner98fa07b2003-05-23 20:03:32 +0000805 ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
Chris Lattnerb50d1352003-10-05 00:17:43 +0000806 MapKey Lookup(Ty, V);
Jim Laskeyc03caef2006-07-17 17:38:29 +0000807 typename MapTy::iterator I = Map.lower_bound(Lookup);
Reid Spencere0fc4df2006-10-20 07:07:24 +0000808 // Is it in the map?
Chris Lattner98fa07b2003-05-23 20:03:32 +0000809 if (I != Map.end() && I->first == Lookup)
Reid Spencere0fc4df2006-10-20 07:07:24 +0000810 return static_cast<ConstantClass *>(I->second);
Chris Lattner98fa07b2003-05-23 20:03:32 +0000811
812 // If no preexisting value, create one now...
813 ConstantClass *Result =
814 ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
815
Chris Lattnerb50d1352003-10-05 00:17:43 +0000816 /// FIXME: why does this assert fail when loading 176.gcc?
817 //assert(Result->getType() == Ty && "Type specified is not correct!");
818 I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
819
Chris Lattner935aa922005-10-04 17:48:46 +0000820 if (HasLargeKey) // Remember the reverse mapping if needed.
821 InverseMap.insert(std::make_pair(Result, I));
822
Chris Lattnerb50d1352003-10-05 00:17:43 +0000823 // If the type of the constant is abstract, make sure that an entry exists
824 // for it in the AbstractTypeMap.
825 if (Ty->isAbstract()) {
826 typename AbstractTypeMapTy::iterator TI =
827 AbstractTypeMap.lower_bound(Ty);
828
829 if (TI == AbstractTypeMap.end() || TI->first != Ty) {
830 // Add ourselves to the ATU list of the type.
831 cast<DerivedType>(Ty)->addAbstractTypeUser(this);
832
833 AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
834 }
835 }
Chris Lattner98fa07b2003-05-23 20:03:32 +0000836 return Result;
837 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000838
Chris Lattner98fa07b2003-05-23 20:03:32 +0000839 void remove(ConstantClass *CP) {
Jim Laskeyc03caef2006-07-17 17:38:29 +0000840 typename MapTy::iterator I = FindExistingElement(CP);
Chris Lattnerb50d1352003-10-05 00:17:43 +0000841 assert(I != Map.end() && "Constant not found in constant table!");
Chris Lattner3e650af2004-08-04 04:48:01 +0000842 assert(I->second == CP && "Didn't find correct element?");
Chris Lattnerb50d1352003-10-05 00:17:43 +0000843
Chris Lattner935aa922005-10-04 17:48:46 +0000844 if (HasLargeKey) // Remember the reverse mapping if needed.
845 InverseMap.erase(CP);
846
Chris Lattnerb50d1352003-10-05 00:17:43 +0000847 // Now that we found the entry, make sure this isn't the entry that
848 // the AbstractTypeMap points to.
Jim Laskeyc03caef2006-07-17 17:38:29 +0000849 const TypeClass *Ty = static_cast<const TypeClass *>(I->first.first);
Chris Lattnerb50d1352003-10-05 00:17:43 +0000850 if (Ty->isAbstract()) {
851 assert(AbstractTypeMap.count(Ty) &&
852 "Abstract type not in AbstractTypeMap?");
Jim Laskeyc03caef2006-07-17 17:38:29 +0000853 typename MapTy::iterator &ATMEntryIt = AbstractTypeMap[Ty];
Chris Lattnerb50d1352003-10-05 00:17:43 +0000854 if (ATMEntryIt == I) {
855 // Yes, we are removing the representative entry for this type.
856 // See if there are any other entries of the same type.
Jim Laskeyc03caef2006-07-17 17:38:29 +0000857 typename MapTy::iterator TmpIt = ATMEntryIt;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000858
Chris Lattnerb50d1352003-10-05 00:17:43 +0000859 // First check the entry before this one...
860 if (TmpIt != Map.begin()) {
861 --TmpIt;
862 if (TmpIt->first.first != Ty) // Not the same type, move back...
863 ++TmpIt;
864 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000865
Chris Lattnerb50d1352003-10-05 00:17:43 +0000866 // If we didn't find the same type, try to move forward...
867 if (TmpIt == ATMEntryIt) {
868 ++TmpIt;
869 if (TmpIt == Map.end() || TmpIt->first.first != Ty)
870 --TmpIt; // No entry afterwards with the same type
871 }
872
873 // If there is another entry in the map of the same abstract type,
874 // update the AbstractTypeMap entry now.
875 if (TmpIt != ATMEntryIt) {
876 ATMEntryIt = TmpIt;
877 } else {
878 // Otherwise, we are removing the last instance of this type
879 // from the table. Remove from the ATM, and from user list.
880 cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
881 AbstractTypeMap.erase(Ty);
882 }
Chris Lattner98fa07b2003-05-23 20:03:32 +0000883 }
Chris Lattnerb50d1352003-10-05 00:17:43 +0000884 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000885
Chris Lattnerb50d1352003-10-05 00:17:43 +0000886 Map.erase(I);
887 }
888
Chris Lattner3b793c62005-10-04 21:35:50 +0000889
890 /// MoveConstantToNewSlot - If we are about to change C to be the element
891 /// specified by I, update our internal data structures to reflect this
892 /// fact.
Jim Laskeyc03caef2006-07-17 17:38:29 +0000893 void MoveConstantToNewSlot(ConstantClass *C, typename MapTy::iterator I) {
Chris Lattner3b793c62005-10-04 21:35:50 +0000894 // First, remove the old location of the specified constant in the map.
Jim Laskeyc03caef2006-07-17 17:38:29 +0000895 typename MapTy::iterator OldI = FindExistingElement(C);
Chris Lattner3b793c62005-10-04 21:35:50 +0000896 assert(OldI != Map.end() && "Constant not found in constant table!");
897 assert(OldI->second == C && "Didn't find correct element?");
898
899 // If this constant is the representative element for its abstract type,
900 // update the AbstractTypeMap so that the representative element is I.
901 if (C->getType()->isAbstract()) {
902 typename AbstractTypeMapTy::iterator ATI =
903 AbstractTypeMap.find(C->getType());
904 assert(ATI != AbstractTypeMap.end() &&
905 "Abstract type not in AbstractTypeMap?");
906 if (ATI->second == OldI)
907 ATI->second = I;
908 }
909
910 // Remove the old entry from the map.
911 Map.erase(OldI);
912
913 // Update the inverse map so that we know that this constant is now
914 // located at descriptor I.
915 if (HasLargeKey) {
916 assert(I->second == C && "Bad inversemap entry!");
917 InverseMap[C] = I;
918 }
919 }
920
Chris Lattnerb50d1352003-10-05 00:17:43 +0000921 void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
Misha Brukmanb1c93172005-04-21 23:48:37 +0000922 typename AbstractTypeMapTy::iterator I =
Jim Laskeyc03caef2006-07-17 17:38:29 +0000923 AbstractTypeMap.find(cast<Type>(OldTy));
Chris Lattnerb50d1352003-10-05 00:17:43 +0000924
925 assert(I != AbstractTypeMap.end() &&
926 "Abstract type not in AbstractTypeMap?");
927
928 // Convert a constant at a time until the last one is gone. The last one
929 // leaving will remove() itself, causing the AbstractTypeMapEntry to be
930 // eliminated eventually.
931 do {
932 ConvertConstantType<ConstantClass,
Jim Laskeyc03caef2006-07-17 17:38:29 +0000933 TypeClass>::convert(
934 static_cast<ConstantClass *>(I->second->second),
Chris Lattnerb50d1352003-10-05 00:17:43 +0000935 cast<TypeClass>(NewTy));
936
Jim Laskeyc03caef2006-07-17 17:38:29 +0000937 I = AbstractTypeMap.find(cast<Type>(OldTy));
Chris Lattnerb50d1352003-10-05 00:17:43 +0000938 } while (I != AbstractTypeMap.end());
939 }
940
941 // If the type became concrete without being refined to any other existing
942 // type, we just remove ourselves from the ATU list.
943 void typeBecameConcrete(const DerivedType *AbsTy) {
944 AbsTy->removeAbstractTypeUser(this);
945 }
946
947 void dump() const {
Bill Wendling6a462f12006-11-17 08:03:48 +0000948 DOUT << "Constant.cpp: ValueMap\n";
Chris Lattner98fa07b2003-05-23 20:03:32 +0000949 }
950 };
951}
952
Chris Lattnera84df0a22006-09-28 23:36:21 +0000953
Chris Lattner28173502007-02-20 06:11:36 +0000954
Chris Lattner9fba3da2004-02-15 05:53:04 +0000955//---- ConstantAggregateZero::get() implementation...
956//
957namespace llvm {
958 // ConstantAggregateZero does not take extra "value" argument...
959 template<class ValType>
960 struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
961 static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
962 return new ConstantAggregateZero(Ty);
963 }
964 };
965
966 template<>
967 struct ConvertConstantType<ConstantAggregateZero, Type> {
968 static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
969 // Make everyone now use a constant of the new type...
970 Constant *New = ConstantAggregateZero::get(NewTy);
971 assert(New != OldC && "Didn't replace constant??");
972 OldC->uncheckedReplaceAllUsesWith(New);
973 OldC->destroyConstant(); // This constant is now dead, destroy it.
974 }
975 };
976}
977
Chris Lattner69edc982006-09-28 00:35:06 +0000978static ManagedStatic<ValueMap<char, Type,
979 ConstantAggregateZero> > AggZeroConstants;
Chris Lattner9fba3da2004-02-15 05:53:04 +0000980
Chris Lattner3e650af2004-08-04 04:48:01 +0000981static char getValType(ConstantAggregateZero *CPZ) { return 0; }
982
Chris Lattner9fba3da2004-02-15 05:53:04 +0000983Constant *ConstantAggregateZero::get(const Type *Ty) {
Reid Spencerd84d35b2007-02-15 02:26:10 +0000984 assert((isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) &&
Chris Lattnerbfd0b6d2006-06-10 04:16:23 +0000985 "Cannot create an aggregate zero of non-aggregate type!");
Chris Lattner69edc982006-09-28 00:35:06 +0000986 return AggZeroConstants->getOrCreate(Ty, 0);
Chris Lattner9fba3da2004-02-15 05:53:04 +0000987}
988
989// destroyConstant - Remove the constant from the constant table...
990//
991void ConstantAggregateZero::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +0000992 AggZeroConstants->remove(this);
Chris Lattner9fba3da2004-02-15 05:53:04 +0000993 destroyConstantImpl();
994}
995
Chris Lattner3462ae32001-12-03 22:26:30 +0000996//---- ConstantArray::get() implementation...
Chris Lattner49d855c2001-09-07 16:46:31 +0000997//
Chris Lattner189d19f2003-11-21 20:23:48 +0000998namespace llvm {
999 template<>
1000 struct ConvertConstantType<ConstantArray, ArrayType> {
1001 static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
1002 // Make everyone now use a constant of the new type...
1003 std::vector<Constant*> C;
1004 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1005 C.push_back(cast<Constant>(OldC->getOperand(i)));
1006 Constant *New = ConstantArray::get(NewTy, C);
1007 assert(New != OldC && "Didn't replace constant??");
1008 OldC->uncheckedReplaceAllUsesWith(New);
1009 OldC->destroyConstant(); // This constant is now dead, destroy it.
1010 }
1011 };
1012}
Chris Lattnerb50d1352003-10-05 00:17:43 +00001013
Chris Lattner3e650af2004-08-04 04:48:01 +00001014static std::vector<Constant*> getValType(ConstantArray *CA) {
1015 std::vector<Constant*> Elements;
1016 Elements.reserve(CA->getNumOperands());
1017 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1018 Elements.push_back(cast<Constant>(CA->getOperand(i)));
1019 return Elements;
1020}
1021
Chris Lattnerb64419a2005-10-03 22:51:37 +00001022typedef ValueMap<std::vector<Constant*>, ArrayType,
Chris Lattner935aa922005-10-04 17:48:46 +00001023 ConstantArray, true /*largekey*/> ArrayConstantsTy;
Chris Lattner69edc982006-09-28 00:35:06 +00001024static ManagedStatic<ArrayConstantsTy> ArrayConstants;
Chris Lattner49d855c2001-09-07 16:46:31 +00001025
Chris Lattner015e8212004-02-15 04:14:47 +00001026Constant *ConstantArray::get(const ArrayType *Ty,
Chris Lattner9fba3da2004-02-15 05:53:04 +00001027 const std::vector<Constant*> &V) {
1028 // If this is an all-zero array, return a ConstantAggregateZero object
1029 if (!V.empty()) {
1030 Constant *C = V[0];
1031 if (!C->isNullValue())
Chris Lattner69edc982006-09-28 00:35:06 +00001032 return ArrayConstants->getOrCreate(Ty, V);
Chris Lattner9fba3da2004-02-15 05:53:04 +00001033 for (unsigned i = 1, e = V.size(); i != e; ++i)
1034 if (V[i] != C)
Chris Lattner69edc982006-09-28 00:35:06 +00001035 return ArrayConstants->getOrCreate(Ty, V);
Chris Lattner9fba3da2004-02-15 05:53:04 +00001036 }
1037 return ConstantAggregateZero::get(Ty);
Chris Lattner49d855c2001-09-07 16:46:31 +00001038}
1039
Chris Lattner98fa07b2003-05-23 20:03:32 +00001040// destroyConstant - Remove the constant from the constant table...
1041//
1042void ConstantArray::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00001043 ArrayConstants->remove(this);
Chris Lattner98fa07b2003-05-23 20:03:32 +00001044 destroyConstantImpl();
1045}
1046
Reid Spencer6f614532006-05-30 08:23:18 +00001047/// ConstantArray::get(const string&) - Return an array that is initialized to
1048/// contain the specified string. If length is zero then a null terminator is
1049/// added to the specified string so that it may be used in a natural way.
1050/// Otherwise, the length parameter specifies how much of the string to use
1051/// and it won't be null terminated.
1052///
Reid Spencer82ebaba2006-05-30 18:15:07 +00001053Constant *ConstantArray::get(const std::string &Str, bool AddNull) {
Chris Lattner7f74a562002-01-20 22:54:45 +00001054 std::vector<Constant*> ElementVals;
Reid Spencer82ebaba2006-05-30 18:15:07 +00001055 for (unsigned i = 0; i < Str.length(); ++i)
Reid Spencer8d9336d2006-12-31 05:26:44 +00001056 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, Str[i]));
Chris Lattner8f80fe02001-10-14 23:54:12 +00001057
1058 // Add a null terminator to the string...
Reid Spencer82ebaba2006-05-30 18:15:07 +00001059 if (AddNull) {
Reid Spencer8d9336d2006-12-31 05:26:44 +00001060 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, 0));
Reid Spencer6f614532006-05-30 08:23:18 +00001061 }
Chris Lattner8f80fe02001-10-14 23:54:12 +00001062
Reid Spencer8d9336d2006-12-31 05:26:44 +00001063 ArrayType *ATy = ArrayType::get(Type::Int8Ty, ElementVals.size());
Chris Lattner3462ae32001-12-03 22:26:30 +00001064 return ConstantArray::get(ATy, ElementVals);
Vikram S. Adve34410432001-10-14 23:17:20 +00001065}
1066
Reid Spencer2546b762007-01-26 07:37:34 +00001067/// isString - This method returns true if the array is an array of i8, and
1068/// if the elements of the array are all ConstantInt's.
Chris Lattnere8dfcca2004-01-14 17:06:38 +00001069bool ConstantArray::isString() const {
Reid Spencer2546b762007-01-26 07:37:34 +00001070 // Check the element type for i8...
Reid Spencer8d9336d2006-12-31 05:26:44 +00001071 if (getType()->getElementType() != Type::Int8Ty)
Chris Lattnere8dfcca2004-01-14 17:06:38 +00001072 return false;
1073 // Check the elements to make sure they are all integers, not constant
1074 // expressions.
1075 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1076 if (!isa<ConstantInt>(getOperand(i)))
1077 return false;
1078 return true;
1079}
1080
Evan Cheng3763c5b2006-10-26 19:15:05 +00001081/// isCString - This method returns true if the array is a string (see
1082/// isString) and it ends in a null byte \0 and does not contains any other
1083/// null bytes except its terminator.
1084bool ConstantArray::isCString() const {
Reid Spencer2546b762007-01-26 07:37:34 +00001085 // Check the element type for i8...
Reid Spencer8d9336d2006-12-31 05:26:44 +00001086 if (getType()->getElementType() != Type::Int8Ty)
Evan Chenge974da62006-10-26 21:48:03 +00001087 return false;
1088 Constant *Zero = Constant::getNullValue(getOperand(0)->getType());
1089 // Last element must be a null.
1090 if (getOperand(getNumOperands()-1) != Zero)
1091 return false;
1092 // Other elements must be non-null integers.
1093 for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
1094 if (!isa<ConstantInt>(getOperand(i)))
Evan Cheng3763c5b2006-10-26 19:15:05 +00001095 return false;
Evan Chenge974da62006-10-26 21:48:03 +00001096 if (getOperand(i) == Zero)
1097 return false;
1098 }
Evan Cheng3763c5b2006-10-26 19:15:05 +00001099 return true;
1100}
1101
1102
Reid Spencer2546b762007-01-26 07:37:34 +00001103// getAsString - If the sub-element type of this array is i8
Chris Lattner81fabb02002-08-26 17:53:56 +00001104// then this method converts the array to an std::string and returns it.
1105// Otherwise, it asserts out.
1106//
1107std::string ConstantArray::getAsString() const {
Chris Lattnere8dfcca2004-01-14 17:06:38 +00001108 assert(isString() && "Not a string!");
Chris Lattner81fabb02002-08-26 17:53:56 +00001109 std::string Result;
Chris Lattner6077c312003-07-23 15:22:26 +00001110 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
Reid Spencere0fc4df2006-10-20 07:07:24 +00001111 Result += (char)cast<ConstantInt>(getOperand(i))->getZExtValue();
Chris Lattner81fabb02002-08-26 17:53:56 +00001112 return Result;
1113}
1114
1115
Chris Lattner3462ae32001-12-03 22:26:30 +00001116//---- ConstantStruct::get() implementation...
Chris Lattner49d855c2001-09-07 16:46:31 +00001117//
Chris Lattnerb50d1352003-10-05 00:17:43 +00001118
Chris Lattner189d19f2003-11-21 20:23:48 +00001119namespace llvm {
1120 template<>
1121 struct ConvertConstantType<ConstantStruct, StructType> {
1122 static void convert(ConstantStruct *OldC, const StructType *NewTy) {
1123 // Make everyone now use a constant of the new type...
1124 std::vector<Constant*> C;
1125 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1126 C.push_back(cast<Constant>(OldC->getOperand(i)));
1127 Constant *New = ConstantStruct::get(NewTy, C);
1128 assert(New != OldC && "Didn't replace constant??");
Misha Brukmanb1c93172005-04-21 23:48:37 +00001129
Chris Lattner189d19f2003-11-21 20:23:48 +00001130 OldC->uncheckedReplaceAllUsesWith(New);
1131 OldC->destroyConstant(); // This constant is now dead, destroy it.
1132 }
1133 };
1134}
Chris Lattnerb50d1352003-10-05 00:17:43 +00001135
Chris Lattner8760ec72005-10-04 01:17:50 +00001136typedef ValueMap<std::vector<Constant*>, StructType,
Chris Lattner935aa922005-10-04 17:48:46 +00001137 ConstantStruct, true /*largekey*/> StructConstantsTy;
Chris Lattner69edc982006-09-28 00:35:06 +00001138static ManagedStatic<StructConstantsTy> StructConstants;
Chris Lattner49d855c2001-09-07 16:46:31 +00001139
Chris Lattner3e650af2004-08-04 04:48:01 +00001140static std::vector<Constant*> getValType(ConstantStruct *CS) {
1141 std::vector<Constant*> Elements;
1142 Elements.reserve(CS->getNumOperands());
1143 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1144 Elements.push_back(cast<Constant>(CS->getOperand(i)));
1145 return Elements;
1146}
1147
Chris Lattner015e8212004-02-15 04:14:47 +00001148Constant *ConstantStruct::get(const StructType *Ty,
1149 const std::vector<Constant*> &V) {
Chris Lattner9fba3da2004-02-15 05:53:04 +00001150 // Create a ConstantAggregateZero value if all elements are zeros...
1151 for (unsigned i = 0, e = V.size(); i != e; ++i)
1152 if (!V[i]->isNullValue())
Chris Lattner69edc982006-09-28 00:35:06 +00001153 return StructConstants->getOrCreate(Ty, V);
Chris Lattner9fba3da2004-02-15 05:53:04 +00001154
1155 return ConstantAggregateZero::get(Ty);
Chris Lattner49d855c2001-09-07 16:46:31 +00001156}
Chris Lattner883ad0b2001-10-03 15:39:36 +00001157
Andrew Lenharthdcb3c972006-12-08 18:06:16 +00001158Constant *ConstantStruct::get(const std::vector<Constant*> &V, bool packed) {
Chris Lattnerd6108ca2004-07-12 20:35:11 +00001159 std::vector<const Type*> StructEls;
1160 StructEls.reserve(V.size());
1161 for (unsigned i = 0, e = V.size(); i != e; ++i)
1162 StructEls.push_back(V[i]->getType());
Andrew Lenharthdcb3c972006-12-08 18:06:16 +00001163 return get(StructType::get(StructEls, packed), V);
Chris Lattnerd6108ca2004-07-12 20:35:11 +00001164}
1165
Chris Lattnerd7a73302001-10-13 06:57:33 +00001166// destroyConstant - Remove the constant from the constant table...
Chris Lattner883ad0b2001-10-03 15:39:36 +00001167//
Chris Lattner3462ae32001-12-03 22:26:30 +00001168void ConstantStruct::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00001169 StructConstants->remove(this);
Chris Lattnerd7a73302001-10-13 06:57:33 +00001170 destroyConstantImpl();
1171}
Chris Lattner883ad0b2001-10-03 15:39:36 +00001172
Reid Spencerd84d35b2007-02-15 02:26:10 +00001173//---- ConstantVector::get() implementation...
Brian Gaeke02209042004-08-20 06:00:58 +00001174//
1175namespace llvm {
1176 template<>
Reid Spencerd84d35b2007-02-15 02:26:10 +00001177 struct ConvertConstantType<ConstantVector, VectorType> {
1178 static void convert(ConstantVector *OldC, const VectorType *NewTy) {
Brian Gaeke02209042004-08-20 06:00:58 +00001179 // Make everyone now use a constant of the new type...
1180 std::vector<Constant*> C;
1181 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1182 C.push_back(cast<Constant>(OldC->getOperand(i)));
Reid Spencerd84d35b2007-02-15 02:26:10 +00001183 Constant *New = ConstantVector::get(NewTy, C);
Brian Gaeke02209042004-08-20 06:00:58 +00001184 assert(New != OldC && "Didn't replace constant??");
1185 OldC->uncheckedReplaceAllUsesWith(New);
1186 OldC->destroyConstant(); // This constant is now dead, destroy it.
1187 }
1188 };
1189}
1190
Reid Spencerd84d35b2007-02-15 02:26:10 +00001191static std::vector<Constant*> getValType(ConstantVector *CP) {
Brian Gaeke02209042004-08-20 06:00:58 +00001192 std::vector<Constant*> Elements;
1193 Elements.reserve(CP->getNumOperands());
1194 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1195 Elements.push_back(CP->getOperand(i));
1196 return Elements;
1197}
1198
Reid Spencerd84d35b2007-02-15 02:26:10 +00001199static ManagedStatic<ValueMap<std::vector<Constant*>, VectorType,
Reid Spencer09575ba2007-02-15 03:39:18 +00001200 ConstantVector> > VectorConstants;
Brian Gaeke02209042004-08-20 06:00:58 +00001201
Reid Spencerd84d35b2007-02-15 02:26:10 +00001202Constant *ConstantVector::get(const VectorType *Ty,
Brian Gaeke02209042004-08-20 06:00:58 +00001203 const std::vector<Constant*> &V) {
Dan Gohman30978072007-05-24 14:36:04 +00001204 // If this is an all-zero vector, return a ConstantAggregateZero object
Brian Gaeke02209042004-08-20 06:00:58 +00001205 if (!V.empty()) {
1206 Constant *C = V[0];
1207 if (!C->isNullValue())
Reid Spencer09575ba2007-02-15 03:39:18 +00001208 return VectorConstants->getOrCreate(Ty, V);
Brian Gaeke02209042004-08-20 06:00:58 +00001209 for (unsigned i = 1, e = V.size(); i != e; ++i)
1210 if (V[i] != C)
Reid Spencer09575ba2007-02-15 03:39:18 +00001211 return VectorConstants->getOrCreate(Ty, V);
Brian Gaeke02209042004-08-20 06:00:58 +00001212 }
1213 return ConstantAggregateZero::get(Ty);
1214}
1215
Reid Spencerd84d35b2007-02-15 02:26:10 +00001216Constant *ConstantVector::get(const std::vector<Constant*> &V) {
Brian Gaeke02209042004-08-20 06:00:58 +00001217 assert(!V.empty() && "Cannot infer type if V is empty");
Reid Spencerd84d35b2007-02-15 02:26:10 +00001218 return get(VectorType::get(V.front()->getType(),V.size()), V);
Brian Gaeke02209042004-08-20 06:00:58 +00001219}
1220
1221// destroyConstant - Remove the constant from the constant table...
1222//
Reid Spencerd84d35b2007-02-15 02:26:10 +00001223void ConstantVector::destroyConstant() {
Reid Spencer09575ba2007-02-15 03:39:18 +00001224 VectorConstants->remove(this);
Brian Gaeke02209042004-08-20 06:00:58 +00001225 destroyConstantImpl();
1226}
1227
Dan Gohman30978072007-05-24 14:36:04 +00001228/// This function will return true iff every element in this vector constant
Jim Laskeyf0478822007-01-12 22:39:14 +00001229/// is set to all ones.
1230/// @returns true iff this constant's emements are all set to all ones.
1231/// @brief Determine if the value is all ones.
Reid Spencerd84d35b2007-02-15 02:26:10 +00001232bool ConstantVector::isAllOnesValue() const {
Jim Laskeyf0478822007-01-12 22:39:14 +00001233 // Check out first element.
1234 const Constant *Elt = getOperand(0);
1235 const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1236 if (!CI || !CI->isAllOnesValue()) return false;
1237 // Then make sure all remaining elements point to the same value.
1238 for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
1239 if (getOperand(I) != Elt) return false;
1240 }
1241 return true;
1242}
1243
Chris Lattner3462ae32001-12-03 22:26:30 +00001244//---- ConstantPointerNull::get() implementation...
Chris Lattnerd7a73302001-10-13 06:57:33 +00001245//
Chris Lattner98fa07b2003-05-23 20:03:32 +00001246
Chris Lattner189d19f2003-11-21 20:23:48 +00001247namespace llvm {
1248 // ConstantPointerNull does not take extra "value" argument...
1249 template<class ValType>
1250 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1251 static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1252 return new ConstantPointerNull(Ty);
1253 }
1254 };
Chris Lattner98fa07b2003-05-23 20:03:32 +00001255
Chris Lattner189d19f2003-11-21 20:23:48 +00001256 template<>
1257 struct ConvertConstantType<ConstantPointerNull, PointerType> {
1258 static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1259 // Make everyone now use a constant of the new type...
1260 Constant *New = ConstantPointerNull::get(NewTy);
1261 assert(New != OldC && "Didn't replace constant??");
1262 OldC->uncheckedReplaceAllUsesWith(New);
1263 OldC->destroyConstant(); // This constant is now dead, destroy it.
1264 }
1265 };
1266}
Chris Lattnerb50d1352003-10-05 00:17:43 +00001267
Chris Lattner69edc982006-09-28 00:35:06 +00001268static ManagedStatic<ValueMap<char, PointerType,
1269 ConstantPointerNull> > NullPtrConstants;
Chris Lattnerd7a73302001-10-13 06:57:33 +00001270
Chris Lattner3e650af2004-08-04 04:48:01 +00001271static char getValType(ConstantPointerNull *) {
1272 return 0;
1273}
1274
1275
Chris Lattner3462ae32001-12-03 22:26:30 +00001276ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
Chris Lattner69edc982006-09-28 00:35:06 +00001277 return NullPtrConstants->getOrCreate(Ty, 0);
Chris Lattner883ad0b2001-10-03 15:39:36 +00001278}
1279
Chris Lattner0c6e0b92002-08-18 00:40:04 +00001280// destroyConstant - Remove the constant from the constant table...
1281//
1282void ConstantPointerNull::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00001283 NullPtrConstants->remove(this);
Chris Lattner0c6e0b92002-08-18 00:40:04 +00001284 destroyConstantImpl();
1285}
1286
1287
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001288//---- UndefValue::get() implementation...
1289//
1290
1291namespace llvm {
1292 // UndefValue does not take extra "value" argument...
1293 template<class ValType>
1294 struct ConstantCreator<UndefValue, Type, ValType> {
1295 static UndefValue *create(const Type *Ty, const ValType &V) {
1296 return new UndefValue(Ty);
1297 }
1298 };
1299
1300 template<>
1301 struct ConvertConstantType<UndefValue, Type> {
1302 static void convert(UndefValue *OldC, const Type *NewTy) {
1303 // Make everyone now use a constant of the new type.
1304 Constant *New = UndefValue::get(NewTy);
1305 assert(New != OldC && "Didn't replace constant??");
1306 OldC->uncheckedReplaceAllUsesWith(New);
1307 OldC->destroyConstant(); // This constant is now dead, destroy it.
1308 }
1309 };
1310}
1311
Chris Lattner69edc982006-09-28 00:35:06 +00001312static ManagedStatic<ValueMap<char, Type, UndefValue> > UndefValueConstants;
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001313
1314static char getValType(UndefValue *) {
1315 return 0;
1316}
1317
1318
1319UndefValue *UndefValue::get(const Type *Ty) {
Chris Lattner69edc982006-09-28 00:35:06 +00001320 return UndefValueConstants->getOrCreate(Ty, 0);
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001321}
1322
1323// destroyConstant - Remove the constant from the constant table.
1324//
1325void UndefValue::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00001326 UndefValueConstants->remove(this);
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001327 destroyConstantImpl();
1328}
1329
1330
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001331//---- ConstantExpr::get() implementations...
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001332//
Reid Spencer8d9336d2006-12-31 05:26:44 +00001333
Reid Spenceree3c9912006-12-04 05:19:50 +00001334struct ExprMapKeyType {
1335 explicit ExprMapKeyType(unsigned opc, std::vector<Constant*> ops,
Reid Spencerdba6aa42006-12-04 18:38:05 +00001336 unsigned short pred = 0) : opcode(opc), predicate(pred), operands(ops) { }
1337 uint16_t opcode;
1338 uint16_t predicate;
Reid Spenceree3c9912006-12-04 05:19:50 +00001339 std::vector<Constant*> operands;
Reid Spenceree3c9912006-12-04 05:19:50 +00001340 bool operator==(const ExprMapKeyType& that) const {
1341 return this->opcode == that.opcode &&
1342 this->predicate == that.predicate &&
1343 this->operands == that.operands;
1344 }
1345 bool operator<(const ExprMapKeyType & that) const {
1346 return this->opcode < that.opcode ||
1347 (this->opcode == that.opcode && this->predicate < that.predicate) ||
1348 (this->opcode == that.opcode && this->predicate == that.predicate &&
1349 this->operands < that.operands);
1350 }
1351
1352 bool operator!=(const ExprMapKeyType& that) const {
1353 return !(*this == that);
1354 }
1355};
Chris Lattner98fa07b2003-05-23 20:03:32 +00001356
Chris Lattner189d19f2003-11-21 20:23:48 +00001357namespace llvm {
1358 template<>
1359 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
Reid Spencer10fbf0e2006-12-03 05:48:19 +00001360 static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V,
1361 unsigned short pred = 0) {
Reid Spenceree3c9912006-12-04 05:19:50 +00001362 if (Instruction::isCast(V.opcode))
1363 return new UnaryConstantExpr(V.opcode, V.operands[0], Ty);
1364 if ((V.opcode >= Instruction::BinaryOpsBegin &&
Reid Spencer2341c222007-02-02 02:16:23 +00001365 V.opcode < Instruction::BinaryOpsEnd))
Reid Spenceree3c9912006-12-04 05:19:50 +00001366 return new BinaryConstantExpr(V.opcode, V.operands[0], V.operands[1]);
1367 if (V.opcode == Instruction::Select)
1368 return new SelectConstantExpr(V.operands[0], V.operands[1],
1369 V.operands[2]);
1370 if (V.opcode == Instruction::ExtractElement)
1371 return new ExtractElementConstantExpr(V.operands[0], V.operands[1]);
1372 if (V.opcode == Instruction::InsertElement)
1373 return new InsertElementConstantExpr(V.operands[0], V.operands[1],
1374 V.operands[2]);
1375 if (V.opcode == Instruction::ShuffleVector)
1376 return new ShuffleVectorConstantExpr(V.operands[0], V.operands[1],
1377 V.operands[2]);
1378 if (V.opcode == Instruction::GetElementPtr) {
1379 std::vector<Constant*> IdxList(V.operands.begin()+1, V.operands.end());
1380 return new GetElementPtrConstantExpr(V.operands[0], IdxList, Ty);
1381 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001382
Reid Spenceree3c9912006-12-04 05:19:50 +00001383 // The compare instructions are weird. We have to encode the predicate
1384 // value and it is combined with the instruction opcode by multiplying
1385 // the opcode by one hundred. We must decode this to get the predicate.
1386 if (V.opcode == Instruction::ICmp)
1387 return new CompareConstantExpr(Instruction::ICmp, V.predicate,
1388 V.operands[0], V.operands[1]);
1389 if (V.opcode == Instruction::FCmp)
1390 return new CompareConstantExpr(Instruction::FCmp, V.predicate,
1391 V.operands[0], V.operands[1]);
1392 assert(0 && "Invalid ConstantExpr!");
Jeff Cohen9f469632006-12-15 21:47:01 +00001393 return 0;
Chris Lattnerb50d1352003-10-05 00:17:43 +00001394 }
Chris Lattner189d19f2003-11-21 20:23:48 +00001395 };
Chris Lattnerb50d1352003-10-05 00:17:43 +00001396
Chris Lattner189d19f2003-11-21 20:23:48 +00001397 template<>
1398 struct ConvertConstantType<ConstantExpr, Type> {
1399 static void convert(ConstantExpr *OldC, const Type *NewTy) {
1400 Constant *New;
1401 switch (OldC->getOpcode()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001402 case Instruction::Trunc:
1403 case Instruction::ZExt:
1404 case Instruction::SExt:
1405 case Instruction::FPTrunc:
1406 case Instruction::FPExt:
1407 case Instruction::UIToFP:
1408 case Instruction::SIToFP:
1409 case Instruction::FPToUI:
1410 case Instruction::FPToSI:
1411 case Instruction::PtrToInt:
1412 case Instruction::IntToPtr:
1413 case Instruction::BitCast:
Reid Spencerbb65ebf2006-12-12 23:36:14 +00001414 New = ConstantExpr::getCast(OldC->getOpcode(), OldC->getOperand(0),
1415 NewTy);
Chris Lattner189d19f2003-11-21 20:23:48 +00001416 break;
Chris Lattner6e415c02004-03-12 05:54:04 +00001417 case Instruction::Select:
1418 New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1419 OldC->getOperand(1),
1420 OldC->getOperand(2));
1421 break;
Chris Lattner189d19f2003-11-21 20:23:48 +00001422 default:
1423 assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
Reid Spencer7eb55b32006-11-02 01:53:59 +00001424 OldC->getOpcode() < Instruction::BinaryOpsEnd);
Chris Lattner189d19f2003-11-21 20:23:48 +00001425 New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1426 OldC->getOperand(1));
1427 break;
1428 case Instruction::GetElementPtr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00001429 // Make everyone now use a constant of the new type...
Chris Lattner13128ab2004-10-11 22:52:25 +00001430 std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
Chris Lattner302116a2007-01-31 04:40:28 +00001431 New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0),
1432 &Idx[0], Idx.size());
Chris Lattner189d19f2003-11-21 20:23:48 +00001433 break;
1434 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001435
Chris Lattner189d19f2003-11-21 20:23:48 +00001436 assert(New != OldC && "Didn't replace constant??");
1437 OldC->uncheckedReplaceAllUsesWith(New);
1438 OldC->destroyConstant(); // This constant is now dead, destroy it.
1439 }
1440 };
1441} // end namespace llvm
Chris Lattnerb50d1352003-10-05 00:17:43 +00001442
1443
Chris Lattner3e650af2004-08-04 04:48:01 +00001444static ExprMapKeyType getValType(ConstantExpr *CE) {
1445 std::vector<Constant*> Operands;
1446 Operands.reserve(CE->getNumOperands());
1447 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
1448 Operands.push_back(cast<Constant>(CE->getOperand(i)));
Reid Spenceree3c9912006-12-04 05:19:50 +00001449 return ExprMapKeyType(CE->getOpcode(), Operands,
1450 CE->isCompare() ? CE->getPredicate() : 0);
Chris Lattner3e650af2004-08-04 04:48:01 +00001451}
1452
Chris Lattner69edc982006-09-28 00:35:06 +00001453static ManagedStatic<ValueMap<ExprMapKeyType, Type,
1454 ConstantExpr> > ExprConstants;
Vikram S. Adve4c485332002-07-15 18:19:33 +00001455
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001456/// This is a utility function to handle folding of casts and lookup of the
1457/// cast in the ExprConstants map. It is usedby the various get* methods below.
1458static inline Constant *getFoldedCast(
1459 Instruction::CastOps opc, Constant *C, const Type *Ty) {
Chris Lattner815ae2b2003-10-07 22:19:19 +00001460 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001461 // Fold a few common cases
1462 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
1463 return FC;
Chris Lattneracdbe712003-04-17 19:24:48 +00001464
Vikram S. Adve4c485332002-07-15 18:19:33 +00001465 // Look up the constant in the table first to ensure uniqueness
Chris Lattner2b383d2e2003-05-13 21:37:02 +00001466 std::vector<Constant*> argVec(1, C);
Reid Spenceree3c9912006-12-04 05:19:50 +00001467 ExprMapKeyType Key(opc, argVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001468 return ExprConstants->getOrCreate(Ty, Key);
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001469}
Reid Spencerf37dc652006-12-05 19:14:13 +00001470
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001471Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
1472 Instruction::CastOps opc = Instruction::CastOps(oc);
1473 assert(Instruction::isCast(opc) && "opcode out of range");
1474 assert(C && Ty && "Null arguments to getCast");
1475 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1476
1477 switch (opc) {
1478 default:
1479 assert(0 && "Invalid cast opcode");
1480 break;
1481 case Instruction::Trunc: return getTrunc(C, Ty);
Reid Spencerbb65ebf2006-12-12 23:36:14 +00001482 case Instruction::ZExt: return getZExt(C, Ty);
1483 case Instruction::SExt: return getSExt(C, Ty);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001484 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
1485 case Instruction::FPExt: return getFPExtend(C, Ty);
1486 case Instruction::UIToFP: return getUIToFP(C, Ty);
1487 case Instruction::SIToFP: return getSIToFP(C, Ty);
1488 case Instruction::FPToUI: return getFPToUI(C, Ty);
1489 case Instruction::FPToSI: return getFPToSI(C, Ty);
1490 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1491 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1492 case Instruction::BitCast: return getBitCast(C, Ty);
Chris Lattner1ece6f82005-01-01 15:59:57 +00001493 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001494 return 0;
Reid Spencerf37dc652006-12-05 19:14:13 +00001495}
1496
Reid Spencer5c140882006-12-04 20:17:56 +00001497Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
1498 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1499 return getCast(Instruction::BitCast, C, Ty);
1500 return getCast(Instruction::ZExt, C, Ty);
1501}
1502
1503Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
1504 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1505 return getCast(Instruction::BitCast, C, Ty);
1506 return getCast(Instruction::SExt, C, Ty);
1507}
1508
1509Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
1510 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1511 return getCast(Instruction::BitCast, C, Ty);
1512 return getCast(Instruction::Trunc, C, Ty);
1513}
1514
Reid Spencerbc245a02006-12-05 03:25:26 +00001515Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
1516 assert(isa<PointerType>(S->getType()) && "Invalid cast");
Chris Lattner03c49532007-01-15 02:27:26 +00001517 assert((Ty->isInteger() || isa<PointerType>(Ty)) && "Invalid cast");
Reid Spencerbc245a02006-12-05 03:25:26 +00001518
Chris Lattner03c49532007-01-15 02:27:26 +00001519 if (Ty->isInteger())
Reid Spencerbc245a02006-12-05 03:25:26 +00001520 return getCast(Instruction::PtrToInt, S, Ty);
1521 return getCast(Instruction::BitCast, S, Ty);
1522}
1523
Reid Spencer56521c42006-12-12 00:51:07 +00001524Constant *ConstantExpr::getIntegerCast(Constant *C, const Type *Ty,
1525 bool isSigned) {
Chris Lattner03c49532007-01-15 02:27:26 +00001526 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
Reid Spencer56521c42006-12-12 00:51:07 +00001527 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1528 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1529 Instruction::CastOps opcode =
1530 (SrcBits == DstBits ? Instruction::BitCast :
1531 (SrcBits > DstBits ? Instruction::Trunc :
1532 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1533 return getCast(opcode, C, Ty);
1534}
1535
1536Constant *ConstantExpr::getFPCast(Constant *C, const Type *Ty) {
1537 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1538 "Invalid cast");
1539 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1540 unsigned DstBits = Ty->getPrimitiveSizeInBits();
Reid Spencerca104e82006-12-12 05:38:50 +00001541 if (SrcBits == DstBits)
1542 return C; // Avoid a useless cast
Reid Spencer56521c42006-12-12 00:51:07 +00001543 Instruction::CastOps opcode =
Reid Spencerca104e82006-12-12 05:38:50 +00001544 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
Reid Spencer56521c42006-12-12 00:51:07 +00001545 return getCast(opcode, C, Ty);
1546}
1547
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001548Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
Chris Lattner03c49532007-01-15 02:27:26 +00001549 assert(C->getType()->isInteger() && "Trunc operand must be integer");
1550 assert(Ty->isInteger() && "Trunc produces only integral");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001551 assert(C->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()&&
1552 "SrcTy must be larger than DestTy for Trunc!");
1553
1554 return getFoldedCast(Instruction::Trunc, C, Ty);
1555}
1556
Reid Spencerbb65ebf2006-12-12 23:36:14 +00001557Constant *ConstantExpr::getSExt(Constant *C, const Type *Ty) {
Chris Lattner03c49532007-01-15 02:27:26 +00001558 assert(C->getType()->isInteger() && "SEXt operand must be integral");
1559 assert(Ty->isInteger() && "SExt produces only integer");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001560 assert(C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1561 "SrcTy must be smaller than DestTy for SExt!");
1562
1563 return getFoldedCast(Instruction::SExt, C, Ty);
Chris Lattnerdd284742004-04-04 23:20:30 +00001564}
1565
Reid Spencerbb65ebf2006-12-12 23:36:14 +00001566Constant *ConstantExpr::getZExt(Constant *C, const Type *Ty) {
Chris Lattner03c49532007-01-15 02:27:26 +00001567 assert(C->getType()->isInteger() && "ZEXt operand must be integral");
1568 assert(Ty->isInteger() && "ZExt produces only integer");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001569 assert(C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1570 "SrcTy must be smaller than DestTy for ZExt!");
1571
1572 return getFoldedCast(Instruction::ZExt, C, Ty);
1573}
1574
1575Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
1576 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1577 C->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()&&
1578 "This is an illegal floating point truncation!");
1579 return getFoldedCast(Instruction::FPTrunc, C, Ty);
1580}
1581
1582Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
1583 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1584 C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1585 "This is an illegal floating point extension!");
1586 return getFoldedCast(Instruction::FPExt, C, Ty);
1587}
1588
1589Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
Chris Lattner03c49532007-01-15 02:27:26 +00001590 assert(C->getType()->isInteger() && Ty->isFloatingPoint() &&
Reid Spencer2546b762007-01-26 07:37:34 +00001591 "This is an illegal i32 to floating point cast!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001592 return getFoldedCast(Instruction::UIToFP, C, Ty);
1593}
1594
1595Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
Chris Lattner03c49532007-01-15 02:27:26 +00001596 assert(C->getType()->isInteger() && Ty->isFloatingPoint() &&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001597 "This is an illegal sint to floating point cast!");
1598 return getFoldedCast(Instruction::SIToFP, C, Ty);
1599}
1600
1601Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
Chris Lattner03c49532007-01-15 02:27:26 +00001602 assert(C->getType()->isFloatingPoint() && Ty->isInteger() &&
Reid Spencer2546b762007-01-26 07:37:34 +00001603 "This is an illegal floating point to i32 cast!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001604 return getFoldedCast(Instruction::FPToUI, C, Ty);
1605}
1606
1607Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
Chris Lattner03c49532007-01-15 02:27:26 +00001608 assert(C->getType()->isFloatingPoint() && Ty->isInteger() &&
Reid Spencer2546b762007-01-26 07:37:34 +00001609 "This is an illegal floating point to i32 cast!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001610 return getFoldedCast(Instruction::FPToSI, C, Ty);
1611}
1612
1613Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
1614 assert(isa<PointerType>(C->getType()) && "PtrToInt source must be pointer");
Chris Lattner03c49532007-01-15 02:27:26 +00001615 assert(DstTy->isInteger() && "PtrToInt destination must be integral");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001616 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
1617}
1618
1619Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
Chris Lattner03c49532007-01-15 02:27:26 +00001620 assert(C->getType()->isInteger() && "IntToPtr source must be integral");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001621 assert(isa<PointerType>(DstTy) && "IntToPtr destination must be a pointer");
1622 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
1623}
1624
1625Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
1626 // BitCast implies a no-op cast of type only. No bits change. However, you
1627 // can't cast pointers to anything but pointers.
1628 const Type *SrcTy = C->getType();
1629 assert((isa<PointerType>(SrcTy) == isa<PointerType>(DstTy)) &&
Reid Spencer5c140882006-12-04 20:17:56 +00001630 "BitCast cannot cast pointer to non-pointer and vice versa");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001631
1632 // Now we know we're not dealing with mismatched pointer casts (ptr->nonptr
1633 // or nonptr->ptr). For all the other types, the cast is okay if source and
1634 // destination bit widths are identical.
1635 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1636 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
Reid Spencer5c140882006-12-04 20:17:56 +00001637 assert(SrcBitSize == DstBitSize && "BitCast requies types of same width");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001638 return getFoldedCast(Instruction::BitCast, C, DstTy);
Chris Lattnerdd284742004-04-04 23:20:30 +00001639}
1640
Alkis Evlogimenosda5de052004-10-24 01:41:10 +00001641Constant *ConstantExpr::getSizeOf(const Type *Ty) {
Chris Lattneracc4e542004-12-13 19:48:51 +00001642 // sizeof is implemented as: (ulong) gep (Ty*)null, 1
Chris Lattnerb5d70302007-02-19 20:01:23 +00001643 Constant *GEPIdx = ConstantInt::get(Type::Int32Ty, 1);
1644 Constant *GEP =
1645 getGetElementPtr(getNullValue(PointerType::get(Ty)), &GEPIdx, 1);
1646 return getCast(Instruction::PtrToInt, GEP, Type::Int64Ty);
Alkis Evlogimenos9160d5f2005-03-19 11:40:31 +00001647}
1648
Chris Lattnerb50d1352003-10-05 00:17:43 +00001649Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
Reid Spencera009d0d2006-12-04 21:35:24 +00001650 Constant *C1, Constant *C2) {
Chris Lattner38a9bcd2003-05-21 17:49:25 +00001651 // Check the operands for consistency first
Reid Spencer7eb55b32006-11-02 01:53:59 +00001652 assert(Opcode >= Instruction::BinaryOpsBegin &&
1653 Opcode < Instruction::BinaryOpsEnd &&
Chris Lattner38a9bcd2003-05-21 17:49:25 +00001654 "Invalid opcode in binary constant expression");
1655 assert(C1->getType() == C2->getType() &&
1656 "Operand types in binary constant expression should match");
Chris Lattnerb50d1352003-10-05 00:17:43 +00001657
Reid Spencer542964f2007-01-11 18:21:29 +00001658 if (ReqTy == C1->getType() || ReqTy == Type::Int1Ty)
Chris Lattnerb50d1352003-10-05 00:17:43 +00001659 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1660 return FC; // Fold a few common cases...
Chris Lattneracdbe712003-04-17 19:24:48 +00001661
Chris Lattner2b383d2e2003-05-13 21:37:02 +00001662 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
Reid Spencera009d0d2006-12-04 21:35:24 +00001663 ExprMapKeyType Key(Opcode, argVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001664 return ExprConstants->getOrCreate(ReqTy, Key);
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001665}
1666
Reid Spencer266e42b2006-12-23 06:05:41 +00001667Constant *ConstantExpr::getCompareTy(unsigned short predicate,
Reid Spencera009d0d2006-12-04 21:35:24 +00001668 Constant *C1, Constant *C2) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001669 switch (predicate) {
1670 default: assert(0 && "Invalid CmpInst predicate");
1671 case FCmpInst::FCMP_FALSE: case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_OGT:
1672 case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OLE:
1673 case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_ORD: case FCmpInst::FCMP_UNO:
1674 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UGT: case FCmpInst::FCMP_UGE:
1675 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_ULE: case FCmpInst::FCMP_UNE:
1676 case FCmpInst::FCMP_TRUE:
1677 return getFCmp(predicate, C1, C2);
1678 case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_UGT:
1679 case ICmpInst::ICMP_UGE: case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE:
1680 case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_SGE: case ICmpInst::ICMP_SLT:
1681 case ICmpInst::ICMP_SLE:
1682 return getICmp(predicate, C1, C2);
1683 }
Reid Spencera009d0d2006-12-04 21:35:24 +00001684}
1685
1686Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001687#ifndef NDEBUG
1688 switch (Opcode) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00001689 case Instruction::Add:
1690 case Instruction::Sub:
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001691 case Instruction::Mul:
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001692 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Chris Lattner03c49532007-01-15 02:27:26 +00001693 assert((C1->getType()->isInteger() || C1->getType()->isFloatingPoint() ||
Reid Spencerd84d35b2007-02-15 02:26:10 +00001694 isa<VectorType>(C1->getType())) &&
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001695 "Tried to create an arithmetic operation on a non-arithmetic type!");
1696 break;
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001697 case Instruction::UDiv:
1698 case Instruction::SDiv:
1699 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00001700 assert((C1->getType()->isInteger() || (isa<VectorType>(C1->getType()) &&
1701 cast<VectorType>(C1->getType())->getElementType()->isInteger())) &&
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001702 "Tried to create an arithmetic operation on a non-arithmetic type!");
1703 break;
1704 case Instruction::FDiv:
1705 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00001706 assert((C1->getType()->isFloatingPoint() || (isa<VectorType>(C1->getType())
1707 && cast<VectorType>(C1->getType())->getElementType()->isFloatingPoint()))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001708 && "Tried to create an arithmetic operation on a non-arithmetic type!");
1709 break;
Reid Spencer7eb55b32006-11-02 01:53:59 +00001710 case Instruction::URem:
1711 case Instruction::SRem:
1712 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00001713 assert((C1->getType()->isInteger() || (isa<VectorType>(C1->getType()) &&
1714 cast<VectorType>(C1->getType())->getElementType()->isInteger())) &&
Reid Spencer7eb55b32006-11-02 01:53:59 +00001715 "Tried to create an arithmetic operation on a non-arithmetic type!");
1716 break;
1717 case Instruction::FRem:
1718 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00001719 assert((C1->getType()->isFloatingPoint() || (isa<VectorType>(C1->getType())
1720 && cast<VectorType>(C1->getType())->getElementType()->isFloatingPoint()))
Reid Spencer7eb55b32006-11-02 01:53:59 +00001721 && "Tried to create an arithmetic operation on a non-arithmetic type!");
1722 break;
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001723 case Instruction::And:
1724 case Instruction::Or:
1725 case Instruction::Xor:
1726 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00001727 assert((C1->getType()->isInteger() || isa<VectorType>(C1->getType())) &&
Misha Brukman3852f652005-01-27 06:46:38 +00001728 "Tried to create a logical operation on a non-integral type!");
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001729 break;
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001730 case Instruction::Shl:
Reid Spencerfdff9382006-11-08 06:47:33 +00001731 case Instruction::LShr:
1732 case Instruction::AShr:
Reid Spencer2341c222007-02-02 02:16:23 +00001733 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Chris Lattner03c49532007-01-15 02:27:26 +00001734 assert(C1->getType()->isInteger() &&
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001735 "Tried to create a shift operation on a non-integer type!");
1736 break;
1737 default:
1738 break;
1739 }
1740#endif
1741
Reid Spencera009d0d2006-12-04 21:35:24 +00001742 return getTy(C1->getType(), Opcode, C1, C2);
1743}
1744
Reid Spencer266e42b2006-12-23 06:05:41 +00001745Constant *ConstantExpr::getCompare(unsigned short pred,
Reid Spencera009d0d2006-12-04 21:35:24 +00001746 Constant *C1, Constant *C2) {
1747 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Reid Spencer266e42b2006-12-23 06:05:41 +00001748 return getCompareTy(pred, C1, C2);
Chris Lattner29ca2c62004-08-04 18:50:09 +00001749}
1750
Chris Lattner6e415c02004-03-12 05:54:04 +00001751Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
1752 Constant *V1, Constant *V2) {
Reid Spencer2546b762007-01-26 07:37:34 +00001753 assert(C->getType() == Type::Int1Ty && "Select condition must be i1!");
Chris Lattner6e415c02004-03-12 05:54:04 +00001754 assert(V1->getType() == V2->getType() && "Select value types must match!");
1755 assert(V1->getType()->isFirstClassType() && "Cannot select aggregate type!");
1756
1757 if (ReqTy == V1->getType())
1758 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1759 return SC; // Fold common cases
1760
1761 std::vector<Constant*> argVec(3, C);
1762 argVec[1] = V1;
1763 argVec[2] = V2;
Reid Spenceree3c9912006-12-04 05:19:50 +00001764 ExprMapKeyType Key(Instruction::Select, argVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001765 return ExprConstants->getOrCreate(ReqTy, Key);
Chris Lattner6e415c02004-03-12 05:54:04 +00001766}
1767
Chris Lattnerb50d1352003-10-05 00:17:43 +00001768Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
Chris Lattner302116a2007-01-31 04:40:28 +00001769 Value* const *Idxs,
1770 unsigned NumIdx) {
1771 assert(GetElementPtrInst::getIndexedType(C->getType(), Idxs, NumIdx, true) &&
Chris Lattner04b60fe2004-02-16 20:46:13 +00001772 "GEP indices invalid!");
1773
Chris Lattner302116a2007-01-31 04:40:28 +00001774 if (Constant *FC = ConstantFoldGetElementPtr(C, (Constant**)Idxs, NumIdx))
Chris Lattneracdbe712003-04-17 19:24:48 +00001775 return FC; // Fold a few common cases...
Chris Lattner04b60fe2004-02-16 20:46:13 +00001776
Chris Lattnerb50d1352003-10-05 00:17:43 +00001777 assert(isa<PointerType>(C->getType()) &&
Chris Lattner98fa07b2003-05-23 20:03:32 +00001778 "Non-pointer type for constant GetElementPtr expression");
Vikram S. Adve4c485332002-07-15 18:19:33 +00001779 // Look up the constant in the table first to ensure uniqueness
Chris Lattner13128ab2004-10-11 22:52:25 +00001780 std::vector<Constant*> ArgVec;
Chris Lattner302116a2007-01-31 04:40:28 +00001781 ArgVec.reserve(NumIdx+1);
Chris Lattner13128ab2004-10-11 22:52:25 +00001782 ArgVec.push_back(C);
Chris Lattner302116a2007-01-31 04:40:28 +00001783 for (unsigned i = 0; i != NumIdx; ++i)
1784 ArgVec.push_back(cast<Constant>(Idxs[i]));
1785 const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001786 return ExprConstants->getOrCreate(ReqTy, Key);
Vikram S. Adve4c485332002-07-15 18:19:33 +00001787}
1788
Chris Lattner302116a2007-01-31 04:40:28 +00001789Constant *ConstantExpr::getGetElementPtr(Constant *C, Value* const *Idxs,
1790 unsigned NumIdx) {
Chris Lattnerb50d1352003-10-05 00:17:43 +00001791 // Get the result type of the getelementptr!
Chris Lattner302116a2007-01-31 04:40:28 +00001792 const Type *Ty =
1793 GetElementPtrInst::getIndexedType(C->getType(), Idxs, NumIdx, true);
Chris Lattnerb50d1352003-10-05 00:17:43 +00001794 assert(Ty && "GEP indices invalid!");
Chris Lattner302116a2007-01-31 04:40:28 +00001795 return getGetElementPtrTy(PointerType::get(Ty), C, Idxs, NumIdx);
Chris Lattner13128ab2004-10-11 22:52:25 +00001796}
1797
Chris Lattner302116a2007-01-31 04:40:28 +00001798Constant *ConstantExpr::getGetElementPtr(Constant *C, Constant* const *Idxs,
1799 unsigned NumIdx) {
1800 return getGetElementPtr(C, (Value* const *)Idxs, NumIdx);
Chris Lattnerb50d1352003-10-05 00:17:43 +00001801}
1802
Chris Lattner302116a2007-01-31 04:40:28 +00001803
Reid Spenceree3c9912006-12-04 05:19:50 +00001804Constant *
1805ConstantExpr::getICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1806 assert(LHS->getType() == RHS->getType());
1807 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
1808 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
1809
Reid Spencer266e42b2006-12-23 06:05:41 +00001810 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
Reid Spenceree3c9912006-12-04 05:19:50 +00001811 return FC; // Fold a few common cases...
1812
1813 // Look up the constant in the table first to ensure uniqueness
1814 std::vector<Constant*> ArgVec;
1815 ArgVec.push_back(LHS);
1816 ArgVec.push_back(RHS);
Reid Spencerb1537492006-12-24 18:42:29 +00001817 // Get the key type with both the opcode and predicate
Reid Spenceree3c9912006-12-04 05:19:50 +00001818 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
Reid Spencer542964f2007-01-11 18:21:29 +00001819 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
Reid Spenceree3c9912006-12-04 05:19:50 +00001820}
1821
1822Constant *
1823ConstantExpr::getFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1824 assert(LHS->getType() == RHS->getType());
1825 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
1826
Reid Spencer266e42b2006-12-23 06:05:41 +00001827 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
Reid Spenceree3c9912006-12-04 05:19:50 +00001828 return FC; // Fold a few common cases...
1829
1830 // Look up the constant in the table first to ensure uniqueness
1831 std::vector<Constant*> ArgVec;
1832 ArgVec.push_back(LHS);
1833 ArgVec.push_back(RHS);
Reid Spencerb1537492006-12-24 18:42:29 +00001834 // Get the key type with both the opcode and predicate
Reid Spenceree3c9912006-12-04 05:19:50 +00001835 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
Reid Spencer542964f2007-01-11 18:21:29 +00001836 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
Reid Spenceree3c9912006-12-04 05:19:50 +00001837}
1838
Robert Bocchino23004482006-01-10 19:05:34 +00001839Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
1840 Constant *Idx) {
Robert Bocchinode7f1c92006-01-10 20:03:46 +00001841 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
1842 return FC; // Fold a few common cases...
Robert Bocchino23004482006-01-10 19:05:34 +00001843 // Look up the constant in the table first to ensure uniqueness
1844 std::vector<Constant*> ArgVec(1, Val);
1845 ArgVec.push_back(Idx);
Reid Spenceree3c9912006-12-04 05:19:50 +00001846 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001847 return ExprConstants->getOrCreate(ReqTy, Key);
Robert Bocchino23004482006-01-10 19:05:34 +00001848}
1849
1850Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001851 assert(isa<VectorType>(Val->getType()) &&
Reid Spencer09575ba2007-02-15 03:39:18 +00001852 "Tried to create extractelement operation on non-vector type!");
Reid Spencer8d9336d2006-12-31 05:26:44 +00001853 assert(Idx->getType() == Type::Int32Ty &&
Reid Spencer2546b762007-01-26 07:37:34 +00001854 "Extractelement index must be i32 type!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00001855 return getExtractElementTy(cast<VectorType>(Val->getType())->getElementType(),
Robert Bocchino23004482006-01-10 19:05:34 +00001856 Val, Idx);
1857}
Chris Lattnerb50d1352003-10-05 00:17:43 +00001858
Robert Bocchinoca27f032006-01-17 20:07:22 +00001859Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
1860 Constant *Elt, Constant *Idx) {
1861 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
1862 return FC; // Fold a few common cases...
1863 // Look up the constant in the table first to ensure uniqueness
1864 std::vector<Constant*> ArgVec(1, Val);
1865 ArgVec.push_back(Elt);
1866 ArgVec.push_back(Idx);
Reid Spenceree3c9912006-12-04 05:19:50 +00001867 const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001868 return ExprConstants->getOrCreate(ReqTy, Key);
Robert Bocchinoca27f032006-01-17 20:07:22 +00001869}
1870
1871Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
1872 Constant *Idx) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001873 assert(isa<VectorType>(Val->getType()) &&
Reid Spencer09575ba2007-02-15 03:39:18 +00001874 "Tried to create insertelement operation on non-vector type!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00001875 assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType()
Robert Bocchinoca27f032006-01-17 20:07:22 +00001876 && "Insertelement types must match!");
Reid Spencer8d9336d2006-12-31 05:26:44 +00001877 assert(Idx->getType() == Type::Int32Ty &&
Reid Spencer2546b762007-01-26 07:37:34 +00001878 "Insertelement index must be i32 type!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00001879 return getInsertElementTy(cast<VectorType>(Val->getType())->getElementType(),
Robert Bocchinoca27f032006-01-17 20:07:22 +00001880 Val, Elt, Idx);
1881}
1882
Chris Lattnerbbe0a422006-04-08 01:18:18 +00001883Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
1884 Constant *V2, Constant *Mask) {
1885 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
1886 return FC; // Fold a few common cases...
1887 // Look up the constant in the table first to ensure uniqueness
1888 std::vector<Constant*> ArgVec(1, V1);
1889 ArgVec.push_back(V2);
1890 ArgVec.push_back(Mask);
Reid Spenceree3c9912006-12-04 05:19:50 +00001891 const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001892 return ExprConstants->getOrCreate(ReqTy, Key);
Chris Lattnerbbe0a422006-04-08 01:18:18 +00001893}
1894
1895Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
1896 Constant *Mask) {
1897 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
1898 "Invalid shuffle vector constant expr operands!");
1899 return getShuffleVectorTy(V1->getType(), V1, V2, Mask);
1900}
1901
Reid Spencer2eadb532007-01-21 00:29:26 +00001902Constant *ConstantExpr::getZeroValueForNegationExpr(const Type *Ty) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001903 if (const VectorType *PTy = dyn_cast<VectorType>(Ty))
Reid Spencer6598ca82007-01-21 02:29:10 +00001904 if (PTy->getElementType()->isFloatingPoint()) {
1905 std::vector<Constant*> zeros(PTy->getNumElements(),
1906 ConstantFP::get(PTy->getElementType(),-0.0));
Reid Spencerd84d35b2007-02-15 02:26:10 +00001907 return ConstantVector::get(PTy, zeros);
Reid Spencer6598ca82007-01-21 02:29:10 +00001908 }
Reid Spencer2eadb532007-01-21 00:29:26 +00001909
1910 if (Ty->isFloatingPoint())
1911 return ConstantFP::get(Ty, -0.0);
1912
1913 return Constant::getNullValue(Ty);
1914}
1915
Vikram S. Adve4c485332002-07-15 18:19:33 +00001916// destroyConstant - Remove the constant from the constant table...
1917//
1918void ConstantExpr::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00001919 ExprConstants->remove(this);
Vikram S. Adve4c485332002-07-15 18:19:33 +00001920 destroyConstantImpl();
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001921}
1922
Chris Lattner3cd8c562002-07-30 18:54:25 +00001923const char *ConstantExpr::getOpcodeName() const {
1924 return Instruction::getOpcodeName(getOpcode());
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001925}
Reid Spencer1ebe1ab2004-07-17 23:48:33 +00001926
Chris Lattnerc4062ba2005-10-03 21:58:36 +00001927//===----------------------------------------------------------------------===//
1928// replaceUsesOfWithOnConstant implementations
1929
Chris Lattner913849b2007-08-21 00:55:23 +00001930/// replaceUsesOfWithOnConstant - Update this constant array to change uses of
1931/// 'From' to be uses of 'To'. This must update the uniquing data structures
1932/// etc.
1933///
1934/// Note that we intentionally replace all uses of From with To here. Consider
1935/// a large array that uses 'From' 1000 times. By handling this case all here,
1936/// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
1937/// single invocation handles all 1000 uses. Handling them one at a time would
1938/// work, but would be really slow because it would have to unique each updated
1939/// array instance.
Chris Lattnerc4062ba2005-10-03 21:58:36 +00001940void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
Chris Lattner7a1450d2005-10-04 18:13:04 +00001941 Use *U) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00001942 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
Chris Lattner8760ec72005-10-04 01:17:50 +00001943 Constant *ToC = cast<Constant>(To);
Chris Lattnerdff59112005-10-04 18:47:09 +00001944
Jim Laskeyc03caef2006-07-17 17:38:29 +00001945 std::pair<ArrayConstantsTy::MapKey, Constant*> Lookup;
Chris Lattnerb64419a2005-10-03 22:51:37 +00001946 Lookup.first.first = getType();
1947 Lookup.second = this;
Chris Lattnerdff59112005-10-04 18:47:09 +00001948
Chris Lattnerb64419a2005-10-03 22:51:37 +00001949 std::vector<Constant*> &Values = Lookup.first.second;
1950 Values.reserve(getNumOperands()); // Build replacement array.
Chris Lattnerdff59112005-10-04 18:47:09 +00001951
Chris Lattner8760ec72005-10-04 01:17:50 +00001952 // Fill values with the modified operands of the constant array. Also,
1953 // compute whether this turns into an all-zeros array.
Chris Lattnerdff59112005-10-04 18:47:09 +00001954 bool isAllZeros = false;
Chris Lattner913849b2007-08-21 00:55:23 +00001955 unsigned NumUpdated = 0;
Chris Lattnerdff59112005-10-04 18:47:09 +00001956 if (!ToC->isNullValue()) {
Chris Lattner913849b2007-08-21 00:55:23 +00001957 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1958 Constant *Val = cast<Constant>(O->get());
1959 if (Val == From) {
1960 Val = ToC;
1961 ++NumUpdated;
1962 }
1963 Values.push_back(Val);
1964 }
Chris Lattnerdff59112005-10-04 18:47:09 +00001965 } else {
1966 isAllZeros = true;
1967 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1968 Constant *Val = cast<Constant>(O->get());
Chris Lattner913849b2007-08-21 00:55:23 +00001969 if (Val == From) {
1970 Val = ToC;
1971 ++NumUpdated;
1972 }
Chris Lattnerdff59112005-10-04 18:47:09 +00001973 Values.push_back(Val);
1974 if (isAllZeros) isAllZeros = Val->isNullValue();
1975 }
Chris Lattnerc4062ba2005-10-03 21:58:36 +00001976 }
1977
Chris Lattnerb64419a2005-10-03 22:51:37 +00001978 Constant *Replacement = 0;
1979 if (isAllZeros) {
1980 Replacement = ConstantAggregateZero::get(getType());
1981 } else {
1982 // Check to see if we have this array type already.
1983 bool Exists;
Jim Laskeyc03caef2006-07-17 17:38:29 +00001984 ArrayConstantsTy::MapTy::iterator I =
Chris Lattner69edc982006-09-28 00:35:06 +00001985 ArrayConstants->InsertOrGetItem(Lookup, Exists);
Chris Lattnerb64419a2005-10-03 22:51:37 +00001986
1987 if (Exists) {
1988 Replacement = I->second;
1989 } else {
1990 // Okay, the new shape doesn't exist in the system yet. Instead of
1991 // creating a new constant array, inserting it, replaceallusesof'ing the
1992 // old with the new, then deleting the old... just update the current one
1993 // in place!
Chris Lattner69edc982006-09-28 00:35:06 +00001994 ArrayConstants->MoveConstantToNewSlot(this, I);
Chris Lattnerb64419a2005-10-03 22:51:37 +00001995
Chris Lattner913849b2007-08-21 00:55:23 +00001996 // Update to the new value. Optimize for the case when we have a single
1997 // operand that we're changing, but handle bulk updates efficiently.
1998 if (NumUpdated == 1) {
1999 unsigned OperandToUpdate = U-OperandList;
2000 assert(getOperand(OperandToUpdate) == From &&
2001 "ReplaceAllUsesWith broken!");
2002 setOperand(OperandToUpdate, ToC);
2003 } else {
2004 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2005 if (getOperand(i) == From)
2006 setOperand(i, ToC);
2007 }
Chris Lattnerb64419a2005-10-03 22:51:37 +00002008 return;
2009 }
2010 }
2011
2012 // Otherwise, I do need to replace this with an existing value.
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002013 assert(Replacement != this && "I didn't contain From!");
2014
Chris Lattner7a1450d2005-10-04 18:13:04 +00002015 // Everyone using this now uses the replacement.
2016 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002017
2018 // Delete the old constant!
2019 destroyConstant();
2020}
2021
2022void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
Chris Lattner7a1450d2005-10-04 18:13:04 +00002023 Use *U) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002024 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
Chris Lattner8760ec72005-10-04 01:17:50 +00002025 Constant *ToC = cast<Constant>(To);
2026
Chris Lattnerdff59112005-10-04 18:47:09 +00002027 unsigned OperandToUpdate = U-OperandList;
2028 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
2029
Jim Laskeyc03caef2006-07-17 17:38:29 +00002030 std::pair<StructConstantsTy::MapKey, Constant*> Lookup;
Chris Lattner8760ec72005-10-04 01:17:50 +00002031 Lookup.first.first = getType();
2032 Lookup.second = this;
2033 std::vector<Constant*> &Values = Lookup.first.second;
2034 Values.reserve(getNumOperands()); // Build replacement struct.
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002035
Chris Lattnerdff59112005-10-04 18:47:09 +00002036
Chris Lattner8760ec72005-10-04 01:17:50 +00002037 // Fill values with the modified operands of the constant struct. Also,
2038 // compute whether this turns into an all-zeros struct.
Chris Lattnerdff59112005-10-04 18:47:09 +00002039 bool isAllZeros = false;
2040 if (!ToC->isNullValue()) {
2041 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
2042 Values.push_back(cast<Constant>(O->get()));
2043 } else {
2044 isAllZeros = true;
2045 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2046 Constant *Val = cast<Constant>(O->get());
2047 Values.push_back(Val);
2048 if (isAllZeros) isAllZeros = Val->isNullValue();
2049 }
Chris Lattner8760ec72005-10-04 01:17:50 +00002050 }
Chris Lattnerdff59112005-10-04 18:47:09 +00002051 Values[OperandToUpdate] = ToC;
2052
Chris Lattner8760ec72005-10-04 01:17:50 +00002053 Constant *Replacement = 0;
2054 if (isAllZeros) {
2055 Replacement = ConstantAggregateZero::get(getType());
2056 } else {
2057 // Check to see if we have this array type already.
2058 bool Exists;
Jim Laskeyc03caef2006-07-17 17:38:29 +00002059 StructConstantsTy::MapTy::iterator I =
Chris Lattner69edc982006-09-28 00:35:06 +00002060 StructConstants->InsertOrGetItem(Lookup, Exists);
Chris Lattner8760ec72005-10-04 01:17:50 +00002061
2062 if (Exists) {
2063 Replacement = I->second;
2064 } else {
2065 // Okay, the new shape doesn't exist in the system yet. Instead of
2066 // creating a new constant struct, inserting it, replaceallusesof'ing the
2067 // old with the new, then deleting the old... just update the current one
2068 // in place!
Chris Lattner69edc982006-09-28 00:35:06 +00002069 StructConstants->MoveConstantToNewSlot(this, I);
Chris Lattner8760ec72005-10-04 01:17:50 +00002070
Chris Lattnerdff59112005-10-04 18:47:09 +00002071 // Update to the new value.
2072 setOperand(OperandToUpdate, ToC);
Chris Lattner8760ec72005-10-04 01:17:50 +00002073 return;
2074 }
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002075 }
2076
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002077 assert(Replacement != this && "I didn't contain From!");
2078
Chris Lattner7a1450d2005-10-04 18:13:04 +00002079 // Everyone using this now uses the replacement.
2080 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002081
2082 // Delete the old constant!
2083 destroyConstant();
2084}
2085
Reid Spencerd84d35b2007-02-15 02:26:10 +00002086void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
Chris Lattner7a1450d2005-10-04 18:13:04 +00002087 Use *U) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002088 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2089
2090 std::vector<Constant*> Values;
2091 Values.reserve(getNumOperands()); // Build replacement array...
2092 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2093 Constant *Val = getOperand(i);
2094 if (Val == From) Val = cast<Constant>(To);
2095 Values.push_back(Val);
2096 }
2097
Reid Spencerd84d35b2007-02-15 02:26:10 +00002098 Constant *Replacement = ConstantVector::get(getType(), Values);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002099 assert(Replacement != this && "I didn't contain From!");
2100
Chris Lattner7a1450d2005-10-04 18:13:04 +00002101 // Everyone using this now uses the replacement.
2102 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002103
2104 // Delete the old constant!
2105 destroyConstant();
2106}
2107
2108void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
Chris Lattner7a1450d2005-10-04 18:13:04 +00002109 Use *U) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002110 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2111 Constant *To = cast<Constant>(ToV);
2112
2113 Constant *Replacement = 0;
2114 if (getOpcode() == Instruction::GetElementPtr) {
Chris Lattnerb5d70302007-02-19 20:01:23 +00002115 SmallVector<Constant*, 8> Indices;
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002116 Constant *Pointer = getOperand(0);
2117 Indices.reserve(getNumOperands()-1);
2118 if (Pointer == From) Pointer = To;
2119
2120 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2121 Constant *Val = getOperand(i);
2122 if (Val == From) Val = To;
2123 Indices.push_back(Val);
2124 }
Chris Lattnerb5d70302007-02-19 20:01:23 +00002125 Replacement = ConstantExpr::getGetElementPtr(Pointer,
2126 &Indices[0], Indices.size());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002127 } else if (isCast()) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002128 assert(getOperand(0) == From && "Cast only has one use!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002129 Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002130 } else if (getOpcode() == Instruction::Select) {
2131 Constant *C1 = getOperand(0);
2132 Constant *C2 = getOperand(1);
2133 Constant *C3 = getOperand(2);
2134 if (C1 == From) C1 = To;
2135 if (C2 == From) C2 = To;
2136 if (C3 == From) C3 = To;
2137 Replacement = ConstantExpr::getSelect(C1, C2, C3);
Robert Bocchino23004482006-01-10 19:05:34 +00002138 } else if (getOpcode() == Instruction::ExtractElement) {
2139 Constant *C1 = getOperand(0);
2140 Constant *C2 = getOperand(1);
2141 if (C1 == From) C1 = To;
2142 if (C2 == From) C2 = To;
2143 Replacement = ConstantExpr::getExtractElement(C1, C2);
Chris Lattnera93b4b52006-04-08 05:09:48 +00002144 } else if (getOpcode() == Instruction::InsertElement) {
2145 Constant *C1 = getOperand(0);
2146 Constant *C2 = getOperand(1);
2147 Constant *C3 = getOperand(1);
2148 if (C1 == From) C1 = To;
2149 if (C2 == From) C2 = To;
2150 if (C3 == From) C3 = To;
2151 Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2152 } else if (getOpcode() == Instruction::ShuffleVector) {
2153 Constant *C1 = getOperand(0);
2154 Constant *C2 = getOperand(1);
2155 Constant *C3 = getOperand(2);
2156 if (C1 == From) C1 = To;
2157 if (C2 == From) C2 = To;
2158 if (C3 == From) C3 = To;
2159 Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
Reid Spenceree3c9912006-12-04 05:19:50 +00002160 } else if (isCompare()) {
2161 Constant *C1 = getOperand(0);
2162 Constant *C2 = getOperand(1);
2163 if (C1 == From) C1 = To;
2164 if (C2 == From) C2 = To;
2165 if (getOpcode() == Instruction::ICmp)
2166 Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
2167 else
2168 Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002169 } else if (getNumOperands() == 2) {
2170 Constant *C1 = getOperand(0);
2171 Constant *C2 = getOperand(1);
2172 if (C1 == From) C1 = To;
2173 if (C2 == From) C2 = To;
2174 Replacement = ConstantExpr::get(getOpcode(), C1, C2);
2175 } else {
2176 assert(0 && "Unknown ConstantExpr type!");
2177 return;
2178 }
2179
2180 assert(Replacement != this && "I didn't contain From!");
2181
Chris Lattner7a1450d2005-10-04 18:13:04 +00002182 // Everyone using this now uses the replacement.
2183 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002184
2185 // Delete the old constant!
2186 destroyConstant();
2187}
2188
2189
Jim Laskey2698f0d2006-03-08 18:11:07 +00002190/// getStringValue - Turn an LLVM constant pointer that eventually points to a
2191/// global into a string value. Return an empty string if we can't do it.
Evan Cheng38280c02006-03-10 23:52:03 +00002192/// Parameter Chop determines if the result is chopped at the first null
2193/// terminator.
Jim Laskey2698f0d2006-03-08 18:11:07 +00002194///
Evan Cheng38280c02006-03-10 23:52:03 +00002195std::string Constant::getStringValue(bool Chop, unsigned Offset) {
Jim Laskey2698f0d2006-03-08 18:11:07 +00002196 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(this)) {
2197 if (GV->hasInitializer() && isa<ConstantArray>(GV->getInitializer())) {
2198 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
2199 if (Init->isString()) {
2200 std::string Result = Init->getAsString();
2201 if (Offset < Result.size()) {
2202 // If we are pointing INTO The string, erase the beginning...
2203 Result.erase(Result.begin(), Result.begin()+Offset);
2204
2205 // Take off the null terminator, and any string fragments after it.
Evan Cheng38280c02006-03-10 23:52:03 +00002206 if (Chop) {
2207 std::string::size_type NullPos = Result.find_first_of((char)0);
2208 if (NullPos != std::string::npos)
2209 Result.erase(Result.begin()+NullPos, Result.end());
2210 }
Jim Laskey2698f0d2006-03-08 18:11:07 +00002211 return Result;
2212 }
2213 }
2214 }
2215 } else if (Constant *C = dyn_cast<Constant>(this)) {
2216 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
Evan Cheng2c5e5302006-03-11 00:13:10 +00002217 return GV->getStringValue(Chop, Offset);
Jim Laskey2698f0d2006-03-08 18:11:07 +00002218 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2219 if (CE->getOpcode() == Instruction::GetElementPtr) {
2220 // Turn a gep into the specified offset.
2221 if (CE->getNumOperands() == 3 &&
2222 cast<Constant>(CE->getOperand(1))->isNullValue() &&
2223 isa<ConstantInt>(CE->getOperand(2))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002224 Offset += cast<ConstantInt>(CE->getOperand(2))->getZExtValue();
Evan Cheng2c5e5302006-03-11 00:13:10 +00002225 return CE->getOperand(0)->getStringValue(Chop, Offset);
Jim Laskey2698f0d2006-03-08 18:11:07 +00002226 }
2227 }
2228 }
2229 }
2230 return "";
2231}