blob: e7953a90e7031195d0a1038abd30edd4976c644e [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
Chris Lattnerb1585a92002-08-13 17:50:20 +0000155
156// Static constructor to create an integral constant with all bits set
157ConstantIntegral *ConstantIntegral::getAllOnesValue(const Type *Ty) {
Chris Lattner6b727592004-06-17 18:19:28 +0000158 switch (Ty->getTypeID()) {
Chris Lattnera84df0a22006-09-28 23:36:21 +0000159 case Type::BoolTyID: return ConstantBool::getTrue();
Chris Lattnerb1585a92002-08-13 17:50:20 +0000160 case Type::SByteTyID:
161 case Type::ShortTyID:
162 case Type::IntTyID:
Reid Spencere0fc4df2006-10-20 07:07:24 +0000163 case Type::LongTyID: return ConstantInt::get(Ty, -1);
Chris Lattnerb1585a92002-08-13 17:50:20 +0000164
165 case Type::UByteTyID:
166 case Type::UShortTyID:
167 case Type::UIntTyID:
168 case Type::ULongTyID: {
169 // Calculate ~0 of the right type...
170 unsigned TypeBits = Ty->getPrimitiveSize()*8;
171 uint64_t Val = ~0ULL; // All ones
172 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
Reid Spencere0fc4df2006-10-20 07:07:24 +0000173 return ConstantInt::get(Ty, Val);
Chris Lattnerb1585a92002-08-13 17:50:20 +0000174 }
Chris Lattner31408f72002-08-14 17:12:13 +0000175 default: return 0;
Chris Lattnerb1585a92002-08-13 17:50:20 +0000176 }
177}
178
Chris Lattner2f7c9632001-06-06 20:29:01 +0000179//===----------------------------------------------------------------------===//
Chris Lattner3462ae32001-12-03 22:26:30 +0000180// ConstantXXX Classes
Chris Lattner2f7c9632001-06-06 20:29:01 +0000181//===----------------------------------------------------------------------===//
182
183//===----------------------------------------------------------------------===//
184// Normal Constructors
185
Chris Lattnere7e139e2005-09-27 06:09:08 +0000186ConstantIntegral::ConstantIntegral(const Type *Ty, ValueTy VT, uint64_t V)
Reid Spencere0fc4df2006-10-20 07:07:24 +0000187 : Constant(Ty, VT, 0, 0), Val(V) {
Chris Lattner2f7c9632001-06-06 20:29:01 +0000188}
Chris Lattner49d855c2001-09-07 16:46:31 +0000189
Chris Lattnere7e139e2005-09-27 06:09:08 +0000190ConstantBool::ConstantBool(bool V)
Reid Spencere0fc4df2006-10-20 07:07:24 +0000191 : ConstantIntegral(Type::BoolTy, ConstantBoolVal, uint64_t(V)) {
Chris Lattner265eb642004-06-21 12:12:12 +0000192}
193
Reid Spencere0fc4df2006-10-20 07:07:24 +0000194ConstantInt::ConstantInt(const Type *Ty, uint64_t V)
195 : ConstantIntegral(Ty, ConstantIntVal, V) {
Chris Lattner2f7c9632001-06-06 20:29:01 +0000196}
197
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000198ConstantFP::ConstantFP(const Type *Ty, double V)
Chris Lattnere7e139e2005-09-27 06:09:08 +0000199 : Constant(Ty, ConstantFPVal, 0, 0) {
Chris Lattner9655e542001-07-20 19:16:02 +0000200 assert(isValueValidForType(Ty, V) && "Value too large for type!");
Chris Lattner2f7c9632001-06-06 20:29:01 +0000201 Val = V;
202}
203
Chris Lattner3462ae32001-12-03 22:26:30 +0000204ConstantArray::ConstantArray(const ArrayType *T,
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000205 const std::vector<Constant*> &V)
Chris Lattnere7e139e2005-09-27 06:09:08 +0000206 : Constant(T, ConstantArrayVal, new Use[V.size()], V.size()) {
Alkis Evlogimenos0507ffe2004-09-15 02:32:15 +0000207 assert(V.size() == T->getNumElements() &&
208 "Invalid initializer vector for constant array");
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000209 Use *OL = OperandList;
Chris Lattner0144fad2005-10-03 21:56:24 +0000210 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
211 I != E; ++I, ++OL) {
Chris Lattner20a24452005-10-07 05:23:36 +0000212 Constant *C = *I;
213 assert((C->getType() == T->getElementType() ||
Alkis Evlogimenoscb031d92004-09-10 04:16:59 +0000214 (T->isAbstract() &&
Chris Lattner20a24452005-10-07 05:23:36 +0000215 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
Alkis Evlogimenoscb031d92004-09-10 04:16:59 +0000216 "Initializer for array element doesn't match array element type!");
Chris Lattner20a24452005-10-07 05:23:36 +0000217 OL->init(C, this);
Chris Lattner2f7c9632001-06-06 20:29:01 +0000218 }
219}
220
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000221ConstantArray::~ConstantArray() {
222 delete [] OperandList;
223}
224
Chris Lattner3462ae32001-12-03 22:26:30 +0000225ConstantStruct::ConstantStruct(const StructType *T,
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000226 const std::vector<Constant*> &V)
Chris Lattnere7e139e2005-09-27 06:09:08 +0000227 : Constant(T, ConstantStructVal, new Use[V.size()], V.size()) {
Chris Lattnerac6db752004-02-09 04:37:31 +0000228 assert(V.size() == T->getNumElements() &&
Vikram S. Adve4e537b22002-07-14 23:13:17 +0000229 "Invalid initializer vector for constant structure");
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000230 Use *OL = OperandList;
Chris Lattner0144fad2005-10-03 21:56:24 +0000231 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
232 I != E; ++I, ++OL) {
Chris Lattner20a24452005-10-07 05:23:36 +0000233 Constant *C = *I;
234 assert((C->getType() == T->getElementType(I-V.begin()) ||
Chris Lattner0144fad2005-10-03 21:56:24 +0000235 ((T->getElementType(I-V.begin())->isAbstract() ||
Chris Lattner20a24452005-10-07 05:23:36 +0000236 C->getType()->isAbstract()) &&
Chris Lattner0144fad2005-10-03 21:56:24 +0000237 T->getElementType(I-V.begin())->getTypeID() ==
Chris Lattner20a24452005-10-07 05:23:36 +0000238 C->getType()->getTypeID())) &&
Chris Lattner93c8f142003-06-02 17:42:47 +0000239 "Initializer for struct element doesn't match struct element type!");
Chris Lattner20a24452005-10-07 05:23:36 +0000240 OL->init(C, this);
Chris Lattner2f7c9632001-06-06 20:29:01 +0000241 }
242}
243
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000244ConstantStruct::~ConstantStruct() {
245 delete [] OperandList;
246}
247
248
Brian Gaeke02209042004-08-20 06:00:58 +0000249ConstantPacked::ConstantPacked(const PackedType *T,
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000250 const std::vector<Constant*> &V)
Chris Lattnere7e139e2005-09-27 06:09:08 +0000251 : Constant(T, ConstantPackedVal, new Use[V.size()], V.size()) {
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000252 Use *OL = OperandList;
Chris Lattner0144fad2005-10-03 21:56:24 +0000253 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
254 I != E; ++I, ++OL) {
Chris Lattner20a24452005-10-07 05:23:36 +0000255 Constant *C = *I;
256 assert((C->getType() == T->getElementType() ||
Alkis Evlogimenoscb031d92004-09-10 04:16:59 +0000257 (T->isAbstract() &&
Chris Lattner20a24452005-10-07 05:23:36 +0000258 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
Alkis Evlogimenoscb031d92004-09-10 04:16:59 +0000259 "Initializer for packed element doesn't match packed element type!");
Chris Lattner20a24452005-10-07 05:23:36 +0000260 OL->init(C, this);
Brian Gaeke02209042004-08-20 06:00:58 +0000261 }
262}
263
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000264ConstantPacked::~ConstantPacked() {
265 delete [] OperandList;
Vikram S. Adve4e537b22002-07-14 23:13:17 +0000266}
267
Chris Lattner22ced562003-06-22 20:48:30 +0000268static bool isSetCC(unsigned Opcode) {
269 return Opcode == Instruction::SetEQ || Opcode == Instruction::SetNE ||
270 Opcode == Instruction::SetLT || Opcode == Instruction::SetGT ||
271 Opcode == Instruction::SetLE || Opcode == Instruction::SetGE;
272}
273
Reid Spencer10fbf0e2006-12-03 05:48:19 +0000274// We declare several classes private to this file, so use an anonymous
275// namespace
276namespace {
277
278/// UnaryConstantExpr - This class is private to Constants.cpp, and is used
279/// behind the scenes to implement unary constant exprs.
280class VISIBILITY_HIDDEN UnaryConstantExpr : public ConstantExpr {
281 Use Op;
282public:
283 UnaryConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
284 : ConstantExpr(Ty, Opcode, &Op, 1), Op(C, this) {}
285};
286
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000287/// BinaryConstantExpr - This class is private to Constants.cpp, and is used
288/// behind the scenes to implement binary constant exprs.
Chris Lattner02157b02006-06-28 21:38:54 +0000289class VISIBILITY_HIDDEN BinaryConstantExpr : public ConstantExpr {
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000290 Use Ops[2];
291public:
292 BinaryConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
293 : ConstantExpr(isSetCC(Opcode) ? Type::BoolTy : C1->getType(),
294 Opcode, Ops, 2) {
295 Ops[0].init(C1, this);
296 Ops[1].init(C2, this);
297 }
298};
Vikram S. Adve4e537b22002-07-14 23:13:17 +0000299
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000300/// SelectConstantExpr - This class is private to Constants.cpp, and is used
301/// behind the scenes to implement select constant exprs.
Chris Lattner02157b02006-06-28 21:38:54 +0000302class VISIBILITY_HIDDEN SelectConstantExpr : public ConstantExpr {
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000303 Use Ops[3];
304public:
305 SelectConstantExpr(Constant *C1, Constant *C2, Constant *C3)
306 : ConstantExpr(C2->getType(), Instruction::Select, Ops, 3) {
307 Ops[0].init(C1, this);
308 Ops[1].init(C2, this);
309 Ops[2].init(C3, this);
310 }
311};
312
Robert Bocchinoca27f032006-01-17 20:07:22 +0000313/// ExtractElementConstantExpr - This class is private to
314/// Constants.cpp, and is used behind the scenes to implement
315/// extractelement constant exprs.
Chris Lattner02157b02006-06-28 21:38:54 +0000316class VISIBILITY_HIDDEN ExtractElementConstantExpr : public ConstantExpr {
Robert Bocchino23004482006-01-10 19:05:34 +0000317 Use Ops[2];
318public:
319 ExtractElementConstantExpr(Constant *C1, Constant *C2)
320 : ConstantExpr(cast<PackedType>(C1->getType())->getElementType(),
321 Instruction::ExtractElement, Ops, 2) {
322 Ops[0].init(C1, this);
323 Ops[1].init(C2, this);
324 }
325};
326
Robert Bocchinoca27f032006-01-17 20:07:22 +0000327/// InsertElementConstantExpr - This class is private to
328/// Constants.cpp, and is used behind the scenes to implement
329/// insertelement constant exprs.
Chris Lattner02157b02006-06-28 21:38:54 +0000330class VISIBILITY_HIDDEN InsertElementConstantExpr : public ConstantExpr {
Robert Bocchinoca27f032006-01-17 20:07:22 +0000331 Use Ops[3];
332public:
333 InsertElementConstantExpr(Constant *C1, Constant *C2, Constant *C3)
334 : ConstantExpr(C1->getType(), Instruction::InsertElement,
335 Ops, 3) {
336 Ops[0].init(C1, this);
337 Ops[1].init(C2, this);
338 Ops[2].init(C3, this);
339 }
340};
341
Chris Lattnerbbe0a422006-04-08 01:18:18 +0000342/// ShuffleVectorConstantExpr - This class is private to
343/// Constants.cpp, and is used behind the scenes to implement
344/// shufflevector constant exprs.
Chris Lattner02157b02006-06-28 21:38:54 +0000345class VISIBILITY_HIDDEN ShuffleVectorConstantExpr : public ConstantExpr {
Chris Lattnerbbe0a422006-04-08 01:18:18 +0000346 Use Ops[3];
347public:
348 ShuffleVectorConstantExpr(Constant *C1, Constant *C2, Constant *C3)
349 : ConstantExpr(C1->getType(), Instruction::ShuffleVector,
350 Ops, 3) {
351 Ops[0].init(C1, this);
352 Ops[1].init(C2, this);
353 Ops[2].init(C3, this);
354 }
355};
356
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000357/// GetElementPtrConstantExpr - This class is private to Constants.cpp, and is
358/// used behind the scenes to implement getelementpr constant exprs.
Chris Lattner02157b02006-06-28 21:38:54 +0000359struct VISIBILITY_HIDDEN GetElementPtrConstantExpr : public ConstantExpr {
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000360 GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
361 const Type *DestTy)
362 : ConstantExpr(DestTy, Instruction::GetElementPtr,
363 new Use[IdxList.size()+1], IdxList.size()+1) {
364 OperandList[0].init(C, this);
365 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
366 OperandList[i+1].init(IdxList[i], this);
367 }
368 ~GetElementPtrConstantExpr() {
Misha Brukmanb1c93172005-04-21 23:48:37 +0000369 delete [] OperandList;
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000370 }
371};
Reid Spencer10fbf0e2006-12-03 05:48:19 +0000372
373// CompareConstantExpr - This class is private to Constants.cpp, and is used
374// behind the scenes to implement ICmp and FCmp constant expressions. This is
375// needed in order to store the predicate value for these instructions.
376struct VISIBILITY_HIDDEN CompareConstantExpr : public ConstantExpr {
377 unsigned short predicate;
378 Use Ops[2];
379 CompareConstantExpr(Instruction::OtherOps opc, unsigned short pred,
380 Constant* LHS, Constant* RHS)
Reid Spencerfcb0dd32006-12-07 04:18:31 +0000381 : ConstantExpr(Type::BoolTy, opc, Ops, 2), predicate(pred) {
Reid Spencer10fbf0e2006-12-03 05:48:19 +0000382 OperandList[0].init(LHS, this);
383 OperandList[1].init(RHS, this);
384 }
385};
386
387} // end anonymous namespace
Vikram S. Adve4e537b22002-07-14 23:13:17 +0000388
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000389
390// Utility function for determining if a ConstantExpr is a CastOp or not. This
391// can't be inline because we don't want to #include Instruction.h into
392// Constant.h
393bool ConstantExpr::isCast() const {
394 return Instruction::isCast(getOpcode());
395}
396
Reid Spenceree3c9912006-12-04 05:19:50 +0000397bool ConstantExpr::isCompare() const {
398 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
399}
400
Chris Lattner817175f2004-03-29 02:37:53 +0000401/// ConstantExpr::get* - Return some common constants without having to
402/// specify the full Instruction::OPCODE identifier.
403///
404Constant *ConstantExpr::getNeg(Constant *C) {
Chris Lattner3cdc27c2004-03-29 19:51:24 +0000405 if (!C->getType()->isFloatingPoint())
406 return get(Instruction::Sub, getNullValue(C->getType()), C);
407 else
408 return get(Instruction::Sub, ConstantFP::get(C->getType(), -0.0), C);
Chris Lattner817175f2004-03-29 02:37:53 +0000409}
410Constant *ConstantExpr::getNot(Constant *C) {
411 assert(isa<ConstantIntegral>(C) && "Cannot NOT a nonintegral type!");
412 return get(Instruction::Xor, C,
413 ConstantIntegral::getAllOnesValue(C->getType()));
414}
415Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2) {
416 return get(Instruction::Add, C1, C2);
417}
418Constant *ConstantExpr::getSub(Constant *C1, Constant *C2) {
419 return get(Instruction::Sub, C1, C2);
420}
421Constant *ConstantExpr::getMul(Constant *C1, Constant *C2) {
422 return get(Instruction::Mul, C1, C2);
423}
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000424Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2) {
425 return get(Instruction::UDiv, C1, C2);
426}
427Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2) {
428 return get(Instruction::SDiv, C1, C2);
429}
430Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
431 return get(Instruction::FDiv, C1, C2);
Chris Lattner817175f2004-03-29 02:37:53 +0000432}
Reid Spencer7eb55b32006-11-02 01:53:59 +0000433Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
434 return get(Instruction::URem, C1, C2);
435}
436Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
437 return get(Instruction::SRem, C1, C2);
438}
439Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
440 return get(Instruction::FRem, C1, C2);
Chris Lattner817175f2004-03-29 02:37:53 +0000441}
442Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
443 return get(Instruction::And, C1, C2);
444}
445Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
446 return get(Instruction::Or, C1, C2);
447}
448Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
449 return get(Instruction::Xor, C1, C2);
450}
451Constant *ConstantExpr::getSetEQ(Constant *C1, Constant *C2) {
452 return get(Instruction::SetEQ, C1, C2);
453}
454Constant *ConstantExpr::getSetNE(Constant *C1, Constant *C2) {
455 return get(Instruction::SetNE, C1, C2);
456}
457Constant *ConstantExpr::getSetLT(Constant *C1, Constant *C2) {
458 return get(Instruction::SetLT, C1, C2);
459}
460Constant *ConstantExpr::getSetGT(Constant *C1, Constant *C2) {
461 return get(Instruction::SetGT, C1, C2);
462}
463Constant *ConstantExpr::getSetLE(Constant *C1, Constant *C2) {
464 return get(Instruction::SetLE, C1, C2);
465}
466Constant *ConstantExpr::getSetGE(Constant *C1, Constant *C2) {
467 return get(Instruction::SetGE, C1, C2);
468}
Reid Spencer10fbf0e2006-12-03 05:48:19 +0000469unsigned ConstantExpr::getPredicate() const {
470 assert(getOpcode() == Instruction::FCmp || getOpcode() == Instruction::ICmp);
471 return dynamic_cast<const CompareConstantExpr*>(this)->predicate;
472}
Chris Lattner817175f2004-03-29 02:37:53 +0000473Constant *ConstantExpr::getShl(Constant *C1, Constant *C2) {
474 return get(Instruction::Shl, C1, C2);
475}
Reid Spencerfdff9382006-11-08 06:47:33 +0000476Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2) {
477 return get(Instruction::LShr, C1, C2);
Chris Lattner817175f2004-03-29 02:37:53 +0000478}
Reid Spencerfdff9382006-11-08 06:47:33 +0000479Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2) {
480 return get(Instruction::AShr, C1, C2);
Chris Lattnerdb8bdba2004-05-25 05:32:43 +0000481}
Chris Lattner60e0dd72001-10-03 06:12:09 +0000482
Chris Lattner7c1018a2006-07-14 19:37:40 +0000483/// getWithOperandReplaced - Return a constant expression identical to this
484/// one, but with the specified operand set to the specified value.
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000485Constant *
486ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
Chris Lattner7c1018a2006-07-14 19:37:40 +0000487 assert(OpNo < getNumOperands() && "Operand num is out of range!");
488 assert(Op->getType() == getOperand(OpNo)->getType() &&
489 "Replacing operand with value of different type!");
Chris Lattner227816342006-07-14 22:20:01 +0000490 if (getOperand(OpNo) == Op)
491 return const_cast<ConstantExpr*>(this);
Chris Lattner7c1018a2006-07-14 19:37:40 +0000492
Chris Lattner227816342006-07-14 22:20:01 +0000493 Constant *Op0, *Op1, *Op2;
Chris Lattner7c1018a2006-07-14 19:37:40 +0000494 switch (getOpcode()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000495 case Instruction::Trunc:
496 case Instruction::ZExt:
497 case Instruction::SExt:
498 case Instruction::FPTrunc:
499 case Instruction::FPExt:
500 case Instruction::UIToFP:
501 case Instruction::SIToFP:
502 case Instruction::FPToUI:
503 case Instruction::FPToSI:
504 case Instruction::PtrToInt:
505 case Instruction::IntToPtr:
506 case Instruction::BitCast:
507 return ConstantExpr::getCast(getOpcode(), Op, getType());
Chris Lattner227816342006-07-14 22:20:01 +0000508 case Instruction::Select:
509 Op0 = (OpNo == 0) ? Op : getOperand(0);
510 Op1 = (OpNo == 1) ? Op : getOperand(1);
511 Op2 = (OpNo == 2) ? Op : getOperand(2);
512 return ConstantExpr::getSelect(Op0, Op1, Op2);
513 case Instruction::InsertElement:
514 Op0 = (OpNo == 0) ? Op : getOperand(0);
515 Op1 = (OpNo == 1) ? Op : getOperand(1);
516 Op2 = (OpNo == 2) ? Op : getOperand(2);
517 return ConstantExpr::getInsertElement(Op0, Op1, Op2);
518 case Instruction::ExtractElement:
519 Op0 = (OpNo == 0) ? Op : getOperand(0);
520 Op1 = (OpNo == 1) ? Op : getOperand(1);
521 return ConstantExpr::getExtractElement(Op0, Op1);
522 case Instruction::ShuffleVector:
523 Op0 = (OpNo == 0) ? Op : getOperand(0);
524 Op1 = (OpNo == 1) ? Op : getOperand(1);
525 Op2 = (OpNo == 2) ? Op : getOperand(2);
526 return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Chris Lattner7c1018a2006-07-14 19:37:40 +0000527 case Instruction::GetElementPtr: {
528 std::vector<Constant*> Ops;
529 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
530 Ops.push_back(getOperand(i));
531 if (OpNo == 0)
532 return ConstantExpr::getGetElementPtr(Op, Ops);
533 Ops[OpNo-1] = Op;
534 return ConstantExpr::getGetElementPtr(getOperand(0), Ops);
535 }
Chris Lattner7c1018a2006-07-14 19:37:40 +0000536 default:
537 assert(getNumOperands() == 2 && "Must be binary operator?");
Chris Lattner227816342006-07-14 22:20:01 +0000538 Op0 = (OpNo == 0) ? Op : getOperand(0);
539 Op1 = (OpNo == 1) ? Op : getOperand(1);
540 return ConstantExpr::get(getOpcode(), Op0, Op1);
541 }
542}
543
544/// getWithOperands - This returns the current constant expression with the
545/// operands replaced with the specified values. The specified operands must
546/// match count and type with the existing ones.
547Constant *ConstantExpr::
548getWithOperands(const std::vector<Constant*> &Ops) const {
549 assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
550 bool AnyChange = false;
551 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
552 assert(Ops[i]->getType() == getOperand(i)->getType() &&
553 "Operand type mismatch!");
554 AnyChange |= Ops[i] != getOperand(i);
555 }
556 if (!AnyChange) // No operands changed, return self.
557 return const_cast<ConstantExpr*>(this);
558
559 switch (getOpcode()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000560 case Instruction::Trunc:
561 case Instruction::ZExt:
562 case Instruction::SExt:
563 case Instruction::FPTrunc:
564 case Instruction::FPExt:
565 case Instruction::UIToFP:
566 case Instruction::SIToFP:
567 case Instruction::FPToUI:
568 case Instruction::FPToSI:
569 case Instruction::PtrToInt:
570 case Instruction::IntToPtr:
571 case Instruction::BitCast:
572 return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
Chris Lattner227816342006-07-14 22:20:01 +0000573 case Instruction::Select:
574 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
575 case Instruction::InsertElement:
576 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
577 case Instruction::ExtractElement:
578 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
579 case Instruction::ShuffleVector:
580 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
581 case Instruction::GetElementPtr: {
582 std::vector<Constant*> ActualOps(Ops.begin()+1, Ops.end());
583 return ConstantExpr::getGetElementPtr(Ops[0], ActualOps);
584 }
585 default:
586 assert(getNumOperands() == 2 && "Must be binary operator?");
587 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1]);
Chris Lattner7c1018a2006-07-14 19:37:40 +0000588 }
589}
590
Chris Lattner2f7c9632001-06-06 20:29:01 +0000591
592//===----------------------------------------------------------------------===//
Chris Lattner2f7c9632001-06-06 20:29:01 +0000593// isValueValidForType implementations
594
Reid Spencere7334722006-12-19 01:28:19 +0000595bool ConstantInt::isValueValidForType(const Type *Ty, uint64_t Val) {
596 switch (Ty->getTypeID()) {
597 default: return false; // These can't be represented as integers!
598 case Type::SByteTyID:
599 case Type::UByteTyID: return Val <= UINT8_MAX;
600 case Type::ShortTyID:
601 case Type::UShortTyID:return Val <= UINT16_MAX;
602 case Type::IntTyID:
603 case Type::UIntTyID: return Val <= UINT32_MAX;
604 case Type::LongTyID:
605 case Type::ULongTyID: return true; // always true, has to fit in largest type
606 }
607}
608
Reid Spencere0fc4df2006-10-20 07:07:24 +0000609bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
Chris Lattner6b727592004-06-17 18:19:28 +0000610 switch (Ty->getTypeID()) {
Reid Spencere7334722006-12-19 01:28:19 +0000611 default: return false; // These can't be represented as integers!
Chris Lattner2f7c9632001-06-06 20:29:01 +0000612 case Type::SByteTyID:
Reid Spencere7334722006-12-19 01:28:19 +0000613 case Type::UByteTyID: return (Val >= INT8_MIN && Val <= INT8_MAX);
Chris Lattner2f7c9632001-06-06 20:29:01 +0000614 case Type::ShortTyID:
Reid Spencere7334722006-12-19 01:28:19 +0000615 case Type::UShortTyID:return (Val >= INT16_MIN && Val <= UINT16_MAX);
Chris Lattner2f7c9632001-06-06 20:29:01 +0000616 case Type::IntTyID:
Reid Spencere7334722006-12-19 01:28:19 +0000617 case Type::UIntTyID: return (Val >= INT32_MIN && Val <= UINT32_MAX);
Reid Spencere0fc4df2006-10-20 07:07:24 +0000618 case Type::LongTyID:
Reid Spencere7334722006-12-19 01:28:19 +0000619 case Type::ULongTyID: return true; // always true, has to fit in largest type
Chris Lattner2f7c9632001-06-06 20:29:01 +0000620 }
Chris Lattner2f7c9632001-06-06 20:29:01 +0000621}
622
Chris Lattner3462ae32001-12-03 22:26:30 +0000623bool ConstantFP::isValueValidForType(const Type *Ty, double Val) {
Chris Lattner6b727592004-06-17 18:19:28 +0000624 switch (Ty->getTypeID()) {
Chris Lattner2f7c9632001-06-06 20:29:01 +0000625 default:
626 return false; // These can't be represented as floating point!
627
Reid Spencerb95f8ab2004-12-07 07:38:08 +0000628 // TODO: Figure out how to test if a double can be cast to a float!
Chris Lattner2f7c9632001-06-06 20:29:01 +0000629 case Type::FloatTyID:
Chris Lattner2f7c9632001-06-06 20:29:01 +0000630 case Type::DoubleTyID:
631 return true; // This is the largest type...
632 }
Chris Lattneraa2372562006-05-24 17:04:05 +0000633}
Chris Lattner9655e542001-07-20 19:16:02 +0000634
Chris Lattner49d855c2001-09-07 16:46:31 +0000635//===----------------------------------------------------------------------===//
Chris Lattner49d855c2001-09-07 16:46:31 +0000636// Factory Function Implementation
637
Chris Lattner98fa07b2003-05-23 20:03:32 +0000638// ConstantCreator - A class that is used to create constants by
639// ValueMap*. This class should be partially specialized if there is
640// something strange that needs to be done to interface to the ctor for the
641// constant.
642//
Chris Lattner189d19f2003-11-21 20:23:48 +0000643namespace llvm {
644 template<class ConstantClass, class TypeClass, class ValType>
Chris Lattner02157b02006-06-28 21:38:54 +0000645 struct VISIBILITY_HIDDEN ConstantCreator {
Chris Lattner189d19f2003-11-21 20:23:48 +0000646 static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
647 return new ConstantClass(Ty, V);
648 }
649 };
Misha Brukmanb1c93172005-04-21 23:48:37 +0000650
Chris Lattner189d19f2003-11-21 20:23:48 +0000651 template<class ConstantClass, class TypeClass>
Chris Lattner02157b02006-06-28 21:38:54 +0000652 struct VISIBILITY_HIDDEN ConvertConstantType {
Chris Lattner189d19f2003-11-21 20:23:48 +0000653 static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
654 assert(0 && "This type cannot be converted!\n");
655 abort();
656 }
657 };
Chris Lattnerb50d1352003-10-05 00:17:43 +0000658
Chris Lattner935aa922005-10-04 17:48:46 +0000659 template<class ValType, class TypeClass, class ConstantClass,
660 bool HasLargeKey = false /*true for arrays and structs*/ >
Chris Lattner02157b02006-06-28 21:38:54 +0000661 class VISIBILITY_HIDDEN ValueMap : public AbstractTypeUser {
Chris Lattnerb64419a2005-10-03 22:51:37 +0000662 public:
Jim Laskeyc03caef2006-07-17 17:38:29 +0000663 typedef std::pair<const Type*, ValType> MapKey;
664 typedef std::map<MapKey, Constant *> MapTy;
665 typedef std::map<Constant*, typename MapTy::iterator> InverseMapTy;
666 typedef std::map<const Type*, typename MapTy::iterator> AbstractTypeMapTy;
Chris Lattnerb64419a2005-10-03 22:51:37 +0000667 private:
Chris Lattner5bbf60a52005-10-04 16:52:46 +0000668 /// Map - This is the main map from the element descriptor to the Constants.
669 /// This is the primary way we avoid creating two of the same shape
670 /// constant.
Chris Lattnerb50d1352003-10-05 00:17:43 +0000671 MapTy Map;
Chris Lattner935aa922005-10-04 17:48:46 +0000672
673 /// InverseMap - If "HasLargeKey" is true, this contains an inverse mapping
674 /// from the constants to their element in Map. This is important for
675 /// removal of constants from the array, which would otherwise have to scan
676 /// through the map with very large keys.
Jim Laskeyc03caef2006-07-17 17:38:29 +0000677 InverseMapTy InverseMap;
Chris Lattnerb50d1352003-10-05 00:17:43 +0000678
Jim Laskeyc03caef2006-07-17 17:38:29 +0000679 /// AbstractTypeMap - Map for abstract type constants.
680 ///
Chris Lattnerb50d1352003-10-05 00:17:43 +0000681 AbstractTypeMapTy AbstractTypeMap;
Chris Lattner99a669b2004-11-19 16:39:44 +0000682
Chris Lattner99a669b2004-11-19 16:39:44 +0000683 private:
684 void clear(std::vector<Constant *> &Constants) {
Jim Laskeyc03caef2006-07-17 17:38:29 +0000685 for(typename MapTy::iterator I = Map.begin(); I != Map.end(); ++I)
Chris Lattner99a669b2004-11-19 16:39:44 +0000686 Constants.push_back(I->second);
687 Map.clear();
688 AbstractTypeMap.clear();
Chris Lattner935aa922005-10-04 17:48:46 +0000689 InverseMap.clear();
Chris Lattner99a669b2004-11-19 16:39:44 +0000690 }
691
Chris Lattner98fa07b2003-05-23 20:03:32 +0000692 public:
Jim Laskeyc03caef2006-07-17 17:38:29 +0000693 typename MapTy::iterator map_end() { return Map.end(); }
Chris Lattnerb64419a2005-10-03 22:51:37 +0000694
695 /// InsertOrGetItem - Return an iterator for the specified element.
696 /// If the element exists in the map, the returned iterator points to the
697 /// entry and Exists=true. If not, the iterator points to the newly
698 /// inserted entry and returns Exists=false. Newly inserted entries have
699 /// I->second == 0, and should be filled in.
Jim Laskeyc03caef2006-07-17 17:38:29 +0000700 typename MapTy::iterator InsertOrGetItem(std::pair<MapKey, Constant *>
701 &InsertVal,
Chris Lattnerb64419a2005-10-03 22:51:37 +0000702 bool &Exists) {
Jim Laskeyc03caef2006-07-17 17:38:29 +0000703 std::pair<typename MapTy::iterator, bool> IP = Map.insert(InsertVal);
Chris Lattnerb64419a2005-10-03 22:51:37 +0000704 Exists = !IP.second;
705 return IP.first;
706 }
Chris Lattner5bbf60a52005-10-04 16:52:46 +0000707
Chris Lattner935aa922005-10-04 17:48:46 +0000708private:
Jim Laskeyc03caef2006-07-17 17:38:29 +0000709 typename MapTy::iterator FindExistingElement(ConstantClass *CP) {
Chris Lattner935aa922005-10-04 17:48:46 +0000710 if (HasLargeKey) {
Jim Laskeyc03caef2006-07-17 17:38:29 +0000711 typename InverseMapTy::iterator IMI = InverseMap.find(CP);
Chris Lattner935aa922005-10-04 17:48:46 +0000712 assert(IMI != InverseMap.end() && IMI->second != Map.end() &&
713 IMI->second->second == CP &&
714 "InverseMap corrupt!");
715 return IMI->second;
716 }
717
Jim Laskeyc03caef2006-07-17 17:38:29 +0000718 typename MapTy::iterator I =
Chris Lattner935aa922005-10-04 17:48:46 +0000719 Map.find(MapKey((TypeClass*)CP->getRawType(), getValType(CP)));
Chris Lattner5bbf60a52005-10-04 16:52:46 +0000720 if (I == Map.end() || I->second != CP) {
721 // FIXME: This should not use a linear scan. If this gets to be a
722 // performance problem, someone should look at this.
723 for (I = Map.begin(); I != Map.end() && I->second != CP; ++I)
724 /* empty */;
725 }
Chris Lattner935aa922005-10-04 17:48:46 +0000726 return I;
727 }
728public:
729
Chris Lattnerb64419a2005-10-03 22:51:37 +0000730 /// getOrCreate - Return the specified constant from the map, creating it if
731 /// necessary.
Chris Lattner98fa07b2003-05-23 20:03:32 +0000732 ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
Chris Lattnerb50d1352003-10-05 00:17:43 +0000733 MapKey Lookup(Ty, V);
Jim Laskeyc03caef2006-07-17 17:38:29 +0000734 typename MapTy::iterator I = Map.lower_bound(Lookup);
Reid Spencere0fc4df2006-10-20 07:07:24 +0000735 // Is it in the map?
Chris Lattner98fa07b2003-05-23 20:03:32 +0000736 if (I != Map.end() && I->first == Lookup)
Reid Spencere0fc4df2006-10-20 07:07:24 +0000737 return static_cast<ConstantClass *>(I->second);
Chris Lattner98fa07b2003-05-23 20:03:32 +0000738
739 // If no preexisting value, create one now...
740 ConstantClass *Result =
741 ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
742
Chris Lattnerb50d1352003-10-05 00:17:43 +0000743 /// FIXME: why does this assert fail when loading 176.gcc?
744 //assert(Result->getType() == Ty && "Type specified is not correct!");
745 I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
746
Chris Lattner935aa922005-10-04 17:48:46 +0000747 if (HasLargeKey) // Remember the reverse mapping if needed.
748 InverseMap.insert(std::make_pair(Result, I));
749
Chris Lattnerb50d1352003-10-05 00:17:43 +0000750 // If the type of the constant is abstract, make sure that an entry exists
751 // for it in the AbstractTypeMap.
752 if (Ty->isAbstract()) {
753 typename AbstractTypeMapTy::iterator TI =
754 AbstractTypeMap.lower_bound(Ty);
755
756 if (TI == AbstractTypeMap.end() || TI->first != Ty) {
757 // Add ourselves to the ATU list of the type.
758 cast<DerivedType>(Ty)->addAbstractTypeUser(this);
759
760 AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
761 }
762 }
Chris Lattner98fa07b2003-05-23 20:03:32 +0000763 return Result;
764 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000765
Chris Lattner98fa07b2003-05-23 20:03:32 +0000766 void remove(ConstantClass *CP) {
Jim Laskeyc03caef2006-07-17 17:38:29 +0000767 typename MapTy::iterator I = FindExistingElement(CP);
Chris Lattnerb50d1352003-10-05 00:17:43 +0000768 assert(I != Map.end() && "Constant not found in constant table!");
Chris Lattner3e650af2004-08-04 04:48:01 +0000769 assert(I->second == CP && "Didn't find correct element?");
Chris Lattnerb50d1352003-10-05 00:17:43 +0000770
Chris Lattner935aa922005-10-04 17:48:46 +0000771 if (HasLargeKey) // Remember the reverse mapping if needed.
772 InverseMap.erase(CP);
773
Chris Lattnerb50d1352003-10-05 00:17:43 +0000774 // Now that we found the entry, make sure this isn't the entry that
775 // the AbstractTypeMap points to.
Jim Laskeyc03caef2006-07-17 17:38:29 +0000776 const TypeClass *Ty = static_cast<const TypeClass *>(I->first.first);
Chris Lattnerb50d1352003-10-05 00:17:43 +0000777 if (Ty->isAbstract()) {
778 assert(AbstractTypeMap.count(Ty) &&
779 "Abstract type not in AbstractTypeMap?");
Jim Laskeyc03caef2006-07-17 17:38:29 +0000780 typename MapTy::iterator &ATMEntryIt = AbstractTypeMap[Ty];
Chris Lattnerb50d1352003-10-05 00:17:43 +0000781 if (ATMEntryIt == I) {
782 // Yes, we are removing the representative entry for this type.
783 // See if there are any other entries of the same type.
Jim Laskeyc03caef2006-07-17 17:38:29 +0000784 typename MapTy::iterator TmpIt = ATMEntryIt;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000785
Chris Lattnerb50d1352003-10-05 00:17:43 +0000786 // First check the entry before this one...
787 if (TmpIt != Map.begin()) {
788 --TmpIt;
789 if (TmpIt->first.first != Ty) // Not the same type, move back...
790 ++TmpIt;
791 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000792
Chris Lattnerb50d1352003-10-05 00:17:43 +0000793 // If we didn't find the same type, try to move forward...
794 if (TmpIt == ATMEntryIt) {
795 ++TmpIt;
796 if (TmpIt == Map.end() || TmpIt->first.first != Ty)
797 --TmpIt; // No entry afterwards with the same type
798 }
799
800 // If there is another entry in the map of the same abstract type,
801 // update the AbstractTypeMap entry now.
802 if (TmpIt != ATMEntryIt) {
803 ATMEntryIt = TmpIt;
804 } else {
805 // Otherwise, we are removing the last instance of this type
806 // from the table. Remove from the ATM, and from user list.
807 cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
808 AbstractTypeMap.erase(Ty);
809 }
Chris Lattner98fa07b2003-05-23 20:03:32 +0000810 }
Chris Lattnerb50d1352003-10-05 00:17:43 +0000811 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000812
Chris Lattnerb50d1352003-10-05 00:17:43 +0000813 Map.erase(I);
814 }
815
Chris Lattner3b793c62005-10-04 21:35:50 +0000816
817 /// MoveConstantToNewSlot - If we are about to change C to be the element
818 /// specified by I, update our internal data structures to reflect this
819 /// fact.
Jim Laskeyc03caef2006-07-17 17:38:29 +0000820 void MoveConstantToNewSlot(ConstantClass *C, typename MapTy::iterator I) {
Chris Lattner3b793c62005-10-04 21:35:50 +0000821 // First, remove the old location of the specified constant in the map.
Jim Laskeyc03caef2006-07-17 17:38:29 +0000822 typename MapTy::iterator OldI = FindExistingElement(C);
Chris Lattner3b793c62005-10-04 21:35:50 +0000823 assert(OldI != Map.end() && "Constant not found in constant table!");
824 assert(OldI->second == C && "Didn't find correct element?");
825
826 // If this constant is the representative element for its abstract type,
827 // update the AbstractTypeMap so that the representative element is I.
828 if (C->getType()->isAbstract()) {
829 typename AbstractTypeMapTy::iterator ATI =
830 AbstractTypeMap.find(C->getType());
831 assert(ATI != AbstractTypeMap.end() &&
832 "Abstract type not in AbstractTypeMap?");
833 if (ATI->second == OldI)
834 ATI->second = I;
835 }
836
837 // Remove the old entry from the map.
838 Map.erase(OldI);
839
840 // Update the inverse map so that we know that this constant is now
841 // located at descriptor I.
842 if (HasLargeKey) {
843 assert(I->second == C && "Bad inversemap entry!");
844 InverseMap[C] = I;
845 }
846 }
847
Chris Lattnerb50d1352003-10-05 00:17:43 +0000848 void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
Misha Brukmanb1c93172005-04-21 23:48:37 +0000849 typename AbstractTypeMapTy::iterator I =
Jim Laskeyc03caef2006-07-17 17:38:29 +0000850 AbstractTypeMap.find(cast<Type>(OldTy));
Chris Lattnerb50d1352003-10-05 00:17:43 +0000851
852 assert(I != AbstractTypeMap.end() &&
853 "Abstract type not in AbstractTypeMap?");
854
855 // Convert a constant at a time until the last one is gone. The last one
856 // leaving will remove() itself, causing the AbstractTypeMapEntry to be
857 // eliminated eventually.
858 do {
859 ConvertConstantType<ConstantClass,
Jim Laskeyc03caef2006-07-17 17:38:29 +0000860 TypeClass>::convert(
861 static_cast<ConstantClass *>(I->second->second),
Chris Lattnerb50d1352003-10-05 00:17:43 +0000862 cast<TypeClass>(NewTy));
863
Jim Laskeyc03caef2006-07-17 17:38:29 +0000864 I = AbstractTypeMap.find(cast<Type>(OldTy));
Chris Lattnerb50d1352003-10-05 00:17:43 +0000865 } while (I != AbstractTypeMap.end());
866 }
867
868 // If the type became concrete without being refined to any other existing
869 // type, we just remove ourselves from the ATU list.
870 void typeBecameConcrete(const DerivedType *AbsTy) {
871 AbsTy->removeAbstractTypeUser(this);
872 }
873
874 void dump() const {
Bill Wendling6a462f12006-11-17 08:03:48 +0000875 DOUT << "Constant.cpp: ValueMap\n";
Chris Lattner98fa07b2003-05-23 20:03:32 +0000876 }
877 };
878}
879
Chris Lattnera84df0a22006-09-28 23:36:21 +0000880
881//---- ConstantBool::get*() implementation.
882
883ConstantBool *ConstantBool::getTrue() {
884 static ConstantBool *T = 0;
885 if (T) return T;
886 return T = new ConstantBool(true);
887}
888ConstantBool *ConstantBool::getFalse() {
889 static ConstantBool *F = 0;
890 if (F) return F;
891 return F = new ConstantBool(false);
892}
893
Reid Spencere0fc4df2006-10-20 07:07:24 +0000894//---- ConstantInt::get() implementations...
Chris Lattner49d855c2001-09-07 16:46:31 +0000895//
Reid Spencere0fc4df2006-10-20 07:07:24 +0000896static ManagedStatic<ValueMap<uint64_t, Type, ConstantInt> > IntConstants;
Chris Lattner49d855c2001-09-07 16:46:31 +0000897
Reid Spencere0fc4df2006-10-20 07:07:24 +0000898// Get a ConstantInt from an int64_t. Note here that we canoncialize the value
899// to a uint64_t value that has been zero extended down to the size of the
900// integer type of the ConstantInt. This allows the getZExtValue method to
901// just return the stored value while getSExtValue has to convert back to sign
902// extended. getZExtValue is more common in LLVM than getSExtValue().
903ConstantInt *ConstantInt::get(const Type *Ty, int64_t V) {
Chris Lattnerf16661c2006-12-01 19:20:02 +0000904 return IntConstants->getOrCreate(Ty, V & Ty->getIntegralTypeMask());
905}
906
907ConstantIntegral *ConstantIntegral::get(const Type *Ty, int64_t V) {
908 if (Ty == Type::BoolTy) return ConstantBool::get(V&1);
909 return IntConstants->getOrCreate(Ty, V & Ty->getIntegralTypeMask());
Chris Lattner49d855c2001-09-07 16:46:31 +0000910}
911
Chris Lattner3462ae32001-12-03 22:26:30 +0000912//---- ConstantFP::get() implementation...
Chris Lattner49d855c2001-09-07 16:46:31 +0000913//
Chris Lattnerac80ea42004-02-01 22:49:04 +0000914namespace llvm {
915 template<>
916 struct ConstantCreator<ConstantFP, Type, uint64_t> {
917 static ConstantFP *create(const Type *Ty, uint64_t V) {
918 assert(Ty == Type::DoubleTy);
Jim Laskeyb74c6662005-08-17 19:34:49 +0000919 return new ConstantFP(Ty, BitsToDouble(V));
Chris Lattnerac80ea42004-02-01 22:49:04 +0000920 }
921 };
922 template<>
923 struct ConstantCreator<ConstantFP, Type, uint32_t> {
924 static ConstantFP *create(const Type *Ty, uint32_t V) {
925 assert(Ty == Type::FloatTy);
Jim Laskeyb74c6662005-08-17 19:34:49 +0000926 return new ConstantFP(Ty, BitsToFloat(V));
Chris Lattnerac80ea42004-02-01 22:49:04 +0000927 }
928 };
929}
930
Chris Lattner69edc982006-09-28 00:35:06 +0000931static ManagedStatic<ValueMap<uint64_t, Type, ConstantFP> > DoubleConstants;
932static ManagedStatic<ValueMap<uint32_t, Type, ConstantFP> > FloatConstants;
Chris Lattner49d855c2001-09-07 16:46:31 +0000933
Jim Laskey8ad8f712005-08-17 20:06:22 +0000934bool ConstantFP::isNullValue() const {
935 return DoubleToBits(Val) == 0;
936}
937
938bool ConstantFP::isExactlyValue(double V) const {
939 return DoubleToBits(V) == DoubleToBits(Val);
940}
941
942
Chris Lattner3462ae32001-12-03 22:26:30 +0000943ConstantFP *ConstantFP::get(const Type *Ty, double V) {
Chris Lattner241ed4c2004-01-23 00:55:21 +0000944 if (Ty == Type::FloatTy) {
945 // Force the value through memory to normalize it.
Chris Lattner69edc982006-09-28 00:35:06 +0000946 return FloatConstants->getOrCreate(Ty, FloatToBits(V));
Chris Lattnerac80ea42004-02-01 22:49:04 +0000947 } else {
948 assert(Ty == Type::DoubleTy);
Chris Lattner69edc982006-09-28 00:35:06 +0000949 return DoubleConstants->getOrCreate(Ty, DoubleToBits(V));
Chris Lattner241ed4c2004-01-23 00:55:21 +0000950 }
Chris Lattner49d855c2001-09-07 16:46:31 +0000951}
952
Chris Lattner9fba3da2004-02-15 05:53:04 +0000953//---- ConstantAggregateZero::get() implementation...
954//
955namespace llvm {
956 // ConstantAggregateZero does not take extra "value" argument...
957 template<class ValType>
958 struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
959 static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
960 return new ConstantAggregateZero(Ty);
961 }
962 };
963
964 template<>
965 struct ConvertConstantType<ConstantAggregateZero, Type> {
966 static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
967 // Make everyone now use a constant of the new type...
968 Constant *New = ConstantAggregateZero::get(NewTy);
969 assert(New != OldC && "Didn't replace constant??");
970 OldC->uncheckedReplaceAllUsesWith(New);
971 OldC->destroyConstant(); // This constant is now dead, destroy it.
972 }
973 };
974}
975
Chris Lattner69edc982006-09-28 00:35:06 +0000976static ManagedStatic<ValueMap<char, Type,
977 ConstantAggregateZero> > AggZeroConstants;
Chris Lattner9fba3da2004-02-15 05:53:04 +0000978
Chris Lattner3e650af2004-08-04 04:48:01 +0000979static char getValType(ConstantAggregateZero *CPZ) { return 0; }
980
Chris Lattner9fba3da2004-02-15 05:53:04 +0000981Constant *ConstantAggregateZero::get(const Type *Ty) {
Chris Lattnerbfd0b6d2006-06-10 04:16:23 +0000982 assert((isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<PackedType>(Ty)) &&
983 "Cannot create an aggregate zero of non-aggregate type!");
Chris Lattner69edc982006-09-28 00:35:06 +0000984 return AggZeroConstants->getOrCreate(Ty, 0);
Chris Lattner9fba3da2004-02-15 05:53:04 +0000985}
986
987// destroyConstant - Remove the constant from the constant table...
988//
989void ConstantAggregateZero::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +0000990 AggZeroConstants->remove(this);
Chris Lattner9fba3da2004-02-15 05:53:04 +0000991 destroyConstantImpl();
992}
993
Chris Lattner3462ae32001-12-03 22:26:30 +0000994//---- ConstantArray::get() implementation...
Chris Lattner49d855c2001-09-07 16:46:31 +0000995//
Chris Lattner189d19f2003-11-21 20:23:48 +0000996namespace llvm {
997 template<>
998 struct ConvertConstantType<ConstantArray, ArrayType> {
999 static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
1000 // Make everyone now use a constant of the new type...
1001 std::vector<Constant*> C;
1002 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1003 C.push_back(cast<Constant>(OldC->getOperand(i)));
1004 Constant *New = ConstantArray::get(NewTy, C);
1005 assert(New != OldC && "Didn't replace constant??");
1006 OldC->uncheckedReplaceAllUsesWith(New);
1007 OldC->destroyConstant(); // This constant is now dead, destroy it.
1008 }
1009 };
1010}
Chris Lattnerb50d1352003-10-05 00:17:43 +00001011
Chris Lattner3e650af2004-08-04 04:48:01 +00001012static std::vector<Constant*> getValType(ConstantArray *CA) {
1013 std::vector<Constant*> Elements;
1014 Elements.reserve(CA->getNumOperands());
1015 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1016 Elements.push_back(cast<Constant>(CA->getOperand(i)));
1017 return Elements;
1018}
1019
Chris Lattnerb64419a2005-10-03 22:51:37 +00001020typedef ValueMap<std::vector<Constant*>, ArrayType,
Chris Lattner935aa922005-10-04 17:48:46 +00001021 ConstantArray, true /*largekey*/> ArrayConstantsTy;
Chris Lattner69edc982006-09-28 00:35:06 +00001022static ManagedStatic<ArrayConstantsTy> ArrayConstants;
Chris Lattner49d855c2001-09-07 16:46:31 +00001023
Chris Lattner015e8212004-02-15 04:14:47 +00001024Constant *ConstantArray::get(const ArrayType *Ty,
Chris Lattner9fba3da2004-02-15 05:53:04 +00001025 const std::vector<Constant*> &V) {
1026 // If this is an all-zero array, return a ConstantAggregateZero object
1027 if (!V.empty()) {
1028 Constant *C = V[0];
1029 if (!C->isNullValue())
Chris Lattner69edc982006-09-28 00:35:06 +00001030 return ArrayConstants->getOrCreate(Ty, V);
Chris Lattner9fba3da2004-02-15 05:53:04 +00001031 for (unsigned i = 1, e = V.size(); i != e; ++i)
1032 if (V[i] != C)
Chris Lattner69edc982006-09-28 00:35:06 +00001033 return ArrayConstants->getOrCreate(Ty, V);
Chris Lattner9fba3da2004-02-15 05:53:04 +00001034 }
1035 return ConstantAggregateZero::get(Ty);
Chris Lattner49d855c2001-09-07 16:46:31 +00001036}
1037
Chris Lattner98fa07b2003-05-23 20:03:32 +00001038// destroyConstant - Remove the constant from the constant table...
1039//
1040void ConstantArray::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00001041 ArrayConstants->remove(this);
Chris Lattner98fa07b2003-05-23 20:03:32 +00001042 destroyConstantImpl();
1043}
1044
Reid Spencer6f614532006-05-30 08:23:18 +00001045/// ConstantArray::get(const string&) - Return an array that is initialized to
1046/// contain the specified string. If length is zero then a null terminator is
1047/// added to the specified string so that it may be used in a natural way.
1048/// Otherwise, the length parameter specifies how much of the string to use
1049/// and it won't be null terminated.
1050///
Reid Spencer82ebaba2006-05-30 18:15:07 +00001051Constant *ConstantArray::get(const std::string &Str, bool AddNull) {
Chris Lattner7f74a562002-01-20 22:54:45 +00001052 std::vector<Constant*> ElementVals;
Reid Spencer82ebaba2006-05-30 18:15:07 +00001053 for (unsigned i = 0; i < Str.length(); ++i)
Reid Spencere0fc4df2006-10-20 07:07:24 +00001054 ElementVals.push_back(ConstantInt::get(Type::SByteTy, Str[i]));
Chris Lattner8f80fe02001-10-14 23:54:12 +00001055
1056 // Add a null terminator to the string...
Reid Spencer82ebaba2006-05-30 18:15:07 +00001057 if (AddNull) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00001058 ElementVals.push_back(ConstantInt::get(Type::SByteTy, 0));
Reid Spencer6f614532006-05-30 08:23:18 +00001059 }
Chris Lattner8f80fe02001-10-14 23:54:12 +00001060
Reid Spencer82ebaba2006-05-30 18:15:07 +00001061 ArrayType *ATy = ArrayType::get(Type::SByteTy, ElementVals.size());
Chris Lattner3462ae32001-12-03 22:26:30 +00001062 return ConstantArray::get(ATy, ElementVals);
Vikram S. Adve34410432001-10-14 23:17:20 +00001063}
1064
Chris Lattnere8dfcca2004-01-14 17:06:38 +00001065/// isString - This method returns true if the array is an array of sbyte or
1066/// ubyte, and if the elements of the array are all ConstantInt's.
1067bool ConstantArray::isString() const {
1068 // Check the element type for sbyte or ubyte...
Chris Lattnere8701f62004-01-14 17:51:53 +00001069 if (getType()->getElementType() != Type::UByteTy &&
Chris Lattnere8dfcca2004-01-14 17:06:38 +00001070 getType()->getElementType() != Type::SByteTy)
1071 return false;
1072 // Check the elements to make sure they are all integers, not constant
1073 // expressions.
1074 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1075 if (!isa<ConstantInt>(getOperand(i)))
1076 return false;
1077 return true;
1078}
1079
Evan Cheng3763c5b2006-10-26 19:15:05 +00001080/// isCString - This method returns true if the array is a string (see
1081/// isString) and it ends in a null byte \0 and does not contains any other
1082/// null bytes except its terminator.
1083bool ConstantArray::isCString() const {
Evan Chenge974da62006-10-26 21:48:03 +00001084 // Check the element type for sbyte or ubyte...
1085 if (getType()->getElementType() != Type::UByteTy &&
1086 getType()->getElementType() != Type::SByteTy)
1087 return false;
1088 Constant *Zero = Constant::getNullValue(getOperand(0)->getType());
1089 // Last element must be a null.
1090 if (getOperand(getNumOperands()-1) != Zero)
1091 return false;
1092 // Other elements must be non-null integers.
1093 for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
1094 if (!isa<ConstantInt>(getOperand(i)))
Evan Cheng3763c5b2006-10-26 19:15:05 +00001095 return false;
Evan Chenge974da62006-10-26 21:48:03 +00001096 if (getOperand(i) == Zero)
1097 return false;
1098 }
Evan Cheng3763c5b2006-10-26 19:15:05 +00001099 return true;
1100}
1101
1102
Chris Lattner81fabb02002-08-26 17:53:56 +00001103// getAsString - If the sub-element type of this array is either sbyte or ubyte,
1104// then this method converts the array to an std::string and returns it.
1105// Otherwise, it asserts out.
1106//
1107std::string ConstantArray::getAsString() const {
Chris Lattnere8dfcca2004-01-14 17:06:38 +00001108 assert(isString() && "Not a string!");
Chris Lattner81fabb02002-08-26 17:53:56 +00001109 std::string Result;
Chris Lattner6077c312003-07-23 15:22:26 +00001110 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
Reid Spencere0fc4df2006-10-20 07:07:24 +00001111 Result += (char)cast<ConstantInt>(getOperand(i))->getZExtValue();
Chris Lattner81fabb02002-08-26 17:53:56 +00001112 return Result;
1113}
1114
1115
Chris Lattner3462ae32001-12-03 22:26:30 +00001116//---- ConstantStruct::get() implementation...
Chris Lattner49d855c2001-09-07 16:46:31 +00001117//
Chris Lattnerb50d1352003-10-05 00:17:43 +00001118
Chris Lattner189d19f2003-11-21 20:23:48 +00001119namespace llvm {
1120 template<>
1121 struct ConvertConstantType<ConstantStruct, StructType> {
1122 static void convert(ConstantStruct *OldC, const StructType *NewTy) {
1123 // Make everyone now use a constant of the new type...
1124 std::vector<Constant*> C;
1125 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1126 C.push_back(cast<Constant>(OldC->getOperand(i)));
1127 Constant *New = ConstantStruct::get(NewTy, C);
1128 assert(New != OldC && "Didn't replace constant??");
Misha Brukmanb1c93172005-04-21 23:48:37 +00001129
Chris Lattner189d19f2003-11-21 20:23:48 +00001130 OldC->uncheckedReplaceAllUsesWith(New);
1131 OldC->destroyConstant(); // This constant is now dead, destroy it.
1132 }
1133 };
1134}
Chris Lattnerb50d1352003-10-05 00:17:43 +00001135
Chris Lattner8760ec72005-10-04 01:17:50 +00001136typedef ValueMap<std::vector<Constant*>, StructType,
Chris Lattner935aa922005-10-04 17:48:46 +00001137 ConstantStruct, true /*largekey*/> StructConstantsTy;
Chris Lattner69edc982006-09-28 00:35:06 +00001138static ManagedStatic<StructConstantsTy> StructConstants;
Chris Lattner49d855c2001-09-07 16:46:31 +00001139
Chris Lattner3e650af2004-08-04 04:48:01 +00001140static std::vector<Constant*> getValType(ConstantStruct *CS) {
1141 std::vector<Constant*> Elements;
1142 Elements.reserve(CS->getNumOperands());
1143 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1144 Elements.push_back(cast<Constant>(CS->getOperand(i)));
1145 return Elements;
1146}
1147
Chris Lattner015e8212004-02-15 04:14:47 +00001148Constant *ConstantStruct::get(const StructType *Ty,
1149 const std::vector<Constant*> &V) {
Chris Lattner9fba3da2004-02-15 05:53:04 +00001150 // Create a ConstantAggregateZero value if all elements are zeros...
1151 for (unsigned i = 0, e = V.size(); i != e; ++i)
1152 if (!V[i]->isNullValue())
Chris Lattner69edc982006-09-28 00:35:06 +00001153 return StructConstants->getOrCreate(Ty, V);
Chris Lattner9fba3da2004-02-15 05:53:04 +00001154
1155 return ConstantAggregateZero::get(Ty);
Chris Lattner49d855c2001-09-07 16:46:31 +00001156}
Chris Lattner883ad0b2001-10-03 15:39:36 +00001157
Andrew Lenharthdcb3c972006-12-08 18:06:16 +00001158Constant *ConstantStruct::get(const std::vector<Constant*> &V, bool packed) {
Chris Lattnerd6108ca2004-07-12 20:35:11 +00001159 std::vector<const Type*> StructEls;
1160 StructEls.reserve(V.size());
1161 for (unsigned i = 0, e = V.size(); i != e; ++i)
1162 StructEls.push_back(V[i]->getType());
Andrew Lenharthdcb3c972006-12-08 18:06:16 +00001163 return get(StructType::get(StructEls, packed), V);
Chris Lattnerd6108ca2004-07-12 20:35:11 +00001164}
1165
Chris Lattnerd7a73302001-10-13 06:57:33 +00001166// destroyConstant - Remove the constant from the constant table...
Chris Lattner883ad0b2001-10-03 15:39:36 +00001167//
Chris Lattner3462ae32001-12-03 22:26:30 +00001168void ConstantStruct::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00001169 StructConstants->remove(this);
Chris Lattnerd7a73302001-10-13 06:57:33 +00001170 destroyConstantImpl();
1171}
Chris Lattner883ad0b2001-10-03 15:39:36 +00001172
Brian Gaeke02209042004-08-20 06:00:58 +00001173//---- ConstantPacked::get() implementation...
1174//
1175namespace llvm {
1176 template<>
1177 struct ConvertConstantType<ConstantPacked, PackedType> {
1178 static void convert(ConstantPacked *OldC, const PackedType *NewTy) {
1179 // Make everyone now use a constant of the new type...
1180 std::vector<Constant*> C;
1181 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1182 C.push_back(cast<Constant>(OldC->getOperand(i)));
1183 Constant *New = ConstantPacked::get(NewTy, C);
1184 assert(New != OldC && "Didn't replace constant??");
1185 OldC->uncheckedReplaceAllUsesWith(New);
1186 OldC->destroyConstant(); // This constant is now dead, destroy it.
1187 }
1188 };
1189}
1190
1191static std::vector<Constant*> getValType(ConstantPacked *CP) {
1192 std::vector<Constant*> Elements;
1193 Elements.reserve(CP->getNumOperands());
1194 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1195 Elements.push_back(CP->getOperand(i));
1196 return Elements;
1197}
1198
Chris Lattner69edc982006-09-28 00:35:06 +00001199static ManagedStatic<ValueMap<std::vector<Constant*>, PackedType,
1200 ConstantPacked> > PackedConstants;
Brian Gaeke02209042004-08-20 06:00:58 +00001201
1202Constant *ConstantPacked::get(const PackedType *Ty,
1203 const std::vector<Constant*> &V) {
1204 // If this is an all-zero packed, return a ConstantAggregateZero object
1205 if (!V.empty()) {
1206 Constant *C = V[0];
1207 if (!C->isNullValue())
Chris Lattner69edc982006-09-28 00:35:06 +00001208 return PackedConstants->getOrCreate(Ty, V);
Brian Gaeke02209042004-08-20 06:00:58 +00001209 for (unsigned i = 1, e = V.size(); i != e; ++i)
1210 if (V[i] != C)
Chris Lattner69edc982006-09-28 00:35:06 +00001211 return PackedConstants->getOrCreate(Ty, V);
Brian Gaeke02209042004-08-20 06:00:58 +00001212 }
1213 return ConstantAggregateZero::get(Ty);
1214}
1215
1216Constant *ConstantPacked::get(const std::vector<Constant*> &V) {
1217 assert(!V.empty() && "Cannot infer type if V is empty");
1218 return get(PackedType::get(V.front()->getType(),V.size()), V);
1219}
1220
1221// destroyConstant - Remove the constant from the constant table...
1222//
1223void ConstantPacked::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00001224 PackedConstants->remove(this);
Brian Gaeke02209042004-08-20 06:00:58 +00001225 destroyConstantImpl();
1226}
1227
Chris Lattner3462ae32001-12-03 22:26:30 +00001228//---- ConstantPointerNull::get() implementation...
Chris Lattnerd7a73302001-10-13 06:57:33 +00001229//
Chris Lattner98fa07b2003-05-23 20:03:32 +00001230
Chris Lattner189d19f2003-11-21 20:23:48 +00001231namespace llvm {
1232 // ConstantPointerNull does not take extra "value" argument...
1233 template<class ValType>
1234 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1235 static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1236 return new ConstantPointerNull(Ty);
1237 }
1238 };
Chris Lattner98fa07b2003-05-23 20:03:32 +00001239
Chris Lattner189d19f2003-11-21 20:23:48 +00001240 template<>
1241 struct ConvertConstantType<ConstantPointerNull, PointerType> {
1242 static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1243 // Make everyone now use a constant of the new type...
1244 Constant *New = ConstantPointerNull::get(NewTy);
1245 assert(New != OldC && "Didn't replace constant??");
1246 OldC->uncheckedReplaceAllUsesWith(New);
1247 OldC->destroyConstant(); // This constant is now dead, destroy it.
1248 }
1249 };
1250}
Chris Lattnerb50d1352003-10-05 00:17:43 +00001251
Chris Lattner69edc982006-09-28 00:35:06 +00001252static ManagedStatic<ValueMap<char, PointerType,
1253 ConstantPointerNull> > NullPtrConstants;
Chris Lattnerd7a73302001-10-13 06:57:33 +00001254
Chris Lattner3e650af2004-08-04 04:48:01 +00001255static char getValType(ConstantPointerNull *) {
1256 return 0;
1257}
1258
1259
Chris Lattner3462ae32001-12-03 22:26:30 +00001260ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
Chris Lattner69edc982006-09-28 00:35:06 +00001261 return NullPtrConstants->getOrCreate(Ty, 0);
Chris Lattner883ad0b2001-10-03 15:39:36 +00001262}
1263
Chris Lattner0c6e0b92002-08-18 00:40:04 +00001264// destroyConstant - Remove the constant from the constant table...
1265//
1266void ConstantPointerNull::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00001267 NullPtrConstants->remove(this);
Chris Lattner0c6e0b92002-08-18 00:40:04 +00001268 destroyConstantImpl();
1269}
1270
1271
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001272//---- UndefValue::get() implementation...
1273//
1274
1275namespace llvm {
1276 // UndefValue does not take extra "value" argument...
1277 template<class ValType>
1278 struct ConstantCreator<UndefValue, Type, ValType> {
1279 static UndefValue *create(const Type *Ty, const ValType &V) {
1280 return new UndefValue(Ty);
1281 }
1282 };
1283
1284 template<>
1285 struct ConvertConstantType<UndefValue, Type> {
1286 static void convert(UndefValue *OldC, const Type *NewTy) {
1287 // Make everyone now use a constant of the new type.
1288 Constant *New = UndefValue::get(NewTy);
1289 assert(New != OldC && "Didn't replace constant??");
1290 OldC->uncheckedReplaceAllUsesWith(New);
1291 OldC->destroyConstant(); // This constant is now dead, destroy it.
1292 }
1293 };
1294}
1295
Chris Lattner69edc982006-09-28 00:35:06 +00001296static ManagedStatic<ValueMap<char, Type, UndefValue> > UndefValueConstants;
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001297
1298static char getValType(UndefValue *) {
1299 return 0;
1300}
1301
1302
1303UndefValue *UndefValue::get(const Type *Ty) {
Chris Lattner69edc982006-09-28 00:35:06 +00001304 return UndefValueConstants->getOrCreate(Ty, 0);
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001305}
1306
1307// destroyConstant - Remove the constant from the constant table.
1308//
1309void UndefValue::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00001310 UndefValueConstants->remove(this);
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001311 destroyConstantImpl();
1312}
1313
1314
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001315//---- ConstantExpr::get() implementations...
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001316//
Reid Spenceree3c9912006-12-04 05:19:50 +00001317struct ExprMapKeyType {
1318 explicit ExprMapKeyType(unsigned opc, std::vector<Constant*> ops,
Reid Spencerdba6aa42006-12-04 18:38:05 +00001319 unsigned short pred = 0) : opcode(opc), predicate(pred), operands(ops) { }
1320 uint16_t opcode;
1321 uint16_t predicate;
Reid Spenceree3c9912006-12-04 05:19:50 +00001322 std::vector<Constant*> operands;
Reid Spenceree3c9912006-12-04 05:19:50 +00001323 bool operator==(const ExprMapKeyType& that) const {
1324 return this->opcode == that.opcode &&
1325 this->predicate == that.predicate &&
1326 this->operands == that.operands;
1327 }
1328 bool operator<(const ExprMapKeyType & that) const {
1329 return this->opcode < that.opcode ||
1330 (this->opcode == that.opcode && this->predicate < that.predicate) ||
1331 (this->opcode == that.opcode && this->predicate == that.predicate &&
1332 this->operands < that.operands);
1333 }
1334
1335 bool operator!=(const ExprMapKeyType& that) const {
1336 return !(*this == that);
1337 }
1338};
Chris Lattner98fa07b2003-05-23 20:03:32 +00001339
Chris Lattner189d19f2003-11-21 20:23:48 +00001340namespace llvm {
1341 template<>
1342 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
Reid Spencer10fbf0e2006-12-03 05:48:19 +00001343 static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V,
1344 unsigned short pred = 0) {
Reid Spenceree3c9912006-12-04 05:19:50 +00001345 if (Instruction::isCast(V.opcode))
1346 return new UnaryConstantExpr(V.opcode, V.operands[0], Ty);
1347 if ((V.opcode >= Instruction::BinaryOpsBegin &&
1348 V.opcode < Instruction::BinaryOpsEnd) ||
1349 V.opcode == Instruction::Shl ||
1350 V.opcode == Instruction::LShr ||
1351 V.opcode == Instruction::AShr)
1352 return new BinaryConstantExpr(V.opcode, V.operands[0], V.operands[1]);
1353 if (V.opcode == Instruction::Select)
1354 return new SelectConstantExpr(V.operands[0], V.operands[1],
1355 V.operands[2]);
1356 if (V.opcode == Instruction::ExtractElement)
1357 return new ExtractElementConstantExpr(V.operands[0], V.operands[1]);
1358 if (V.opcode == Instruction::InsertElement)
1359 return new InsertElementConstantExpr(V.operands[0], V.operands[1],
1360 V.operands[2]);
1361 if (V.opcode == Instruction::ShuffleVector)
1362 return new ShuffleVectorConstantExpr(V.operands[0], V.operands[1],
1363 V.operands[2]);
1364 if (V.opcode == Instruction::GetElementPtr) {
1365 std::vector<Constant*> IdxList(V.operands.begin()+1, V.operands.end());
1366 return new GetElementPtrConstantExpr(V.operands[0], IdxList, Ty);
1367 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001368
Reid Spenceree3c9912006-12-04 05:19:50 +00001369 // The compare instructions are weird. We have to encode the predicate
1370 // value and it is combined with the instruction opcode by multiplying
1371 // the opcode by one hundred. We must decode this to get the predicate.
1372 if (V.opcode == Instruction::ICmp)
1373 return new CompareConstantExpr(Instruction::ICmp, V.predicate,
1374 V.operands[0], V.operands[1]);
1375 if (V.opcode == Instruction::FCmp)
1376 return new CompareConstantExpr(Instruction::FCmp, V.predicate,
1377 V.operands[0], V.operands[1]);
1378 assert(0 && "Invalid ConstantExpr!");
Jeff Cohen9f469632006-12-15 21:47:01 +00001379 return 0;
Chris Lattnerb50d1352003-10-05 00:17:43 +00001380 }
Chris Lattner189d19f2003-11-21 20:23:48 +00001381 };
Chris Lattnerb50d1352003-10-05 00:17:43 +00001382
Chris Lattner189d19f2003-11-21 20:23:48 +00001383 template<>
1384 struct ConvertConstantType<ConstantExpr, Type> {
1385 static void convert(ConstantExpr *OldC, const Type *NewTy) {
1386 Constant *New;
1387 switch (OldC->getOpcode()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001388 case Instruction::Trunc:
1389 case Instruction::ZExt:
1390 case Instruction::SExt:
1391 case Instruction::FPTrunc:
1392 case Instruction::FPExt:
1393 case Instruction::UIToFP:
1394 case Instruction::SIToFP:
1395 case Instruction::FPToUI:
1396 case Instruction::FPToSI:
1397 case Instruction::PtrToInt:
1398 case Instruction::IntToPtr:
1399 case Instruction::BitCast:
Reid Spencerbb65ebf2006-12-12 23:36:14 +00001400 New = ConstantExpr::getCast(OldC->getOpcode(), OldC->getOperand(0),
1401 NewTy);
Chris Lattner189d19f2003-11-21 20:23:48 +00001402 break;
Chris Lattner6e415c02004-03-12 05:54:04 +00001403 case Instruction::Select:
1404 New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1405 OldC->getOperand(1),
1406 OldC->getOperand(2));
1407 break;
Chris Lattner189d19f2003-11-21 20:23:48 +00001408 case Instruction::Shl:
Reid Spencerfdff9382006-11-08 06:47:33 +00001409 case Instruction::LShr:
1410 case Instruction::AShr:
Chris Lattner189d19f2003-11-21 20:23:48 +00001411 New = ConstantExpr::getShiftTy(NewTy, OldC->getOpcode(),
1412 OldC->getOperand(0), OldC->getOperand(1));
1413 break;
1414 default:
1415 assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
Reid Spencer7eb55b32006-11-02 01:53:59 +00001416 OldC->getOpcode() < Instruction::BinaryOpsEnd);
Chris Lattner189d19f2003-11-21 20:23:48 +00001417 New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1418 OldC->getOperand(1));
1419 break;
1420 case Instruction::GetElementPtr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00001421 // Make everyone now use a constant of the new type...
Chris Lattner13128ab2004-10-11 22:52:25 +00001422 std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
1423 New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0), Idx);
Chris Lattner189d19f2003-11-21 20:23:48 +00001424 break;
1425 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001426
Chris Lattner189d19f2003-11-21 20:23:48 +00001427 assert(New != OldC && "Didn't replace constant??");
1428 OldC->uncheckedReplaceAllUsesWith(New);
1429 OldC->destroyConstant(); // This constant is now dead, destroy it.
1430 }
1431 };
1432} // end namespace llvm
Chris Lattnerb50d1352003-10-05 00:17:43 +00001433
1434
Chris Lattner3e650af2004-08-04 04:48:01 +00001435static ExprMapKeyType getValType(ConstantExpr *CE) {
1436 std::vector<Constant*> Operands;
1437 Operands.reserve(CE->getNumOperands());
1438 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
1439 Operands.push_back(cast<Constant>(CE->getOperand(i)));
Reid Spenceree3c9912006-12-04 05:19:50 +00001440 return ExprMapKeyType(CE->getOpcode(), Operands,
1441 CE->isCompare() ? CE->getPredicate() : 0);
Chris Lattner3e650af2004-08-04 04:48:01 +00001442}
1443
Chris Lattner69edc982006-09-28 00:35:06 +00001444static ManagedStatic<ValueMap<ExprMapKeyType, Type,
1445 ConstantExpr> > ExprConstants;
Vikram S. Adve4c485332002-07-15 18:19:33 +00001446
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001447/// This is a utility function to handle folding of casts and lookup of the
1448/// cast in the ExprConstants map. It is usedby the various get* methods below.
1449static inline Constant *getFoldedCast(
1450 Instruction::CastOps opc, Constant *C, const Type *Ty) {
Chris Lattner815ae2b2003-10-07 22:19:19 +00001451 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001452 // Fold a few common cases
1453 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
1454 return FC;
Chris Lattneracdbe712003-04-17 19:24:48 +00001455
Vikram S. Adve4c485332002-07-15 18:19:33 +00001456 // Look up the constant in the table first to ensure uniqueness
Chris Lattner2b383d2e2003-05-13 21:37:02 +00001457 std::vector<Constant*> argVec(1, C);
Reid Spenceree3c9912006-12-04 05:19:50 +00001458 ExprMapKeyType Key(opc, argVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001459 return ExprConstants->getOrCreate(Ty, Key);
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001460}
Reid Spencerf37dc652006-12-05 19:14:13 +00001461
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001462Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
1463 Instruction::CastOps opc = Instruction::CastOps(oc);
1464 assert(Instruction::isCast(opc) && "opcode out of range");
1465 assert(C && Ty && "Null arguments to getCast");
1466 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1467
1468 switch (opc) {
1469 default:
1470 assert(0 && "Invalid cast opcode");
1471 break;
1472 case Instruction::Trunc: return getTrunc(C, Ty);
Reid Spencerbb65ebf2006-12-12 23:36:14 +00001473 case Instruction::ZExt: return getZExt(C, Ty);
1474 case Instruction::SExt: return getSExt(C, Ty);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001475 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
1476 case Instruction::FPExt: return getFPExtend(C, Ty);
1477 case Instruction::UIToFP: return getUIToFP(C, Ty);
1478 case Instruction::SIToFP: return getSIToFP(C, Ty);
1479 case Instruction::FPToUI: return getFPToUI(C, Ty);
1480 case Instruction::FPToSI: return getFPToSI(C, Ty);
1481 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1482 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1483 case Instruction::BitCast: return getBitCast(C, Ty);
Chris Lattner1ece6f82005-01-01 15:59:57 +00001484 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001485 return 0;
Reid Spencerf37dc652006-12-05 19:14:13 +00001486}
1487
Reid Spencer5c140882006-12-04 20:17:56 +00001488Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
1489 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1490 return getCast(Instruction::BitCast, C, Ty);
1491 return getCast(Instruction::ZExt, C, Ty);
1492}
1493
1494Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
1495 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1496 return getCast(Instruction::BitCast, C, Ty);
1497 return getCast(Instruction::SExt, C, Ty);
1498}
1499
1500Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
1501 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1502 return getCast(Instruction::BitCast, C, Ty);
1503 return getCast(Instruction::Trunc, C, Ty);
1504}
1505
Reid Spencerbc245a02006-12-05 03:25:26 +00001506Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
1507 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1508 assert((Ty->isIntegral() || Ty->getTypeID() == Type::PointerTyID) &&
1509 "Invalid cast");
1510
1511 if (Ty->isIntegral())
1512 return getCast(Instruction::PtrToInt, S, Ty);
1513 return getCast(Instruction::BitCast, S, Ty);
1514}
1515
Reid Spencer56521c42006-12-12 00:51:07 +00001516Constant *ConstantExpr::getIntegerCast(Constant *C, const Type *Ty,
1517 bool isSigned) {
1518 assert(C->getType()->isIntegral() && Ty->isIntegral() && "Invalid cast");
1519 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1520 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1521 Instruction::CastOps opcode =
1522 (SrcBits == DstBits ? Instruction::BitCast :
1523 (SrcBits > DstBits ? Instruction::Trunc :
1524 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1525 return getCast(opcode, C, Ty);
1526}
1527
1528Constant *ConstantExpr::getFPCast(Constant *C, const Type *Ty) {
1529 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1530 "Invalid cast");
1531 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1532 unsigned DstBits = Ty->getPrimitiveSizeInBits();
Reid Spencerca104e82006-12-12 05:38:50 +00001533 if (SrcBits == DstBits)
1534 return C; // Avoid a useless cast
Reid Spencer56521c42006-12-12 00:51:07 +00001535 Instruction::CastOps opcode =
Reid Spencerca104e82006-12-12 05:38:50 +00001536 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
Reid Spencer56521c42006-12-12 00:51:07 +00001537 return getCast(opcode, C, Ty);
1538}
1539
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001540Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
1541 assert(C->getType()->isInteger() && "Trunc operand must be integer");
1542 assert(Ty->isIntegral() && "Trunc produces only integral");
1543 assert(C->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()&&
1544 "SrcTy must be larger than DestTy for Trunc!");
1545
1546 return getFoldedCast(Instruction::Trunc, C, Ty);
1547}
1548
Reid Spencerbb65ebf2006-12-12 23:36:14 +00001549Constant *ConstantExpr::getSExt(Constant *C, const Type *Ty) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001550 assert(C->getType()->isIntegral() && "SEXt operand must be integral");
1551 assert(Ty->isInteger() && "SExt produces only integer");
1552 assert(C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1553 "SrcTy must be smaller than DestTy for SExt!");
1554
1555 return getFoldedCast(Instruction::SExt, C, Ty);
Chris Lattnerdd284742004-04-04 23:20:30 +00001556}
1557
Reid Spencerbb65ebf2006-12-12 23:36:14 +00001558Constant *ConstantExpr::getZExt(Constant *C, const Type *Ty) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001559 assert(C->getType()->isIntegral() && "ZEXt operand must be integral");
1560 assert(Ty->isInteger() && "ZExt produces only integer");
1561 assert(C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1562 "SrcTy must be smaller than DestTy for ZExt!");
1563
1564 return getFoldedCast(Instruction::ZExt, C, Ty);
1565}
1566
1567Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
1568 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1569 C->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()&&
1570 "This is an illegal floating point truncation!");
1571 return getFoldedCast(Instruction::FPTrunc, C, Ty);
1572}
1573
1574Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
1575 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1576 C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1577 "This is an illegal floating point extension!");
1578 return getFoldedCast(Instruction::FPExt, C, Ty);
1579}
1580
1581Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
1582 assert(C->getType()->isIntegral() && Ty->isFloatingPoint() &&
1583 "This is an illegal uint to floating point cast!");
1584 return getFoldedCast(Instruction::UIToFP, C, Ty);
1585}
1586
1587Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
1588 assert(C->getType()->isIntegral() && Ty->isFloatingPoint() &&
1589 "This is an illegal sint to floating point cast!");
1590 return getFoldedCast(Instruction::SIToFP, C, Ty);
1591}
1592
1593Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
1594 assert(C->getType()->isFloatingPoint() && Ty->isIntegral() &&
1595 "This is an illegal floating point to uint cast!");
1596 return getFoldedCast(Instruction::FPToUI, C, Ty);
1597}
1598
1599Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
1600 assert(C->getType()->isFloatingPoint() && Ty->isIntegral() &&
1601 "This is an illegal floating point to sint cast!");
1602 return getFoldedCast(Instruction::FPToSI, C, Ty);
1603}
1604
1605Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
1606 assert(isa<PointerType>(C->getType()) && "PtrToInt source must be pointer");
1607 assert(DstTy->isIntegral() && "PtrToInt destination must be integral");
1608 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
1609}
1610
1611Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
1612 assert(C->getType()->isIntegral() && "IntToPtr source must be integral");
1613 assert(isa<PointerType>(DstTy) && "IntToPtr destination must be a pointer");
1614 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
1615}
1616
1617Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
1618 // BitCast implies a no-op cast of type only. No bits change. However, you
1619 // can't cast pointers to anything but pointers.
1620 const Type *SrcTy = C->getType();
1621 assert((isa<PointerType>(SrcTy) == isa<PointerType>(DstTy)) &&
Reid Spencer5c140882006-12-04 20:17:56 +00001622 "BitCast cannot cast pointer to non-pointer and vice versa");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001623
1624 // Now we know we're not dealing with mismatched pointer casts (ptr->nonptr
1625 // or nonptr->ptr). For all the other types, the cast is okay if source and
1626 // destination bit widths are identical.
1627 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1628 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
Reid Spencer5c140882006-12-04 20:17:56 +00001629 assert(SrcBitSize == DstBitSize && "BitCast requies types of same width");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001630 return getFoldedCast(Instruction::BitCast, C, DstTy);
Chris Lattnerdd284742004-04-04 23:20:30 +00001631}
1632
Alkis Evlogimenosda5de052004-10-24 01:41:10 +00001633Constant *ConstantExpr::getSizeOf(const Type *Ty) {
Chris Lattneracc4e542004-12-13 19:48:51 +00001634 // sizeof is implemented as: (ulong) gep (Ty*)null, 1
Reid Spencerc4dacf22006-12-04 02:43:42 +00001635 return getCast(Instruction::PtrToInt, getGetElementPtr(getNullValue(
1636 PointerType::get(Ty)), std::vector<Constant*>(1,
1637 ConstantInt::get(Type::UIntTy, 1))), Type::ULongTy);
Alkis Evlogimenosda5de052004-10-24 01:41:10 +00001638}
1639
Alkis Evlogimenos9160d5f2005-03-19 11:40:31 +00001640Constant *ConstantExpr::getPtrPtrFromArrayPtr(Constant *C) {
1641 // pointer from array is implemented as: getelementptr arr ptr, 0, 0
Reid Spencere0fc4df2006-10-20 07:07:24 +00001642 static std::vector<Constant*> Indices(2, ConstantInt::get(Type::UIntTy, 0));
Alkis Evlogimenos9160d5f2005-03-19 11:40:31 +00001643
1644 return ConstantExpr::getGetElementPtr(C, Indices);
1645}
1646
Chris Lattnerb50d1352003-10-05 00:17:43 +00001647Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
Reid Spencera009d0d2006-12-04 21:35:24 +00001648 Constant *C1, Constant *C2) {
Reid Spencerfdff9382006-11-08 06:47:33 +00001649 if (Opcode == Instruction::Shl || Opcode == Instruction::LShr ||
1650 Opcode == Instruction::AShr)
Chris Lattner5645e8a2004-01-12 19:04:55 +00001651 return getShiftTy(ReqTy, Opcode, C1, C2);
Reid Spenceree3c9912006-12-04 05:19:50 +00001652
Chris Lattner38a9bcd2003-05-21 17:49:25 +00001653 // Check the operands for consistency first
Reid Spencer7eb55b32006-11-02 01:53:59 +00001654 assert(Opcode >= Instruction::BinaryOpsBegin &&
1655 Opcode < Instruction::BinaryOpsEnd &&
Chris Lattner38a9bcd2003-05-21 17:49:25 +00001656 "Invalid opcode in binary constant expression");
1657 assert(C1->getType() == C2->getType() &&
1658 "Operand types in binary constant expression should match");
Chris Lattnerb50d1352003-10-05 00:17:43 +00001659
Chris Lattnere1496fb2006-09-17 19:14:47 +00001660 if (ReqTy == C1->getType() || (Instruction::isComparison(Opcode) &&
Chris Lattner29ca2c62004-08-04 18:50:09 +00001661 ReqTy == Type::BoolTy))
Chris Lattnerb50d1352003-10-05 00:17:43 +00001662 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1663 return FC; // Fold a few common cases...
Chris Lattneracdbe712003-04-17 19:24:48 +00001664
Chris Lattner2b383d2e2003-05-13 21:37:02 +00001665 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
Reid Spencera009d0d2006-12-04 21:35:24 +00001666 ExprMapKeyType Key(Opcode, argVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001667 return ExprConstants->getOrCreate(ReqTy, Key);
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001668}
1669
Reid Spencera009d0d2006-12-04 21:35:24 +00001670Constant *ConstantExpr::getCompareTy(unsigned Opcode, unsigned short predicate,
1671 Constant *C1, Constant *C2) {
1672 if (Opcode == Instruction::ICmp)
1673 return getICmp(predicate, C1, C2);
1674 return getFCmp(predicate, C1, C2);
1675}
1676
1677Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001678#ifndef NDEBUG
1679 switch (Opcode) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00001680 case Instruction::Add:
1681 case Instruction::Sub:
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001682 case Instruction::Mul:
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001683 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Chris Lattnerc421a262006-01-04 01:01:04 +00001684 assert((C1->getType()->isInteger() || C1->getType()->isFloatingPoint() ||
1685 isa<PackedType>(C1->getType())) &&
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001686 "Tried to create an arithmetic operation on a non-arithmetic type!");
1687 break;
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001688 case Instruction::UDiv:
1689 case Instruction::SDiv:
1690 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1691 assert((C1->getType()->isInteger() || (isa<PackedType>(C1->getType()) &&
1692 cast<PackedType>(C1->getType())->getElementType()->isInteger())) &&
1693 "Tried to create an arithmetic operation on a non-arithmetic type!");
1694 break;
1695 case Instruction::FDiv:
1696 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1697 assert((C1->getType()->isFloatingPoint() || (isa<PackedType>(C1->getType())
1698 && cast<PackedType>(C1->getType())->getElementType()->isFloatingPoint()))
1699 && "Tried to create an arithmetic operation on a non-arithmetic type!");
1700 break;
Reid Spencer7eb55b32006-11-02 01:53:59 +00001701 case Instruction::URem:
1702 case Instruction::SRem:
1703 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1704 assert((C1->getType()->isInteger() || (isa<PackedType>(C1->getType()) &&
1705 cast<PackedType>(C1->getType())->getElementType()->isInteger())) &&
1706 "Tried to create an arithmetic operation on a non-arithmetic type!");
1707 break;
1708 case Instruction::FRem:
1709 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1710 assert((C1->getType()->isFloatingPoint() || (isa<PackedType>(C1->getType())
1711 && cast<PackedType>(C1->getType())->getElementType()->isFloatingPoint()))
1712 && "Tried to create an arithmetic operation on a non-arithmetic type!");
1713 break;
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001714 case Instruction::And:
1715 case Instruction::Or:
1716 case Instruction::Xor:
1717 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Chris Lattnerc421a262006-01-04 01:01:04 +00001718 assert((C1->getType()->isIntegral() || isa<PackedType>(C1->getType())) &&
Misha Brukman3852f652005-01-27 06:46:38 +00001719 "Tried to create a logical operation on a non-integral type!");
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001720 break;
1721 case Instruction::SetLT: case Instruction::SetGT: case Instruction::SetLE:
1722 case Instruction::SetGE: case Instruction::SetEQ: case Instruction::SetNE:
1723 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1724 break;
1725 case Instruction::Shl:
Reid Spencerfdff9382006-11-08 06:47:33 +00001726 case Instruction::LShr:
1727 case Instruction::AShr:
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001728 assert(C2->getType() == Type::UByteTy && "Shift should be by ubyte!");
Reid Spencerfdff9382006-11-08 06:47:33 +00001729 assert(C1->getType()->isInteger() &&
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001730 "Tried to create a shift operation on a non-integer type!");
1731 break;
1732 default:
1733 break;
1734 }
1735#endif
1736
Reid Spencera009d0d2006-12-04 21:35:24 +00001737 return getTy(C1->getType(), Opcode, C1, C2);
1738}
1739
1740Constant *ConstantExpr::getCompare(unsigned Opcode, unsigned short pred,
1741 Constant *C1, Constant *C2) {
1742 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1743 return getCompareTy(Opcode, pred, C1, C2);
Chris Lattner29ca2c62004-08-04 18:50:09 +00001744}
1745
Chris Lattner6e415c02004-03-12 05:54:04 +00001746Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
1747 Constant *V1, Constant *V2) {
1748 assert(C->getType() == Type::BoolTy && "Select condition must be bool!");
1749 assert(V1->getType() == V2->getType() && "Select value types must match!");
1750 assert(V1->getType()->isFirstClassType() && "Cannot select aggregate type!");
1751
1752 if (ReqTy == V1->getType())
1753 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1754 return SC; // Fold common cases
1755
1756 std::vector<Constant*> argVec(3, C);
1757 argVec[1] = V1;
1758 argVec[2] = V2;
Reid Spenceree3c9912006-12-04 05:19:50 +00001759 ExprMapKeyType Key(Instruction::Select, argVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001760 return ExprConstants->getOrCreate(ReqTy, Key);
Chris Lattner6e415c02004-03-12 05:54:04 +00001761}
1762
Chris Lattner9eb2b522004-01-12 19:12:58 +00001763/// getShiftTy - Return a shift left or shift right constant expr
Chris Lattnerb50d1352003-10-05 00:17:43 +00001764Constant *ConstantExpr::getShiftTy(const Type *ReqTy, unsigned Opcode,
1765 Constant *C1, Constant *C2) {
Chris Lattner38a9bcd2003-05-21 17:49:25 +00001766 // Check the operands for consistency first
Reid Spencerfdff9382006-11-08 06:47:33 +00001767 assert((Opcode == Instruction::Shl ||
1768 Opcode == Instruction::LShr ||
1769 Opcode == Instruction::AShr) &&
Chris Lattner38a9bcd2003-05-21 17:49:25 +00001770 "Invalid opcode in binary constant expression");
1771 assert(C1->getType()->isIntegral() && C2->getType() == Type::UByteTy &&
1772 "Invalid operand types for Shift constant expr!");
1773
Chris Lattner0bba7712004-01-12 20:40:42 +00001774 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
Chris Lattner38a9bcd2003-05-21 17:49:25 +00001775 return FC; // Fold a few common cases...
1776
1777 // Look up the constant in the table first to ensure uniqueness
1778 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
Reid Spenceree3c9912006-12-04 05:19:50 +00001779 ExprMapKeyType Key(Opcode, argVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001780 return ExprConstants->getOrCreate(ReqTy, Key);
Chris Lattner38a9bcd2003-05-21 17:49:25 +00001781}
1782
Chris Lattnerb50d1352003-10-05 00:17:43 +00001783Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
Chris Lattner13128ab2004-10-11 22:52:25 +00001784 const std::vector<Value*> &IdxList) {
1785 assert(GetElementPtrInst::getIndexedType(C->getType(), IdxList, true) &&
Chris Lattner04b60fe2004-02-16 20:46:13 +00001786 "GEP indices invalid!");
1787
Chris Lattneracdbe712003-04-17 19:24:48 +00001788 if (Constant *FC = ConstantFoldGetElementPtr(C, IdxList))
1789 return FC; // Fold a few common cases...
Chris Lattner04b60fe2004-02-16 20:46:13 +00001790
Chris Lattnerb50d1352003-10-05 00:17:43 +00001791 assert(isa<PointerType>(C->getType()) &&
Chris Lattner98fa07b2003-05-23 20:03:32 +00001792 "Non-pointer type for constant GetElementPtr expression");
Vikram S. Adve4c485332002-07-15 18:19:33 +00001793 // Look up the constant in the table first to ensure uniqueness
Chris Lattner13128ab2004-10-11 22:52:25 +00001794 std::vector<Constant*> ArgVec;
1795 ArgVec.reserve(IdxList.size()+1);
1796 ArgVec.push_back(C);
1797 for (unsigned i = 0, e = IdxList.size(); i != e; ++i)
1798 ArgVec.push_back(cast<Constant>(IdxList[i]));
Reid Spenceree3c9912006-12-04 05:19:50 +00001799 const ExprMapKeyType Key(Instruction::GetElementPtr,ArgVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001800 return ExprConstants->getOrCreate(ReqTy, Key);
Vikram S. Adve4c485332002-07-15 18:19:33 +00001801}
1802
Chris Lattnerb50d1352003-10-05 00:17:43 +00001803Constant *ConstantExpr::getGetElementPtr(Constant *C,
1804 const std::vector<Constant*> &IdxList){
1805 // Get the result type of the getelementptr!
1806 std::vector<Value*> VIdxList(IdxList.begin(), IdxList.end());
1807
1808 const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), VIdxList,
1809 true);
1810 assert(Ty && "GEP indices invalid!");
Chris Lattner13128ab2004-10-11 22:52:25 +00001811 return getGetElementPtrTy(PointerType::get(Ty), C, VIdxList);
1812}
1813
1814Constant *ConstantExpr::getGetElementPtr(Constant *C,
1815 const std::vector<Value*> &IdxList) {
1816 // Get the result type of the getelementptr!
1817 const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), IdxList,
1818 true);
1819 assert(Ty && "GEP indices invalid!");
Chris Lattnerb50d1352003-10-05 00:17:43 +00001820 return getGetElementPtrTy(PointerType::get(Ty), C, IdxList);
1821}
1822
Reid Spenceree3c9912006-12-04 05:19:50 +00001823Constant *
1824ConstantExpr::getICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1825 assert(LHS->getType() == RHS->getType());
1826 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
1827 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
1828
1829 if (Constant *FC = ConstantFoldCompare(Instruction::ICmp, LHS, RHS, pred))
1830 return FC; // Fold a few common cases...
1831
1832 // Look up the constant in the table first to ensure uniqueness
1833 std::vector<Constant*> ArgVec;
1834 ArgVec.push_back(LHS);
1835 ArgVec.push_back(RHS);
1836 // Fake up an opcode value that encodes both the opcode and predicate
1837 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
1838 return ExprConstants->getOrCreate(Type::BoolTy, Key);
1839}
1840
1841Constant *
1842ConstantExpr::getFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1843 assert(LHS->getType() == RHS->getType());
1844 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
1845
1846 if (Constant *FC = ConstantFoldCompare(Instruction::FCmp, LHS, RHS, pred))
1847 return FC; // Fold a few common cases...
1848
1849 // Look up the constant in the table first to ensure uniqueness
1850 std::vector<Constant*> ArgVec;
1851 ArgVec.push_back(LHS);
1852 ArgVec.push_back(RHS);
1853 // Fake up an opcode value that encodes both the opcode and predicate
1854 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
1855 return ExprConstants->getOrCreate(Type::BoolTy, Key);
1856}
1857
Robert Bocchino23004482006-01-10 19:05:34 +00001858Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
1859 Constant *Idx) {
Robert Bocchinode7f1c92006-01-10 20:03:46 +00001860 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
1861 return FC; // Fold a few common cases...
Robert Bocchino23004482006-01-10 19:05:34 +00001862 // Look up the constant in the table first to ensure uniqueness
1863 std::vector<Constant*> ArgVec(1, Val);
1864 ArgVec.push_back(Idx);
Reid Spenceree3c9912006-12-04 05:19:50 +00001865 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001866 return ExprConstants->getOrCreate(ReqTy, Key);
Robert Bocchino23004482006-01-10 19:05:34 +00001867}
1868
1869Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
1870 assert(isa<PackedType>(Val->getType()) &&
1871 "Tried to create extractelement operation on non-packed type!");
1872 assert(Idx->getType() == Type::UIntTy &&
Robert Bocchinoca27f032006-01-17 20:07:22 +00001873 "Extractelement index must be uint type!");
Robert Bocchino23004482006-01-10 19:05:34 +00001874 return getExtractElementTy(cast<PackedType>(Val->getType())->getElementType(),
1875 Val, Idx);
1876}
Chris Lattnerb50d1352003-10-05 00:17:43 +00001877
Robert Bocchinoca27f032006-01-17 20:07:22 +00001878Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
1879 Constant *Elt, Constant *Idx) {
1880 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
1881 return FC; // Fold a few common cases...
1882 // Look up the constant in the table first to ensure uniqueness
1883 std::vector<Constant*> ArgVec(1, Val);
1884 ArgVec.push_back(Elt);
1885 ArgVec.push_back(Idx);
Reid Spenceree3c9912006-12-04 05:19:50 +00001886 const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001887 return ExprConstants->getOrCreate(ReqTy, Key);
Robert Bocchinoca27f032006-01-17 20:07:22 +00001888}
1889
1890Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
1891 Constant *Idx) {
1892 assert(isa<PackedType>(Val->getType()) &&
1893 "Tried to create insertelement operation on non-packed type!");
1894 assert(Elt->getType() == cast<PackedType>(Val->getType())->getElementType()
1895 && "Insertelement types must match!");
1896 assert(Idx->getType() == Type::UIntTy &&
1897 "Insertelement index must be uint type!");
1898 return getInsertElementTy(cast<PackedType>(Val->getType())->getElementType(),
1899 Val, Elt, Idx);
1900}
1901
Chris Lattnerbbe0a422006-04-08 01:18:18 +00001902Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
1903 Constant *V2, Constant *Mask) {
1904 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
1905 return FC; // Fold a few common cases...
1906 // Look up the constant in the table first to ensure uniqueness
1907 std::vector<Constant*> ArgVec(1, V1);
1908 ArgVec.push_back(V2);
1909 ArgVec.push_back(Mask);
Reid Spenceree3c9912006-12-04 05:19:50 +00001910 const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001911 return ExprConstants->getOrCreate(ReqTy, Key);
Chris Lattnerbbe0a422006-04-08 01:18:18 +00001912}
1913
1914Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
1915 Constant *Mask) {
1916 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
1917 "Invalid shuffle vector constant expr operands!");
1918 return getShuffleVectorTy(V1->getType(), V1, V2, Mask);
1919}
1920
Vikram S. Adve4c485332002-07-15 18:19:33 +00001921// destroyConstant - Remove the constant from the constant table...
1922//
1923void ConstantExpr::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00001924 ExprConstants->remove(this);
Vikram S. Adve4c485332002-07-15 18:19:33 +00001925 destroyConstantImpl();
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001926}
1927
Chris Lattner3cd8c562002-07-30 18:54:25 +00001928const char *ConstantExpr::getOpcodeName() const {
1929 return Instruction::getOpcodeName(getOpcode());
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001930}
Reid Spencer1ebe1ab2004-07-17 23:48:33 +00001931
Chris Lattnerc4062ba2005-10-03 21:58:36 +00001932//===----------------------------------------------------------------------===//
1933// replaceUsesOfWithOnConstant implementations
1934
1935void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
Chris Lattner7a1450d2005-10-04 18:13:04 +00001936 Use *U) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00001937 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
Chris Lattner8760ec72005-10-04 01:17:50 +00001938 Constant *ToC = cast<Constant>(To);
Chris Lattnerdff59112005-10-04 18:47:09 +00001939
1940 unsigned OperandToUpdate = U-OperandList;
1941 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
1942
Jim Laskeyc03caef2006-07-17 17:38:29 +00001943 std::pair<ArrayConstantsTy::MapKey, Constant*> Lookup;
Chris Lattnerb64419a2005-10-03 22:51:37 +00001944 Lookup.first.first = getType();
1945 Lookup.second = this;
Chris Lattnerdff59112005-10-04 18:47:09 +00001946
Chris Lattnerb64419a2005-10-03 22:51:37 +00001947 std::vector<Constant*> &Values = Lookup.first.second;
1948 Values.reserve(getNumOperands()); // Build replacement array.
Chris Lattnerdff59112005-10-04 18:47:09 +00001949
Chris Lattner8760ec72005-10-04 01:17:50 +00001950 // Fill values with the modified operands of the constant array. Also,
1951 // compute whether this turns into an all-zeros array.
Chris Lattnerdff59112005-10-04 18:47:09 +00001952 bool isAllZeros = false;
1953 if (!ToC->isNullValue()) {
1954 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
1955 Values.push_back(cast<Constant>(O->get()));
1956 } else {
1957 isAllZeros = true;
1958 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1959 Constant *Val = cast<Constant>(O->get());
1960 Values.push_back(Val);
1961 if (isAllZeros) isAllZeros = Val->isNullValue();
1962 }
Chris Lattnerc4062ba2005-10-03 21:58:36 +00001963 }
Chris Lattnerdff59112005-10-04 18:47:09 +00001964 Values[OperandToUpdate] = ToC;
Chris Lattnerc4062ba2005-10-03 21:58:36 +00001965
Chris Lattnerb64419a2005-10-03 22:51:37 +00001966 Constant *Replacement = 0;
1967 if (isAllZeros) {
1968 Replacement = ConstantAggregateZero::get(getType());
1969 } else {
1970 // Check to see if we have this array type already.
1971 bool Exists;
Jim Laskeyc03caef2006-07-17 17:38:29 +00001972 ArrayConstantsTy::MapTy::iterator I =
Chris Lattner69edc982006-09-28 00:35:06 +00001973 ArrayConstants->InsertOrGetItem(Lookup, Exists);
Chris Lattnerb64419a2005-10-03 22:51:37 +00001974
1975 if (Exists) {
1976 Replacement = I->second;
1977 } else {
1978 // Okay, the new shape doesn't exist in the system yet. Instead of
1979 // creating a new constant array, inserting it, replaceallusesof'ing the
1980 // old with the new, then deleting the old... just update the current one
1981 // in place!
Chris Lattner69edc982006-09-28 00:35:06 +00001982 ArrayConstants->MoveConstantToNewSlot(this, I);
Chris Lattnerb64419a2005-10-03 22:51:37 +00001983
Chris Lattnerdff59112005-10-04 18:47:09 +00001984 // Update to the new value.
1985 setOperand(OperandToUpdate, ToC);
Chris Lattnerb64419a2005-10-03 22:51:37 +00001986 return;
1987 }
1988 }
1989
1990 // Otherwise, I do need to replace this with an existing value.
Chris Lattnerc4062ba2005-10-03 21:58:36 +00001991 assert(Replacement != this && "I didn't contain From!");
1992
Chris Lattner7a1450d2005-10-04 18:13:04 +00001993 // Everyone using this now uses the replacement.
1994 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00001995
1996 // Delete the old constant!
1997 destroyConstant();
1998}
1999
2000void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
Chris Lattner7a1450d2005-10-04 18:13:04 +00002001 Use *U) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002002 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
Chris Lattner8760ec72005-10-04 01:17:50 +00002003 Constant *ToC = cast<Constant>(To);
2004
Chris Lattnerdff59112005-10-04 18:47:09 +00002005 unsigned OperandToUpdate = U-OperandList;
2006 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
2007
Jim Laskeyc03caef2006-07-17 17:38:29 +00002008 std::pair<StructConstantsTy::MapKey, Constant*> Lookup;
Chris Lattner8760ec72005-10-04 01:17:50 +00002009 Lookup.first.first = getType();
2010 Lookup.second = this;
2011 std::vector<Constant*> &Values = Lookup.first.second;
2012 Values.reserve(getNumOperands()); // Build replacement struct.
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002013
Chris Lattnerdff59112005-10-04 18:47:09 +00002014
Chris Lattner8760ec72005-10-04 01:17:50 +00002015 // Fill values with the modified operands of the constant struct. Also,
2016 // compute whether this turns into an all-zeros struct.
Chris Lattnerdff59112005-10-04 18:47:09 +00002017 bool isAllZeros = false;
2018 if (!ToC->isNullValue()) {
2019 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
2020 Values.push_back(cast<Constant>(O->get()));
2021 } else {
2022 isAllZeros = true;
2023 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2024 Constant *Val = cast<Constant>(O->get());
2025 Values.push_back(Val);
2026 if (isAllZeros) isAllZeros = Val->isNullValue();
2027 }
Chris Lattner8760ec72005-10-04 01:17:50 +00002028 }
Chris Lattnerdff59112005-10-04 18:47:09 +00002029 Values[OperandToUpdate] = ToC;
2030
Chris Lattner8760ec72005-10-04 01:17:50 +00002031 Constant *Replacement = 0;
2032 if (isAllZeros) {
2033 Replacement = ConstantAggregateZero::get(getType());
2034 } else {
2035 // Check to see if we have this array type already.
2036 bool Exists;
Jim Laskeyc03caef2006-07-17 17:38:29 +00002037 StructConstantsTy::MapTy::iterator I =
Chris Lattner69edc982006-09-28 00:35:06 +00002038 StructConstants->InsertOrGetItem(Lookup, Exists);
Chris Lattner8760ec72005-10-04 01:17:50 +00002039
2040 if (Exists) {
2041 Replacement = I->second;
2042 } else {
2043 // Okay, the new shape doesn't exist in the system yet. Instead of
2044 // creating a new constant struct, inserting it, replaceallusesof'ing the
2045 // old with the new, then deleting the old... just update the current one
2046 // in place!
Chris Lattner69edc982006-09-28 00:35:06 +00002047 StructConstants->MoveConstantToNewSlot(this, I);
Chris Lattner8760ec72005-10-04 01:17:50 +00002048
Chris Lattnerdff59112005-10-04 18:47:09 +00002049 // Update to the new value.
2050 setOperand(OperandToUpdate, ToC);
Chris Lattner8760ec72005-10-04 01:17:50 +00002051 return;
2052 }
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002053 }
2054
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002055 assert(Replacement != this && "I didn't contain From!");
2056
Chris Lattner7a1450d2005-10-04 18:13:04 +00002057 // Everyone using this now uses the replacement.
2058 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002059
2060 // Delete the old constant!
2061 destroyConstant();
2062}
2063
2064void ConstantPacked::replaceUsesOfWithOnConstant(Value *From, Value *To,
Chris Lattner7a1450d2005-10-04 18:13:04 +00002065 Use *U) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002066 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2067
2068 std::vector<Constant*> Values;
2069 Values.reserve(getNumOperands()); // Build replacement array...
2070 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2071 Constant *Val = getOperand(i);
2072 if (Val == From) Val = cast<Constant>(To);
2073 Values.push_back(Val);
2074 }
2075
2076 Constant *Replacement = ConstantPacked::get(getType(), Values);
2077 assert(Replacement != this && "I didn't contain From!");
2078
Chris Lattner7a1450d2005-10-04 18:13:04 +00002079 // Everyone using this now uses the replacement.
2080 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002081
2082 // Delete the old constant!
2083 destroyConstant();
2084}
2085
2086void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
Chris Lattner7a1450d2005-10-04 18:13:04 +00002087 Use *U) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002088 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2089 Constant *To = cast<Constant>(ToV);
2090
2091 Constant *Replacement = 0;
2092 if (getOpcode() == Instruction::GetElementPtr) {
2093 std::vector<Constant*> Indices;
2094 Constant *Pointer = getOperand(0);
2095 Indices.reserve(getNumOperands()-1);
2096 if (Pointer == From) Pointer = To;
2097
2098 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2099 Constant *Val = getOperand(i);
2100 if (Val == From) Val = To;
2101 Indices.push_back(Val);
2102 }
2103 Replacement = ConstantExpr::getGetElementPtr(Pointer, Indices);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002104 } else if (isCast()) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002105 assert(getOperand(0) == From && "Cast only has one use!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002106 Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002107 } else if (getOpcode() == Instruction::Select) {
2108 Constant *C1 = getOperand(0);
2109 Constant *C2 = getOperand(1);
2110 Constant *C3 = getOperand(2);
2111 if (C1 == From) C1 = To;
2112 if (C2 == From) C2 = To;
2113 if (C3 == From) C3 = To;
2114 Replacement = ConstantExpr::getSelect(C1, C2, C3);
Robert Bocchino23004482006-01-10 19:05:34 +00002115 } else if (getOpcode() == Instruction::ExtractElement) {
2116 Constant *C1 = getOperand(0);
2117 Constant *C2 = getOperand(1);
2118 if (C1 == From) C1 = To;
2119 if (C2 == From) C2 = To;
2120 Replacement = ConstantExpr::getExtractElement(C1, C2);
Chris Lattnera93b4b52006-04-08 05:09:48 +00002121 } else if (getOpcode() == Instruction::InsertElement) {
2122 Constant *C1 = getOperand(0);
2123 Constant *C2 = getOperand(1);
2124 Constant *C3 = getOperand(1);
2125 if (C1 == From) C1 = To;
2126 if (C2 == From) C2 = To;
2127 if (C3 == From) C3 = To;
2128 Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2129 } else if (getOpcode() == Instruction::ShuffleVector) {
2130 Constant *C1 = getOperand(0);
2131 Constant *C2 = getOperand(1);
2132 Constant *C3 = getOperand(2);
2133 if (C1 == From) C1 = To;
2134 if (C2 == From) C2 = To;
2135 if (C3 == From) C3 = To;
2136 Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
Reid Spenceree3c9912006-12-04 05:19:50 +00002137 } else if (isCompare()) {
2138 Constant *C1 = getOperand(0);
2139 Constant *C2 = getOperand(1);
2140 if (C1 == From) C1 = To;
2141 if (C2 == From) C2 = To;
2142 if (getOpcode() == Instruction::ICmp)
2143 Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
2144 else
2145 Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002146 } else if (getNumOperands() == 2) {
2147 Constant *C1 = getOperand(0);
2148 Constant *C2 = getOperand(1);
2149 if (C1 == From) C1 = To;
2150 if (C2 == From) C2 = To;
2151 Replacement = ConstantExpr::get(getOpcode(), C1, C2);
2152 } else {
2153 assert(0 && "Unknown ConstantExpr type!");
2154 return;
2155 }
2156
2157 assert(Replacement != this && "I didn't contain From!");
2158
Chris Lattner7a1450d2005-10-04 18:13:04 +00002159 // Everyone using this now uses the replacement.
2160 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002161
2162 // Delete the old constant!
2163 destroyConstant();
2164}
2165
2166
Jim Laskey2698f0d2006-03-08 18:11:07 +00002167/// getStringValue - Turn an LLVM constant pointer that eventually points to a
2168/// global into a string value. Return an empty string if we can't do it.
Evan Cheng38280c02006-03-10 23:52:03 +00002169/// Parameter Chop determines if the result is chopped at the first null
2170/// terminator.
Jim Laskey2698f0d2006-03-08 18:11:07 +00002171///
Evan Cheng38280c02006-03-10 23:52:03 +00002172std::string Constant::getStringValue(bool Chop, unsigned Offset) {
Jim Laskey2698f0d2006-03-08 18:11:07 +00002173 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(this)) {
2174 if (GV->hasInitializer() && isa<ConstantArray>(GV->getInitializer())) {
2175 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
2176 if (Init->isString()) {
2177 std::string Result = Init->getAsString();
2178 if (Offset < Result.size()) {
2179 // If we are pointing INTO The string, erase the beginning...
2180 Result.erase(Result.begin(), Result.begin()+Offset);
2181
2182 // Take off the null terminator, and any string fragments after it.
Evan Cheng38280c02006-03-10 23:52:03 +00002183 if (Chop) {
2184 std::string::size_type NullPos = Result.find_first_of((char)0);
2185 if (NullPos != std::string::npos)
2186 Result.erase(Result.begin()+NullPos, Result.end());
2187 }
Jim Laskey2698f0d2006-03-08 18:11:07 +00002188 return Result;
2189 }
2190 }
2191 }
2192 } else if (Constant *C = dyn_cast<Constant>(this)) {
2193 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
Evan Cheng2c5e5302006-03-11 00:13:10 +00002194 return GV->getStringValue(Chop, Offset);
Jim Laskey2698f0d2006-03-08 18:11:07 +00002195 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2196 if (CE->getOpcode() == Instruction::GetElementPtr) {
2197 // Turn a gep into the specified offset.
2198 if (CE->getNumOperands() == 3 &&
2199 cast<Constant>(CE->getOperand(1))->isNullValue() &&
2200 isa<ConstantInt>(CE->getOperand(2))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002201 Offset += cast<ConstantInt>(CE->getOperand(2))->getZExtValue();
Evan Cheng2c5e5302006-03-11 00:13:10 +00002202 return CE->getOperand(0)->getStringValue(Chop, Offset);
Jim Laskey2698f0d2006-03-08 18:11:07 +00002203 }
2204 }
2205 }
2206 }
2207 return "";
2208}