blob: dc3d9935d6922187e9ad5c2170c6a6d565d3d885 [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 Lattner5a945e32004-01-12 21:13:12 +000015#include "ConstantFolding.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 Lattner2f7c9632001-06-06 20:29:01 +000019#include "llvm/SymbolTable.h"
Chris Lattnerd7a73302001-10-13 06:57:33 +000020#include "llvm/Module.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000021#include "llvm/ADT/StringExtras.h"
Chris Lattner3d27be12006-08-27 12:54:02 +000022#include "llvm/Support/Compiler.h"
Bill Wendling6a462f12006-11-17 08:03:48 +000023#include "llvm/Support/Debug.h"
Chris Lattner69edc982006-09-28 00:35:06 +000024#include "llvm/Support/ManagedStatic.h"
Bill Wendling6a462f12006-11-17 08:03:48 +000025#include "llvm/Support/MathExtras.h"
Chris Lattner2f7c9632001-06-06 20:29:01 +000026#include <algorithm>
Chris Lattner189d19f2003-11-21 20:23:48 +000027using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000028
Chris Lattner2f7c9632001-06-06 20:29:01 +000029//===----------------------------------------------------------------------===//
Chris Lattner3462ae32001-12-03 22:26:30 +000030// Constant Class
Chris Lattner2f7c9632001-06-06 20:29:01 +000031//===----------------------------------------------------------------------===//
32
Chris Lattner3462ae32001-12-03 22:26:30 +000033void Constant::destroyConstantImpl() {
34 // When a Constant is destroyed, there may be lingering
Chris Lattnerd7a73302001-10-13 06:57:33 +000035 // references to the constant by other constants in the constant pool. These
Misha Brukmanbe372b92003-08-21 22:14:26 +000036 // constants are implicitly dependent on the module that is being deleted,
Chris Lattnerd7a73302001-10-13 06:57:33 +000037 // but they don't know that. Because we only find out when the CPV is
38 // deleted, we must now notify all of our users (that should only be
Chris Lattner3462ae32001-12-03 22:26:30 +000039 // Constants) that they are, in fact, invalid now and should be deleted.
Chris Lattnerd7a73302001-10-13 06:57:33 +000040 //
41 while (!use_empty()) {
42 Value *V = use_back();
43#ifndef NDEBUG // Only in -g mode...
Chris Lattnerd9f4ac662002-07-18 00:14:50 +000044 if (!isa<Constant>(V))
Bill Wendling6a462f12006-11-17 08:03:48 +000045 DOUT << "While deleting: " << *this
46 << "\n\nUse still stuck around after Def is destroyed: "
47 << *V << "\n\n";
Chris Lattnerd7a73302001-10-13 06:57:33 +000048#endif
Vikram S. Adve4e537b22002-07-14 23:13:17 +000049 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
Reid Spencer1ebe1ab2004-07-17 23:48:33 +000050 Constant *CV = cast<Constant>(V);
51 CV->destroyConstant();
Chris Lattnerd7a73302001-10-13 06:57:33 +000052
53 // The constant should remove itself from our use list...
Vikram S. Adve4e537b22002-07-14 23:13:17 +000054 assert((use_empty() || use_back() != V) && "Constant not removed!");
Chris Lattnerd7a73302001-10-13 06:57:33 +000055 }
56
57 // Value has no outstanding references it is safe to delete it now...
58 delete this;
Chris Lattner38569342001-10-01 20:11:19 +000059}
Chris Lattner2f7c9632001-06-06 20:29:01 +000060
Chris Lattner23dd1f62006-10-20 00:27:06 +000061/// canTrap - Return true if evaluation of this constant could trap. This is
62/// true for things like constant expressions that could divide by zero.
63bool Constant::canTrap() const {
64 assert(getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
65 // The only thing that could possibly trap are constant exprs.
66 const ConstantExpr *CE = dyn_cast<ConstantExpr>(this);
67 if (!CE) return false;
68
69 // ConstantExpr traps if any operands can trap.
70 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
71 if (getOperand(i)->canTrap())
72 return true;
73
74 // Otherwise, only specific operations can trap.
75 switch (CE->getOpcode()) {
76 default:
77 return false;
Reid Spencer7e80b0b2006-10-26 06:15:43 +000078 case Instruction::UDiv:
79 case Instruction::SDiv:
80 case Instruction::FDiv:
Reid Spencer7eb55b32006-11-02 01:53:59 +000081 case Instruction::URem:
82 case Instruction::SRem:
83 case Instruction::FRem:
Chris Lattner23dd1f62006-10-20 00:27:06 +000084 // Div and rem can trap if the RHS is not known to be non-zero.
85 if (!isa<ConstantInt>(getOperand(1)) || getOperand(1)->isNullValue())
86 return true;
87 return false;
88 }
89}
90
91
Chris Lattnerb1585a92002-08-13 17:50:20 +000092// Static constructor to create a '0' constant of arbitrary type...
93Constant *Constant::getNullValue(const Type *Ty) {
Chris Lattner6b727592004-06-17 18:19:28 +000094 switch (Ty->getTypeID()) {
Chris Lattner3e88ef92003-10-03 19:34:51 +000095 case Type::BoolTyID: {
96 static Constant *NullBool = ConstantBool::get(false);
97 return NullBool;
98 }
99 case Type::SByteTyID: {
Reid Spencere0fc4df2006-10-20 07:07:24 +0000100 static Constant *NullSByte = ConstantInt::get(Type::SByteTy, 0);
Chris Lattner3e88ef92003-10-03 19:34:51 +0000101 return NullSByte;
102 }
103 case Type::UByteTyID: {
Reid Spencere0fc4df2006-10-20 07:07:24 +0000104 static Constant *NullUByte = ConstantInt::get(Type::UByteTy, 0);
Chris Lattner3e88ef92003-10-03 19:34:51 +0000105 return NullUByte;
106 }
107 case Type::ShortTyID: {
Reid Spencere0fc4df2006-10-20 07:07:24 +0000108 static Constant *NullShort = ConstantInt::get(Type::ShortTy, 0);
Chris Lattner3e88ef92003-10-03 19:34:51 +0000109 return NullShort;
110 }
111 case Type::UShortTyID: {
Reid Spencere0fc4df2006-10-20 07:07:24 +0000112 static Constant *NullUShort = ConstantInt::get(Type::UShortTy, 0);
Chris Lattner3e88ef92003-10-03 19:34:51 +0000113 return NullUShort;
114 }
115 case Type::IntTyID: {
Reid Spencere0fc4df2006-10-20 07:07:24 +0000116 static Constant *NullInt = ConstantInt::get(Type::IntTy, 0);
Chris Lattner3e88ef92003-10-03 19:34:51 +0000117 return NullInt;
118 }
119 case Type::UIntTyID: {
Reid Spencere0fc4df2006-10-20 07:07:24 +0000120 static Constant *NullUInt = ConstantInt::get(Type::UIntTy, 0);
Chris Lattner3e88ef92003-10-03 19:34:51 +0000121 return NullUInt;
122 }
123 case Type::LongTyID: {
Reid Spencere0fc4df2006-10-20 07:07:24 +0000124 static Constant *NullLong = ConstantInt::get(Type::LongTy, 0);
Chris Lattner3e88ef92003-10-03 19:34:51 +0000125 return NullLong;
126 }
127 case Type::ULongTyID: {
Reid Spencere0fc4df2006-10-20 07:07:24 +0000128 static Constant *NullULong = ConstantInt::get(Type::ULongTy, 0);
Chris Lattner3e88ef92003-10-03 19:34:51 +0000129 return NullULong;
130 }
Chris Lattnerb1585a92002-08-13 17:50:20 +0000131
Chris Lattner3e88ef92003-10-03 19:34:51 +0000132 case Type::FloatTyID: {
133 static Constant *NullFloat = ConstantFP::get(Type::FloatTy, 0);
134 return NullFloat;
135 }
136 case Type::DoubleTyID: {
137 static Constant *NullDouble = ConstantFP::get(Type::DoubleTy, 0);
138 return NullDouble;
139 }
Chris Lattnerb1585a92002-08-13 17:50:20 +0000140
Misha Brukmanb1c93172005-04-21 23:48:37 +0000141 case Type::PointerTyID:
Chris Lattnerb1585a92002-08-13 17:50:20 +0000142 return ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattner3e88ef92003-10-03 19:34:51 +0000143
Chris Lattner9fba3da2004-02-15 05:53:04 +0000144 case Type::StructTyID:
145 case Type::ArrayTyID:
Brian Gaeke02209042004-08-20 06:00:58 +0000146 case Type::PackedTyID:
Chris Lattner9fba3da2004-02-15 05:53:04 +0000147 return ConstantAggregateZero::get(Ty);
Chris Lattnerb1585a92002-08-13 17:50:20 +0000148 default:
Reid Spencercf394bf2004-07-04 11:51:24 +0000149 // Function, Label, or Opaque type?
150 assert(!"Cannot create a null constant of that type!");
Chris Lattnerb1585a92002-08-13 17:50:20 +0000151 return 0;
152 }
153}
154
155// Static constructor to create the maximum constant of an integral type...
156ConstantIntegral *ConstantIntegral::getMaxValue(const Type *Ty) {
Chris Lattner6b727592004-06-17 18:19:28 +0000157 switch (Ty->getTypeID()) {
Chris Lattnera84df0a22006-09-28 23:36:21 +0000158 case Type::BoolTyID: return ConstantBool::getTrue();
Chris Lattnerb1585a92002-08-13 17:50:20 +0000159 case Type::SByteTyID:
160 case Type::ShortTyID:
161 case Type::IntTyID:
162 case Type::LongTyID: {
Misha Brukmanb1c93172005-04-21 23:48:37 +0000163 // Calculate 011111111111111...
Chris Lattnerb1585a92002-08-13 17:50:20 +0000164 unsigned TypeBits = Ty->getPrimitiveSize()*8;
165 int64_t Val = INT64_MAX; // All ones
166 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
Reid Spencere0fc4df2006-10-20 07:07:24 +0000167 return ConstantInt::get(Ty, Val);
Chris Lattnerb1585a92002-08-13 17:50:20 +0000168 }
169
170 case Type::UByteTyID:
171 case Type::UShortTyID:
172 case Type::UIntTyID:
173 case Type::ULongTyID: return getAllOnesValue(Ty);
174
Chris Lattner31408f72002-08-14 17:12:13 +0000175 default: return 0;
Chris Lattnerb1585a92002-08-13 17:50:20 +0000176 }
177}
178
179// Static constructor to create the minimum constant for an integral type...
180ConstantIntegral *ConstantIntegral::getMinValue(const Type *Ty) {
Chris Lattner6b727592004-06-17 18:19:28 +0000181 switch (Ty->getTypeID()) {
Chris Lattnera84df0a22006-09-28 23:36:21 +0000182 case Type::BoolTyID: return ConstantBool::getFalse();
Chris Lattnerb1585a92002-08-13 17:50:20 +0000183 case Type::SByteTyID:
184 case Type::ShortTyID:
185 case Type::IntTyID:
186 case Type::LongTyID: {
Misha Brukmanb1c93172005-04-21 23:48:37 +0000187 // Calculate 1111111111000000000000
Chris Lattnerb1585a92002-08-13 17:50:20 +0000188 unsigned TypeBits = Ty->getPrimitiveSize()*8;
189 int64_t Val = -1; // All ones
190 Val <<= TypeBits-1; // Shift over to the right spot
Reid Spencere0fc4df2006-10-20 07:07:24 +0000191 return ConstantInt::get(Ty, Val);
Chris Lattnerb1585a92002-08-13 17:50:20 +0000192 }
193
194 case Type::UByteTyID:
195 case Type::UShortTyID:
196 case Type::UIntTyID:
Reid Spencere0fc4df2006-10-20 07:07:24 +0000197 case Type::ULongTyID: return ConstantInt::get(Ty, 0);
Chris Lattnerb1585a92002-08-13 17:50:20 +0000198
Chris Lattner31408f72002-08-14 17:12:13 +0000199 default: return 0;
Chris Lattnerb1585a92002-08-13 17:50:20 +0000200 }
201}
202
203// Static constructor to create an integral constant with all bits set
204ConstantIntegral *ConstantIntegral::getAllOnesValue(const Type *Ty) {
Chris Lattner6b727592004-06-17 18:19:28 +0000205 switch (Ty->getTypeID()) {
Chris Lattnera84df0a22006-09-28 23:36:21 +0000206 case Type::BoolTyID: return ConstantBool::getTrue();
Chris Lattnerb1585a92002-08-13 17:50:20 +0000207 case Type::SByteTyID:
208 case Type::ShortTyID:
209 case Type::IntTyID:
Reid Spencere0fc4df2006-10-20 07:07:24 +0000210 case Type::LongTyID: return ConstantInt::get(Ty, -1);
Chris Lattnerb1585a92002-08-13 17:50:20 +0000211
212 case Type::UByteTyID:
213 case Type::UShortTyID:
214 case Type::UIntTyID:
215 case Type::ULongTyID: {
216 // Calculate ~0 of the right type...
217 unsigned TypeBits = Ty->getPrimitiveSize()*8;
218 uint64_t Val = ~0ULL; // All ones
219 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
Reid Spencere0fc4df2006-10-20 07:07:24 +0000220 return ConstantInt::get(Ty, Val);
Chris Lattnerb1585a92002-08-13 17:50:20 +0000221 }
Chris Lattner31408f72002-08-14 17:12:13 +0000222 default: return 0;
Chris Lattnerb1585a92002-08-13 17:50:20 +0000223 }
224}
225
Chris Lattner2f7c9632001-06-06 20:29:01 +0000226//===----------------------------------------------------------------------===//
Chris Lattner3462ae32001-12-03 22:26:30 +0000227// ConstantXXX Classes
Chris Lattner2f7c9632001-06-06 20:29:01 +0000228//===----------------------------------------------------------------------===//
229
230//===----------------------------------------------------------------------===//
231// Normal Constructors
232
Chris Lattnere7e139e2005-09-27 06:09:08 +0000233ConstantIntegral::ConstantIntegral(const Type *Ty, ValueTy VT, uint64_t V)
Reid Spencere0fc4df2006-10-20 07:07:24 +0000234 : Constant(Ty, VT, 0, 0), Val(V) {
Chris Lattner2f7c9632001-06-06 20:29:01 +0000235}
Chris Lattner49d855c2001-09-07 16:46:31 +0000236
Chris Lattnere7e139e2005-09-27 06:09:08 +0000237ConstantBool::ConstantBool(bool V)
Reid Spencere0fc4df2006-10-20 07:07:24 +0000238 : ConstantIntegral(Type::BoolTy, ConstantBoolVal, uint64_t(V)) {
Chris Lattner265eb642004-06-21 12:12:12 +0000239}
240
Reid Spencere0fc4df2006-10-20 07:07:24 +0000241ConstantInt::ConstantInt(const Type *Ty, uint64_t V)
242 : ConstantIntegral(Ty, ConstantIntVal, V) {
Chris Lattner2f7c9632001-06-06 20:29:01 +0000243}
244
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000245ConstantFP::ConstantFP(const Type *Ty, double V)
Chris Lattnere7e139e2005-09-27 06:09:08 +0000246 : Constant(Ty, ConstantFPVal, 0, 0) {
Chris Lattner9655e542001-07-20 19:16:02 +0000247 assert(isValueValidForType(Ty, V) && "Value too large for type!");
Chris Lattner2f7c9632001-06-06 20:29:01 +0000248 Val = V;
249}
250
Chris Lattner3462ae32001-12-03 22:26:30 +0000251ConstantArray::ConstantArray(const ArrayType *T,
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000252 const std::vector<Constant*> &V)
Chris Lattnere7e139e2005-09-27 06:09:08 +0000253 : Constant(T, ConstantArrayVal, new Use[V.size()], V.size()) {
Alkis Evlogimenos0507ffe2004-09-15 02:32:15 +0000254 assert(V.size() == T->getNumElements() &&
255 "Invalid initializer vector for constant array");
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000256 Use *OL = OperandList;
Chris Lattner0144fad2005-10-03 21:56:24 +0000257 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
258 I != E; ++I, ++OL) {
Chris Lattner20a24452005-10-07 05:23:36 +0000259 Constant *C = *I;
260 assert((C->getType() == T->getElementType() ||
Alkis Evlogimenoscb031d92004-09-10 04:16:59 +0000261 (T->isAbstract() &&
Chris Lattner20a24452005-10-07 05:23:36 +0000262 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
Alkis Evlogimenoscb031d92004-09-10 04:16:59 +0000263 "Initializer for array element doesn't match array element type!");
Chris Lattner20a24452005-10-07 05:23:36 +0000264 OL->init(C, this);
Chris Lattner2f7c9632001-06-06 20:29:01 +0000265 }
266}
267
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000268ConstantArray::~ConstantArray() {
269 delete [] OperandList;
270}
271
Chris Lattner3462ae32001-12-03 22:26:30 +0000272ConstantStruct::ConstantStruct(const StructType *T,
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000273 const std::vector<Constant*> &V)
Chris Lattnere7e139e2005-09-27 06:09:08 +0000274 : Constant(T, ConstantStructVal, new Use[V.size()], V.size()) {
Chris Lattnerac6db752004-02-09 04:37:31 +0000275 assert(V.size() == T->getNumElements() &&
Vikram S. Adve4e537b22002-07-14 23:13:17 +0000276 "Invalid initializer vector for constant structure");
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000277 Use *OL = OperandList;
Chris Lattner0144fad2005-10-03 21:56:24 +0000278 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
279 I != E; ++I, ++OL) {
Chris Lattner20a24452005-10-07 05:23:36 +0000280 Constant *C = *I;
281 assert((C->getType() == T->getElementType(I-V.begin()) ||
Chris Lattner0144fad2005-10-03 21:56:24 +0000282 ((T->getElementType(I-V.begin())->isAbstract() ||
Chris Lattner20a24452005-10-07 05:23:36 +0000283 C->getType()->isAbstract()) &&
Chris Lattner0144fad2005-10-03 21:56:24 +0000284 T->getElementType(I-V.begin())->getTypeID() ==
Chris Lattner20a24452005-10-07 05:23:36 +0000285 C->getType()->getTypeID())) &&
Chris Lattner93c8f142003-06-02 17:42:47 +0000286 "Initializer for struct element doesn't match struct element type!");
Chris Lattner20a24452005-10-07 05:23:36 +0000287 OL->init(C, this);
Chris Lattner2f7c9632001-06-06 20:29:01 +0000288 }
289}
290
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000291ConstantStruct::~ConstantStruct() {
292 delete [] OperandList;
293}
294
295
Brian Gaeke02209042004-08-20 06:00:58 +0000296ConstantPacked::ConstantPacked(const PackedType *T,
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000297 const std::vector<Constant*> &V)
Chris Lattnere7e139e2005-09-27 06:09:08 +0000298 : Constant(T, ConstantPackedVal, new Use[V.size()], V.size()) {
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000299 Use *OL = OperandList;
Chris Lattner0144fad2005-10-03 21:56:24 +0000300 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
301 I != E; ++I, ++OL) {
Chris Lattner20a24452005-10-07 05:23:36 +0000302 Constant *C = *I;
303 assert((C->getType() == T->getElementType() ||
Alkis Evlogimenoscb031d92004-09-10 04:16:59 +0000304 (T->isAbstract() &&
Chris Lattner20a24452005-10-07 05:23:36 +0000305 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
Alkis Evlogimenoscb031d92004-09-10 04:16:59 +0000306 "Initializer for packed element doesn't match packed element type!");
Chris Lattner20a24452005-10-07 05:23:36 +0000307 OL->init(C, this);
Brian Gaeke02209042004-08-20 06:00:58 +0000308 }
309}
310
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000311ConstantPacked::~ConstantPacked() {
312 delete [] OperandList;
Vikram S. Adve4e537b22002-07-14 23:13:17 +0000313}
314
Chris Lattner22ced562003-06-22 20:48:30 +0000315static bool isSetCC(unsigned Opcode) {
316 return Opcode == Instruction::SetEQ || Opcode == Instruction::SetNE ||
317 Opcode == Instruction::SetLT || Opcode == Instruction::SetGT ||
318 Opcode == Instruction::SetLE || Opcode == Instruction::SetGE;
319}
320
Reid Spencer10fbf0e2006-12-03 05:48:19 +0000321// We declare several classes private to this file, so use an anonymous
322// namespace
323namespace {
324
325/// UnaryConstantExpr - This class is private to Constants.cpp, and is used
326/// behind the scenes to implement unary constant exprs.
327class VISIBILITY_HIDDEN UnaryConstantExpr : public ConstantExpr {
328 Use Op;
329public:
330 UnaryConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
331 : ConstantExpr(Ty, Opcode, &Op, 1), Op(C, this) {}
332};
333
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000334/// BinaryConstantExpr - This class is private to Constants.cpp, and is used
335/// behind the scenes to implement binary constant exprs.
Chris Lattner02157b02006-06-28 21:38:54 +0000336class VISIBILITY_HIDDEN BinaryConstantExpr : public ConstantExpr {
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000337 Use Ops[2];
338public:
339 BinaryConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
340 : ConstantExpr(isSetCC(Opcode) ? Type::BoolTy : C1->getType(),
341 Opcode, Ops, 2) {
342 Ops[0].init(C1, this);
343 Ops[1].init(C2, this);
344 }
345};
Vikram S. Adve4e537b22002-07-14 23:13:17 +0000346
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000347/// SelectConstantExpr - This class is private to Constants.cpp, and is used
348/// behind the scenes to implement select constant exprs.
Chris Lattner02157b02006-06-28 21:38:54 +0000349class VISIBILITY_HIDDEN SelectConstantExpr : public ConstantExpr {
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000350 Use Ops[3];
351public:
352 SelectConstantExpr(Constant *C1, Constant *C2, Constant *C3)
353 : ConstantExpr(C2->getType(), Instruction::Select, Ops, 3) {
354 Ops[0].init(C1, this);
355 Ops[1].init(C2, this);
356 Ops[2].init(C3, this);
357 }
358};
359
Robert Bocchinoca27f032006-01-17 20:07:22 +0000360/// ExtractElementConstantExpr - This class is private to
361/// Constants.cpp, and is used behind the scenes to implement
362/// extractelement constant exprs.
Chris Lattner02157b02006-06-28 21:38:54 +0000363class VISIBILITY_HIDDEN ExtractElementConstantExpr : public ConstantExpr {
Robert Bocchino23004482006-01-10 19:05:34 +0000364 Use Ops[2];
365public:
366 ExtractElementConstantExpr(Constant *C1, Constant *C2)
367 : ConstantExpr(cast<PackedType>(C1->getType())->getElementType(),
368 Instruction::ExtractElement, Ops, 2) {
369 Ops[0].init(C1, this);
370 Ops[1].init(C2, this);
371 }
372};
373
Robert Bocchinoca27f032006-01-17 20:07:22 +0000374/// InsertElementConstantExpr - This class is private to
375/// Constants.cpp, and is used behind the scenes to implement
376/// insertelement constant exprs.
Chris Lattner02157b02006-06-28 21:38:54 +0000377class VISIBILITY_HIDDEN InsertElementConstantExpr : public ConstantExpr {
Robert Bocchinoca27f032006-01-17 20:07:22 +0000378 Use Ops[3];
379public:
380 InsertElementConstantExpr(Constant *C1, Constant *C2, Constant *C3)
381 : ConstantExpr(C1->getType(), Instruction::InsertElement,
382 Ops, 3) {
383 Ops[0].init(C1, this);
384 Ops[1].init(C2, this);
385 Ops[2].init(C3, this);
386 }
387};
388
Chris Lattnerbbe0a422006-04-08 01:18:18 +0000389/// ShuffleVectorConstantExpr - This class is private to
390/// Constants.cpp, and is used behind the scenes to implement
391/// shufflevector constant exprs.
Chris Lattner02157b02006-06-28 21:38:54 +0000392class VISIBILITY_HIDDEN ShuffleVectorConstantExpr : public ConstantExpr {
Chris Lattnerbbe0a422006-04-08 01:18:18 +0000393 Use Ops[3];
394public:
395 ShuffleVectorConstantExpr(Constant *C1, Constant *C2, Constant *C3)
396 : ConstantExpr(C1->getType(), Instruction::ShuffleVector,
397 Ops, 3) {
398 Ops[0].init(C1, this);
399 Ops[1].init(C2, this);
400 Ops[2].init(C3, this);
401 }
402};
403
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000404/// GetElementPtrConstantExpr - This class is private to Constants.cpp, and is
405/// used behind the scenes to implement getelementpr constant exprs.
Chris Lattner02157b02006-06-28 21:38:54 +0000406struct VISIBILITY_HIDDEN GetElementPtrConstantExpr : public ConstantExpr {
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000407 GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
408 const Type *DestTy)
409 : ConstantExpr(DestTy, Instruction::GetElementPtr,
410 new Use[IdxList.size()+1], IdxList.size()+1) {
411 OperandList[0].init(C, this);
412 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
413 OperandList[i+1].init(IdxList[i], this);
414 }
415 ~GetElementPtrConstantExpr() {
Misha Brukmanb1c93172005-04-21 23:48:37 +0000416 delete [] OperandList;
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000417 }
418};
Reid Spencer10fbf0e2006-12-03 05:48:19 +0000419
420// CompareConstantExpr - This class is private to Constants.cpp, and is used
421// behind the scenes to implement ICmp and FCmp constant expressions. This is
422// needed in order to store the predicate value for these instructions.
423struct VISIBILITY_HIDDEN CompareConstantExpr : public ConstantExpr {
424 unsigned short predicate;
425 Use Ops[2];
426 CompareConstantExpr(Instruction::OtherOps opc, unsigned short pred,
427 Constant* LHS, Constant* RHS)
428 : ConstantExpr(Type::BoolTy, Instruction::OtherOps(opc), Ops, 2),
429 predicate(pred) {
430 OperandList[0].init(LHS, this);
431 OperandList[1].init(RHS, this);
432 }
433};
434
435} // end anonymous namespace
Vikram S. Adve4e537b22002-07-14 23:13:17 +0000436
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000437
438// Utility function for determining if a ConstantExpr is a CastOp or not. This
439// can't be inline because we don't want to #include Instruction.h into
440// Constant.h
441bool ConstantExpr::isCast() const {
442 return Instruction::isCast(getOpcode());
443}
444
Reid Spenceree3c9912006-12-04 05:19:50 +0000445bool ConstantExpr::isCompare() const {
446 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
447}
448
Chris Lattner817175f2004-03-29 02:37:53 +0000449/// ConstantExpr::get* - Return some common constants without having to
450/// specify the full Instruction::OPCODE identifier.
451///
452Constant *ConstantExpr::getNeg(Constant *C) {
Chris Lattner3cdc27c2004-03-29 19:51:24 +0000453 if (!C->getType()->isFloatingPoint())
454 return get(Instruction::Sub, getNullValue(C->getType()), C);
455 else
456 return get(Instruction::Sub, ConstantFP::get(C->getType(), -0.0), C);
Chris Lattner817175f2004-03-29 02:37:53 +0000457}
458Constant *ConstantExpr::getNot(Constant *C) {
459 assert(isa<ConstantIntegral>(C) && "Cannot NOT a nonintegral type!");
460 return get(Instruction::Xor, C,
461 ConstantIntegral::getAllOnesValue(C->getType()));
462}
463Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2) {
464 return get(Instruction::Add, C1, C2);
465}
466Constant *ConstantExpr::getSub(Constant *C1, Constant *C2) {
467 return get(Instruction::Sub, C1, C2);
468}
469Constant *ConstantExpr::getMul(Constant *C1, Constant *C2) {
470 return get(Instruction::Mul, C1, C2);
471}
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000472Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2) {
473 return get(Instruction::UDiv, C1, C2);
474}
475Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2) {
476 return get(Instruction::SDiv, C1, C2);
477}
478Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
479 return get(Instruction::FDiv, C1, C2);
Chris Lattner817175f2004-03-29 02:37:53 +0000480}
Reid Spencer7eb55b32006-11-02 01:53:59 +0000481Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
482 return get(Instruction::URem, C1, C2);
483}
484Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
485 return get(Instruction::SRem, C1, C2);
486}
487Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
488 return get(Instruction::FRem, C1, C2);
Chris Lattner817175f2004-03-29 02:37:53 +0000489}
490Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
491 return get(Instruction::And, C1, C2);
492}
493Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
494 return get(Instruction::Or, C1, C2);
495}
496Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
497 return get(Instruction::Xor, C1, C2);
498}
499Constant *ConstantExpr::getSetEQ(Constant *C1, Constant *C2) {
500 return get(Instruction::SetEQ, C1, C2);
501}
502Constant *ConstantExpr::getSetNE(Constant *C1, Constant *C2) {
503 return get(Instruction::SetNE, C1, C2);
504}
505Constant *ConstantExpr::getSetLT(Constant *C1, Constant *C2) {
506 return get(Instruction::SetLT, C1, C2);
507}
508Constant *ConstantExpr::getSetGT(Constant *C1, Constant *C2) {
509 return get(Instruction::SetGT, C1, C2);
510}
511Constant *ConstantExpr::getSetLE(Constant *C1, Constant *C2) {
512 return get(Instruction::SetLE, C1, C2);
513}
514Constant *ConstantExpr::getSetGE(Constant *C1, Constant *C2) {
515 return get(Instruction::SetGE, C1, C2);
516}
Reid Spencer10fbf0e2006-12-03 05:48:19 +0000517unsigned ConstantExpr::getPredicate() const {
518 assert(getOpcode() == Instruction::FCmp || getOpcode() == Instruction::ICmp);
519 return dynamic_cast<const CompareConstantExpr*>(this)->predicate;
520}
Chris Lattner817175f2004-03-29 02:37:53 +0000521Constant *ConstantExpr::getShl(Constant *C1, Constant *C2) {
522 return get(Instruction::Shl, C1, C2);
523}
Reid Spencerfdff9382006-11-08 06:47:33 +0000524Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2) {
525 return get(Instruction::LShr, C1, C2);
Chris Lattner817175f2004-03-29 02:37:53 +0000526}
Reid Spencerfdff9382006-11-08 06:47:33 +0000527Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2) {
528 return get(Instruction::AShr, C1, C2);
Chris Lattnerdb8bdba2004-05-25 05:32:43 +0000529}
Chris Lattner60e0dd72001-10-03 06:12:09 +0000530
Chris Lattner7c1018a2006-07-14 19:37:40 +0000531/// getWithOperandReplaced - Return a constant expression identical to this
532/// one, but with the specified operand set to the specified value.
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000533Constant *
534ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
Chris Lattner7c1018a2006-07-14 19:37:40 +0000535 assert(OpNo < getNumOperands() && "Operand num is out of range!");
536 assert(Op->getType() == getOperand(OpNo)->getType() &&
537 "Replacing operand with value of different type!");
Chris Lattner227816342006-07-14 22:20:01 +0000538 if (getOperand(OpNo) == Op)
539 return const_cast<ConstantExpr*>(this);
Chris Lattner7c1018a2006-07-14 19:37:40 +0000540
Chris Lattner227816342006-07-14 22:20:01 +0000541 Constant *Op0, *Op1, *Op2;
Chris Lattner7c1018a2006-07-14 19:37:40 +0000542 switch (getOpcode()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000543 case Instruction::Trunc:
544 case Instruction::ZExt:
545 case Instruction::SExt:
546 case Instruction::FPTrunc:
547 case Instruction::FPExt:
548 case Instruction::UIToFP:
549 case Instruction::SIToFP:
550 case Instruction::FPToUI:
551 case Instruction::FPToSI:
552 case Instruction::PtrToInt:
553 case Instruction::IntToPtr:
554 case Instruction::BitCast:
555 return ConstantExpr::getCast(getOpcode(), Op, getType());
Chris Lattner227816342006-07-14 22:20:01 +0000556 case Instruction::Select:
557 Op0 = (OpNo == 0) ? Op : getOperand(0);
558 Op1 = (OpNo == 1) ? Op : getOperand(1);
559 Op2 = (OpNo == 2) ? Op : getOperand(2);
560 return ConstantExpr::getSelect(Op0, Op1, Op2);
561 case Instruction::InsertElement:
562 Op0 = (OpNo == 0) ? Op : getOperand(0);
563 Op1 = (OpNo == 1) ? Op : getOperand(1);
564 Op2 = (OpNo == 2) ? Op : getOperand(2);
565 return ConstantExpr::getInsertElement(Op0, Op1, Op2);
566 case Instruction::ExtractElement:
567 Op0 = (OpNo == 0) ? Op : getOperand(0);
568 Op1 = (OpNo == 1) ? Op : getOperand(1);
569 return ConstantExpr::getExtractElement(Op0, Op1);
570 case Instruction::ShuffleVector:
571 Op0 = (OpNo == 0) ? Op : getOperand(0);
572 Op1 = (OpNo == 1) ? Op : getOperand(1);
573 Op2 = (OpNo == 2) ? Op : getOperand(2);
574 return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Chris Lattner7c1018a2006-07-14 19:37:40 +0000575 case Instruction::GetElementPtr: {
576 std::vector<Constant*> Ops;
577 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
578 Ops.push_back(getOperand(i));
579 if (OpNo == 0)
580 return ConstantExpr::getGetElementPtr(Op, Ops);
581 Ops[OpNo-1] = Op;
582 return ConstantExpr::getGetElementPtr(getOperand(0), Ops);
583 }
Chris Lattner7c1018a2006-07-14 19:37:40 +0000584 default:
585 assert(getNumOperands() == 2 && "Must be binary operator?");
Chris Lattner227816342006-07-14 22:20:01 +0000586 Op0 = (OpNo == 0) ? Op : getOperand(0);
587 Op1 = (OpNo == 1) ? Op : getOperand(1);
588 return ConstantExpr::get(getOpcode(), Op0, Op1);
589 }
590}
591
592/// getWithOperands - This returns the current constant expression with the
593/// operands replaced with the specified values. The specified operands must
594/// match count and type with the existing ones.
595Constant *ConstantExpr::
596getWithOperands(const std::vector<Constant*> &Ops) const {
597 assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
598 bool AnyChange = false;
599 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
600 assert(Ops[i]->getType() == getOperand(i)->getType() &&
601 "Operand type mismatch!");
602 AnyChange |= Ops[i] != getOperand(i);
603 }
604 if (!AnyChange) // No operands changed, return self.
605 return const_cast<ConstantExpr*>(this);
606
607 switch (getOpcode()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000608 case Instruction::Trunc:
609 case Instruction::ZExt:
610 case Instruction::SExt:
611 case Instruction::FPTrunc:
612 case Instruction::FPExt:
613 case Instruction::UIToFP:
614 case Instruction::SIToFP:
615 case Instruction::FPToUI:
616 case Instruction::FPToSI:
617 case Instruction::PtrToInt:
618 case Instruction::IntToPtr:
619 case Instruction::BitCast:
620 return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
Chris Lattner227816342006-07-14 22:20:01 +0000621 case Instruction::Select:
622 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
623 case Instruction::InsertElement:
624 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
625 case Instruction::ExtractElement:
626 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
627 case Instruction::ShuffleVector:
628 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
629 case Instruction::GetElementPtr: {
630 std::vector<Constant*> ActualOps(Ops.begin()+1, Ops.end());
631 return ConstantExpr::getGetElementPtr(Ops[0], ActualOps);
632 }
633 default:
634 assert(getNumOperands() == 2 && "Must be binary operator?");
635 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1]);
Chris Lattner7c1018a2006-07-14 19:37:40 +0000636 }
637}
638
Chris Lattner2f7c9632001-06-06 20:29:01 +0000639
640//===----------------------------------------------------------------------===//
Chris Lattner2f7c9632001-06-06 20:29:01 +0000641// isValueValidForType implementations
642
Reid Spencere0fc4df2006-10-20 07:07:24 +0000643bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
Chris Lattner6b727592004-06-17 18:19:28 +0000644 switch (Ty->getTypeID()) {
Chris Lattner2f7c9632001-06-06 20:29:01 +0000645 default:
646 return false; // These can't be represented as integers!!!
Chris Lattner2f7c9632001-06-06 20:29:01 +0000647 // Signed types...
648 case Type::SByteTyID:
649 return (Val <= INT8_MAX && Val >= INT8_MIN);
Reid Spencere0fc4df2006-10-20 07:07:24 +0000650 case Type::UByteTyID:
651 return (Val >= 0) && (Val <= UINT8_MAX);
Chris Lattner2f7c9632001-06-06 20:29:01 +0000652 case Type::ShortTyID:
653 return (Val <= INT16_MAX && Val >= INT16_MIN);
Reid Spencere0fc4df2006-10-20 07:07:24 +0000654 case Type::UShortTyID:
655 return (Val >= 0) && (Val <= UINT16_MAX);
Chris Lattner2f7c9632001-06-06 20:29:01 +0000656 case Type::IntTyID:
Chris Lattner74248512004-06-08 23:21:39 +0000657 return (Val <= int(INT32_MAX) && Val >= int(INT32_MIN));
Chris Lattner2f7c9632001-06-06 20:29:01 +0000658 case Type::UIntTyID:
Reid Spencere0fc4df2006-10-20 07:07:24 +0000659 return (Val >= 0) && (Val <= UINT32_MAX);
660 case Type::LongTyID:
Chris Lattner2f7c9632001-06-06 20:29:01 +0000661 case Type::ULongTyID:
Reid Spencere0fc4df2006-10-20 07:07:24 +0000662 return true; // always true, has to fit in largest type
Chris Lattner2f7c9632001-06-06 20:29:01 +0000663 }
Chris Lattner2f7c9632001-06-06 20:29:01 +0000664}
665
Chris Lattner3462ae32001-12-03 22:26:30 +0000666bool ConstantFP::isValueValidForType(const Type *Ty, double Val) {
Chris Lattner6b727592004-06-17 18:19:28 +0000667 switch (Ty->getTypeID()) {
Chris Lattner2f7c9632001-06-06 20:29:01 +0000668 default:
669 return false; // These can't be represented as floating point!
670
Reid Spencerb95f8ab2004-12-07 07:38:08 +0000671 // TODO: Figure out how to test if a double can be cast to a float!
Chris Lattner2f7c9632001-06-06 20:29:01 +0000672 case Type::FloatTyID:
Chris Lattner2f7c9632001-06-06 20:29:01 +0000673 case Type::DoubleTyID:
674 return true; // This is the largest type...
675 }
Chris Lattneraa2372562006-05-24 17:04:05 +0000676}
Chris Lattner9655e542001-07-20 19:16:02 +0000677
Chris Lattner49d855c2001-09-07 16:46:31 +0000678//===----------------------------------------------------------------------===//
Chris Lattner49d855c2001-09-07 16:46:31 +0000679// Factory Function Implementation
680
Chris Lattner98fa07b2003-05-23 20:03:32 +0000681// ConstantCreator - A class that is used to create constants by
682// ValueMap*. This class should be partially specialized if there is
683// something strange that needs to be done to interface to the ctor for the
684// constant.
685//
Chris Lattner189d19f2003-11-21 20:23:48 +0000686namespace llvm {
687 template<class ConstantClass, class TypeClass, class ValType>
Chris Lattner02157b02006-06-28 21:38:54 +0000688 struct VISIBILITY_HIDDEN ConstantCreator {
Chris Lattner189d19f2003-11-21 20:23:48 +0000689 static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
690 return new ConstantClass(Ty, V);
691 }
692 };
Misha Brukmanb1c93172005-04-21 23:48:37 +0000693
Chris Lattner189d19f2003-11-21 20:23:48 +0000694 template<class ConstantClass, class TypeClass>
Chris Lattner02157b02006-06-28 21:38:54 +0000695 struct VISIBILITY_HIDDEN ConvertConstantType {
Chris Lattner189d19f2003-11-21 20:23:48 +0000696 static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
697 assert(0 && "This type cannot be converted!\n");
698 abort();
699 }
700 };
Chris Lattnerb50d1352003-10-05 00:17:43 +0000701
Chris Lattner935aa922005-10-04 17:48:46 +0000702 template<class ValType, class TypeClass, class ConstantClass,
703 bool HasLargeKey = false /*true for arrays and structs*/ >
Chris Lattner02157b02006-06-28 21:38:54 +0000704 class VISIBILITY_HIDDEN ValueMap : public AbstractTypeUser {
Chris Lattnerb64419a2005-10-03 22:51:37 +0000705 public:
Jim Laskeyc03caef2006-07-17 17:38:29 +0000706 typedef std::pair<const Type*, ValType> MapKey;
707 typedef std::map<MapKey, Constant *> MapTy;
708 typedef std::map<Constant*, typename MapTy::iterator> InverseMapTy;
709 typedef std::map<const Type*, typename MapTy::iterator> AbstractTypeMapTy;
Chris Lattnerb64419a2005-10-03 22:51:37 +0000710 private:
Chris Lattner5bbf60a52005-10-04 16:52:46 +0000711 /// Map - This is the main map from the element descriptor to the Constants.
712 /// This is the primary way we avoid creating two of the same shape
713 /// constant.
Chris Lattnerb50d1352003-10-05 00:17:43 +0000714 MapTy Map;
Chris Lattner935aa922005-10-04 17:48:46 +0000715
716 /// InverseMap - If "HasLargeKey" is true, this contains an inverse mapping
717 /// from the constants to their element in Map. This is important for
718 /// removal of constants from the array, which would otherwise have to scan
719 /// through the map with very large keys.
Jim Laskeyc03caef2006-07-17 17:38:29 +0000720 InverseMapTy InverseMap;
Chris Lattnerb50d1352003-10-05 00:17:43 +0000721
Jim Laskeyc03caef2006-07-17 17:38:29 +0000722 /// AbstractTypeMap - Map for abstract type constants.
723 ///
Chris Lattnerb50d1352003-10-05 00:17:43 +0000724 AbstractTypeMapTy AbstractTypeMap;
Chris Lattner99a669b2004-11-19 16:39:44 +0000725
Chris Lattner99a669b2004-11-19 16:39:44 +0000726 private:
727 void clear(std::vector<Constant *> &Constants) {
Jim Laskeyc03caef2006-07-17 17:38:29 +0000728 for(typename MapTy::iterator I = Map.begin(); I != Map.end(); ++I)
Chris Lattner99a669b2004-11-19 16:39:44 +0000729 Constants.push_back(I->second);
730 Map.clear();
731 AbstractTypeMap.clear();
Chris Lattner935aa922005-10-04 17:48:46 +0000732 InverseMap.clear();
Chris Lattner99a669b2004-11-19 16:39:44 +0000733 }
734
Chris Lattner98fa07b2003-05-23 20:03:32 +0000735 public:
Jim Laskeyc03caef2006-07-17 17:38:29 +0000736 typename MapTy::iterator map_end() { return Map.end(); }
Chris Lattnerb64419a2005-10-03 22:51:37 +0000737
738 /// InsertOrGetItem - Return an iterator for the specified element.
739 /// If the element exists in the map, the returned iterator points to the
740 /// entry and Exists=true. If not, the iterator points to the newly
741 /// inserted entry and returns Exists=false. Newly inserted entries have
742 /// I->second == 0, and should be filled in.
Jim Laskeyc03caef2006-07-17 17:38:29 +0000743 typename MapTy::iterator InsertOrGetItem(std::pair<MapKey, Constant *>
744 &InsertVal,
Chris Lattnerb64419a2005-10-03 22:51:37 +0000745 bool &Exists) {
Jim Laskeyc03caef2006-07-17 17:38:29 +0000746 std::pair<typename MapTy::iterator, bool> IP = Map.insert(InsertVal);
Chris Lattnerb64419a2005-10-03 22:51:37 +0000747 Exists = !IP.second;
748 return IP.first;
749 }
Chris Lattner5bbf60a52005-10-04 16:52:46 +0000750
Chris Lattner935aa922005-10-04 17:48:46 +0000751private:
Jim Laskeyc03caef2006-07-17 17:38:29 +0000752 typename MapTy::iterator FindExistingElement(ConstantClass *CP) {
Chris Lattner935aa922005-10-04 17:48:46 +0000753 if (HasLargeKey) {
Jim Laskeyc03caef2006-07-17 17:38:29 +0000754 typename InverseMapTy::iterator IMI = InverseMap.find(CP);
Chris Lattner935aa922005-10-04 17:48:46 +0000755 assert(IMI != InverseMap.end() && IMI->second != Map.end() &&
756 IMI->second->second == CP &&
757 "InverseMap corrupt!");
758 return IMI->second;
759 }
760
Jim Laskeyc03caef2006-07-17 17:38:29 +0000761 typename MapTy::iterator I =
Chris Lattner935aa922005-10-04 17:48:46 +0000762 Map.find(MapKey((TypeClass*)CP->getRawType(), getValType(CP)));
Chris Lattner5bbf60a52005-10-04 16:52:46 +0000763 if (I == Map.end() || I->second != CP) {
764 // FIXME: This should not use a linear scan. If this gets to be a
765 // performance problem, someone should look at this.
766 for (I = Map.begin(); I != Map.end() && I->second != CP; ++I)
767 /* empty */;
768 }
Chris Lattner935aa922005-10-04 17:48:46 +0000769 return I;
770 }
771public:
772
Chris Lattnerb64419a2005-10-03 22:51:37 +0000773 /// getOrCreate - Return the specified constant from the map, creating it if
774 /// necessary.
Chris Lattner98fa07b2003-05-23 20:03:32 +0000775 ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
Chris Lattnerb50d1352003-10-05 00:17:43 +0000776 MapKey Lookup(Ty, V);
Jim Laskeyc03caef2006-07-17 17:38:29 +0000777 typename MapTy::iterator I = Map.lower_bound(Lookup);
Reid Spencere0fc4df2006-10-20 07:07:24 +0000778 // Is it in the map?
Chris Lattner98fa07b2003-05-23 20:03:32 +0000779 if (I != Map.end() && I->first == Lookup)
Reid Spencere0fc4df2006-10-20 07:07:24 +0000780 return static_cast<ConstantClass *>(I->second);
Chris Lattner98fa07b2003-05-23 20:03:32 +0000781
782 // If no preexisting value, create one now...
783 ConstantClass *Result =
784 ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
785
Chris Lattnerb50d1352003-10-05 00:17:43 +0000786 /// FIXME: why does this assert fail when loading 176.gcc?
787 //assert(Result->getType() == Ty && "Type specified is not correct!");
788 I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
789
Chris Lattner935aa922005-10-04 17:48:46 +0000790 if (HasLargeKey) // Remember the reverse mapping if needed.
791 InverseMap.insert(std::make_pair(Result, I));
792
Chris Lattnerb50d1352003-10-05 00:17:43 +0000793 // If the type of the constant is abstract, make sure that an entry exists
794 // for it in the AbstractTypeMap.
795 if (Ty->isAbstract()) {
796 typename AbstractTypeMapTy::iterator TI =
797 AbstractTypeMap.lower_bound(Ty);
798
799 if (TI == AbstractTypeMap.end() || TI->first != Ty) {
800 // Add ourselves to the ATU list of the type.
801 cast<DerivedType>(Ty)->addAbstractTypeUser(this);
802
803 AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
804 }
805 }
Chris Lattner98fa07b2003-05-23 20:03:32 +0000806 return Result;
807 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000808
Chris Lattner98fa07b2003-05-23 20:03:32 +0000809 void remove(ConstantClass *CP) {
Jim Laskeyc03caef2006-07-17 17:38:29 +0000810 typename MapTy::iterator I = FindExistingElement(CP);
Chris Lattnerb50d1352003-10-05 00:17:43 +0000811 assert(I != Map.end() && "Constant not found in constant table!");
Chris Lattner3e650af2004-08-04 04:48:01 +0000812 assert(I->second == CP && "Didn't find correct element?");
Chris Lattnerb50d1352003-10-05 00:17:43 +0000813
Chris Lattner935aa922005-10-04 17:48:46 +0000814 if (HasLargeKey) // Remember the reverse mapping if needed.
815 InverseMap.erase(CP);
816
Chris Lattnerb50d1352003-10-05 00:17:43 +0000817 // Now that we found the entry, make sure this isn't the entry that
818 // the AbstractTypeMap points to.
Jim Laskeyc03caef2006-07-17 17:38:29 +0000819 const TypeClass *Ty = static_cast<const TypeClass *>(I->first.first);
Chris Lattnerb50d1352003-10-05 00:17:43 +0000820 if (Ty->isAbstract()) {
821 assert(AbstractTypeMap.count(Ty) &&
822 "Abstract type not in AbstractTypeMap?");
Jim Laskeyc03caef2006-07-17 17:38:29 +0000823 typename MapTy::iterator &ATMEntryIt = AbstractTypeMap[Ty];
Chris Lattnerb50d1352003-10-05 00:17:43 +0000824 if (ATMEntryIt == I) {
825 // Yes, we are removing the representative entry for this type.
826 // See if there are any other entries of the same type.
Jim Laskeyc03caef2006-07-17 17:38:29 +0000827 typename MapTy::iterator TmpIt = ATMEntryIt;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000828
Chris Lattnerb50d1352003-10-05 00:17:43 +0000829 // First check the entry before this one...
830 if (TmpIt != Map.begin()) {
831 --TmpIt;
832 if (TmpIt->first.first != Ty) // Not the same type, move back...
833 ++TmpIt;
834 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000835
Chris Lattnerb50d1352003-10-05 00:17:43 +0000836 // If we didn't find the same type, try to move forward...
837 if (TmpIt == ATMEntryIt) {
838 ++TmpIt;
839 if (TmpIt == Map.end() || TmpIt->first.first != Ty)
840 --TmpIt; // No entry afterwards with the same type
841 }
842
843 // If there is another entry in the map of the same abstract type,
844 // update the AbstractTypeMap entry now.
845 if (TmpIt != ATMEntryIt) {
846 ATMEntryIt = TmpIt;
847 } else {
848 // Otherwise, we are removing the last instance of this type
849 // from the table. Remove from the ATM, and from user list.
850 cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
851 AbstractTypeMap.erase(Ty);
852 }
Chris Lattner98fa07b2003-05-23 20:03:32 +0000853 }
Chris Lattnerb50d1352003-10-05 00:17:43 +0000854 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000855
Chris Lattnerb50d1352003-10-05 00:17:43 +0000856 Map.erase(I);
857 }
858
Chris Lattner3b793c62005-10-04 21:35:50 +0000859
860 /// MoveConstantToNewSlot - If we are about to change C to be the element
861 /// specified by I, update our internal data structures to reflect this
862 /// fact.
Jim Laskeyc03caef2006-07-17 17:38:29 +0000863 void MoveConstantToNewSlot(ConstantClass *C, typename MapTy::iterator I) {
Chris Lattner3b793c62005-10-04 21:35:50 +0000864 // First, remove the old location of the specified constant in the map.
Jim Laskeyc03caef2006-07-17 17:38:29 +0000865 typename MapTy::iterator OldI = FindExistingElement(C);
Chris Lattner3b793c62005-10-04 21:35:50 +0000866 assert(OldI != Map.end() && "Constant not found in constant table!");
867 assert(OldI->second == C && "Didn't find correct element?");
868
869 // If this constant is the representative element for its abstract type,
870 // update the AbstractTypeMap so that the representative element is I.
871 if (C->getType()->isAbstract()) {
872 typename AbstractTypeMapTy::iterator ATI =
873 AbstractTypeMap.find(C->getType());
874 assert(ATI != AbstractTypeMap.end() &&
875 "Abstract type not in AbstractTypeMap?");
876 if (ATI->second == OldI)
877 ATI->second = I;
878 }
879
880 // Remove the old entry from the map.
881 Map.erase(OldI);
882
883 // Update the inverse map so that we know that this constant is now
884 // located at descriptor I.
885 if (HasLargeKey) {
886 assert(I->second == C && "Bad inversemap entry!");
887 InverseMap[C] = I;
888 }
889 }
890
Chris Lattnerb50d1352003-10-05 00:17:43 +0000891 void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
Misha Brukmanb1c93172005-04-21 23:48:37 +0000892 typename AbstractTypeMapTy::iterator I =
Jim Laskeyc03caef2006-07-17 17:38:29 +0000893 AbstractTypeMap.find(cast<Type>(OldTy));
Chris Lattnerb50d1352003-10-05 00:17:43 +0000894
895 assert(I != AbstractTypeMap.end() &&
896 "Abstract type not in AbstractTypeMap?");
897
898 // Convert a constant at a time until the last one is gone. The last one
899 // leaving will remove() itself, causing the AbstractTypeMapEntry to be
900 // eliminated eventually.
901 do {
902 ConvertConstantType<ConstantClass,
Jim Laskeyc03caef2006-07-17 17:38:29 +0000903 TypeClass>::convert(
904 static_cast<ConstantClass *>(I->second->second),
Chris Lattnerb50d1352003-10-05 00:17:43 +0000905 cast<TypeClass>(NewTy));
906
Jim Laskeyc03caef2006-07-17 17:38:29 +0000907 I = AbstractTypeMap.find(cast<Type>(OldTy));
Chris Lattnerb50d1352003-10-05 00:17:43 +0000908 } while (I != AbstractTypeMap.end());
909 }
910
911 // If the type became concrete without being refined to any other existing
912 // type, we just remove ourselves from the ATU list.
913 void typeBecameConcrete(const DerivedType *AbsTy) {
914 AbsTy->removeAbstractTypeUser(this);
915 }
916
917 void dump() const {
Bill Wendling6a462f12006-11-17 08:03:48 +0000918 DOUT << "Constant.cpp: ValueMap\n";
Chris Lattner98fa07b2003-05-23 20:03:32 +0000919 }
920 };
921}
922
Chris Lattnera84df0a22006-09-28 23:36:21 +0000923
924//---- ConstantBool::get*() implementation.
925
926ConstantBool *ConstantBool::getTrue() {
927 static ConstantBool *T = 0;
928 if (T) return T;
929 return T = new ConstantBool(true);
930}
931ConstantBool *ConstantBool::getFalse() {
932 static ConstantBool *F = 0;
933 if (F) return F;
934 return F = new ConstantBool(false);
935}
936
Reid Spencere0fc4df2006-10-20 07:07:24 +0000937//---- ConstantInt::get() implementations...
Chris Lattner49d855c2001-09-07 16:46:31 +0000938//
Reid Spencere0fc4df2006-10-20 07:07:24 +0000939static ManagedStatic<ValueMap<uint64_t, Type, ConstantInt> > IntConstants;
Chris Lattner49d855c2001-09-07 16:46:31 +0000940
Reid Spencere0fc4df2006-10-20 07:07:24 +0000941// Get a ConstantInt from an int64_t. Note here that we canoncialize the value
942// to a uint64_t value that has been zero extended down to the size of the
943// integer type of the ConstantInt. This allows the getZExtValue method to
944// just return the stored value while getSExtValue has to convert back to sign
945// extended. getZExtValue is more common in LLVM than getSExtValue().
946ConstantInt *ConstantInt::get(const Type *Ty, int64_t V) {
Chris Lattnerf16661c2006-12-01 19:20:02 +0000947 return IntConstants->getOrCreate(Ty, V & Ty->getIntegralTypeMask());
948}
949
950ConstantIntegral *ConstantIntegral::get(const Type *Ty, int64_t V) {
951 if (Ty == Type::BoolTy) return ConstantBool::get(V&1);
952 return IntConstants->getOrCreate(Ty, V & Ty->getIntegralTypeMask());
Chris Lattner49d855c2001-09-07 16:46:31 +0000953}
954
Chris Lattner3462ae32001-12-03 22:26:30 +0000955//---- ConstantFP::get() implementation...
Chris Lattner49d855c2001-09-07 16:46:31 +0000956//
Chris Lattnerac80ea42004-02-01 22:49:04 +0000957namespace llvm {
958 template<>
959 struct ConstantCreator<ConstantFP, Type, uint64_t> {
960 static ConstantFP *create(const Type *Ty, uint64_t V) {
961 assert(Ty == Type::DoubleTy);
Jim Laskeyb74c6662005-08-17 19:34:49 +0000962 return new ConstantFP(Ty, BitsToDouble(V));
Chris Lattnerac80ea42004-02-01 22:49:04 +0000963 }
964 };
965 template<>
966 struct ConstantCreator<ConstantFP, Type, uint32_t> {
967 static ConstantFP *create(const Type *Ty, uint32_t V) {
968 assert(Ty == Type::FloatTy);
Jim Laskeyb74c6662005-08-17 19:34:49 +0000969 return new ConstantFP(Ty, BitsToFloat(V));
Chris Lattnerac80ea42004-02-01 22:49:04 +0000970 }
971 };
972}
973
Chris Lattner69edc982006-09-28 00:35:06 +0000974static ManagedStatic<ValueMap<uint64_t, Type, ConstantFP> > DoubleConstants;
975static ManagedStatic<ValueMap<uint32_t, Type, ConstantFP> > FloatConstants;
Chris Lattner49d855c2001-09-07 16:46:31 +0000976
Jim Laskey8ad8f712005-08-17 20:06:22 +0000977bool ConstantFP::isNullValue() const {
978 return DoubleToBits(Val) == 0;
979}
980
981bool ConstantFP::isExactlyValue(double V) const {
982 return DoubleToBits(V) == DoubleToBits(Val);
983}
984
985
Chris Lattner3462ae32001-12-03 22:26:30 +0000986ConstantFP *ConstantFP::get(const Type *Ty, double V) {
Chris Lattner241ed4c2004-01-23 00:55:21 +0000987 if (Ty == Type::FloatTy) {
988 // Force the value through memory to normalize it.
Chris Lattner69edc982006-09-28 00:35:06 +0000989 return FloatConstants->getOrCreate(Ty, FloatToBits(V));
Chris Lattnerac80ea42004-02-01 22:49:04 +0000990 } else {
991 assert(Ty == Type::DoubleTy);
Chris Lattner69edc982006-09-28 00:35:06 +0000992 return DoubleConstants->getOrCreate(Ty, DoubleToBits(V));
Chris Lattner241ed4c2004-01-23 00:55:21 +0000993 }
Chris Lattner49d855c2001-09-07 16:46:31 +0000994}
995
Chris Lattner9fba3da2004-02-15 05:53:04 +0000996//---- ConstantAggregateZero::get() implementation...
997//
998namespace llvm {
999 // ConstantAggregateZero does not take extra "value" argument...
1000 template<class ValType>
1001 struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
1002 static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
1003 return new ConstantAggregateZero(Ty);
1004 }
1005 };
1006
1007 template<>
1008 struct ConvertConstantType<ConstantAggregateZero, Type> {
1009 static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
1010 // Make everyone now use a constant of the new type...
1011 Constant *New = ConstantAggregateZero::get(NewTy);
1012 assert(New != OldC && "Didn't replace constant??");
1013 OldC->uncheckedReplaceAllUsesWith(New);
1014 OldC->destroyConstant(); // This constant is now dead, destroy it.
1015 }
1016 };
1017}
1018
Chris Lattner69edc982006-09-28 00:35:06 +00001019static ManagedStatic<ValueMap<char, Type,
1020 ConstantAggregateZero> > AggZeroConstants;
Chris Lattner9fba3da2004-02-15 05:53:04 +00001021
Chris Lattner3e650af2004-08-04 04:48:01 +00001022static char getValType(ConstantAggregateZero *CPZ) { return 0; }
1023
Chris Lattner9fba3da2004-02-15 05:53:04 +00001024Constant *ConstantAggregateZero::get(const Type *Ty) {
Chris Lattnerbfd0b6d2006-06-10 04:16:23 +00001025 assert((isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<PackedType>(Ty)) &&
1026 "Cannot create an aggregate zero of non-aggregate type!");
Chris Lattner69edc982006-09-28 00:35:06 +00001027 return AggZeroConstants->getOrCreate(Ty, 0);
Chris Lattner9fba3da2004-02-15 05:53:04 +00001028}
1029
1030// destroyConstant - Remove the constant from the constant table...
1031//
1032void ConstantAggregateZero::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00001033 AggZeroConstants->remove(this);
Chris Lattner9fba3da2004-02-15 05:53:04 +00001034 destroyConstantImpl();
1035}
1036
Chris Lattner3462ae32001-12-03 22:26:30 +00001037//---- ConstantArray::get() implementation...
Chris Lattner49d855c2001-09-07 16:46:31 +00001038//
Chris Lattner189d19f2003-11-21 20:23:48 +00001039namespace llvm {
1040 template<>
1041 struct ConvertConstantType<ConstantArray, ArrayType> {
1042 static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
1043 // Make everyone now use a constant of the new type...
1044 std::vector<Constant*> C;
1045 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1046 C.push_back(cast<Constant>(OldC->getOperand(i)));
1047 Constant *New = ConstantArray::get(NewTy, C);
1048 assert(New != OldC && "Didn't replace constant??");
1049 OldC->uncheckedReplaceAllUsesWith(New);
1050 OldC->destroyConstant(); // This constant is now dead, destroy it.
1051 }
1052 };
1053}
Chris Lattnerb50d1352003-10-05 00:17:43 +00001054
Chris Lattner3e650af2004-08-04 04:48:01 +00001055static std::vector<Constant*> getValType(ConstantArray *CA) {
1056 std::vector<Constant*> Elements;
1057 Elements.reserve(CA->getNumOperands());
1058 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1059 Elements.push_back(cast<Constant>(CA->getOperand(i)));
1060 return Elements;
1061}
1062
Chris Lattnerb64419a2005-10-03 22:51:37 +00001063typedef ValueMap<std::vector<Constant*>, ArrayType,
Chris Lattner935aa922005-10-04 17:48:46 +00001064 ConstantArray, true /*largekey*/> ArrayConstantsTy;
Chris Lattner69edc982006-09-28 00:35:06 +00001065static ManagedStatic<ArrayConstantsTy> ArrayConstants;
Chris Lattner49d855c2001-09-07 16:46:31 +00001066
Chris Lattner015e8212004-02-15 04:14:47 +00001067Constant *ConstantArray::get(const ArrayType *Ty,
Chris Lattner9fba3da2004-02-15 05:53:04 +00001068 const std::vector<Constant*> &V) {
1069 // If this is an all-zero array, return a ConstantAggregateZero object
1070 if (!V.empty()) {
1071 Constant *C = V[0];
1072 if (!C->isNullValue())
Chris Lattner69edc982006-09-28 00:35:06 +00001073 return ArrayConstants->getOrCreate(Ty, V);
Chris Lattner9fba3da2004-02-15 05:53:04 +00001074 for (unsigned i = 1, e = V.size(); i != e; ++i)
1075 if (V[i] != C)
Chris Lattner69edc982006-09-28 00:35:06 +00001076 return ArrayConstants->getOrCreate(Ty, V);
Chris Lattner9fba3da2004-02-15 05:53:04 +00001077 }
1078 return ConstantAggregateZero::get(Ty);
Chris Lattner49d855c2001-09-07 16:46:31 +00001079}
1080
Chris Lattner98fa07b2003-05-23 20:03:32 +00001081// destroyConstant - Remove the constant from the constant table...
1082//
1083void ConstantArray::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00001084 ArrayConstants->remove(this);
Chris Lattner98fa07b2003-05-23 20:03:32 +00001085 destroyConstantImpl();
1086}
1087
Reid Spencer6f614532006-05-30 08:23:18 +00001088/// ConstantArray::get(const string&) - Return an array that is initialized to
1089/// contain the specified string. If length is zero then a null terminator is
1090/// added to the specified string so that it may be used in a natural way.
1091/// Otherwise, the length parameter specifies how much of the string to use
1092/// and it won't be null terminated.
1093///
Reid Spencer82ebaba2006-05-30 18:15:07 +00001094Constant *ConstantArray::get(const std::string &Str, bool AddNull) {
Chris Lattner7f74a562002-01-20 22:54:45 +00001095 std::vector<Constant*> ElementVals;
Reid Spencer82ebaba2006-05-30 18:15:07 +00001096 for (unsigned i = 0; i < Str.length(); ++i)
Reid Spencere0fc4df2006-10-20 07:07:24 +00001097 ElementVals.push_back(ConstantInt::get(Type::SByteTy, Str[i]));
Chris Lattner8f80fe02001-10-14 23:54:12 +00001098
1099 // Add a null terminator to the string...
Reid Spencer82ebaba2006-05-30 18:15:07 +00001100 if (AddNull) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00001101 ElementVals.push_back(ConstantInt::get(Type::SByteTy, 0));
Reid Spencer6f614532006-05-30 08:23:18 +00001102 }
Chris Lattner8f80fe02001-10-14 23:54:12 +00001103
Reid Spencer82ebaba2006-05-30 18:15:07 +00001104 ArrayType *ATy = ArrayType::get(Type::SByteTy, ElementVals.size());
Chris Lattner3462ae32001-12-03 22:26:30 +00001105 return ConstantArray::get(ATy, ElementVals);
Vikram S. Adve34410432001-10-14 23:17:20 +00001106}
1107
Chris Lattnere8dfcca2004-01-14 17:06:38 +00001108/// isString - This method returns true if the array is an array of sbyte or
1109/// ubyte, and if the elements of the array are all ConstantInt's.
1110bool ConstantArray::isString() const {
1111 // Check the element type for sbyte or ubyte...
Chris Lattnere8701f62004-01-14 17:51:53 +00001112 if (getType()->getElementType() != Type::UByteTy &&
Chris Lattnere8dfcca2004-01-14 17:06:38 +00001113 getType()->getElementType() != Type::SByteTy)
1114 return false;
1115 // Check the elements to make sure they are all integers, not constant
1116 // expressions.
1117 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1118 if (!isa<ConstantInt>(getOperand(i)))
1119 return false;
1120 return true;
1121}
1122
Evan Cheng3763c5b2006-10-26 19:15:05 +00001123/// isCString - This method returns true if the array is a string (see
1124/// isString) and it ends in a null byte \0 and does not contains any other
1125/// null bytes except its terminator.
1126bool ConstantArray::isCString() const {
Evan Chenge974da62006-10-26 21:48:03 +00001127 // Check the element type for sbyte or ubyte...
1128 if (getType()->getElementType() != Type::UByteTy &&
1129 getType()->getElementType() != Type::SByteTy)
1130 return false;
1131 Constant *Zero = Constant::getNullValue(getOperand(0)->getType());
1132 // Last element must be a null.
1133 if (getOperand(getNumOperands()-1) != Zero)
1134 return false;
1135 // Other elements must be non-null integers.
1136 for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
1137 if (!isa<ConstantInt>(getOperand(i)))
Evan Cheng3763c5b2006-10-26 19:15:05 +00001138 return false;
Evan Chenge974da62006-10-26 21:48:03 +00001139 if (getOperand(i) == Zero)
1140 return false;
1141 }
Evan Cheng3763c5b2006-10-26 19:15:05 +00001142 return true;
1143}
1144
1145
Chris Lattner81fabb02002-08-26 17:53:56 +00001146// getAsString - If the sub-element type of this array is either sbyte or ubyte,
1147// then this method converts the array to an std::string and returns it.
1148// Otherwise, it asserts out.
1149//
1150std::string ConstantArray::getAsString() const {
Chris Lattnere8dfcca2004-01-14 17:06:38 +00001151 assert(isString() && "Not a string!");
Chris Lattner81fabb02002-08-26 17:53:56 +00001152 std::string Result;
Chris Lattner6077c312003-07-23 15:22:26 +00001153 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
Reid Spencere0fc4df2006-10-20 07:07:24 +00001154 Result += (char)cast<ConstantInt>(getOperand(i))->getZExtValue();
Chris Lattner81fabb02002-08-26 17:53:56 +00001155 return Result;
1156}
1157
1158
Chris Lattner3462ae32001-12-03 22:26:30 +00001159//---- ConstantStruct::get() implementation...
Chris Lattner49d855c2001-09-07 16:46:31 +00001160//
Chris Lattnerb50d1352003-10-05 00:17:43 +00001161
Chris Lattner189d19f2003-11-21 20:23:48 +00001162namespace llvm {
1163 template<>
1164 struct ConvertConstantType<ConstantStruct, StructType> {
1165 static void convert(ConstantStruct *OldC, const StructType *NewTy) {
1166 // Make everyone now use a constant of the new type...
1167 std::vector<Constant*> C;
1168 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1169 C.push_back(cast<Constant>(OldC->getOperand(i)));
1170 Constant *New = ConstantStruct::get(NewTy, C);
1171 assert(New != OldC && "Didn't replace constant??");
Misha Brukmanb1c93172005-04-21 23:48:37 +00001172
Chris Lattner189d19f2003-11-21 20:23:48 +00001173 OldC->uncheckedReplaceAllUsesWith(New);
1174 OldC->destroyConstant(); // This constant is now dead, destroy it.
1175 }
1176 };
1177}
Chris Lattnerb50d1352003-10-05 00:17:43 +00001178
Chris Lattner8760ec72005-10-04 01:17:50 +00001179typedef ValueMap<std::vector<Constant*>, StructType,
Chris Lattner935aa922005-10-04 17:48:46 +00001180 ConstantStruct, true /*largekey*/> StructConstantsTy;
Chris Lattner69edc982006-09-28 00:35:06 +00001181static ManagedStatic<StructConstantsTy> StructConstants;
Chris Lattner49d855c2001-09-07 16:46:31 +00001182
Chris Lattner3e650af2004-08-04 04:48:01 +00001183static std::vector<Constant*> getValType(ConstantStruct *CS) {
1184 std::vector<Constant*> Elements;
1185 Elements.reserve(CS->getNumOperands());
1186 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1187 Elements.push_back(cast<Constant>(CS->getOperand(i)));
1188 return Elements;
1189}
1190
Chris Lattner015e8212004-02-15 04:14:47 +00001191Constant *ConstantStruct::get(const StructType *Ty,
1192 const std::vector<Constant*> &V) {
Chris Lattner9fba3da2004-02-15 05:53:04 +00001193 // Create a ConstantAggregateZero value if all elements are zeros...
1194 for (unsigned i = 0, e = V.size(); i != e; ++i)
1195 if (!V[i]->isNullValue())
Chris Lattner69edc982006-09-28 00:35:06 +00001196 return StructConstants->getOrCreate(Ty, V);
Chris Lattner9fba3da2004-02-15 05:53:04 +00001197
1198 return ConstantAggregateZero::get(Ty);
Chris Lattner49d855c2001-09-07 16:46:31 +00001199}
Chris Lattner883ad0b2001-10-03 15:39:36 +00001200
Chris Lattnerd6108ca2004-07-12 20:35:11 +00001201Constant *ConstantStruct::get(const std::vector<Constant*> &V) {
1202 std::vector<const Type*> StructEls;
1203 StructEls.reserve(V.size());
1204 for (unsigned i = 0, e = V.size(); i != e; ++i)
1205 StructEls.push_back(V[i]->getType());
1206 return get(StructType::get(StructEls), V);
1207}
1208
Chris Lattnerd7a73302001-10-13 06:57:33 +00001209// destroyConstant - Remove the constant from the constant table...
Chris Lattner883ad0b2001-10-03 15:39:36 +00001210//
Chris Lattner3462ae32001-12-03 22:26:30 +00001211void ConstantStruct::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00001212 StructConstants->remove(this);
Chris Lattnerd7a73302001-10-13 06:57:33 +00001213 destroyConstantImpl();
1214}
Chris Lattner883ad0b2001-10-03 15:39:36 +00001215
Brian Gaeke02209042004-08-20 06:00:58 +00001216//---- ConstantPacked::get() implementation...
1217//
1218namespace llvm {
1219 template<>
1220 struct ConvertConstantType<ConstantPacked, PackedType> {
1221 static void convert(ConstantPacked *OldC, const PackedType *NewTy) {
1222 // Make everyone now use a constant of the new type...
1223 std::vector<Constant*> C;
1224 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1225 C.push_back(cast<Constant>(OldC->getOperand(i)));
1226 Constant *New = ConstantPacked::get(NewTy, C);
1227 assert(New != OldC && "Didn't replace constant??");
1228 OldC->uncheckedReplaceAllUsesWith(New);
1229 OldC->destroyConstant(); // This constant is now dead, destroy it.
1230 }
1231 };
1232}
1233
1234static std::vector<Constant*> getValType(ConstantPacked *CP) {
1235 std::vector<Constant*> Elements;
1236 Elements.reserve(CP->getNumOperands());
1237 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1238 Elements.push_back(CP->getOperand(i));
1239 return Elements;
1240}
1241
Chris Lattner69edc982006-09-28 00:35:06 +00001242static ManagedStatic<ValueMap<std::vector<Constant*>, PackedType,
1243 ConstantPacked> > PackedConstants;
Brian Gaeke02209042004-08-20 06:00:58 +00001244
1245Constant *ConstantPacked::get(const PackedType *Ty,
1246 const std::vector<Constant*> &V) {
1247 // If this is an all-zero packed, return a ConstantAggregateZero object
1248 if (!V.empty()) {
1249 Constant *C = V[0];
1250 if (!C->isNullValue())
Chris Lattner69edc982006-09-28 00:35:06 +00001251 return PackedConstants->getOrCreate(Ty, V);
Brian Gaeke02209042004-08-20 06:00:58 +00001252 for (unsigned i = 1, e = V.size(); i != e; ++i)
1253 if (V[i] != C)
Chris Lattner69edc982006-09-28 00:35:06 +00001254 return PackedConstants->getOrCreate(Ty, V);
Brian Gaeke02209042004-08-20 06:00:58 +00001255 }
1256 return ConstantAggregateZero::get(Ty);
1257}
1258
1259Constant *ConstantPacked::get(const std::vector<Constant*> &V) {
1260 assert(!V.empty() && "Cannot infer type if V is empty");
1261 return get(PackedType::get(V.front()->getType(),V.size()), V);
1262}
1263
1264// destroyConstant - Remove the constant from the constant table...
1265//
1266void ConstantPacked::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00001267 PackedConstants->remove(this);
Brian Gaeke02209042004-08-20 06:00:58 +00001268 destroyConstantImpl();
1269}
1270
Chris Lattner3462ae32001-12-03 22:26:30 +00001271//---- ConstantPointerNull::get() implementation...
Chris Lattnerd7a73302001-10-13 06:57:33 +00001272//
Chris Lattner98fa07b2003-05-23 20:03:32 +00001273
Chris Lattner189d19f2003-11-21 20:23:48 +00001274namespace llvm {
1275 // ConstantPointerNull does not take extra "value" argument...
1276 template<class ValType>
1277 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1278 static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1279 return new ConstantPointerNull(Ty);
1280 }
1281 };
Chris Lattner98fa07b2003-05-23 20:03:32 +00001282
Chris Lattner189d19f2003-11-21 20:23:48 +00001283 template<>
1284 struct ConvertConstantType<ConstantPointerNull, PointerType> {
1285 static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1286 // Make everyone now use a constant of the new type...
1287 Constant *New = ConstantPointerNull::get(NewTy);
1288 assert(New != OldC && "Didn't replace constant??");
1289 OldC->uncheckedReplaceAllUsesWith(New);
1290 OldC->destroyConstant(); // This constant is now dead, destroy it.
1291 }
1292 };
1293}
Chris Lattnerb50d1352003-10-05 00:17:43 +00001294
Chris Lattner69edc982006-09-28 00:35:06 +00001295static ManagedStatic<ValueMap<char, PointerType,
1296 ConstantPointerNull> > NullPtrConstants;
Chris Lattnerd7a73302001-10-13 06:57:33 +00001297
Chris Lattner3e650af2004-08-04 04:48:01 +00001298static char getValType(ConstantPointerNull *) {
1299 return 0;
1300}
1301
1302
Chris Lattner3462ae32001-12-03 22:26:30 +00001303ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
Chris Lattner69edc982006-09-28 00:35:06 +00001304 return NullPtrConstants->getOrCreate(Ty, 0);
Chris Lattner883ad0b2001-10-03 15:39:36 +00001305}
1306
Chris Lattner0c6e0b92002-08-18 00:40:04 +00001307// destroyConstant - Remove the constant from the constant table...
1308//
1309void ConstantPointerNull::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00001310 NullPtrConstants->remove(this);
Chris Lattner0c6e0b92002-08-18 00:40:04 +00001311 destroyConstantImpl();
1312}
1313
1314
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001315//---- UndefValue::get() implementation...
1316//
1317
1318namespace llvm {
1319 // UndefValue does not take extra "value" argument...
1320 template<class ValType>
1321 struct ConstantCreator<UndefValue, Type, ValType> {
1322 static UndefValue *create(const Type *Ty, const ValType &V) {
1323 return new UndefValue(Ty);
1324 }
1325 };
1326
1327 template<>
1328 struct ConvertConstantType<UndefValue, Type> {
1329 static void convert(UndefValue *OldC, const Type *NewTy) {
1330 // Make everyone now use a constant of the new type.
1331 Constant *New = UndefValue::get(NewTy);
1332 assert(New != OldC && "Didn't replace constant??");
1333 OldC->uncheckedReplaceAllUsesWith(New);
1334 OldC->destroyConstant(); // This constant is now dead, destroy it.
1335 }
1336 };
1337}
1338
Chris Lattner69edc982006-09-28 00:35:06 +00001339static ManagedStatic<ValueMap<char, Type, UndefValue> > UndefValueConstants;
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001340
1341static char getValType(UndefValue *) {
1342 return 0;
1343}
1344
1345
1346UndefValue *UndefValue::get(const Type *Ty) {
Chris Lattner69edc982006-09-28 00:35:06 +00001347 return UndefValueConstants->getOrCreate(Ty, 0);
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001348}
1349
1350// destroyConstant - Remove the constant from the constant table.
1351//
1352void UndefValue::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00001353 UndefValueConstants->remove(this);
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001354 destroyConstantImpl();
1355}
1356
1357
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001358//---- ConstantExpr::get() implementations...
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001359//
Reid Spenceree3c9912006-12-04 05:19:50 +00001360struct ExprMapKeyType {
1361 explicit ExprMapKeyType(unsigned opc, std::vector<Constant*> ops,
Reid Spencerdba6aa42006-12-04 18:38:05 +00001362 unsigned short pred = 0) : opcode(opc), predicate(pred), operands(ops) { }
1363 uint16_t opcode;
1364 uint16_t predicate;
Reid Spenceree3c9912006-12-04 05:19:50 +00001365 std::vector<Constant*> operands;
Reid Spenceree3c9912006-12-04 05:19:50 +00001366 bool operator==(const ExprMapKeyType& that) const {
1367 return this->opcode == that.opcode &&
1368 this->predicate == that.predicate &&
1369 this->operands == that.operands;
1370 }
1371 bool operator<(const ExprMapKeyType & that) const {
1372 return this->opcode < that.opcode ||
1373 (this->opcode == that.opcode && this->predicate < that.predicate) ||
1374 (this->opcode == that.opcode && this->predicate == that.predicate &&
1375 this->operands < that.operands);
1376 }
1377
1378 bool operator!=(const ExprMapKeyType& that) const {
1379 return !(*this == that);
1380 }
1381};
Chris Lattner98fa07b2003-05-23 20:03:32 +00001382
Chris Lattner189d19f2003-11-21 20:23:48 +00001383namespace llvm {
1384 template<>
1385 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
Reid Spencer10fbf0e2006-12-03 05:48:19 +00001386 static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V,
1387 unsigned short pred = 0) {
Reid Spenceree3c9912006-12-04 05:19:50 +00001388 if (Instruction::isCast(V.opcode))
1389 return new UnaryConstantExpr(V.opcode, V.operands[0], Ty);
1390 if ((V.opcode >= Instruction::BinaryOpsBegin &&
1391 V.opcode < Instruction::BinaryOpsEnd) ||
1392 V.opcode == Instruction::Shl ||
1393 V.opcode == Instruction::LShr ||
1394 V.opcode == Instruction::AShr)
1395 return new BinaryConstantExpr(V.opcode, V.operands[0], V.operands[1]);
1396 if (V.opcode == Instruction::Select)
1397 return new SelectConstantExpr(V.operands[0], V.operands[1],
1398 V.operands[2]);
1399 if (V.opcode == Instruction::ExtractElement)
1400 return new ExtractElementConstantExpr(V.operands[0], V.operands[1]);
1401 if (V.opcode == Instruction::InsertElement)
1402 return new InsertElementConstantExpr(V.operands[0], V.operands[1],
1403 V.operands[2]);
1404 if (V.opcode == Instruction::ShuffleVector)
1405 return new ShuffleVectorConstantExpr(V.operands[0], V.operands[1],
1406 V.operands[2]);
1407 if (V.opcode == Instruction::GetElementPtr) {
1408 std::vector<Constant*> IdxList(V.operands.begin()+1, V.operands.end());
1409 return new GetElementPtrConstantExpr(V.operands[0], IdxList, Ty);
1410 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001411
Reid Spenceree3c9912006-12-04 05:19:50 +00001412 // The compare instructions are weird. We have to encode the predicate
1413 // value and it is combined with the instruction opcode by multiplying
1414 // the opcode by one hundred. We must decode this to get the predicate.
1415 if (V.opcode == Instruction::ICmp)
1416 return new CompareConstantExpr(Instruction::ICmp, V.predicate,
1417 V.operands[0], V.operands[1]);
1418 if (V.opcode == Instruction::FCmp)
1419 return new CompareConstantExpr(Instruction::FCmp, V.predicate,
1420 V.operands[0], V.operands[1]);
1421 assert(0 && "Invalid ConstantExpr!");
Chris Lattnerb50d1352003-10-05 00:17:43 +00001422 }
Chris Lattner189d19f2003-11-21 20:23:48 +00001423 };
Chris Lattnerb50d1352003-10-05 00:17:43 +00001424
Chris Lattner189d19f2003-11-21 20:23:48 +00001425 template<>
1426 struct ConvertConstantType<ConstantExpr, Type> {
1427 static void convert(ConstantExpr *OldC, const Type *NewTy) {
1428 Constant *New;
1429 switch (OldC->getOpcode()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001430 case Instruction::Trunc:
1431 case Instruction::ZExt:
1432 case Instruction::SExt:
1433 case Instruction::FPTrunc:
1434 case Instruction::FPExt:
1435 case Instruction::UIToFP:
1436 case Instruction::SIToFP:
1437 case Instruction::FPToUI:
1438 case Instruction::FPToSI:
1439 case Instruction::PtrToInt:
1440 case Instruction::IntToPtr:
1441 case Instruction::BitCast:
1442 New = ConstantExpr::getCast(
1443 OldC->getOpcode(), OldC->getOperand(0), NewTy);
Chris Lattner189d19f2003-11-21 20:23:48 +00001444 break;
Chris Lattner6e415c02004-03-12 05:54:04 +00001445 case Instruction::Select:
1446 New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1447 OldC->getOperand(1),
1448 OldC->getOperand(2));
1449 break;
Chris Lattner189d19f2003-11-21 20:23:48 +00001450 case Instruction::Shl:
Reid Spencerfdff9382006-11-08 06:47:33 +00001451 case Instruction::LShr:
1452 case Instruction::AShr:
Chris Lattner189d19f2003-11-21 20:23:48 +00001453 New = ConstantExpr::getShiftTy(NewTy, OldC->getOpcode(),
1454 OldC->getOperand(0), OldC->getOperand(1));
1455 break;
1456 default:
1457 assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
Reid Spencer7eb55b32006-11-02 01:53:59 +00001458 OldC->getOpcode() < Instruction::BinaryOpsEnd);
Chris Lattner189d19f2003-11-21 20:23:48 +00001459 New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1460 OldC->getOperand(1));
1461 break;
1462 case Instruction::GetElementPtr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00001463 // Make everyone now use a constant of the new type...
Chris Lattner13128ab2004-10-11 22:52:25 +00001464 std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
1465 New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0), Idx);
Chris Lattner189d19f2003-11-21 20:23:48 +00001466 break;
1467 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001468
Chris Lattner189d19f2003-11-21 20:23:48 +00001469 assert(New != OldC && "Didn't replace constant??");
1470 OldC->uncheckedReplaceAllUsesWith(New);
1471 OldC->destroyConstant(); // This constant is now dead, destroy it.
1472 }
1473 };
1474} // end namespace llvm
Chris Lattnerb50d1352003-10-05 00:17:43 +00001475
1476
Chris Lattner3e650af2004-08-04 04:48:01 +00001477static ExprMapKeyType getValType(ConstantExpr *CE) {
1478 std::vector<Constant*> Operands;
1479 Operands.reserve(CE->getNumOperands());
1480 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
1481 Operands.push_back(cast<Constant>(CE->getOperand(i)));
Reid Spenceree3c9912006-12-04 05:19:50 +00001482 return ExprMapKeyType(CE->getOpcode(), Operands,
1483 CE->isCompare() ? CE->getPredicate() : 0);
Chris Lattner3e650af2004-08-04 04:48:01 +00001484}
1485
Chris Lattner69edc982006-09-28 00:35:06 +00001486static ManagedStatic<ValueMap<ExprMapKeyType, Type,
1487 ConstantExpr> > ExprConstants;
Vikram S. Adve4c485332002-07-15 18:19:33 +00001488
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001489/// This is a utility function to handle folding of casts and lookup of the
1490/// cast in the ExprConstants map. It is usedby the various get* methods below.
1491static inline Constant *getFoldedCast(
1492 Instruction::CastOps opc, Constant *C, const Type *Ty) {
Chris Lattner815ae2b2003-10-07 22:19:19 +00001493 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001494 // Fold a few common cases
1495 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
1496 return FC;
Chris Lattneracdbe712003-04-17 19:24:48 +00001497
Vikram S. Adve4c485332002-07-15 18:19:33 +00001498 // Look up the constant in the table first to ensure uniqueness
Chris Lattner2b383d2e2003-05-13 21:37:02 +00001499 std::vector<Constant*> argVec(1, C);
Reid Spenceree3c9912006-12-04 05:19:50 +00001500 ExprMapKeyType Key(opc, argVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001501 return ExprConstants->getOrCreate(Ty, Key);
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001502}
Chris Lattnerd7a73302001-10-13 06:57:33 +00001503
Reid Spencerc4dacf22006-12-04 02:43:42 +00001504Constant *ConstantExpr::getInferredCast(Constant *C, bool SrcIsSigned,
1505 const Type *Ty, bool DestIsSigned) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001506 // Note: we can't inline this because it requires the Instructions.h header
Reid Spencerc4dacf22006-12-04 02:43:42 +00001507 return getCast(
1508 CastInst::getCastOpcode(C, SrcIsSigned, Ty, DestIsSigned), C, Ty);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001509}
1510
1511Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
1512 Instruction::CastOps opc = Instruction::CastOps(oc);
1513 assert(Instruction::isCast(opc) && "opcode out of range");
1514 assert(C && Ty && "Null arguments to getCast");
1515 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1516
1517 switch (opc) {
1518 default:
1519 assert(0 && "Invalid cast opcode");
1520 break;
1521 case Instruction::Trunc: return getTrunc(C, Ty);
1522 case Instruction::ZExt: return getZeroExtend(C, Ty);
1523 case Instruction::SExt: return getSignExtend(C, Ty);
1524 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
1525 case Instruction::FPExt: return getFPExtend(C, Ty);
1526 case Instruction::UIToFP: return getUIToFP(C, Ty);
1527 case Instruction::SIToFP: return getSIToFP(C, Ty);
1528 case Instruction::FPToUI: return getFPToUI(C, Ty);
1529 case Instruction::FPToSI: return getFPToSI(C, Ty);
1530 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1531 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1532 case Instruction::BitCast: return getBitCast(C, Ty);
Chris Lattner1ece6f82005-01-01 15:59:57 +00001533 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001534 return 0;
1535}
1536
Reid Spencer5c140882006-12-04 20:17:56 +00001537Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
1538 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1539 return getCast(Instruction::BitCast, C, Ty);
1540 return getCast(Instruction::ZExt, C, Ty);
1541}
1542
1543Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
1544 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1545 return getCast(Instruction::BitCast, C, Ty);
1546 return getCast(Instruction::SExt, C, Ty);
1547}
1548
1549Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
1550 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1551 return getCast(Instruction::BitCast, C, Ty);
1552 return getCast(Instruction::Trunc, C, Ty);
1553}
1554
Reid Spencerbc245a02006-12-05 03:25:26 +00001555Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
1556 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1557 assert((Ty->isIntegral() || Ty->getTypeID() == Type::PointerTyID) &&
1558 "Invalid cast");
1559
1560 if (Ty->isIntegral())
1561 return getCast(Instruction::PtrToInt, S, Ty);
1562 return getCast(Instruction::BitCast, S, Ty);
1563}
1564
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001565Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
1566 assert(C->getType()->isInteger() && "Trunc operand must be integer");
1567 assert(Ty->isIntegral() && "Trunc produces only integral");
1568 assert(C->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()&&
1569 "SrcTy must be larger than DestTy for Trunc!");
1570
1571 return getFoldedCast(Instruction::Trunc, C, Ty);
1572}
1573
1574Constant *ConstantExpr::getSignExtend(Constant *C, const Type *Ty) {
1575 assert(C->getType()->isIntegral() && "SEXt operand must be integral");
1576 assert(Ty->isInteger() && "SExt produces only integer");
1577 assert(C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1578 "SrcTy must be smaller than DestTy for SExt!");
1579
1580 return getFoldedCast(Instruction::SExt, C, Ty);
Chris Lattnerdd284742004-04-04 23:20:30 +00001581}
1582
1583Constant *ConstantExpr::getZeroExtend(Constant *C, const Type *Ty) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001584 assert(C->getType()->isIntegral() && "ZEXt operand must be integral");
1585 assert(Ty->isInteger() && "ZExt produces only integer");
1586 assert(C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1587 "SrcTy must be smaller than DestTy for ZExt!");
1588
1589 return getFoldedCast(Instruction::ZExt, C, Ty);
1590}
1591
1592Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
1593 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1594 C->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()&&
1595 "This is an illegal floating point truncation!");
1596 return getFoldedCast(Instruction::FPTrunc, C, Ty);
1597}
1598
1599Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
1600 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1601 C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1602 "This is an illegal floating point extension!");
1603 return getFoldedCast(Instruction::FPExt, C, Ty);
1604}
1605
1606Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
1607 assert(C->getType()->isIntegral() && Ty->isFloatingPoint() &&
1608 "This is an illegal uint to floating point cast!");
1609 return getFoldedCast(Instruction::UIToFP, C, Ty);
1610}
1611
1612Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
1613 assert(C->getType()->isIntegral() && Ty->isFloatingPoint() &&
1614 "This is an illegal sint to floating point cast!");
1615 return getFoldedCast(Instruction::SIToFP, C, Ty);
1616}
1617
1618Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
1619 assert(C->getType()->isFloatingPoint() && Ty->isIntegral() &&
1620 "This is an illegal floating point to uint cast!");
1621 return getFoldedCast(Instruction::FPToUI, C, Ty);
1622}
1623
1624Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
1625 assert(C->getType()->isFloatingPoint() && Ty->isIntegral() &&
1626 "This is an illegal floating point to sint cast!");
1627 return getFoldedCast(Instruction::FPToSI, C, Ty);
1628}
1629
1630Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
1631 assert(isa<PointerType>(C->getType()) && "PtrToInt source must be pointer");
1632 assert(DstTy->isIntegral() && "PtrToInt destination must be integral");
1633 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
1634}
1635
1636Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
1637 assert(C->getType()->isIntegral() && "IntToPtr source must be integral");
1638 assert(isa<PointerType>(DstTy) && "IntToPtr destination must be a pointer");
1639 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
1640}
1641
1642Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
1643 // BitCast implies a no-op cast of type only. No bits change. However, you
1644 // can't cast pointers to anything but pointers.
1645 const Type *SrcTy = C->getType();
1646 assert((isa<PointerType>(SrcTy) == isa<PointerType>(DstTy)) &&
Reid Spencer5c140882006-12-04 20:17:56 +00001647 "BitCast cannot cast pointer to non-pointer and vice versa");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001648
1649 // Now we know we're not dealing with mismatched pointer casts (ptr->nonptr
1650 // or nonptr->ptr). For all the other types, the cast is okay if source and
1651 // destination bit widths are identical.
1652 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1653 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
Reid Spencer5c140882006-12-04 20:17:56 +00001654 assert(SrcBitSize == DstBitSize && "BitCast requies types of same width");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001655 return getFoldedCast(Instruction::BitCast, C, DstTy);
Chris Lattnerdd284742004-04-04 23:20:30 +00001656}
1657
Alkis Evlogimenosda5de052004-10-24 01:41:10 +00001658Constant *ConstantExpr::getSizeOf(const Type *Ty) {
Chris Lattneracc4e542004-12-13 19:48:51 +00001659 // sizeof is implemented as: (ulong) gep (Ty*)null, 1
Reid Spencerc4dacf22006-12-04 02:43:42 +00001660 return getCast(Instruction::PtrToInt, getGetElementPtr(getNullValue(
1661 PointerType::get(Ty)), std::vector<Constant*>(1,
1662 ConstantInt::get(Type::UIntTy, 1))), Type::ULongTy);
Alkis Evlogimenosda5de052004-10-24 01:41:10 +00001663}
1664
Alkis Evlogimenos9160d5f2005-03-19 11:40:31 +00001665Constant *ConstantExpr::getPtrPtrFromArrayPtr(Constant *C) {
1666 // pointer from array is implemented as: getelementptr arr ptr, 0, 0
Reid Spencere0fc4df2006-10-20 07:07:24 +00001667 static std::vector<Constant*> Indices(2, ConstantInt::get(Type::UIntTy, 0));
Alkis Evlogimenos9160d5f2005-03-19 11:40:31 +00001668
1669 return ConstantExpr::getGetElementPtr(C, Indices);
1670}
1671
Chris Lattnerb50d1352003-10-05 00:17:43 +00001672Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
Reid Spencera009d0d2006-12-04 21:35:24 +00001673 Constant *C1, Constant *C2) {
Reid Spencerfdff9382006-11-08 06:47:33 +00001674 if (Opcode == Instruction::Shl || Opcode == Instruction::LShr ||
1675 Opcode == Instruction::AShr)
Chris Lattner5645e8a2004-01-12 19:04:55 +00001676 return getShiftTy(ReqTy, Opcode, C1, C2);
Reid Spenceree3c9912006-12-04 05:19:50 +00001677
Chris Lattner38a9bcd2003-05-21 17:49:25 +00001678 // Check the operands for consistency first
Reid Spencer7eb55b32006-11-02 01:53:59 +00001679 assert(Opcode >= Instruction::BinaryOpsBegin &&
1680 Opcode < Instruction::BinaryOpsEnd &&
Chris Lattner38a9bcd2003-05-21 17:49:25 +00001681 "Invalid opcode in binary constant expression");
1682 assert(C1->getType() == C2->getType() &&
1683 "Operand types in binary constant expression should match");
Chris Lattnerb50d1352003-10-05 00:17:43 +00001684
Chris Lattnere1496fb2006-09-17 19:14:47 +00001685 if (ReqTy == C1->getType() || (Instruction::isComparison(Opcode) &&
Chris Lattner29ca2c62004-08-04 18:50:09 +00001686 ReqTy == Type::BoolTy))
Chris Lattnerb50d1352003-10-05 00:17:43 +00001687 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1688 return FC; // Fold a few common cases...
Chris Lattneracdbe712003-04-17 19:24:48 +00001689
Chris Lattner2b383d2e2003-05-13 21:37:02 +00001690 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
Reid Spencera009d0d2006-12-04 21:35:24 +00001691 ExprMapKeyType Key(Opcode, argVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001692 return ExprConstants->getOrCreate(ReqTy, Key);
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001693}
1694
Reid Spencera009d0d2006-12-04 21:35:24 +00001695Constant *ConstantExpr::getCompareTy(unsigned Opcode, unsigned short predicate,
1696 Constant *C1, Constant *C2) {
1697 if (Opcode == Instruction::ICmp)
1698 return getICmp(predicate, C1, C2);
1699 return getFCmp(predicate, C1, C2);
1700}
1701
1702Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001703#ifndef NDEBUG
1704 switch (Opcode) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00001705 case Instruction::Add:
1706 case Instruction::Sub:
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001707 case Instruction::Mul:
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001708 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Chris Lattnerc421a262006-01-04 01:01:04 +00001709 assert((C1->getType()->isInteger() || C1->getType()->isFloatingPoint() ||
1710 isa<PackedType>(C1->getType())) &&
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001711 "Tried to create an arithmetic operation on a non-arithmetic type!");
1712 break;
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001713 case Instruction::UDiv:
1714 case Instruction::SDiv:
1715 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1716 assert((C1->getType()->isInteger() || (isa<PackedType>(C1->getType()) &&
1717 cast<PackedType>(C1->getType())->getElementType()->isInteger())) &&
1718 "Tried to create an arithmetic operation on a non-arithmetic type!");
1719 break;
1720 case Instruction::FDiv:
1721 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1722 assert((C1->getType()->isFloatingPoint() || (isa<PackedType>(C1->getType())
1723 && cast<PackedType>(C1->getType())->getElementType()->isFloatingPoint()))
1724 && "Tried to create an arithmetic operation on a non-arithmetic type!");
1725 break;
Reid Spencer7eb55b32006-11-02 01:53:59 +00001726 case Instruction::URem:
1727 case Instruction::SRem:
1728 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1729 assert((C1->getType()->isInteger() || (isa<PackedType>(C1->getType()) &&
1730 cast<PackedType>(C1->getType())->getElementType()->isInteger())) &&
1731 "Tried to create an arithmetic operation on a non-arithmetic type!");
1732 break;
1733 case Instruction::FRem:
1734 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1735 assert((C1->getType()->isFloatingPoint() || (isa<PackedType>(C1->getType())
1736 && cast<PackedType>(C1->getType())->getElementType()->isFloatingPoint()))
1737 && "Tried to create an arithmetic operation on a non-arithmetic type!");
1738 break;
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001739 case Instruction::And:
1740 case Instruction::Or:
1741 case Instruction::Xor:
1742 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Chris Lattnerc421a262006-01-04 01:01:04 +00001743 assert((C1->getType()->isIntegral() || isa<PackedType>(C1->getType())) &&
Misha Brukman3852f652005-01-27 06:46:38 +00001744 "Tried to create a logical operation on a non-integral type!");
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001745 break;
1746 case Instruction::SetLT: case Instruction::SetGT: case Instruction::SetLE:
1747 case Instruction::SetGE: case Instruction::SetEQ: case Instruction::SetNE:
1748 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1749 break;
1750 case Instruction::Shl:
Reid Spencerfdff9382006-11-08 06:47:33 +00001751 case Instruction::LShr:
1752 case Instruction::AShr:
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001753 assert(C2->getType() == Type::UByteTy && "Shift should be by ubyte!");
Reid Spencerfdff9382006-11-08 06:47:33 +00001754 assert(C1->getType()->isInteger() &&
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001755 "Tried to create a shift operation on a non-integer type!");
1756 break;
1757 default:
1758 break;
1759 }
1760#endif
1761
Reid Spencera009d0d2006-12-04 21:35:24 +00001762 return getTy(C1->getType(), Opcode, C1, C2);
1763}
1764
1765Constant *ConstantExpr::getCompare(unsigned Opcode, unsigned short pred,
1766 Constant *C1, Constant *C2) {
1767 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1768 return getCompareTy(Opcode, pred, C1, C2);
Chris Lattner29ca2c62004-08-04 18:50:09 +00001769}
1770
Chris Lattner6e415c02004-03-12 05:54:04 +00001771Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
1772 Constant *V1, Constant *V2) {
1773 assert(C->getType() == Type::BoolTy && "Select condition must be bool!");
1774 assert(V1->getType() == V2->getType() && "Select value types must match!");
1775 assert(V1->getType()->isFirstClassType() && "Cannot select aggregate type!");
1776
1777 if (ReqTy == V1->getType())
1778 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1779 return SC; // Fold common cases
1780
1781 std::vector<Constant*> argVec(3, C);
1782 argVec[1] = V1;
1783 argVec[2] = V2;
Reid Spenceree3c9912006-12-04 05:19:50 +00001784 ExprMapKeyType Key(Instruction::Select, argVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001785 return ExprConstants->getOrCreate(ReqTy, Key);
Chris Lattner6e415c02004-03-12 05:54:04 +00001786}
1787
Chris Lattner9eb2b522004-01-12 19:12:58 +00001788/// getShiftTy - Return a shift left or shift right constant expr
Chris Lattnerb50d1352003-10-05 00:17:43 +00001789Constant *ConstantExpr::getShiftTy(const Type *ReqTy, unsigned Opcode,
1790 Constant *C1, Constant *C2) {
Chris Lattner38a9bcd2003-05-21 17:49:25 +00001791 // Check the operands for consistency first
Reid Spencerfdff9382006-11-08 06:47:33 +00001792 assert((Opcode == Instruction::Shl ||
1793 Opcode == Instruction::LShr ||
1794 Opcode == Instruction::AShr) &&
Chris Lattner38a9bcd2003-05-21 17:49:25 +00001795 "Invalid opcode in binary constant expression");
1796 assert(C1->getType()->isIntegral() && C2->getType() == Type::UByteTy &&
1797 "Invalid operand types for Shift constant expr!");
1798
Chris Lattner0bba7712004-01-12 20:40:42 +00001799 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
Chris Lattner38a9bcd2003-05-21 17:49:25 +00001800 return FC; // Fold a few common cases...
1801
1802 // Look up the constant in the table first to ensure uniqueness
1803 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
Reid Spenceree3c9912006-12-04 05:19:50 +00001804 ExprMapKeyType Key(Opcode, argVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001805 return ExprConstants->getOrCreate(ReqTy, Key);
Chris Lattner38a9bcd2003-05-21 17:49:25 +00001806}
1807
Chris Lattnerb50d1352003-10-05 00:17:43 +00001808Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
Chris Lattner13128ab2004-10-11 22:52:25 +00001809 const std::vector<Value*> &IdxList) {
1810 assert(GetElementPtrInst::getIndexedType(C->getType(), IdxList, true) &&
Chris Lattner04b60fe2004-02-16 20:46:13 +00001811 "GEP indices invalid!");
1812
Chris Lattneracdbe712003-04-17 19:24:48 +00001813 if (Constant *FC = ConstantFoldGetElementPtr(C, IdxList))
1814 return FC; // Fold a few common cases...
Chris Lattner04b60fe2004-02-16 20:46:13 +00001815
Chris Lattnerb50d1352003-10-05 00:17:43 +00001816 assert(isa<PointerType>(C->getType()) &&
Chris Lattner98fa07b2003-05-23 20:03:32 +00001817 "Non-pointer type for constant GetElementPtr expression");
Vikram S. Adve4c485332002-07-15 18:19:33 +00001818 // Look up the constant in the table first to ensure uniqueness
Chris Lattner13128ab2004-10-11 22:52:25 +00001819 std::vector<Constant*> ArgVec;
1820 ArgVec.reserve(IdxList.size()+1);
1821 ArgVec.push_back(C);
1822 for (unsigned i = 0, e = IdxList.size(); i != e; ++i)
1823 ArgVec.push_back(cast<Constant>(IdxList[i]));
Reid Spenceree3c9912006-12-04 05:19:50 +00001824 const ExprMapKeyType Key(Instruction::GetElementPtr,ArgVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001825 return ExprConstants->getOrCreate(ReqTy, Key);
Vikram S. Adve4c485332002-07-15 18:19:33 +00001826}
1827
Chris Lattnerb50d1352003-10-05 00:17:43 +00001828Constant *ConstantExpr::getGetElementPtr(Constant *C,
1829 const std::vector<Constant*> &IdxList){
1830 // Get the result type of the getelementptr!
1831 std::vector<Value*> VIdxList(IdxList.begin(), IdxList.end());
1832
1833 const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), VIdxList,
1834 true);
1835 assert(Ty && "GEP indices invalid!");
Chris Lattner13128ab2004-10-11 22:52:25 +00001836 return getGetElementPtrTy(PointerType::get(Ty), C, VIdxList);
1837}
1838
1839Constant *ConstantExpr::getGetElementPtr(Constant *C,
1840 const std::vector<Value*> &IdxList) {
1841 // Get the result type of the getelementptr!
1842 const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), IdxList,
1843 true);
1844 assert(Ty && "GEP indices invalid!");
Chris Lattnerb50d1352003-10-05 00:17:43 +00001845 return getGetElementPtrTy(PointerType::get(Ty), C, IdxList);
1846}
1847
Reid Spenceree3c9912006-12-04 05:19:50 +00001848Constant *
1849ConstantExpr::getICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1850 assert(LHS->getType() == RHS->getType());
1851 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
1852 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
1853
1854 if (Constant *FC = ConstantFoldCompare(Instruction::ICmp, LHS, RHS, pred))
1855 return FC; // Fold a few common cases...
1856
1857 // Look up the constant in the table first to ensure uniqueness
1858 std::vector<Constant*> ArgVec;
1859 ArgVec.push_back(LHS);
1860 ArgVec.push_back(RHS);
1861 // Fake up an opcode value that encodes both the opcode and predicate
1862 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
1863 return ExprConstants->getOrCreate(Type::BoolTy, Key);
1864}
1865
1866Constant *
1867ConstantExpr::getFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1868 assert(LHS->getType() == RHS->getType());
1869 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
1870
1871 if (Constant *FC = ConstantFoldCompare(Instruction::FCmp, LHS, RHS, pred))
1872 return FC; // Fold a few common cases...
1873
1874 // Look up the constant in the table first to ensure uniqueness
1875 std::vector<Constant*> ArgVec;
1876 ArgVec.push_back(LHS);
1877 ArgVec.push_back(RHS);
1878 // Fake up an opcode value that encodes both the opcode and predicate
1879 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
1880 return ExprConstants->getOrCreate(Type::BoolTy, Key);
1881}
1882
Robert Bocchino23004482006-01-10 19:05:34 +00001883Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
1884 Constant *Idx) {
Robert Bocchinode7f1c92006-01-10 20:03:46 +00001885 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
1886 return FC; // Fold a few common cases...
Robert Bocchino23004482006-01-10 19:05:34 +00001887 // Look up the constant in the table first to ensure uniqueness
1888 std::vector<Constant*> ArgVec(1, Val);
1889 ArgVec.push_back(Idx);
Reid Spenceree3c9912006-12-04 05:19:50 +00001890 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001891 return ExprConstants->getOrCreate(ReqTy, Key);
Robert Bocchino23004482006-01-10 19:05:34 +00001892}
1893
1894Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
1895 assert(isa<PackedType>(Val->getType()) &&
1896 "Tried to create extractelement operation on non-packed type!");
1897 assert(Idx->getType() == Type::UIntTy &&
Robert Bocchinoca27f032006-01-17 20:07:22 +00001898 "Extractelement index must be uint type!");
Robert Bocchino23004482006-01-10 19:05:34 +00001899 return getExtractElementTy(cast<PackedType>(Val->getType())->getElementType(),
1900 Val, Idx);
1901}
Chris Lattnerb50d1352003-10-05 00:17:43 +00001902
Robert Bocchinoca27f032006-01-17 20:07:22 +00001903Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
1904 Constant *Elt, Constant *Idx) {
1905 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
1906 return FC; // Fold a few common cases...
1907 // Look up the constant in the table first to ensure uniqueness
1908 std::vector<Constant*> ArgVec(1, Val);
1909 ArgVec.push_back(Elt);
1910 ArgVec.push_back(Idx);
Reid Spenceree3c9912006-12-04 05:19:50 +00001911 const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001912 return ExprConstants->getOrCreate(ReqTy, Key);
Robert Bocchinoca27f032006-01-17 20:07:22 +00001913}
1914
1915Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
1916 Constant *Idx) {
1917 assert(isa<PackedType>(Val->getType()) &&
1918 "Tried to create insertelement operation on non-packed type!");
1919 assert(Elt->getType() == cast<PackedType>(Val->getType())->getElementType()
1920 && "Insertelement types must match!");
1921 assert(Idx->getType() == Type::UIntTy &&
1922 "Insertelement index must be uint type!");
1923 return getInsertElementTy(cast<PackedType>(Val->getType())->getElementType(),
1924 Val, Elt, Idx);
1925}
1926
Chris Lattnerbbe0a422006-04-08 01:18:18 +00001927Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
1928 Constant *V2, Constant *Mask) {
1929 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
1930 return FC; // Fold a few common cases...
1931 // Look up the constant in the table first to ensure uniqueness
1932 std::vector<Constant*> ArgVec(1, V1);
1933 ArgVec.push_back(V2);
1934 ArgVec.push_back(Mask);
Reid Spenceree3c9912006-12-04 05:19:50 +00001935 const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001936 return ExprConstants->getOrCreate(ReqTy, Key);
Chris Lattnerbbe0a422006-04-08 01:18:18 +00001937}
1938
1939Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
1940 Constant *Mask) {
1941 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
1942 "Invalid shuffle vector constant expr operands!");
1943 return getShuffleVectorTy(V1->getType(), V1, V2, Mask);
1944}
1945
Vikram S. Adve4c485332002-07-15 18:19:33 +00001946// destroyConstant - Remove the constant from the constant table...
1947//
1948void ConstantExpr::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00001949 ExprConstants->remove(this);
Vikram S. Adve4c485332002-07-15 18:19:33 +00001950 destroyConstantImpl();
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001951}
1952
Chris Lattner3cd8c562002-07-30 18:54:25 +00001953const char *ConstantExpr::getOpcodeName() const {
1954 return Instruction::getOpcodeName(getOpcode());
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001955}
Reid Spencer1ebe1ab2004-07-17 23:48:33 +00001956
Chris Lattnerc4062ba2005-10-03 21:58:36 +00001957//===----------------------------------------------------------------------===//
1958// replaceUsesOfWithOnConstant implementations
1959
1960void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
Chris Lattner7a1450d2005-10-04 18:13:04 +00001961 Use *U) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00001962 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
Chris Lattner8760ec72005-10-04 01:17:50 +00001963 Constant *ToC = cast<Constant>(To);
Chris Lattnerdff59112005-10-04 18:47:09 +00001964
1965 unsigned OperandToUpdate = U-OperandList;
1966 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
1967
Jim Laskeyc03caef2006-07-17 17:38:29 +00001968 std::pair<ArrayConstantsTy::MapKey, Constant*> Lookup;
Chris Lattnerb64419a2005-10-03 22:51:37 +00001969 Lookup.first.first = getType();
1970 Lookup.second = this;
Chris Lattnerdff59112005-10-04 18:47:09 +00001971
Chris Lattnerb64419a2005-10-03 22:51:37 +00001972 std::vector<Constant*> &Values = Lookup.first.second;
1973 Values.reserve(getNumOperands()); // Build replacement array.
Chris Lattnerdff59112005-10-04 18:47:09 +00001974
Chris Lattner8760ec72005-10-04 01:17:50 +00001975 // Fill values with the modified operands of the constant array. Also,
1976 // compute whether this turns into an all-zeros array.
Chris Lattnerdff59112005-10-04 18:47:09 +00001977 bool isAllZeros = false;
1978 if (!ToC->isNullValue()) {
1979 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
1980 Values.push_back(cast<Constant>(O->get()));
1981 } else {
1982 isAllZeros = true;
1983 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1984 Constant *Val = cast<Constant>(O->get());
1985 Values.push_back(Val);
1986 if (isAllZeros) isAllZeros = Val->isNullValue();
1987 }
Chris Lattnerc4062ba2005-10-03 21:58:36 +00001988 }
Chris Lattnerdff59112005-10-04 18:47:09 +00001989 Values[OperandToUpdate] = ToC;
Chris Lattnerc4062ba2005-10-03 21:58:36 +00001990
Chris Lattnerb64419a2005-10-03 22:51:37 +00001991 Constant *Replacement = 0;
1992 if (isAllZeros) {
1993 Replacement = ConstantAggregateZero::get(getType());
1994 } else {
1995 // Check to see if we have this array type already.
1996 bool Exists;
Jim Laskeyc03caef2006-07-17 17:38:29 +00001997 ArrayConstantsTy::MapTy::iterator I =
Chris Lattner69edc982006-09-28 00:35:06 +00001998 ArrayConstants->InsertOrGetItem(Lookup, Exists);
Chris Lattnerb64419a2005-10-03 22:51:37 +00001999
2000 if (Exists) {
2001 Replacement = I->second;
2002 } else {
2003 // Okay, the new shape doesn't exist in the system yet. Instead of
2004 // creating a new constant array, inserting it, replaceallusesof'ing the
2005 // old with the new, then deleting the old... just update the current one
2006 // in place!
Chris Lattner69edc982006-09-28 00:35:06 +00002007 ArrayConstants->MoveConstantToNewSlot(this, I);
Chris Lattnerb64419a2005-10-03 22:51:37 +00002008
Chris Lattnerdff59112005-10-04 18:47:09 +00002009 // Update to the new value.
2010 setOperand(OperandToUpdate, ToC);
Chris Lattnerb64419a2005-10-03 22:51:37 +00002011 return;
2012 }
2013 }
2014
2015 // Otherwise, I do need to replace this with an existing value.
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002016 assert(Replacement != this && "I didn't contain From!");
2017
Chris Lattner7a1450d2005-10-04 18:13:04 +00002018 // Everyone using this now uses the replacement.
2019 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002020
2021 // Delete the old constant!
2022 destroyConstant();
2023}
2024
2025void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
Chris Lattner7a1450d2005-10-04 18:13:04 +00002026 Use *U) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002027 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
Chris Lattner8760ec72005-10-04 01:17:50 +00002028 Constant *ToC = cast<Constant>(To);
2029
Chris Lattnerdff59112005-10-04 18:47:09 +00002030 unsigned OperandToUpdate = U-OperandList;
2031 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
2032
Jim Laskeyc03caef2006-07-17 17:38:29 +00002033 std::pair<StructConstantsTy::MapKey, Constant*> Lookup;
Chris Lattner8760ec72005-10-04 01:17:50 +00002034 Lookup.first.first = getType();
2035 Lookup.second = this;
2036 std::vector<Constant*> &Values = Lookup.first.second;
2037 Values.reserve(getNumOperands()); // Build replacement struct.
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002038
Chris Lattnerdff59112005-10-04 18:47:09 +00002039
Chris Lattner8760ec72005-10-04 01:17:50 +00002040 // Fill values with the modified operands of the constant struct. Also,
2041 // compute whether this turns into an all-zeros struct.
Chris Lattnerdff59112005-10-04 18:47:09 +00002042 bool isAllZeros = false;
2043 if (!ToC->isNullValue()) {
2044 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
2045 Values.push_back(cast<Constant>(O->get()));
2046 } else {
2047 isAllZeros = true;
2048 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2049 Constant *Val = cast<Constant>(O->get());
2050 Values.push_back(Val);
2051 if (isAllZeros) isAllZeros = Val->isNullValue();
2052 }
Chris Lattner8760ec72005-10-04 01:17:50 +00002053 }
Chris Lattnerdff59112005-10-04 18:47:09 +00002054 Values[OperandToUpdate] = ToC;
2055
Chris Lattner8760ec72005-10-04 01:17:50 +00002056 Constant *Replacement = 0;
2057 if (isAllZeros) {
2058 Replacement = ConstantAggregateZero::get(getType());
2059 } else {
2060 // Check to see if we have this array type already.
2061 bool Exists;
Jim Laskeyc03caef2006-07-17 17:38:29 +00002062 StructConstantsTy::MapTy::iterator I =
Chris Lattner69edc982006-09-28 00:35:06 +00002063 StructConstants->InsertOrGetItem(Lookup, Exists);
Chris Lattner8760ec72005-10-04 01:17:50 +00002064
2065 if (Exists) {
2066 Replacement = I->second;
2067 } else {
2068 // Okay, the new shape doesn't exist in the system yet. Instead of
2069 // creating a new constant struct, inserting it, replaceallusesof'ing the
2070 // old with the new, then deleting the old... just update the current one
2071 // in place!
Chris Lattner69edc982006-09-28 00:35:06 +00002072 StructConstants->MoveConstantToNewSlot(this, I);
Chris Lattner8760ec72005-10-04 01:17:50 +00002073
Chris Lattnerdff59112005-10-04 18:47:09 +00002074 // Update to the new value.
2075 setOperand(OperandToUpdate, ToC);
Chris Lattner8760ec72005-10-04 01:17:50 +00002076 return;
2077 }
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002078 }
2079
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002080 assert(Replacement != this && "I didn't contain From!");
2081
Chris Lattner7a1450d2005-10-04 18:13:04 +00002082 // Everyone using this now uses the replacement.
2083 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002084
2085 // Delete the old constant!
2086 destroyConstant();
2087}
2088
2089void ConstantPacked::replaceUsesOfWithOnConstant(Value *From, Value *To,
Chris Lattner7a1450d2005-10-04 18:13:04 +00002090 Use *U) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002091 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2092
2093 std::vector<Constant*> Values;
2094 Values.reserve(getNumOperands()); // Build replacement array...
2095 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2096 Constant *Val = getOperand(i);
2097 if (Val == From) Val = cast<Constant>(To);
2098 Values.push_back(Val);
2099 }
2100
2101 Constant *Replacement = ConstantPacked::get(getType(), Values);
2102 assert(Replacement != this && "I didn't contain From!");
2103
Chris Lattner7a1450d2005-10-04 18:13:04 +00002104 // Everyone using this now uses the replacement.
2105 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002106
2107 // Delete the old constant!
2108 destroyConstant();
2109}
2110
2111void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
Chris Lattner7a1450d2005-10-04 18:13:04 +00002112 Use *U) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002113 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2114 Constant *To = cast<Constant>(ToV);
2115
2116 Constant *Replacement = 0;
2117 if (getOpcode() == Instruction::GetElementPtr) {
2118 std::vector<Constant*> Indices;
2119 Constant *Pointer = getOperand(0);
2120 Indices.reserve(getNumOperands()-1);
2121 if (Pointer == From) Pointer = To;
2122
2123 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2124 Constant *Val = getOperand(i);
2125 if (Val == From) Val = To;
2126 Indices.push_back(Val);
2127 }
2128 Replacement = ConstantExpr::getGetElementPtr(Pointer, Indices);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002129 } else if (isCast()) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002130 assert(getOperand(0) == From && "Cast only has one use!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002131 Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002132 } else if (getOpcode() == Instruction::Select) {
2133 Constant *C1 = getOperand(0);
2134 Constant *C2 = getOperand(1);
2135 Constant *C3 = getOperand(2);
2136 if (C1 == From) C1 = To;
2137 if (C2 == From) C2 = To;
2138 if (C3 == From) C3 = To;
2139 Replacement = ConstantExpr::getSelect(C1, C2, C3);
Robert Bocchino23004482006-01-10 19:05:34 +00002140 } else if (getOpcode() == Instruction::ExtractElement) {
2141 Constant *C1 = getOperand(0);
2142 Constant *C2 = getOperand(1);
2143 if (C1 == From) C1 = To;
2144 if (C2 == From) C2 = To;
2145 Replacement = ConstantExpr::getExtractElement(C1, C2);
Chris Lattnera93b4b52006-04-08 05:09:48 +00002146 } else if (getOpcode() == Instruction::InsertElement) {
2147 Constant *C1 = getOperand(0);
2148 Constant *C2 = getOperand(1);
2149 Constant *C3 = getOperand(1);
2150 if (C1 == From) C1 = To;
2151 if (C2 == From) C2 = To;
2152 if (C3 == From) C3 = To;
2153 Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2154 } else if (getOpcode() == Instruction::ShuffleVector) {
2155 Constant *C1 = getOperand(0);
2156 Constant *C2 = getOperand(1);
2157 Constant *C3 = getOperand(2);
2158 if (C1 == From) C1 = To;
2159 if (C2 == From) C2 = To;
2160 if (C3 == From) C3 = To;
2161 Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
Reid Spenceree3c9912006-12-04 05:19:50 +00002162 } else if (isCompare()) {
2163 Constant *C1 = getOperand(0);
2164 Constant *C2 = getOperand(1);
2165 if (C1 == From) C1 = To;
2166 if (C2 == From) C2 = To;
2167 if (getOpcode() == Instruction::ICmp)
2168 Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
2169 else
2170 Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002171 } else if (getNumOperands() == 2) {
2172 Constant *C1 = getOperand(0);
2173 Constant *C2 = getOperand(1);
2174 if (C1 == From) C1 = To;
2175 if (C2 == From) C2 = To;
2176 Replacement = ConstantExpr::get(getOpcode(), C1, C2);
2177 } else {
2178 assert(0 && "Unknown ConstantExpr type!");
2179 return;
2180 }
2181
2182 assert(Replacement != this && "I didn't contain From!");
2183
Chris Lattner7a1450d2005-10-04 18:13:04 +00002184 // Everyone using this now uses the replacement.
2185 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002186
2187 // Delete the old constant!
2188 destroyConstant();
2189}
2190
2191
Jim Laskey2698f0d2006-03-08 18:11:07 +00002192/// getStringValue - Turn an LLVM constant pointer that eventually points to a
2193/// global into a string value. Return an empty string if we can't do it.
Evan Cheng38280c02006-03-10 23:52:03 +00002194/// Parameter Chop determines if the result is chopped at the first null
2195/// terminator.
Jim Laskey2698f0d2006-03-08 18:11:07 +00002196///
Evan Cheng38280c02006-03-10 23:52:03 +00002197std::string Constant::getStringValue(bool Chop, unsigned Offset) {
Jim Laskey2698f0d2006-03-08 18:11:07 +00002198 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(this)) {
2199 if (GV->hasInitializer() && isa<ConstantArray>(GV->getInitializer())) {
2200 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
2201 if (Init->isString()) {
2202 std::string Result = Init->getAsString();
2203 if (Offset < Result.size()) {
2204 // If we are pointing INTO The string, erase the beginning...
2205 Result.erase(Result.begin(), Result.begin()+Offset);
2206
2207 // Take off the null terminator, and any string fragments after it.
Evan Cheng38280c02006-03-10 23:52:03 +00002208 if (Chop) {
2209 std::string::size_type NullPos = Result.find_first_of((char)0);
2210 if (NullPos != std::string::npos)
2211 Result.erase(Result.begin()+NullPos, Result.end());
2212 }
Jim Laskey2698f0d2006-03-08 18:11:07 +00002213 return Result;
2214 }
2215 }
2216 }
2217 } else if (Constant *C = dyn_cast<Constant>(this)) {
2218 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
Evan Cheng2c5e5302006-03-11 00:13:10 +00002219 return GV->getStringValue(Chop, Offset);
Jim Laskey2698f0d2006-03-08 18:11:07 +00002220 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2221 if (CE->getOpcode() == Instruction::GetElementPtr) {
2222 // Turn a gep into the specified offset.
2223 if (CE->getNumOperands() == 3 &&
2224 cast<Constant>(CE->getOperand(1))->isNullValue() &&
2225 isa<ConstantInt>(CE->getOperand(2))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002226 Offset += cast<ConstantInt>(CE->getOperand(2))->getZExtValue();
Evan Cheng2c5e5302006-03-11 00:13:10 +00002227 return CE->getOperand(0)->getStringValue(Chop, Offset);
Jim Laskey2698f0d2006-03-08 18:11:07 +00002228 }
2229 }
2230 }
2231 }
2232 return "";
2233}
2234