blob: 9c92b90778382b8ab17097b71bd5c18017b471e5 [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"
Jim Laskeyb74c6662005-08-17 19:34:49 +000022#include "llvm/Support/MathExtras.h"
Chris Lattner3d27be12006-08-27 12:54:02 +000023#include "llvm/Support/Compiler.h"
Chris Lattner69edc982006-09-28 00:35:06 +000024#include "llvm/Support/ManagedStatic.h"
Chris Lattner2f7c9632001-06-06 20:29:01 +000025#include <algorithm>
Reid Spencercf394bf2004-07-04 11:51:24 +000026#include <iostream>
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))
45 std::cerr << "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:
Chris Lattner23dd1f62006-10-20 00:27:06 +000081 case Instruction::Rem:
82 // Div and rem can trap if the RHS is not known to be non-zero.
83 if (!isa<ConstantInt>(getOperand(1)) || getOperand(1)->isNullValue())
84 return true;
85 return false;
86 }
87}
88
89
Chris Lattnerb1585a92002-08-13 17:50:20 +000090// Static constructor to create a '0' constant of arbitrary type...
91Constant *Constant::getNullValue(const Type *Ty) {
Chris Lattner6b727592004-06-17 18:19:28 +000092 switch (Ty->getTypeID()) {
Chris Lattner3e88ef92003-10-03 19:34:51 +000093 case Type::BoolTyID: {
94 static Constant *NullBool = ConstantBool::get(false);
95 return NullBool;
96 }
97 case Type::SByteTyID: {
Reid Spencere0fc4df2006-10-20 07:07:24 +000098 static Constant *NullSByte = ConstantInt::get(Type::SByteTy, 0);
Chris Lattner3e88ef92003-10-03 19:34:51 +000099 return NullSByte;
100 }
101 case Type::UByteTyID: {
Reid Spencere0fc4df2006-10-20 07:07:24 +0000102 static Constant *NullUByte = ConstantInt::get(Type::UByteTy, 0);
Chris Lattner3e88ef92003-10-03 19:34:51 +0000103 return NullUByte;
104 }
105 case Type::ShortTyID: {
Reid Spencere0fc4df2006-10-20 07:07:24 +0000106 static Constant *NullShort = ConstantInt::get(Type::ShortTy, 0);
Chris Lattner3e88ef92003-10-03 19:34:51 +0000107 return NullShort;
108 }
109 case Type::UShortTyID: {
Reid Spencere0fc4df2006-10-20 07:07:24 +0000110 static Constant *NullUShort = ConstantInt::get(Type::UShortTy, 0);
Chris Lattner3e88ef92003-10-03 19:34:51 +0000111 return NullUShort;
112 }
113 case Type::IntTyID: {
Reid Spencere0fc4df2006-10-20 07:07:24 +0000114 static Constant *NullInt = ConstantInt::get(Type::IntTy, 0);
Chris Lattner3e88ef92003-10-03 19:34:51 +0000115 return NullInt;
116 }
117 case Type::UIntTyID: {
Reid Spencere0fc4df2006-10-20 07:07:24 +0000118 static Constant *NullUInt = ConstantInt::get(Type::UIntTy, 0);
Chris Lattner3e88ef92003-10-03 19:34:51 +0000119 return NullUInt;
120 }
121 case Type::LongTyID: {
Reid Spencere0fc4df2006-10-20 07:07:24 +0000122 static Constant *NullLong = ConstantInt::get(Type::LongTy, 0);
Chris Lattner3e88ef92003-10-03 19:34:51 +0000123 return NullLong;
124 }
125 case Type::ULongTyID: {
Reid Spencere0fc4df2006-10-20 07:07:24 +0000126 static Constant *NullULong = ConstantInt::get(Type::ULongTy, 0);
Chris Lattner3e88ef92003-10-03 19:34:51 +0000127 return NullULong;
128 }
Chris Lattnerb1585a92002-08-13 17:50:20 +0000129
Chris Lattner3e88ef92003-10-03 19:34:51 +0000130 case Type::FloatTyID: {
131 static Constant *NullFloat = ConstantFP::get(Type::FloatTy, 0);
132 return NullFloat;
133 }
134 case Type::DoubleTyID: {
135 static Constant *NullDouble = ConstantFP::get(Type::DoubleTy, 0);
136 return NullDouble;
137 }
Chris Lattnerb1585a92002-08-13 17:50:20 +0000138
Misha Brukmanb1c93172005-04-21 23:48:37 +0000139 case Type::PointerTyID:
Chris Lattnerb1585a92002-08-13 17:50:20 +0000140 return ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattner3e88ef92003-10-03 19:34:51 +0000141
Chris Lattner9fba3da2004-02-15 05:53:04 +0000142 case Type::StructTyID:
143 case Type::ArrayTyID:
Brian Gaeke02209042004-08-20 06:00:58 +0000144 case Type::PackedTyID:
Chris Lattner9fba3da2004-02-15 05:53:04 +0000145 return ConstantAggregateZero::get(Ty);
Chris Lattnerb1585a92002-08-13 17:50:20 +0000146 default:
Reid Spencercf394bf2004-07-04 11:51:24 +0000147 // Function, Label, or Opaque type?
148 assert(!"Cannot create a null constant of that type!");
Chris Lattnerb1585a92002-08-13 17:50:20 +0000149 return 0;
150 }
151}
152
153// Static constructor to create the maximum constant of an integral type...
154ConstantIntegral *ConstantIntegral::getMaxValue(const Type *Ty) {
Chris Lattner6b727592004-06-17 18:19:28 +0000155 switch (Ty->getTypeID()) {
Chris Lattnera84df0a22006-09-28 23:36:21 +0000156 case Type::BoolTyID: return ConstantBool::getTrue();
Chris Lattnerb1585a92002-08-13 17:50:20 +0000157 case Type::SByteTyID:
158 case Type::ShortTyID:
159 case Type::IntTyID:
160 case Type::LongTyID: {
Misha Brukmanb1c93172005-04-21 23:48:37 +0000161 // Calculate 011111111111111...
Chris Lattnerb1585a92002-08-13 17:50:20 +0000162 unsigned TypeBits = Ty->getPrimitiveSize()*8;
163 int64_t Val = INT64_MAX; // All ones
164 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
Reid Spencere0fc4df2006-10-20 07:07:24 +0000165 return ConstantInt::get(Ty, Val);
Chris Lattnerb1585a92002-08-13 17:50:20 +0000166 }
167
168 case Type::UByteTyID:
169 case Type::UShortTyID:
170 case Type::UIntTyID:
171 case Type::ULongTyID: return getAllOnesValue(Ty);
172
Chris Lattner31408f72002-08-14 17:12:13 +0000173 default: return 0;
Chris Lattnerb1585a92002-08-13 17:50:20 +0000174 }
175}
176
177// Static constructor to create the minimum constant for an integral type...
178ConstantIntegral *ConstantIntegral::getMinValue(const Type *Ty) {
Chris Lattner6b727592004-06-17 18:19:28 +0000179 switch (Ty->getTypeID()) {
Chris Lattnera84df0a22006-09-28 23:36:21 +0000180 case Type::BoolTyID: return ConstantBool::getFalse();
Chris Lattnerb1585a92002-08-13 17:50:20 +0000181 case Type::SByteTyID:
182 case Type::ShortTyID:
183 case Type::IntTyID:
184 case Type::LongTyID: {
Misha Brukmanb1c93172005-04-21 23:48:37 +0000185 // Calculate 1111111111000000000000
Chris Lattnerb1585a92002-08-13 17:50:20 +0000186 unsigned TypeBits = Ty->getPrimitiveSize()*8;
187 int64_t Val = -1; // All ones
188 Val <<= TypeBits-1; // Shift over to the right spot
Reid Spencere0fc4df2006-10-20 07:07:24 +0000189 return ConstantInt::get(Ty, Val);
Chris Lattnerb1585a92002-08-13 17:50:20 +0000190 }
191
192 case Type::UByteTyID:
193 case Type::UShortTyID:
194 case Type::UIntTyID:
Reid Spencere0fc4df2006-10-20 07:07:24 +0000195 case Type::ULongTyID: return ConstantInt::get(Ty, 0);
Chris Lattnerb1585a92002-08-13 17:50:20 +0000196
Chris Lattner31408f72002-08-14 17:12:13 +0000197 default: return 0;
Chris Lattnerb1585a92002-08-13 17:50:20 +0000198 }
199}
200
201// Static constructor to create an integral constant with all bits set
202ConstantIntegral *ConstantIntegral::getAllOnesValue(const Type *Ty) {
Chris Lattner6b727592004-06-17 18:19:28 +0000203 switch (Ty->getTypeID()) {
Chris Lattnera84df0a22006-09-28 23:36:21 +0000204 case Type::BoolTyID: return ConstantBool::getTrue();
Chris Lattnerb1585a92002-08-13 17:50:20 +0000205 case Type::SByteTyID:
206 case Type::ShortTyID:
207 case Type::IntTyID:
Reid Spencere0fc4df2006-10-20 07:07:24 +0000208 case Type::LongTyID: return ConstantInt::get(Ty, -1);
Chris Lattnerb1585a92002-08-13 17:50:20 +0000209
210 case Type::UByteTyID:
211 case Type::UShortTyID:
212 case Type::UIntTyID:
213 case Type::ULongTyID: {
214 // Calculate ~0 of the right type...
215 unsigned TypeBits = Ty->getPrimitiveSize()*8;
216 uint64_t Val = ~0ULL; // All ones
217 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
Reid Spencere0fc4df2006-10-20 07:07:24 +0000218 return ConstantInt::get(Ty, Val);
Chris Lattnerb1585a92002-08-13 17:50:20 +0000219 }
Chris Lattner31408f72002-08-14 17:12:13 +0000220 default: return 0;
Chris Lattnerb1585a92002-08-13 17:50:20 +0000221 }
222}
223
Chris Lattner2f7c9632001-06-06 20:29:01 +0000224//===----------------------------------------------------------------------===//
Chris Lattner3462ae32001-12-03 22:26:30 +0000225// ConstantXXX Classes
Chris Lattner2f7c9632001-06-06 20:29:01 +0000226//===----------------------------------------------------------------------===//
227
228//===----------------------------------------------------------------------===//
229// Normal Constructors
230
Chris Lattnere7e139e2005-09-27 06:09:08 +0000231ConstantIntegral::ConstantIntegral(const Type *Ty, ValueTy VT, uint64_t V)
Reid Spencere0fc4df2006-10-20 07:07:24 +0000232 : Constant(Ty, VT, 0, 0), Val(V) {
Chris Lattner2f7c9632001-06-06 20:29:01 +0000233}
Chris Lattner49d855c2001-09-07 16:46:31 +0000234
Chris Lattnere7e139e2005-09-27 06:09:08 +0000235ConstantBool::ConstantBool(bool V)
Reid Spencere0fc4df2006-10-20 07:07:24 +0000236 : ConstantIntegral(Type::BoolTy, ConstantBoolVal, uint64_t(V)) {
Chris Lattner265eb642004-06-21 12:12:12 +0000237}
238
Reid Spencere0fc4df2006-10-20 07:07:24 +0000239ConstantInt::ConstantInt(const Type *Ty, uint64_t V)
240 : ConstantIntegral(Ty, ConstantIntVal, V) {
Chris Lattner2f7c9632001-06-06 20:29:01 +0000241}
242
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000243ConstantFP::ConstantFP(const Type *Ty, double V)
Chris Lattnere7e139e2005-09-27 06:09:08 +0000244 : Constant(Ty, ConstantFPVal, 0, 0) {
Chris Lattner9655e542001-07-20 19:16:02 +0000245 assert(isValueValidForType(Ty, V) && "Value too large for type!");
Chris Lattner2f7c9632001-06-06 20:29:01 +0000246 Val = V;
247}
248
Chris Lattner3462ae32001-12-03 22:26:30 +0000249ConstantArray::ConstantArray(const ArrayType *T,
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000250 const std::vector<Constant*> &V)
Chris Lattnere7e139e2005-09-27 06:09:08 +0000251 : Constant(T, ConstantArrayVal, new Use[V.size()], V.size()) {
Alkis Evlogimenos0507ffe2004-09-15 02:32:15 +0000252 assert(V.size() == T->getNumElements() &&
253 "Invalid initializer vector for constant array");
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000254 Use *OL = OperandList;
Chris Lattner0144fad2005-10-03 21:56:24 +0000255 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
256 I != E; ++I, ++OL) {
Chris Lattner20a24452005-10-07 05:23:36 +0000257 Constant *C = *I;
258 assert((C->getType() == T->getElementType() ||
Alkis Evlogimenoscb031d92004-09-10 04:16:59 +0000259 (T->isAbstract() &&
Chris Lattner20a24452005-10-07 05:23:36 +0000260 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
Alkis Evlogimenoscb031d92004-09-10 04:16:59 +0000261 "Initializer for array element doesn't match array element type!");
Chris Lattner20a24452005-10-07 05:23:36 +0000262 OL->init(C, this);
Chris Lattner2f7c9632001-06-06 20:29:01 +0000263 }
264}
265
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000266ConstantArray::~ConstantArray() {
267 delete [] OperandList;
268}
269
Chris Lattner3462ae32001-12-03 22:26:30 +0000270ConstantStruct::ConstantStruct(const StructType *T,
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000271 const std::vector<Constant*> &V)
Chris Lattnere7e139e2005-09-27 06:09:08 +0000272 : Constant(T, ConstantStructVal, new Use[V.size()], V.size()) {
Chris Lattnerac6db752004-02-09 04:37:31 +0000273 assert(V.size() == T->getNumElements() &&
Vikram S. Adve4e537b22002-07-14 23:13:17 +0000274 "Invalid initializer vector for constant structure");
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000275 Use *OL = OperandList;
Chris Lattner0144fad2005-10-03 21:56:24 +0000276 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
277 I != E; ++I, ++OL) {
Chris Lattner20a24452005-10-07 05:23:36 +0000278 Constant *C = *I;
279 assert((C->getType() == T->getElementType(I-V.begin()) ||
Chris Lattner0144fad2005-10-03 21:56:24 +0000280 ((T->getElementType(I-V.begin())->isAbstract() ||
Chris Lattner20a24452005-10-07 05:23:36 +0000281 C->getType()->isAbstract()) &&
Chris Lattner0144fad2005-10-03 21:56:24 +0000282 T->getElementType(I-V.begin())->getTypeID() ==
Chris Lattner20a24452005-10-07 05:23:36 +0000283 C->getType()->getTypeID())) &&
Chris Lattner93c8f142003-06-02 17:42:47 +0000284 "Initializer for struct element doesn't match struct element type!");
Chris Lattner20a24452005-10-07 05:23:36 +0000285 OL->init(C, this);
Chris Lattner2f7c9632001-06-06 20:29:01 +0000286 }
287}
288
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000289ConstantStruct::~ConstantStruct() {
290 delete [] OperandList;
291}
292
293
Brian Gaeke02209042004-08-20 06:00:58 +0000294ConstantPacked::ConstantPacked(const PackedType *T,
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000295 const std::vector<Constant*> &V)
Chris Lattnere7e139e2005-09-27 06:09:08 +0000296 : Constant(T, ConstantPackedVal, new Use[V.size()], V.size()) {
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000297 Use *OL = OperandList;
Chris Lattner0144fad2005-10-03 21:56:24 +0000298 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
299 I != E; ++I, ++OL) {
Chris Lattner20a24452005-10-07 05:23:36 +0000300 Constant *C = *I;
301 assert((C->getType() == T->getElementType() ||
Alkis Evlogimenoscb031d92004-09-10 04:16:59 +0000302 (T->isAbstract() &&
Chris Lattner20a24452005-10-07 05:23:36 +0000303 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
Alkis Evlogimenoscb031d92004-09-10 04:16:59 +0000304 "Initializer for packed element doesn't match packed element type!");
Chris Lattner20a24452005-10-07 05:23:36 +0000305 OL->init(C, this);
Brian Gaeke02209042004-08-20 06:00:58 +0000306 }
307}
308
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000309ConstantPacked::~ConstantPacked() {
310 delete [] OperandList;
Vikram S. Adve4e537b22002-07-14 23:13:17 +0000311}
312
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000313/// UnaryConstantExpr - This class is private to Constants.cpp, and is used
314/// behind the scenes to implement unary constant exprs.
Chris Lattner02157b02006-06-28 21:38:54 +0000315namespace {
316class VISIBILITY_HIDDEN UnaryConstantExpr : public ConstantExpr {
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000317 Use Op;
318public:
319 UnaryConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
320 : ConstantExpr(Ty, Opcode, &Op, 1), Op(C, this) {}
321};
Chris Lattner02157b02006-06-28 21:38:54 +0000322}
Chris Lattner6e415c02004-03-12 05:54:04 +0000323
Chris Lattner22ced562003-06-22 20:48:30 +0000324static bool isSetCC(unsigned Opcode) {
325 return Opcode == Instruction::SetEQ || Opcode == Instruction::SetNE ||
326 Opcode == Instruction::SetLT || Opcode == Instruction::SetGT ||
327 Opcode == Instruction::SetLE || Opcode == Instruction::SetGE;
328}
329
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000330/// BinaryConstantExpr - This class is private to Constants.cpp, and is used
331/// behind the scenes to implement binary constant exprs.
Chris Lattner02157b02006-06-28 21:38:54 +0000332namespace {
333class VISIBILITY_HIDDEN BinaryConstantExpr : public ConstantExpr {
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000334 Use Ops[2];
335public:
336 BinaryConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
337 : ConstantExpr(isSetCC(Opcode) ? Type::BoolTy : C1->getType(),
338 Opcode, Ops, 2) {
339 Ops[0].init(C1, this);
340 Ops[1].init(C2, this);
341 }
342};
Chris Lattner02157b02006-06-28 21:38:54 +0000343}
Vikram S. Adve4e537b22002-07-14 23:13:17 +0000344
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000345/// SelectConstantExpr - This class is private to Constants.cpp, and is used
346/// behind the scenes to implement select constant exprs.
Chris Lattner02157b02006-06-28 21:38:54 +0000347namespace {
348class VISIBILITY_HIDDEN SelectConstantExpr : public ConstantExpr {
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000349 Use Ops[3];
350public:
351 SelectConstantExpr(Constant *C1, Constant *C2, Constant *C3)
352 : ConstantExpr(C2->getType(), Instruction::Select, Ops, 3) {
353 Ops[0].init(C1, this);
354 Ops[1].init(C2, this);
355 Ops[2].init(C3, this);
356 }
357};
Chris Lattner02157b02006-06-28 21:38:54 +0000358}
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000359
Robert Bocchinoca27f032006-01-17 20:07:22 +0000360/// ExtractElementConstantExpr - This class is private to
361/// Constants.cpp, and is used behind the scenes to implement
362/// extractelement constant exprs.
Chris Lattner02157b02006-06-28 21:38:54 +0000363namespace {
364class VISIBILITY_HIDDEN ExtractElementConstantExpr : public ConstantExpr {
Robert Bocchino23004482006-01-10 19:05:34 +0000365 Use Ops[2];
366public:
367 ExtractElementConstantExpr(Constant *C1, Constant *C2)
368 : ConstantExpr(cast<PackedType>(C1->getType())->getElementType(),
369 Instruction::ExtractElement, Ops, 2) {
370 Ops[0].init(C1, this);
371 Ops[1].init(C2, this);
372 }
373};
Chris Lattner02157b02006-06-28 21:38:54 +0000374}
Robert Bocchino23004482006-01-10 19:05:34 +0000375
Robert Bocchinoca27f032006-01-17 20:07:22 +0000376/// InsertElementConstantExpr - This class is private to
377/// Constants.cpp, and is used behind the scenes to implement
378/// insertelement constant exprs.
Chris Lattner02157b02006-06-28 21:38:54 +0000379namespace {
380class VISIBILITY_HIDDEN InsertElementConstantExpr : public ConstantExpr {
Robert Bocchinoca27f032006-01-17 20:07:22 +0000381 Use Ops[3];
382public:
383 InsertElementConstantExpr(Constant *C1, Constant *C2, Constant *C3)
384 : ConstantExpr(C1->getType(), Instruction::InsertElement,
385 Ops, 3) {
386 Ops[0].init(C1, this);
387 Ops[1].init(C2, this);
388 Ops[2].init(C3, this);
389 }
390};
Chris Lattner02157b02006-06-28 21:38:54 +0000391}
Robert Bocchinoca27f032006-01-17 20:07:22 +0000392
Chris Lattnerbbe0a422006-04-08 01:18:18 +0000393/// ShuffleVectorConstantExpr - This class is private to
394/// Constants.cpp, and is used behind the scenes to implement
395/// shufflevector constant exprs.
Chris Lattner02157b02006-06-28 21:38:54 +0000396namespace {
397class VISIBILITY_HIDDEN ShuffleVectorConstantExpr : public ConstantExpr {
Chris Lattnerbbe0a422006-04-08 01:18:18 +0000398 Use Ops[3];
399public:
400 ShuffleVectorConstantExpr(Constant *C1, Constant *C2, Constant *C3)
401 : ConstantExpr(C1->getType(), Instruction::ShuffleVector,
402 Ops, 3) {
403 Ops[0].init(C1, this);
404 Ops[1].init(C2, this);
405 Ops[2].init(C3, this);
406 }
407};
Chris Lattner02157b02006-06-28 21:38:54 +0000408}
Chris Lattnerbbe0a422006-04-08 01:18:18 +0000409
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000410/// GetElementPtrConstantExpr - This class is private to Constants.cpp, and is
411/// used behind the scenes to implement getelementpr constant exprs.
Chris Lattner02157b02006-06-28 21:38:54 +0000412namespace {
413struct VISIBILITY_HIDDEN GetElementPtrConstantExpr : public ConstantExpr {
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000414 GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
415 const Type *DestTy)
416 : ConstantExpr(DestTy, Instruction::GetElementPtr,
417 new Use[IdxList.size()+1], IdxList.size()+1) {
418 OperandList[0].init(C, this);
419 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
420 OperandList[i+1].init(IdxList[i], this);
421 }
422 ~GetElementPtrConstantExpr() {
Misha Brukmanb1c93172005-04-21 23:48:37 +0000423 delete [] OperandList;
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000424 }
425};
Chris Lattner02157b02006-06-28 21:38:54 +0000426}
Vikram S. Adve4e537b22002-07-14 23:13:17 +0000427
Chris Lattner817175f2004-03-29 02:37:53 +0000428/// ConstantExpr::get* - Return some common constants without having to
429/// specify the full Instruction::OPCODE identifier.
430///
431Constant *ConstantExpr::getNeg(Constant *C) {
Chris Lattner3cdc27c2004-03-29 19:51:24 +0000432 if (!C->getType()->isFloatingPoint())
433 return get(Instruction::Sub, getNullValue(C->getType()), C);
434 else
435 return get(Instruction::Sub, ConstantFP::get(C->getType(), -0.0), C);
Chris Lattner817175f2004-03-29 02:37:53 +0000436}
437Constant *ConstantExpr::getNot(Constant *C) {
438 assert(isa<ConstantIntegral>(C) && "Cannot NOT a nonintegral type!");
439 return get(Instruction::Xor, C,
440 ConstantIntegral::getAllOnesValue(C->getType()));
441}
442Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2) {
443 return get(Instruction::Add, C1, C2);
444}
445Constant *ConstantExpr::getSub(Constant *C1, Constant *C2) {
446 return get(Instruction::Sub, C1, C2);
447}
448Constant *ConstantExpr::getMul(Constant *C1, Constant *C2) {
449 return get(Instruction::Mul, C1, C2);
450}
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000451Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2) {
452 return get(Instruction::UDiv, C1, C2);
453}
454Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2) {
455 return get(Instruction::SDiv, C1, C2);
456}
457Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
458 return get(Instruction::FDiv, C1, C2);
Chris Lattner817175f2004-03-29 02:37:53 +0000459}
460Constant *ConstantExpr::getRem(Constant *C1, Constant *C2) {
461 return get(Instruction::Rem, C1, C2);
462}
463Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
464 return get(Instruction::And, C1, C2);
465}
466Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
467 return get(Instruction::Or, C1, C2);
468}
469Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
470 return get(Instruction::Xor, C1, C2);
471}
472Constant *ConstantExpr::getSetEQ(Constant *C1, Constant *C2) {
473 return get(Instruction::SetEQ, C1, C2);
474}
475Constant *ConstantExpr::getSetNE(Constant *C1, Constant *C2) {
476 return get(Instruction::SetNE, C1, C2);
477}
478Constant *ConstantExpr::getSetLT(Constant *C1, Constant *C2) {
479 return get(Instruction::SetLT, C1, C2);
480}
481Constant *ConstantExpr::getSetGT(Constant *C1, Constant *C2) {
482 return get(Instruction::SetGT, C1, C2);
483}
484Constant *ConstantExpr::getSetLE(Constant *C1, Constant *C2) {
485 return get(Instruction::SetLE, C1, C2);
486}
487Constant *ConstantExpr::getSetGE(Constant *C1, Constant *C2) {
488 return get(Instruction::SetGE, C1, C2);
489}
490Constant *ConstantExpr::getShl(Constant *C1, Constant *C2) {
491 return get(Instruction::Shl, C1, C2);
492}
493Constant *ConstantExpr::getShr(Constant *C1, Constant *C2) {
494 return get(Instruction::Shr, C1, C2);
495}
496
Chris Lattnerdb8bdba2004-05-25 05:32:43 +0000497Constant *ConstantExpr::getUShr(Constant *C1, Constant *C2) {
498 if (C1->getType()->isUnsigned()) return getShr(C1, C2);
499 return getCast(getShr(getCast(C1,
500 C1->getType()->getUnsignedVersion()), C2), C1->getType());
501}
Chris Lattner817175f2004-03-29 02:37:53 +0000502
Chris Lattnerdb8bdba2004-05-25 05:32:43 +0000503Constant *ConstantExpr::getSShr(Constant *C1, Constant *C2) {
504 if (C1->getType()->isSigned()) return getShr(C1, C2);
505 return getCast(getShr(getCast(C1,
506 C1->getType()->getSignedVersion()), C2), C1->getType());
507}
Chris Lattner60e0dd72001-10-03 06:12:09 +0000508
Chris Lattner7c1018a2006-07-14 19:37:40 +0000509/// getWithOperandReplaced - Return a constant expression identical to this
510/// one, but with the specified operand set to the specified value.
511Constant *ConstantExpr::getWithOperandReplaced(unsigned OpNo,
512 Constant *Op) const {
513 assert(OpNo < getNumOperands() && "Operand num is out of range!");
514 assert(Op->getType() == getOperand(OpNo)->getType() &&
515 "Replacing operand with value of different type!");
Chris Lattner227816342006-07-14 22:20:01 +0000516 if (getOperand(OpNo) == Op)
517 return const_cast<ConstantExpr*>(this);
Chris Lattner7c1018a2006-07-14 19:37:40 +0000518
Chris Lattner227816342006-07-14 22:20:01 +0000519 Constant *Op0, *Op1, *Op2;
Chris Lattner7c1018a2006-07-14 19:37:40 +0000520 switch (getOpcode()) {
521 case Instruction::Cast:
522 return ConstantExpr::getCast(Op, getType());
Chris Lattner227816342006-07-14 22:20:01 +0000523 case Instruction::Select:
524 Op0 = (OpNo == 0) ? Op : getOperand(0);
525 Op1 = (OpNo == 1) ? Op : getOperand(1);
526 Op2 = (OpNo == 2) ? Op : getOperand(2);
527 return ConstantExpr::getSelect(Op0, Op1, Op2);
528 case Instruction::InsertElement:
529 Op0 = (OpNo == 0) ? Op : getOperand(0);
530 Op1 = (OpNo == 1) ? Op : getOperand(1);
531 Op2 = (OpNo == 2) ? Op : getOperand(2);
532 return ConstantExpr::getInsertElement(Op0, Op1, Op2);
533 case Instruction::ExtractElement:
534 Op0 = (OpNo == 0) ? Op : getOperand(0);
535 Op1 = (OpNo == 1) ? Op : getOperand(1);
536 return ConstantExpr::getExtractElement(Op0, Op1);
537 case Instruction::ShuffleVector:
538 Op0 = (OpNo == 0) ? Op : getOperand(0);
539 Op1 = (OpNo == 1) ? Op : getOperand(1);
540 Op2 = (OpNo == 2) ? Op : getOperand(2);
541 return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Chris Lattner7c1018a2006-07-14 19:37:40 +0000542 case Instruction::GetElementPtr: {
543 std::vector<Constant*> Ops;
544 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
545 Ops.push_back(getOperand(i));
546 if (OpNo == 0)
547 return ConstantExpr::getGetElementPtr(Op, Ops);
548 Ops[OpNo-1] = Op;
549 return ConstantExpr::getGetElementPtr(getOperand(0), Ops);
550 }
Chris Lattner7c1018a2006-07-14 19:37:40 +0000551 default:
552 assert(getNumOperands() == 2 && "Must be binary operator?");
Chris Lattner227816342006-07-14 22:20:01 +0000553 Op0 = (OpNo == 0) ? Op : getOperand(0);
554 Op1 = (OpNo == 1) ? Op : getOperand(1);
555 return ConstantExpr::get(getOpcode(), Op0, Op1);
556 }
557}
558
559/// getWithOperands - This returns the current constant expression with the
560/// operands replaced with the specified values. The specified operands must
561/// match count and type with the existing ones.
562Constant *ConstantExpr::
563getWithOperands(const std::vector<Constant*> &Ops) const {
564 assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
565 bool AnyChange = false;
566 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
567 assert(Ops[i]->getType() == getOperand(i)->getType() &&
568 "Operand type mismatch!");
569 AnyChange |= Ops[i] != getOperand(i);
570 }
571 if (!AnyChange) // No operands changed, return self.
572 return const_cast<ConstantExpr*>(this);
573
574 switch (getOpcode()) {
575 case Instruction::Cast:
576 return ConstantExpr::getCast(Ops[0], getType());
577 case Instruction::Select:
578 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
579 case Instruction::InsertElement:
580 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
581 case Instruction::ExtractElement:
582 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
583 case Instruction::ShuffleVector:
584 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
585 case Instruction::GetElementPtr: {
586 std::vector<Constant*> ActualOps(Ops.begin()+1, Ops.end());
587 return ConstantExpr::getGetElementPtr(Ops[0], ActualOps);
588 }
589 default:
590 assert(getNumOperands() == 2 && "Must be binary operator?");
591 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1]);
Chris Lattner7c1018a2006-07-14 19:37:40 +0000592 }
593}
594
Chris Lattner2f7c9632001-06-06 20:29:01 +0000595
596//===----------------------------------------------------------------------===//
Chris Lattner2f7c9632001-06-06 20:29:01 +0000597// isValueValidForType implementations
598
Reid Spencere0fc4df2006-10-20 07:07:24 +0000599bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
Chris Lattner6b727592004-06-17 18:19:28 +0000600 switch (Ty->getTypeID()) {
Chris Lattner2f7c9632001-06-06 20:29:01 +0000601 default:
602 return false; // These can't be represented as integers!!!
Chris Lattner2f7c9632001-06-06 20:29:01 +0000603 // Signed types...
604 case Type::SByteTyID:
605 return (Val <= INT8_MAX && Val >= INT8_MIN);
Reid Spencere0fc4df2006-10-20 07:07:24 +0000606 case Type::UByteTyID:
607 return (Val >= 0) && (Val <= UINT8_MAX);
Chris Lattner2f7c9632001-06-06 20:29:01 +0000608 case Type::ShortTyID:
609 return (Val <= INT16_MAX && Val >= INT16_MIN);
Reid Spencere0fc4df2006-10-20 07:07:24 +0000610 case Type::UShortTyID:
611 return (Val >= 0) && (Val <= UINT16_MAX);
Chris Lattner2f7c9632001-06-06 20:29:01 +0000612 case Type::IntTyID:
Chris Lattner74248512004-06-08 23:21:39 +0000613 return (Val <= int(INT32_MAX) && Val >= int(INT32_MIN));
Chris Lattner2f7c9632001-06-06 20:29:01 +0000614 case Type::UIntTyID:
Reid Spencere0fc4df2006-10-20 07:07:24 +0000615 return (Val >= 0) && (Val <= UINT32_MAX);
616 case Type::LongTyID:
Chris Lattner2f7c9632001-06-06 20:29:01 +0000617 case Type::ULongTyID:
Reid Spencere0fc4df2006-10-20 07:07:24 +0000618 return true; // always true, has to fit in largest type
Chris Lattner2f7c9632001-06-06 20:29:01 +0000619 }
Chris Lattner2f7c9632001-06-06 20:29:01 +0000620}
621
Chris Lattner3462ae32001-12-03 22:26:30 +0000622bool ConstantFP::isValueValidForType(const Type *Ty, double Val) {
Chris Lattner6b727592004-06-17 18:19:28 +0000623 switch (Ty->getTypeID()) {
Chris Lattner2f7c9632001-06-06 20:29:01 +0000624 default:
625 return false; // These can't be represented as floating point!
626
Reid Spencerb95f8ab2004-12-07 07:38:08 +0000627 // TODO: Figure out how to test if a double can be cast to a float!
Chris Lattner2f7c9632001-06-06 20:29:01 +0000628 case Type::FloatTyID:
Chris Lattner2f7c9632001-06-06 20:29:01 +0000629 case Type::DoubleTyID:
630 return true; // This is the largest type...
631 }
Chris Lattneraa2372562006-05-24 17:04:05 +0000632}
Chris Lattner9655e542001-07-20 19:16:02 +0000633
Chris Lattner49d855c2001-09-07 16:46:31 +0000634//===----------------------------------------------------------------------===//
Chris Lattner49d855c2001-09-07 16:46:31 +0000635// Factory Function Implementation
636
Chris Lattner98fa07b2003-05-23 20:03:32 +0000637// ConstantCreator - A class that is used to create constants by
638// ValueMap*. This class should be partially specialized if there is
639// something strange that needs to be done to interface to the ctor for the
640// constant.
641//
Chris Lattner189d19f2003-11-21 20:23:48 +0000642namespace llvm {
643 template<class ConstantClass, class TypeClass, class ValType>
Chris Lattner02157b02006-06-28 21:38:54 +0000644 struct VISIBILITY_HIDDEN ConstantCreator {
Chris Lattner189d19f2003-11-21 20:23:48 +0000645 static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
646 return new ConstantClass(Ty, V);
647 }
648 };
Misha Brukmanb1c93172005-04-21 23:48:37 +0000649
Chris Lattner189d19f2003-11-21 20:23:48 +0000650 template<class ConstantClass, class TypeClass>
Chris Lattner02157b02006-06-28 21:38:54 +0000651 struct VISIBILITY_HIDDEN ConvertConstantType {
Chris Lattner189d19f2003-11-21 20:23:48 +0000652 static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
653 assert(0 && "This type cannot be converted!\n");
654 abort();
655 }
656 };
Chris Lattnerb50d1352003-10-05 00:17:43 +0000657
Chris Lattner935aa922005-10-04 17:48:46 +0000658 template<class ValType, class TypeClass, class ConstantClass,
659 bool HasLargeKey = false /*true for arrays and structs*/ >
Chris Lattner02157b02006-06-28 21:38:54 +0000660 class VISIBILITY_HIDDEN ValueMap : public AbstractTypeUser {
Chris Lattnerb64419a2005-10-03 22:51:37 +0000661 public:
Jim Laskeyc03caef2006-07-17 17:38:29 +0000662 typedef std::pair<const Type*, ValType> MapKey;
663 typedef std::map<MapKey, Constant *> MapTy;
664 typedef std::map<Constant*, typename MapTy::iterator> InverseMapTy;
665 typedef std::map<const Type*, typename MapTy::iterator> AbstractTypeMapTy;
Chris Lattnerb64419a2005-10-03 22:51:37 +0000666 private:
Chris Lattner5bbf60a52005-10-04 16:52:46 +0000667 /// Map - This is the main map from the element descriptor to the Constants.
668 /// This is the primary way we avoid creating two of the same shape
669 /// constant.
Chris Lattnerb50d1352003-10-05 00:17:43 +0000670 MapTy Map;
Chris Lattner935aa922005-10-04 17:48:46 +0000671
672 /// InverseMap - If "HasLargeKey" is true, this contains an inverse mapping
673 /// from the constants to their element in Map. This is important for
674 /// removal of constants from the array, which would otherwise have to scan
675 /// through the map with very large keys.
Jim Laskeyc03caef2006-07-17 17:38:29 +0000676 InverseMapTy InverseMap;
Chris Lattnerb50d1352003-10-05 00:17:43 +0000677
Jim Laskeyc03caef2006-07-17 17:38:29 +0000678 /// AbstractTypeMap - Map for abstract type constants.
679 ///
Chris Lattnerb50d1352003-10-05 00:17:43 +0000680 AbstractTypeMapTy AbstractTypeMap;
Chris Lattner99a669b2004-11-19 16:39:44 +0000681
Chris Lattner99a669b2004-11-19 16:39:44 +0000682 private:
683 void clear(std::vector<Constant *> &Constants) {
Jim Laskeyc03caef2006-07-17 17:38:29 +0000684 for(typename MapTy::iterator I = Map.begin(); I != Map.end(); ++I)
Chris Lattner99a669b2004-11-19 16:39:44 +0000685 Constants.push_back(I->second);
686 Map.clear();
687 AbstractTypeMap.clear();
Chris Lattner935aa922005-10-04 17:48:46 +0000688 InverseMap.clear();
Chris Lattner99a669b2004-11-19 16:39:44 +0000689 }
690
Chris Lattner98fa07b2003-05-23 20:03:32 +0000691 public:
Jim Laskeyc03caef2006-07-17 17:38:29 +0000692 typename MapTy::iterator map_end() { return Map.end(); }
Chris Lattnerb64419a2005-10-03 22:51:37 +0000693
694 /// InsertOrGetItem - Return an iterator for the specified element.
695 /// If the element exists in the map, the returned iterator points to the
696 /// entry and Exists=true. If not, the iterator points to the newly
697 /// inserted entry and returns Exists=false. Newly inserted entries have
698 /// I->second == 0, and should be filled in.
Jim Laskeyc03caef2006-07-17 17:38:29 +0000699 typename MapTy::iterator InsertOrGetItem(std::pair<MapKey, Constant *>
700 &InsertVal,
Chris Lattnerb64419a2005-10-03 22:51:37 +0000701 bool &Exists) {
Jim Laskeyc03caef2006-07-17 17:38:29 +0000702 std::pair<typename MapTy::iterator, bool> IP = Map.insert(InsertVal);
Chris Lattnerb64419a2005-10-03 22:51:37 +0000703 Exists = !IP.second;
704 return IP.first;
705 }
Chris Lattner5bbf60a52005-10-04 16:52:46 +0000706
Chris Lattner935aa922005-10-04 17:48:46 +0000707private:
Jim Laskeyc03caef2006-07-17 17:38:29 +0000708 typename MapTy::iterator FindExistingElement(ConstantClass *CP) {
Chris Lattner935aa922005-10-04 17:48:46 +0000709 if (HasLargeKey) {
Jim Laskeyc03caef2006-07-17 17:38:29 +0000710 typename InverseMapTy::iterator IMI = InverseMap.find(CP);
Chris Lattner935aa922005-10-04 17:48:46 +0000711 assert(IMI != InverseMap.end() && IMI->second != Map.end() &&
712 IMI->second->second == CP &&
713 "InverseMap corrupt!");
714 return IMI->second;
715 }
716
Jim Laskeyc03caef2006-07-17 17:38:29 +0000717 typename MapTy::iterator I =
Chris Lattner935aa922005-10-04 17:48:46 +0000718 Map.find(MapKey((TypeClass*)CP->getRawType(), getValType(CP)));
Chris Lattner5bbf60a52005-10-04 16:52:46 +0000719 if (I == Map.end() || I->second != CP) {
720 // FIXME: This should not use a linear scan. If this gets to be a
721 // performance problem, someone should look at this.
722 for (I = Map.begin(); I != Map.end() && I->second != CP; ++I)
723 /* empty */;
724 }
Chris Lattner935aa922005-10-04 17:48:46 +0000725 return I;
726 }
727public:
728
Chris Lattnerb64419a2005-10-03 22:51:37 +0000729 /// getOrCreate - Return the specified constant from the map, creating it if
730 /// necessary.
Chris Lattner98fa07b2003-05-23 20:03:32 +0000731 ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
Chris Lattnerb50d1352003-10-05 00:17:43 +0000732 MapKey Lookup(Ty, V);
Jim Laskeyc03caef2006-07-17 17:38:29 +0000733 typename MapTy::iterator I = Map.lower_bound(Lookup);
Reid Spencere0fc4df2006-10-20 07:07:24 +0000734 // Is it in the map?
Chris Lattner98fa07b2003-05-23 20:03:32 +0000735 if (I != Map.end() && I->first == Lookup)
Reid Spencere0fc4df2006-10-20 07:07:24 +0000736 return static_cast<ConstantClass *>(I->second);
Chris Lattner98fa07b2003-05-23 20:03:32 +0000737
738 // If no preexisting value, create one now...
739 ConstantClass *Result =
740 ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
741
Chris Lattnerb50d1352003-10-05 00:17:43 +0000742 /// FIXME: why does this assert fail when loading 176.gcc?
743 //assert(Result->getType() == Ty && "Type specified is not correct!");
744 I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
745
Chris Lattner935aa922005-10-04 17:48:46 +0000746 if (HasLargeKey) // Remember the reverse mapping if needed.
747 InverseMap.insert(std::make_pair(Result, I));
748
Chris Lattnerb50d1352003-10-05 00:17:43 +0000749 // If the type of the constant is abstract, make sure that an entry exists
750 // for it in the AbstractTypeMap.
751 if (Ty->isAbstract()) {
752 typename AbstractTypeMapTy::iterator TI =
753 AbstractTypeMap.lower_bound(Ty);
754
755 if (TI == AbstractTypeMap.end() || TI->first != Ty) {
756 // Add ourselves to the ATU list of the type.
757 cast<DerivedType>(Ty)->addAbstractTypeUser(this);
758
759 AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
760 }
761 }
Chris Lattner98fa07b2003-05-23 20:03:32 +0000762 return Result;
763 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000764
Chris Lattner98fa07b2003-05-23 20:03:32 +0000765 void remove(ConstantClass *CP) {
Jim Laskeyc03caef2006-07-17 17:38:29 +0000766 typename MapTy::iterator I = FindExistingElement(CP);
Chris Lattnerb50d1352003-10-05 00:17:43 +0000767 assert(I != Map.end() && "Constant not found in constant table!");
Chris Lattner3e650af2004-08-04 04:48:01 +0000768 assert(I->second == CP && "Didn't find correct element?");
Chris Lattnerb50d1352003-10-05 00:17:43 +0000769
Chris Lattner935aa922005-10-04 17:48:46 +0000770 if (HasLargeKey) // Remember the reverse mapping if needed.
771 InverseMap.erase(CP);
772
Chris Lattnerb50d1352003-10-05 00:17:43 +0000773 // Now that we found the entry, make sure this isn't the entry that
774 // the AbstractTypeMap points to.
Jim Laskeyc03caef2006-07-17 17:38:29 +0000775 const TypeClass *Ty = static_cast<const TypeClass *>(I->first.first);
Chris Lattnerb50d1352003-10-05 00:17:43 +0000776 if (Ty->isAbstract()) {
777 assert(AbstractTypeMap.count(Ty) &&
778 "Abstract type not in AbstractTypeMap?");
Jim Laskeyc03caef2006-07-17 17:38:29 +0000779 typename MapTy::iterator &ATMEntryIt = AbstractTypeMap[Ty];
Chris Lattnerb50d1352003-10-05 00:17:43 +0000780 if (ATMEntryIt == I) {
781 // Yes, we are removing the representative entry for this type.
782 // See if there are any other entries of the same type.
Jim Laskeyc03caef2006-07-17 17:38:29 +0000783 typename MapTy::iterator TmpIt = ATMEntryIt;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000784
Chris Lattnerb50d1352003-10-05 00:17:43 +0000785 // First check the entry before this one...
786 if (TmpIt != Map.begin()) {
787 --TmpIt;
788 if (TmpIt->first.first != Ty) // Not the same type, move back...
789 ++TmpIt;
790 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000791
Chris Lattnerb50d1352003-10-05 00:17:43 +0000792 // If we didn't find the same type, try to move forward...
793 if (TmpIt == ATMEntryIt) {
794 ++TmpIt;
795 if (TmpIt == Map.end() || TmpIt->first.first != Ty)
796 --TmpIt; // No entry afterwards with the same type
797 }
798
799 // If there is another entry in the map of the same abstract type,
800 // update the AbstractTypeMap entry now.
801 if (TmpIt != ATMEntryIt) {
802 ATMEntryIt = TmpIt;
803 } else {
804 // Otherwise, we are removing the last instance of this type
805 // from the table. Remove from the ATM, and from user list.
806 cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
807 AbstractTypeMap.erase(Ty);
808 }
Chris Lattner98fa07b2003-05-23 20:03:32 +0000809 }
Chris Lattnerb50d1352003-10-05 00:17:43 +0000810 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000811
Chris Lattnerb50d1352003-10-05 00:17:43 +0000812 Map.erase(I);
813 }
814
Chris Lattner3b793c62005-10-04 21:35:50 +0000815
816 /// MoveConstantToNewSlot - If we are about to change C to be the element
817 /// specified by I, update our internal data structures to reflect this
818 /// fact.
Jim Laskeyc03caef2006-07-17 17:38:29 +0000819 void MoveConstantToNewSlot(ConstantClass *C, typename MapTy::iterator I) {
Chris Lattner3b793c62005-10-04 21:35:50 +0000820 // First, remove the old location of the specified constant in the map.
Jim Laskeyc03caef2006-07-17 17:38:29 +0000821 typename MapTy::iterator OldI = FindExistingElement(C);
Chris Lattner3b793c62005-10-04 21:35:50 +0000822 assert(OldI != Map.end() && "Constant not found in constant table!");
823 assert(OldI->second == C && "Didn't find correct element?");
824
825 // If this constant is the representative element for its abstract type,
826 // update the AbstractTypeMap so that the representative element is I.
827 if (C->getType()->isAbstract()) {
828 typename AbstractTypeMapTy::iterator ATI =
829 AbstractTypeMap.find(C->getType());
830 assert(ATI != AbstractTypeMap.end() &&
831 "Abstract type not in AbstractTypeMap?");
832 if (ATI->second == OldI)
833 ATI->second = I;
834 }
835
836 // Remove the old entry from the map.
837 Map.erase(OldI);
838
839 // Update the inverse map so that we know that this constant is now
840 // located at descriptor I.
841 if (HasLargeKey) {
842 assert(I->second == C && "Bad inversemap entry!");
843 InverseMap[C] = I;
844 }
845 }
846
Chris Lattnerb50d1352003-10-05 00:17:43 +0000847 void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
Misha Brukmanb1c93172005-04-21 23:48:37 +0000848 typename AbstractTypeMapTy::iterator I =
Jim Laskeyc03caef2006-07-17 17:38:29 +0000849 AbstractTypeMap.find(cast<Type>(OldTy));
Chris Lattnerb50d1352003-10-05 00:17:43 +0000850
851 assert(I != AbstractTypeMap.end() &&
852 "Abstract type not in AbstractTypeMap?");
853
854 // Convert a constant at a time until the last one is gone. The last one
855 // leaving will remove() itself, causing the AbstractTypeMapEntry to be
856 // eliminated eventually.
857 do {
858 ConvertConstantType<ConstantClass,
Jim Laskeyc03caef2006-07-17 17:38:29 +0000859 TypeClass>::convert(
860 static_cast<ConstantClass *>(I->second->second),
Chris Lattnerb50d1352003-10-05 00:17:43 +0000861 cast<TypeClass>(NewTy));
862
Jim Laskeyc03caef2006-07-17 17:38:29 +0000863 I = AbstractTypeMap.find(cast<Type>(OldTy));
Chris Lattnerb50d1352003-10-05 00:17:43 +0000864 } while (I != AbstractTypeMap.end());
865 }
866
867 // If the type became concrete without being refined to any other existing
868 // type, we just remove ourselves from the ATU list.
869 void typeBecameConcrete(const DerivedType *AbsTy) {
870 AbsTy->removeAbstractTypeUser(this);
871 }
872
873 void dump() const {
874 std::cerr << "Constant.cpp: ValueMap\n";
Chris Lattner98fa07b2003-05-23 20:03:32 +0000875 }
876 };
877}
878
Chris Lattnera84df0a22006-09-28 23:36:21 +0000879
880//---- ConstantBool::get*() implementation.
881
882ConstantBool *ConstantBool::getTrue() {
883 static ConstantBool *T = 0;
884 if (T) return T;
885 return T = new ConstantBool(true);
886}
887ConstantBool *ConstantBool::getFalse() {
888 static ConstantBool *F = 0;
889 if (F) return F;
890 return F = new ConstantBool(false);
891}
892
Reid Spencere0fc4df2006-10-20 07:07:24 +0000893//---- ConstantInt::get() implementations...
Chris Lattner49d855c2001-09-07 16:46:31 +0000894//
Reid Spencere0fc4df2006-10-20 07:07:24 +0000895static ManagedStatic<ValueMap<uint64_t, Type, ConstantInt> > IntConstants;
Chris Lattner49d855c2001-09-07 16:46:31 +0000896
Reid Spencere0fc4df2006-10-20 07:07:24 +0000897// Get a ConstantInt from an int64_t. Note here that we canoncialize the value
898// to a uint64_t value that has been zero extended down to the size of the
899// integer type of the ConstantInt. This allows the getZExtValue method to
900// just return the stored value while getSExtValue has to convert back to sign
901// extended. getZExtValue is more common in LLVM than getSExtValue().
902ConstantInt *ConstantInt::get(const Type *Ty, int64_t V) {
903 unsigned Size = Ty->getPrimitiveSizeInBits();
904 uint64_t ZeroExtendedCanonicalization = V & (~uint64_t(0UL) >> (64-Size));
905 return IntConstants->getOrCreate(Ty, ZeroExtendedCanonicalization );
Chris Lattner49d855c2001-09-07 16:46:31 +0000906}
907
Chris Lattner3462ae32001-12-03 22:26:30 +0000908//---- ConstantFP::get() implementation...
Chris Lattner49d855c2001-09-07 16:46:31 +0000909//
Chris Lattnerac80ea42004-02-01 22:49:04 +0000910namespace llvm {
911 template<>
912 struct ConstantCreator<ConstantFP, Type, uint64_t> {
913 static ConstantFP *create(const Type *Ty, uint64_t V) {
914 assert(Ty == Type::DoubleTy);
Jim Laskeyb74c6662005-08-17 19:34:49 +0000915 return new ConstantFP(Ty, BitsToDouble(V));
Chris Lattnerac80ea42004-02-01 22:49:04 +0000916 }
917 };
918 template<>
919 struct ConstantCreator<ConstantFP, Type, uint32_t> {
920 static ConstantFP *create(const Type *Ty, uint32_t V) {
921 assert(Ty == Type::FloatTy);
Jim Laskeyb74c6662005-08-17 19:34:49 +0000922 return new ConstantFP(Ty, BitsToFloat(V));
Chris Lattnerac80ea42004-02-01 22:49:04 +0000923 }
924 };
925}
926
Chris Lattner69edc982006-09-28 00:35:06 +0000927static ManagedStatic<ValueMap<uint64_t, Type, ConstantFP> > DoubleConstants;
928static ManagedStatic<ValueMap<uint32_t, Type, ConstantFP> > FloatConstants;
Chris Lattner49d855c2001-09-07 16:46:31 +0000929
Jim Laskey8ad8f712005-08-17 20:06:22 +0000930bool ConstantFP::isNullValue() const {
931 return DoubleToBits(Val) == 0;
932}
933
934bool ConstantFP::isExactlyValue(double V) const {
935 return DoubleToBits(V) == DoubleToBits(Val);
936}
937
938
Chris Lattner3462ae32001-12-03 22:26:30 +0000939ConstantFP *ConstantFP::get(const Type *Ty, double V) {
Chris Lattner241ed4c2004-01-23 00:55:21 +0000940 if (Ty == Type::FloatTy) {
941 // Force the value through memory to normalize it.
Chris Lattner69edc982006-09-28 00:35:06 +0000942 return FloatConstants->getOrCreate(Ty, FloatToBits(V));
Chris Lattnerac80ea42004-02-01 22:49:04 +0000943 } else {
944 assert(Ty == Type::DoubleTy);
Chris Lattner69edc982006-09-28 00:35:06 +0000945 return DoubleConstants->getOrCreate(Ty, DoubleToBits(V));
Chris Lattner241ed4c2004-01-23 00:55:21 +0000946 }
Chris Lattner49d855c2001-09-07 16:46:31 +0000947}
948
Chris Lattner9fba3da2004-02-15 05:53:04 +0000949//---- ConstantAggregateZero::get() implementation...
950//
951namespace llvm {
952 // ConstantAggregateZero does not take extra "value" argument...
953 template<class ValType>
954 struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
955 static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
956 return new ConstantAggregateZero(Ty);
957 }
958 };
959
960 template<>
961 struct ConvertConstantType<ConstantAggregateZero, Type> {
962 static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
963 // Make everyone now use a constant of the new type...
964 Constant *New = ConstantAggregateZero::get(NewTy);
965 assert(New != OldC && "Didn't replace constant??");
966 OldC->uncheckedReplaceAllUsesWith(New);
967 OldC->destroyConstant(); // This constant is now dead, destroy it.
968 }
969 };
970}
971
Chris Lattner69edc982006-09-28 00:35:06 +0000972static ManagedStatic<ValueMap<char, Type,
973 ConstantAggregateZero> > AggZeroConstants;
Chris Lattner9fba3da2004-02-15 05:53:04 +0000974
Chris Lattner3e650af2004-08-04 04:48:01 +0000975static char getValType(ConstantAggregateZero *CPZ) { return 0; }
976
Chris Lattner9fba3da2004-02-15 05:53:04 +0000977Constant *ConstantAggregateZero::get(const Type *Ty) {
Chris Lattnerbfd0b6d2006-06-10 04:16:23 +0000978 assert((isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<PackedType>(Ty)) &&
979 "Cannot create an aggregate zero of non-aggregate type!");
Chris Lattner69edc982006-09-28 00:35:06 +0000980 return AggZeroConstants->getOrCreate(Ty, 0);
Chris Lattner9fba3da2004-02-15 05:53:04 +0000981}
982
983// destroyConstant - Remove the constant from the constant table...
984//
985void ConstantAggregateZero::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +0000986 AggZeroConstants->remove(this);
Chris Lattner9fba3da2004-02-15 05:53:04 +0000987 destroyConstantImpl();
988}
989
Chris Lattner3462ae32001-12-03 22:26:30 +0000990//---- ConstantArray::get() implementation...
Chris Lattner49d855c2001-09-07 16:46:31 +0000991//
Chris Lattner189d19f2003-11-21 20:23:48 +0000992namespace llvm {
993 template<>
994 struct ConvertConstantType<ConstantArray, ArrayType> {
995 static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
996 // Make everyone now use a constant of the new type...
997 std::vector<Constant*> C;
998 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
999 C.push_back(cast<Constant>(OldC->getOperand(i)));
1000 Constant *New = ConstantArray::get(NewTy, C);
1001 assert(New != OldC && "Didn't replace constant??");
1002 OldC->uncheckedReplaceAllUsesWith(New);
1003 OldC->destroyConstant(); // This constant is now dead, destroy it.
1004 }
1005 };
1006}
Chris Lattnerb50d1352003-10-05 00:17:43 +00001007
Chris Lattner3e650af2004-08-04 04:48:01 +00001008static std::vector<Constant*> getValType(ConstantArray *CA) {
1009 std::vector<Constant*> Elements;
1010 Elements.reserve(CA->getNumOperands());
1011 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1012 Elements.push_back(cast<Constant>(CA->getOperand(i)));
1013 return Elements;
1014}
1015
Chris Lattnerb64419a2005-10-03 22:51:37 +00001016typedef ValueMap<std::vector<Constant*>, ArrayType,
Chris Lattner935aa922005-10-04 17:48:46 +00001017 ConstantArray, true /*largekey*/> ArrayConstantsTy;
Chris Lattner69edc982006-09-28 00:35:06 +00001018static ManagedStatic<ArrayConstantsTy> ArrayConstants;
Chris Lattner49d855c2001-09-07 16:46:31 +00001019
Chris Lattner015e8212004-02-15 04:14:47 +00001020Constant *ConstantArray::get(const ArrayType *Ty,
Chris Lattner9fba3da2004-02-15 05:53:04 +00001021 const std::vector<Constant*> &V) {
1022 // If this is an all-zero array, return a ConstantAggregateZero object
1023 if (!V.empty()) {
1024 Constant *C = V[0];
1025 if (!C->isNullValue())
Chris Lattner69edc982006-09-28 00:35:06 +00001026 return ArrayConstants->getOrCreate(Ty, V);
Chris Lattner9fba3da2004-02-15 05:53:04 +00001027 for (unsigned i = 1, e = V.size(); i != e; ++i)
1028 if (V[i] != C)
Chris Lattner69edc982006-09-28 00:35:06 +00001029 return ArrayConstants->getOrCreate(Ty, V);
Chris Lattner9fba3da2004-02-15 05:53:04 +00001030 }
1031 return ConstantAggregateZero::get(Ty);
Chris Lattner49d855c2001-09-07 16:46:31 +00001032}
1033
Chris Lattner98fa07b2003-05-23 20:03:32 +00001034// destroyConstant - Remove the constant from the constant table...
1035//
1036void ConstantArray::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00001037 ArrayConstants->remove(this);
Chris Lattner98fa07b2003-05-23 20:03:32 +00001038 destroyConstantImpl();
1039}
1040
Reid Spencer6f614532006-05-30 08:23:18 +00001041/// ConstantArray::get(const string&) - Return an array that is initialized to
1042/// contain the specified string. If length is zero then a null terminator is
1043/// added to the specified string so that it may be used in a natural way.
1044/// Otherwise, the length parameter specifies how much of the string to use
1045/// and it won't be null terminated.
1046///
Reid Spencer82ebaba2006-05-30 18:15:07 +00001047Constant *ConstantArray::get(const std::string &Str, bool AddNull) {
Chris Lattner7f74a562002-01-20 22:54:45 +00001048 std::vector<Constant*> ElementVals;
Reid Spencer82ebaba2006-05-30 18:15:07 +00001049 for (unsigned i = 0; i < Str.length(); ++i)
Reid Spencere0fc4df2006-10-20 07:07:24 +00001050 ElementVals.push_back(ConstantInt::get(Type::SByteTy, Str[i]));
Chris Lattner8f80fe02001-10-14 23:54:12 +00001051
1052 // Add a null terminator to the string...
Reid Spencer82ebaba2006-05-30 18:15:07 +00001053 if (AddNull) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00001054 ElementVals.push_back(ConstantInt::get(Type::SByteTy, 0));
Reid Spencer6f614532006-05-30 08:23:18 +00001055 }
Chris Lattner8f80fe02001-10-14 23:54:12 +00001056
Reid Spencer82ebaba2006-05-30 18:15:07 +00001057 ArrayType *ATy = ArrayType::get(Type::SByteTy, ElementVals.size());
Chris Lattner3462ae32001-12-03 22:26:30 +00001058 return ConstantArray::get(ATy, ElementVals);
Vikram S. Adve34410432001-10-14 23:17:20 +00001059}
1060
Chris Lattnere8dfcca2004-01-14 17:06:38 +00001061/// isString - This method returns true if the array is an array of sbyte or
1062/// ubyte, and if the elements of the array are all ConstantInt's.
1063bool ConstantArray::isString() const {
1064 // Check the element type for sbyte or ubyte...
Chris Lattnere8701f62004-01-14 17:51:53 +00001065 if (getType()->getElementType() != Type::UByteTy &&
Chris Lattnere8dfcca2004-01-14 17:06:38 +00001066 getType()->getElementType() != Type::SByteTy)
1067 return false;
1068 // Check the elements to make sure they are all integers, not constant
1069 // expressions.
1070 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1071 if (!isa<ConstantInt>(getOperand(i)))
1072 return false;
1073 return true;
1074}
1075
Evan Cheng3763c5b2006-10-26 19:15:05 +00001076/// isCString - This method returns true if the array is a string (see
1077/// isString) and it ends in a null byte \0 and does not contains any other
1078/// null bytes except its terminator.
1079bool ConstantArray::isCString() const {
Evan Chenge974da62006-10-26 21:48:03 +00001080 // Check the element type for sbyte or ubyte...
1081 if (getType()->getElementType() != Type::UByteTy &&
1082 getType()->getElementType() != Type::SByteTy)
1083 return false;
1084 Constant *Zero = Constant::getNullValue(getOperand(0)->getType());
1085 // Last element must be a null.
1086 if (getOperand(getNumOperands()-1) != Zero)
1087 return false;
1088 // Other elements must be non-null integers.
1089 for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
1090 if (!isa<ConstantInt>(getOperand(i)))
Evan Cheng3763c5b2006-10-26 19:15:05 +00001091 return false;
Evan Chenge974da62006-10-26 21:48:03 +00001092 if (getOperand(i) == Zero)
1093 return false;
1094 }
Evan Cheng3763c5b2006-10-26 19:15:05 +00001095 return true;
1096}
1097
1098
Chris Lattner81fabb02002-08-26 17:53:56 +00001099// getAsString - If the sub-element type of this array is either sbyte or ubyte,
1100// then this method converts the array to an std::string and returns it.
1101// Otherwise, it asserts out.
1102//
1103std::string ConstantArray::getAsString() const {
Chris Lattnere8dfcca2004-01-14 17:06:38 +00001104 assert(isString() && "Not a string!");
Chris Lattner81fabb02002-08-26 17:53:56 +00001105 std::string Result;
Chris Lattner6077c312003-07-23 15:22:26 +00001106 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
Reid Spencere0fc4df2006-10-20 07:07:24 +00001107 Result += (char)cast<ConstantInt>(getOperand(i))->getZExtValue();
Chris Lattner81fabb02002-08-26 17:53:56 +00001108 return Result;
1109}
1110
1111
Chris Lattner3462ae32001-12-03 22:26:30 +00001112//---- ConstantStruct::get() implementation...
Chris Lattner49d855c2001-09-07 16:46:31 +00001113//
Chris Lattnerb50d1352003-10-05 00:17:43 +00001114
Chris Lattner189d19f2003-11-21 20:23:48 +00001115namespace llvm {
1116 template<>
1117 struct ConvertConstantType<ConstantStruct, StructType> {
1118 static void convert(ConstantStruct *OldC, const StructType *NewTy) {
1119 // Make everyone now use a constant of the new type...
1120 std::vector<Constant*> C;
1121 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1122 C.push_back(cast<Constant>(OldC->getOperand(i)));
1123 Constant *New = ConstantStruct::get(NewTy, C);
1124 assert(New != OldC && "Didn't replace constant??");
Misha Brukmanb1c93172005-04-21 23:48:37 +00001125
Chris Lattner189d19f2003-11-21 20:23:48 +00001126 OldC->uncheckedReplaceAllUsesWith(New);
1127 OldC->destroyConstant(); // This constant is now dead, destroy it.
1128 }
1129 };
1130}
Chris Lattnerb50d1352003-10-05 00:17:43 +00001131
Chris Lattner8760ec72005-10-04 01:17:50 +00001132typedef ValueMap<std::vector<Constant*>, StructType,
Chris Lattner935aa922005-10-04 17:48:46 +00001133 ConstantStruct, true /*largekey*/> StructConstantsTy;
Chris Lattner69edc982006-09-28 00:35:06 +00001134static ManagedStatic<StructConstantsTy> StructConstants;
Chris Lattner49d855c2001-09-07 16:46:31 +00001135
Chris Lattner3e650af2004-08-04 04:48:01 +00001136static std::vector<Constant*> getValType(ConstantStruct *CS) {
1137 std::vector<Constant*> Elements;
1138 Elements.reserve(CS->getNumOperands());
1139 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1140 Elements.push_back(cast<Constant>(CS->getOperand(i)));
1141 return Elements;
1142}
1143
Chris Lattner015e8212004-02-15 04:14:47 +00001144Constant *ConstantStruct::get(const StructType *Ty,
1145 const std::vector<Constant*> &V) {
Chris Lattner9fba3da2004-02-15 05:53:04 +00001146 // Create a ConstantAggregateZero value if all elements are zeros...
1147 for (unsigned i = 0, e = V.size(); i != e; ++i)
1148 if (!V[i]->isNullValue())
Chris Lattner69edc982006-09-28 00:35:06 +00001149 return StructConstants->getOrCreate(Ty, V);
Chris Lattner9fba3da2004-02-15 05:53:04 +00001150
1151 return ConstantAggregateZero::get(Ty);
Chris Lattner49d855c2001-09-07 16:46:31 +00001152}
Chris Lattner883ad0b2001-10-03 15:39:36 +00001153
Chris Lattnerd6108ca2004-07-12 20:35:11 +00001154Constant *ConstantStruct::get(const std::vector<Constant*> &V) {
1155 std::vector<const Type*> StructEls;
1156 StructEls.reserve(V.size());
1157 for (unsigned i = 0, e = V.size(); i != e; ++i)
1158 StructEls.push_back(V[i]->getType());
1159 return get(StructType::get(StructEls), V);
1160}
1161
Chris Lattnerd7a73302001-10-13 06:57:33 +00001162// destroyConstant - Remove the constant from the constant table...
Chris Lattner883ad0b2001-10-03 15:39:36 +00001163//
Chris Lattner3462ae32001-12-03 22:26:30 +00001164void ConstantStruct::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00001165 StructConstants->remove(this);
Chris Lattnerd7a73302001-10-13 06:57:33 +00001166 destroyConstantImpl();
1167}
Chris Lattner883ad0b2001-10-03 15:39:36 +00001168
Brian Gaeke02209042004-08-20 06:00:58 +00001169//---- ConstantPacked::get() implementation...
1170//
1171namespace llvm {
1172 template<>
1173 struct ConvertConstantType<ConstantPacked, PackedType> {
1174 static void convert(ConstantPacked *OldC, const PackedType *NewTy) {
1175 // Make everyone now use a constant of the new type...
1176 std::vector<Constant*> C;
1177 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1178 C.push_back(cast<Constant>(OldC->getOperand(i)));
1179 Constant *New = ConstantPacked::get(NewTy, C);
1180 assert(New != OldC && "Didn't replace constant??");
1181 OldC->uncheckedReplaceAllUsesWith(New);
1182 OldC->destroyConstant(); // This constant is now dead, destroy it.
1183 }
1184 };
1185}
1186
1187static std::vector<Constant*> getValType(ConstantPacked *CP) {
1188 std::vector<Constant*> Elements;
1189 Elements.reserve(CP->getNumOperands());
1190 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1191 Elements.push_back(CP->getOperand(i));
1192 return Elements;
1193}
1194
Chris Lattner69edc982006-09-28 00:35:06 +00001195static ManagedStatic<ValueMap<std::vector<Constant*>, PackedType,
1196 ConstantPacked> > PackedConstants;
Brian Gaeke02209042004-08-20 06:00:58 +00001197
1198Constant *ConstantPacked::get(const PackedType *Ty,
1199 const std::vector<Constant*> &V) {
1200 // If this is an all-zero packed, return a ConstantAggregateZero object
1201 if (!V.empty()) {
1202 Constant *C = V[0];
1203 if (!C->isNullValue())
Chris Lattner69edc982006-09-28 00:35:06 +00001204 return PackedConstants->getOrCreate(Ty, V);
Brian Gaeke02209042004-08-20 06:00:58 +00001205 for (unsigned i = 1, e = V.size(); i != e; ++i)
1206 if (V[i] != C)
Chris Lattner69edc982006-09-28 00:35:06 +00001207 return PackedConstants->getOrCreate(Ty, V);
Brian Gaeke02209042004-08-20 06:00:58 +00001208 }
1209 return ConstantAggregateZero::get(Ty);
1210}
1211
1212Constant *ConstantPacked::get(const std::vector<Constant*> &V) {
1213 assert(!V.empty() && "Cannot infer type if V is empty");
1214 return get(PackedType::get(V.front()->getType(),V.size()), V);
1215}
1216
1217// destroyConstant - Remove the constant from the constant table...
1218//
1219void ConstantPacked::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00001220 PackedConstants->remove(this);
Brian Gaeke02209042004-08-20 06:00:58 +00001221 destroyConstantImpl();
1222}
1223
Chris Lattner3462ae32001-12-03 22:26:30 +00001224//---- ConstantPointerNull::get() implementation...
Chris Lattnerd7a73302001-10-13 06:57:33 +00001225//
Chris Lattner98fa07b2003-05-23 20:03:32 +00001226
Chris Lattner189d19f2003-11-21 20:23:48 +00001227namespace llvm {
1228 // ConstantPointerNull does not take extra "value" argument...
1229 template<class ValType>
1230 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1231 static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1232 return new ConstantPointerNull(Ty);
1233 }
1234 };
Chris Lattner98fa07b2003-05-23 20:03:32 +00001235
Chris Lattner189d19f2003-11-21 20:23:48 +00001236 template<>
1237 struct ConvertConstantType<ConstantPointerNull, PointerType> {
1238 static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1239 // Make everyone now use a constant of the new type...
1240 Constant *New = ConstantPointerNull::get(NewTy);
1241 assert(New != OldC && "Didn't replace constant??");
1242 OldC->uncheckedReplaceAllUsesWith(New);
1243 OldC->destroyConstant(); // This constant is now dead, destroy it.
1244 }
1245 };
1246}
Chris Lattnerb50d1352003-10-05 00:17:43 +00001247
Chris Lattner69edc982006-09-28 00:35:06 +00001248static ManagedStatic<ValueMap<char, PointerType,
1249 ConstantPointerNull> > NullPtrConstants;
Chris Lattnerd7a73302001-10-13 06:57:33 +00001250
Chris Lattner3e650af2004-08-04 04:48:01 +00001251static char getValType(ConstantPointerNull *) {
1252 return 0;
1253}
1254
1255
Chris Lattner3462ae32001-12-03 22:26:30 +00001256ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
Chris Lattner69edc982006-09-28 00:35:06 +00001257 return NullPtrConstants->getOrCreate(Ty, 0);
Chris Lattner883ad0b2001-10-03 15:39:36 +00001258}
1259
Chris Lattner0c6e0b92002-08-18 00:40:04 +00001260// destroyConstant - Remove the constant from the constant table...
1261//
1262void ConstantPointerNull::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00001263 NullPtrConstants->remove(this);
Chris Lattner0c6e0b92002-08-18 00:40:04 +00001264 destroyConstantImpl();
1265}
1266
1267
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001268//---- UndefValue::get() implementation...
1269//
1270
1271namespace llvm {
1272 // UndefValue does not take extra "value" argument...
1273 template<class ValType>
1274 struct ConstantCreator<UndefValue, Type, ValType> {
1275 static UndefValue *create(const Type *Ty, const ValType &V) {
1276 return new UndefValue(Ty);
1277 }
1278 };
1279
1280 template<>
1281 struct ConvertConstantType<UndefValue, Type> {
1282 static void convert(UndefValue *OldC, const Type *NewTy) {
1283 // Make everyone now use a constant of the new type.
1284 Constant *New = UndefValue::get(NewTy);
1285 assert(New != OldC && "Didn't replace constant??");
1286 OldC->uncheckedReplaceAllUsesWith(New);
1287 OldC->destroyConstant(); // This constant is now dead, destroy it.
1288 }
1289 };
1290}
1291
Chris Lattner69edc982006-09-28 00:35:06 +00001292static ManagedStatic<ValueMap<char, Type, UndefValue> > UndefValueConstants;
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001293
1294static char getValType(UndefValue *) {
1295 return 0;
1296}
1297
1298
1299UndefValue *UndefValue::get(const Type *Ty) {
Chris Lattner69edc982006-09-28 00:35:06 +00001300 return UndefValueConstants->getOrCreate(Ty, 0);
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001301}
1302
1303// destroyConstant - Remove the constant from the constant table.
1304//
1305void UndefValue::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00001306 UndefValueConstants->remove(this);
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001307 destroyConstantImpl();
1308}
1309
1310
1311
1312
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001313//---- ConstantExpr::get() implementations...
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001314//
Chris Lattner2b383d2e2003-05-13 21:37:02 +00001315typedef std::pair<unsigned, std::vector<Constant*> > ExprMapKeyType;
Chris Lattner98fa07b2003-05-23 20:03:32 +00001316
Chris Lattner189d19f2003-11-21 20:23:48 +00001317namespace llvm {
1318 template<>
1319 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
1320 static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V) {
1321 if (V.first == Instruction::Cast)
Chris Lattnerd0df99c2005-01-29 00:34:39 +00001322 return new UnaryConstantExpr(Instruction::Cast, V.second[0], Ty);
Chris Lattner189d19f2003-11-21 20:23:48 +00001323 if ((V.first >= Instruction::BinaryOpsBegin &&
1324 V.first < Instruction::BinaryOpsEnd) ||
1325 V.first == Instruction::Shl || V.first == Instruction::Shr)
Chris Lattnerd0df99c2005-01-29 00:34:39 +00001326 return new BinaryConstantExpr(V.first, V.second[0], V.second[1]);
Chris Lattnerb7897ce2004-03-30 22:51:03 +00001327 if (V.first == Instruction::Select)
Chris Lattnerd0df99c2005-01-29 00:34:39 +00001328 return new SelectConstantExpr(V.second[0], V.second[1], V.second[2]);
Robert Bocchino23004482006-01-10 19:05:34 +00001329 if (V.first == Instruction::ExtractElement)
1330 return new ExtractElementConstantExpr(V.second[0], V.second[1]);
Robert Bocchinoca27f032006-01-17 20:07:22 +00001331 if (V.first == Instruction::InsertElement)
1332 return new InsertElementConstantExpr(V.second[0], V.second[1],
1333 V.second[2]);
Chris Lattnerbbe0a422006-04-08 01:18:18 +00001334 if (V.first == Instruction::ShuffleVector)
1335 return new ShuffleVectorConstantExpr(V.second[0], V.second[1],
1336 V.second[2]);
1337
Chris Lattner189d19f2003-11-21 20:23:48 +00001338 assert(V.first == Instruction::GetElementPtr && "Invalid ConstantExpr!");
Misha Brukmanb1c93172005-04-21 23:48:37 +00001339
Chris Lattner189d19f2003-11-21 20:23:48 +00001340 std::vector<Constant*> IdxList(V.second.begin()+1, V.second.end());
Chris Lattnerd0df99c2005-01-29 00:34:39 +00001341 return new GetElementPtrConstantExpr(V.second[0], IdxList, Ty);
Chris Lattnerb50d1352003-10-05 00:17:43 +00001342 }
Chris Lattner189d19f2003-11-21 20:23:48 +00001343 };
Chris Lattnerb50d1352003-10-05 00:17:43 +00001344
Chris Lattner189d19f2003-11-21 20:23:48 +00001345 template<>
1346 struct ConvertConstantType<ConstantExpr, Type> {
1347 static void convert(ConstantExpr *OldC, const Type *NewTy) {
1348 Constant *New;
1349 switch (OldC->getOpcode()) {
1350 case Instruction::Cast:
1351 New = ConstantExpr::getCast(OldC->getOperand(0), NewTy);
1352 break;
Chris Lattner6e415c02004-03-12 05:54:04 +00001353 case Instruction::Select:
1354 New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1355 OldC->getOperand(1),
1356 OldC->getOperand(2));
1357 break;
Chris Lattner189d19f2003-11-21 20:23:48 +00001358 case Instruction::Shl:
1359 case Instruction::Shr:
1360 New = ConstantExpr::getShiftTy(NewTy, OldC->getOpcode(),
1361 OldC->getOperand(0), OldC->getOperand(1));
1362 break;
1363 default:
1364 assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
1365 OldC->getOpcode() < Instruction::BinaryOpsEnd);
1366 New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1367 OldC->getOperand(1));
1368 break;
1369 case Instruction::GetElementPtr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00001370 // Make everyone now use a constant of the new type...
Chris Lattner13128ab2004-10-11 22:52:25 +00001371 std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
1372 New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0), Idx);
Chris Lattner189d19f2003-11-21 20:23:48 +00001373 break;
1374 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001375
Chris Lattner189d19f2003-11-21 20:23:48 +00001376 assert(New != OldC && "Didn't replace constant??");
1377 OldC->uncheckedReplaceAllUsesWith(New);
1378 OldC->destroyConstant(); // This constant is now dead, destroy it.
1379 }
1380 };
1381} // end namespace llvm
Chris Lattnerb50d1352003-10-05 00:17:43 +00001382
1383
Chris Lattner3e650af2004-08-04 04:48:01 +00001384static ExprMapKeyType getValType(ConstantExpr *CE) {
1385 std::vector<Constant*> Operands;
1386 Operands.reserve(CE->getNumOperands());
1387 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
1388 Operands.push_back(cast<Constant>(CE->getOperand(i)));
1389 return ExprMapKeyType(CE->getOpcode(), Operands);
1390}
1391
Chris Lattner69edc982006-09-28 00:35:06 +00001392static ManagedStatic<ValueMap<ExprMapKeyType, Type,
1393 ConstantExpr> > ExprConstants;
Vikram S. Adve4c485332002-07-15 18:19:33 +00001394
Chris Lattner46b3d302003-04-16 22:40:51 +00001395Constant *ConstantExpr::getCast(Constant *C, const Type *Ty) {
Chris Lattner815ae2b2003-10-07 22:19:19 +00001396 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1397
Chris Lattneracdbe712003-04-17 19:24:48 +00001398 if (Constant *FC = ConstantFoldCastInstruction(C, Ty))
1399 return FC; // Fold a few common cases...
1400
Vikram S. Adve4c485332002-07-15 18:19:33 +00001401 // Look up the constant in the table first to ensure uniqueness
Chris Lattner2b383d2e2003-05-13 21:37:02 +00001402 std::vector<Constant*> argVec(1, C);
Chris Lattner98fa07b2003-05-23 20:03:32 +00001403 ExprMapKeyType Key = std::make_pair(Instruction::Cast, argVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001404 return ExprConstants->getOrCreate(Ty, Key);
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001405}
Chris Lattnerd7a73302001-10-13 06:57:33 +00001406
Chris Lattnerdd284742004-04-04 23:20:30 +00001407Constant *ConstantExpr::getSignExtend(Constant *C, const Type *Ty) {
Chris Lattner1ece6f82005-01-01 15:59:57 +00001408 assert(C->getType()->isIntegral() && Ty->isIntegral() &&
Chris Lattnerdd284742004-04-04 23:20:30 +00001409 C->getType()->getPrimitiveSize() <= Ty->getPrimitiveSize() &&
1410 "This is an illegal sign extension!");
Chris Lattner1ece6f82005-01-01 15:59:57 +00001411 if (C->getType() != Type::BoolTy) {
1412 C = ConstantExpr::getCast(C, C->getType()->getSignedVersion());
1413 return ConstantExpr::getCast(C, Ty);
1414 } else {
Chris Lattnera84df0a22006-09-28 23:36:21 +00001415 if (C == ConstantBool::getTrue())
Chris Lattner1ece6f82005-01-01 15:59:57 +00001416 return ConstantIntegral::getAllOnesValue(Ty);
1417 else
1418 return ConstantIntegral::getNullValue(Ty);
1419 }
Chris Lattnerdd284742004-04-04 23:20:30 +00001420}
1421
1422Constant *ConstantExpr::getZeroExtend(Constant *C, const Type *Ty) {
Chris Lattner1ece6f82005-01-01 15:59:57 +00001423 assert(C->getType()->isIntegral() && Ty->isIntegral() &&
Chris Lattnerdd284742004-04-04 23:20:30 +00001424 C->getType()->getPrimitiveSize() <= Ty->getPrimitiveSize() &&
1425 "This is an illegal zero extension!");
Chris Lattner1ece6f82005-01-01 15:59:57 +00001426 if (C->getType() != Type::BoolTy)
1427 C = ConstantExpr::getCast(C, C->getType()->getUnsignedVersion());
Chris Lattnerdd284742004-04-04 23:20:30 +00001428 return ConstantExpr::getCast(C, Ty);
1429}
1430
Alkis Evlogimenosda5de052004-10-24 01:41:10 +00001431Constant *ConstantExpr::getSizeOf(const Type *Ty) {
Chris Lattneracc4e542004-12-13 19:48:51 +00001432 // sizeof is implemented as: (ulong) gep (Ty*)null, 1
Alkis Evlogimenosda5de052004-10-24 01:41:10 +00001433 return getCast(
Chris Lattneracc4e542004-12-13 19:48:51 +00001434 getGetElementPtr(getNullValue(PointerType::get(Ty)),
1435 std::vector<Constant*>(1, ConstantInt::get(Type::UIntTy, 1))),
1436 Type::ULongTy);
Alkis Evlogimenosda5de052004-10-24 01:41:10 +00001437}
1438
Alkis Evlogimenos9160d5f2005-03-19 11:40:31 +00001439Constant *ConstantExpr::getPtrPtrFromArrayPtr(Constant *C) {
1440 // pointer from array is implemented as: getelementptr arr ptr, 0, 0
Reid Spencere0fc4df2006-10-20 07:07:24 +00001441 static std::vector<Constant*> Indices(2, ConstantInt::get(Type::UIntTy, 0));
Alkis Evlogimenos9160d5f2005-03-19 11:40:31 +00001442
1443 return ConstantExpr::getGetElementPtr(C, Indices);
1444}
1445
Chris Lattnerb50d1352003-10-05 00:17:43 +00001446Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
1447 Constant *C1, Constant *C2) {
Chris Lattner5645e8a2004-01-12 19:04:55 +00001448 if (Opcode == Instruction::Shl || Opcode == Instruction::Shr)
1449 return getShiftTy(ReqTy, Opcode, C1, C2);
Chris Lattner38a9bcd2003-05-21 17:49:25 +00001450 // Check the operands for consistency first
1451 assert((Opcode >= Instruction::BinaryOpsBegin &&
1452 Opcode < Instruction::BinaryOpsEnd) &&
1453 "Invalid opcode in binary constant expression");
1454 assert(C1->getType() == C2->getType() &&
1455 "Operand types in binary constant expression should match");
Chris Lattnerb50d1352003-10-05 00:17:43 +00001456
Chris Lattnere1496fb2006-09-17 19:14:47 +00001457 if (ReqTy == C1->getType() || (Instruction::isComparison(Opcode) &&
Chris Lattner29ca2c62004-08-04 18:50:09 +00001458 ReqTy == Type::BoolTy))
Chris Lattnerb50d1352003-10-05 00:17:43 +00001459 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1460 return FC; // Fold a few common cases...
Chris Lattneracdbe712003-04-17 19:24:48 +00001461
Chris Lattner2b383d2e2003-05-13 21:37:02 +00001462 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
Chris Lattner98fa07b2003-05-23 20:03:32 +00001463 ExprMapKeyType Key = std::make_pair(Opcode, argVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001464 return ExprConstants->getOrCreate(ReqTy, Key);
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001465}
1466
Chris Lattner29ca2c62004-08-04 18:50:09 +00001467Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001468#ifndef NDEBUG
1469 switch (Opcode) {
1470 case Instruction::Add: case Instruction::Sub:
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001471 case Instruction::Mul:
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001472 case Instruction::Rem:
1473 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Chris Lattnerc421a262006-01-04 01:01:04 +00001474 assert((C1->getType()->isInteger() || C1->getType()->isFloatingPoint() ||
1475 isa<PackedType>(C1->getType())) &&
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001476 "Tried to create an arithmetic operation on a non-arithmetic type!");
1477 break;
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001478
1479 case Instruction::UDiv:
1480 case Instruction::SDiv:
1481 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1482 assert((C1->getType()->isInteger() || (isa<PackedType>(C1->getType()) &&
1483 cast<PackedType>(C1->getType())->getElementType()->isInteger())) &&
1484 "Tried to create an arithmetic operation on a non-arithmetic type!");
1485 break;
1486 case Instruction::FDiv:
1487 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1488 assert((C1->getType()->isFloatingPoint() || (isa<PackedType>(C1->getType())
1489 && cast<PackedType>(C1->getType())->getElementType()->isFloatingPoint()))
1490 && "Tried to create an arithmetic operation on a non-arithmetic type!");
1491 break;
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001492 case Instruction::And:
1493 case Instruction::Or:
1494 case Instruction::Xor:
1495 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Chris Lattnerc421a262006-01-04 01:01:04 +00001496 assert((C1->getType()->isIntegral() || isa<PackedType>(C1->getType())) &&
Misha Brukman3852f652005-01-27 06:46:38 +00001497 "Tried to create a logical operation on a non-integral type!");
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001498 break;
1499 case Instruction::SetLT: case Instruction::SetGT: case Instruction::SetLE:
1500 case Instruction::SetGE: case Instruction::SetEQ: case Instruction::SetNE:
1501 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1502 break;
1503 case Instruction::Shl:
1504 case Instruction::Shr:
1505 assert(C2->getType() == Type::UByteTy && "Shift should be by ubyte!");
Chris Lattnerc421a262006-01-04 01:01:04 +00001506 assert((C1->getType()->isInteger() || isa<PackedType>(C1->getType())) &&
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001507 "Tried to create a shift operation on a non-integer type!");
1508 break;
1509 default:
1510 break;
1511 }
1512#endif
1513
Chris Lattnere1496fb2006-09-17 19:14:47 +00001514 if (Instruction::isComparison(Opcode))
Chris Lattner29ca2c62004-08-04 18:50:09 +00001515 return getTy(Type::BoolTy, Opcode, C1, C2);
1516 else
1517 return getTy(C1->getType(), Opcode, C1, C2);
1518}
1519
Chris Lattner6e415c02004-03-12 05:54:04 +00001520Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
1521 Constant *V1, Constant *V2) {
1522 assert(C->getType() == Type::BoolTy && "Select condition must be bool!");
1523 assert(V1->getType() == V2->getType() && "Select value types must match!");
1524 assert(V1->getType()->isFirstClassType() && "Cannot select aggregate type!");
1525
1526 if (ReqTy == V1->getType())
1527 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1528 return SC; // Fold common cases
1529
1530 std::vector<Constant*> argVec(3, C);
1531 argVec[1] = V1;
1532 argVec[2] = V2;
1533 ExprMapKeyType Key = std::make_pair(Instruction::Select, argVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001534 return ExprConstants->getOrCreate(ReqTy, Key);
Chris Lattner6e415c02004-03-12 05:54:04 +00001535}
1536
Chris Lattner9eb2b522004-01-12 19:12:58 +00001537/// getShiftTy - Return a shift left or shift right constant expr
Chris Lattnerb50d1352003-10-05 00:17:43 +00001538Constant *ConstantExpr::getShiftTy(const Type *ReqTy, unsigned Opcode,
1539 Constant *C1, Constant *C2) {
Chris Lattner38a9bcd2003-05-21 17:49:25 +00001540 // Check the operands for consistency first
1541 assert((Opcode == Instruction::Shl ||
1542 Opcode == Instruction::Shr) &&
1543 "Invalid opcode in binary constant expression");
1544 assert(C1->getType()->isIntegral() && C2->getType() == Type::UByteTy &&
1545 "Invalid operand types for Shift constant expr!");
1546
Chris Lattner0bba7712004-01-12 20:40:42 +00001547 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
Chris Lattner38a9bcd2003-05-21 17:49:25 +00001548 return FC; // Fold a few common cases...
1549
1550 // Look up the constant in the table first to ensure uniqueness
1551 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
Chris Lattner98fa07b2003-05-23 20:03:32 +00001552 ExprMapKeyType Key = std::make_pair(Opcode, argVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001553 return ExprConstants->getOrCreate(ReqTy, Key);
Chris Lattner38a9bcd2003-05-21 17:49:25 +00001554}
1555
1556
Chris Lattnerb50d1352003-10-05 00:17:43 +00001557Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
Chris Lattner13128ab2004-10-11 22:52:25 +00001558 const std::vector<Value*> &IdxList) {
1559 assert(GetElementPtrInst::getIndexedType(C->getType(), IdxList, true) &&
Chris Lattner04b60fe2004-02-16 20:46:13 +00001560 "GEP indices invalid!");
1561
Chris Lattneracdbe712003-04-17 19:24:48 +00001562 if (Constant *FC = ConstantFoldGetElementPtr(C, IdxList))
1563 return FC; // Fold a few common cases...
Chris Lattner04b60fe2004-02-16 20:46:13 +00001564
Chris Lattnerb50d1352003-10-05 00:17:43 +00001565 assert(isa<PointerType>(C->getType()) &&
Chris Lattner98fa07b2003-05-23 20:03:32 +00001566 "Non-pointer type for constant GetElementPtr expression");
Vikram S. Adve4c485332002-07-15 18:19:33 +00001567 // Look up the constant in the table first to ensure uniqueness
Chris Lattner13128ab2004-10-11 22:52:25 +00001568 std::vector<Constant*> ArgVec;
1569 ArgVec.reserve(IdxList.size()+1);
1570 ArgVec.push_back(C);
1571 for (unsigned i = 0, e = IdxList.size(); i != e; ++i)
1572 ArgVec.push_back(cast<Constant>(IdxList[i]));
1573 const ExprMapKeyType &Key = std::make_pair(Instruction::GetElementPtr,ArgVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001574 return ExprConstants->getOrCreate(ReqTy, Key);
Vikram S. Adve4c485332002-07-15 18:19:33 +00001575}
1576
Chris Lattnerb50d1352003-10-05 00:17:43 +00001577Constant *ConstantExpr::getGetElementPtr(Constant *C,
1578 const std::vector<Constant*> &IdxList){
1579 // Get the result type of the getelementptr!
1580 std::vector<Value*> VIdxList(IdxList.begin(), IdxList.end());
1581
1582 const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), VIdxList,
1583 true);
1584 assert(Ty && "GEP indices invalid!");
Chris Lattner13128ab2004-10-11 22:52:25 +00001585 return getGetElementPtrTy(PointerType::get(Ty), C, VIdxList);
1586}
1587
1588Constant *ConstantExpr::getGetElementPtr(Constant *C,
1589 const std::vector<Value*> &IdxList) {
1590 // Get the result type of the getelementptr!
1591 const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), IdxList,
1592 true);
1593 assert(Ty && "GEP indices invalid!");
Chris Lattnerb50d1352003-10-05 00:17:43 +00001594 return getGetElementPtrTy(PointerType::get(Ty), C, IdxList);
1595}
1596
Robert Bocchino23004482006-01-10 19:05:34 +00001597Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
1598 Constant *Idx) {
Robert Bocchinode7f1c92006-01-10 20:03:46 +00001599 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
1600 return FC; // Fold a few common cases...
Robert Bocchino23004482006-01-10 19:05:34 +00001601 // Look up the constant in the table first to ensure uniqueness
1602 std::vector<Constant*> ArgVec(1, Val);
1603 ArgVec.push_back(Idx);
1604 const ExprMapKeyType &Key = std::make_pair(Instruction::ExtractElement,ArgVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001605 return ExprConstants->getOrCreate(ReqTy, Key);
Robert Bocchino23004482006-01-10 19:05:34 +00001606}
1607
1608Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
1609 assert(isa<PackedType>(Val->getType()) &&
1610 "Tried to create extractelement operation on non-packed type!");
1611 assert(Idx->getType() == Type::UIntTy &&
Robert Bocchinoca27f032006-01-17 20:07:22 +00001612 "Extractelement index must be uint type!");
Robert Bocchino23004482006-01-10 19:05:34 +00001613 return getExtractElementTy(cast<PackedType>(Val->getType())->getElementType(),
1614 Val, Idx);
1615}
Chris Lattnerb50d1352003-10-05 00:17:43 +00001616
Robert Bocchinoca27f032006-01-17 20:07:22 +00001617Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
1618 Constant *Elt, Constant *Idx) {
1619 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
1620 return FC; // Fold a few common cases...
1621 // Look up the constant in the table first to ensure uniqueness
1622 std::vector<Constant*> ArgVec(1, Val);
1623 ArgVec.push_back(Elt);
1624 ArgVec.push_back(Idx);
1625 const ExprMapKeyType &Key = std::make_pair(Instruction::InsertElement,ArgVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001626 return ExprConstants->getOrCreate(ReqTy, Key);
Robert Bocchinoca27f032006-01-17 20:07:22 +00001627}
1628
1629Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
1630 Constant *Idx) {
1631 assert(isa<PackedType>(Val->getType()) &&
1632 "Tried to create insertelement operation on non-packed type!");
1633 assert(Elt->getType() == cast<PackedType>(Val->getType())->getElementType()
1634 && "Insertelement types must match!");
1635 assert(Idx->getType() == Type::UIntTy &&
1636 "Insertelement index must be uint type!");
1637 return getInsertElementTy(cast<PackedType>(Val->getType())->getElementType(),
1638 Val, Elt, Idx);
1639}
1640
Chris Lattnerbbe0a422006-04-08 01:18:18 +00001641Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
1642 Constant *V2, Constant *Mask) {
1643 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
1644 return FC; // Fold a few common cases...
1645 // Look up the constant in the table first to ensure uniqueness
1646 std::vector<Constant*> ArgVec(1, V1);
1647 ArgVec.push_back(V2);
1648 ArgVec.push_back(Mask);
1649 const ExprMapKeyType &Key = std::make_pair(Instruction::ShuffleVector,ArgVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001650 return ExprConstants->getOrCreate(ReqTy, Key);
Chris Lattnerbbe0a422006-04-08 01:18:18 +00001651}
1652
1653Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
1654 Constant *Mask) {
1655 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
1656 "Invalid shuffle vector constant expr operands!");
1657 return getShuffleVectorTy(V1->getType(), V1, V2, Mask);
1658}
1659
1660
Vikram S. Adve4c485332002-07-15 18:19:33 +00001661// destroyConstant - Remove the constant from the constant table...
1662//
1663void ConstantExpr::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00001664 ExprConstants->remove(this);
Vikram S. Adve4c485332002-07-15 18:19:33 +00001665 destroyConstantImpl();
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001666}
1667
Chris Lattner3cd8c562002-07-30 18:54:25 +00001668const char *ConstantExpr::getOpcodeName() const {
1669 return Instruction::getOpcodeName(getOpcode());
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001670}
Reid Spencer1ebe1ab2004-07-17 23:48:33 +00001671
Chris Lattnerc4062ba2005-10-03 21:58:36 +00001672//===----------------------------------------------------------------------===//
1673// replaceUsesOfWithOnConstant implementations
1674
1675void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
Chris Lattner7a1450d2005-10-04 18:13:04 +00001676 Use *U) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00001677 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
Chris Lattner8760ec72005-10-04 01:17:50 +00001678 Constant *ToC = cast<Constant>(To);
Chris Lattnerdff59112005-10-04 18:47:09 +00001679
1680 unsigned OperandToUpdate = U-OperandList;
1681 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
1682
Jim Laskeyc03caef2006-07-17 17:38:29 +00001683 std::pair<ArrayConstantsTy::MapKey, Constant*> Lookup;
Chris Lattnerb64419a2005-10-03 22:51:37 +00001684 Lookup.first.first = getType();
1685 Lookup.second = this;
Chris Lattnerdff59112005-10-04 18:47:09 +00001686
Chris Lattnerb64419a2005-10-03 22:51:37 +00001687 std::vector<Constant*> &Values = Lookup.first.second;
1688 Values.reserve(getNumOperands()); // Build replacement array.
Chris Lattnerdff59112005-10-04 18:47:09 +00001689
Chris Lattner8760ec72005-10-04 01:17:50 +00001690 // Fill values with the modified operands of the constant array. Also,
1691 // compute whether this turns into an all-zeros array.
Chris Lattnerdff59112005-10-04 18:47:09 +00001692 bool isAllZeros = false;
1693 if (!ToC->isNullValue()) {
1694 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
1695 Values.push_back(cast<Constant>(O->get()));
1696 } else {
1697 isAllZeros = true;
1698 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1699 Constant *Val = cast<Constant>(O->get());
1700 Values.push_back(Val);
1701 if (isAllZeros) isAllZeros = Val->isNullValue();
1702 }
Chris Lattnerc4062ba2005-10-03 21:58:36 +00001703 }
Chris Lattnerdff59112005-10-04 18:47:09 +00001704 Values[OperandToUpdate] = ToC;
Chris Lattnerc4062ba2005-10-03 21:58:36 +00001705
Chris Lattnerb64419a2005-10-03 22:51:37 +00001706 Constant *Replacement = 0;
1707 if (isAllZeros) {
1708 Replacement = ConstantAggregateZero::get(getType());
1709 } else {
1710 // Check to see if we have this array type already.
1711 bool Exists;
Jim Laskeyc03caef2006-07-17 17:38:29 +00001712 ArrayConstantsTy::MapTy::iterator I =
Chris Lattner69edc982006-09-28 00:35:06 +00001713 ArrayConstants->InsertOrGetItem(Lookup, Exists);
Chris Lattnerb64419a2005-10-03 22:51:37 +00001714
1715 if (Exists) {
1716 Replacement = I->second;
1717 } else {
1718 // Okay, the new shape doesn't exist in the system yet. Instead of
1719 // creating a new constant array, inserting it, replaceallusesof'ing the
1720 // old with the new, then deleting the old... just update the current one
1721 // in place!
Chris Lattner69edc982006-09-28 00:35:06 +00001722 ArrayConstants->MoveConstantToNewSlot(this, I);
Chris Lattnerb64419a2005-10-03 22:51:37 +00001723
Chris Lattnerdff59112005-10-04 18:47:09 +00001724 // Update to the new value.
1725 setOperand(OperandToUpdate, ToC);
Chris Lattnerb64419a2005-10-03 22:51:37 +00001726 return;
1727 }
1728 }
1729
1730 // Otherwise, I do need to replace this with an existing value.
Chris Lattnerc4062ba2005-10-03 21:58:36 +00001731 assert(Replacement != this && "I didn't contain From!");
1732
Chris Lattner7a1450d2005-10-04 18:13:04 +00001733 // Everyone using this now uses the replacement.
1734 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00001735
1736 // Delete the old constant!
1737 destroyConstant();
1738}
1739
1740void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
Chris Lattner7a1450d2005-10-04 18:13:04 +00001741 Use *U) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00001742 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
Chris Lattner8760ec72005-10-04 01:17:50 +00001743 Constant *ToC = cast<Constant>(To);
1744
Chris Lattnerdff59112005-10-04 18:47:09 +00001745 unsigned OperandToUpdate = U-OperandList;
1746 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
1747
Jim Laskeyc03caef2006-07-17 17:38:29 +00001748 std::pair<StructConstantsTy::MapKey, Constant*> Lookup;
Chris Lattner8760ec72005-10-04 01:17:50 +00001749 Lookup.first.first = getType();
1750 Lookup.second = this;
1751 std::vector<Constant*> &Values = Lookup.first.second;
1752 Values.reserve(getNumOperands()); // Build replacement struct.
Chris Lattnerc4062ba2005-10-03 21:58:36 +00001753
Chris Lattnerdff59112005-10-04 18:47:09 +00001754
Chris Lattner8760ec72005-10-04 01:17:50 +00001755 // Fill values with the modified operands of the constant struct. Also,
1756 // compute whether this turns into an all-zeros struct.
Chris Lattnerdff59112005-10-04 18:47:09 +00001757 bool isAllZeros = false;
1758 if (!ToC->isNullValue()) {
1759 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
1760 Values.push_back(cast<Constant>(O->get()));
1761 } else {
1762 isAllZeros = true;
1763 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1764 Constant *Val = cast<Constant>(O->get());
1765 Values.push_back(Val);
1766 if (isAllZeros) isAllZeros = Val->isNullValue();
1767 }
Chris Lattner8760ec72005-10-04 01:17:50 +00001768 }
Chris Lattnerdff59112005-10-04 18:47:09 +00001769 Values[OperandToUpdate] = ToC;
1770
Chris Lattner8760ec72005-10-04 01:17:50 +00001771 Constant *Replacement = 0;
1772 if (isAllZeros) {
1773 Replacement = ConstantAggregateZero::get(getType());
1774 } else {
1775 // Check to see if we have this array type already.
1776 bool Exists;
Jim Laskeyc03caef2006-07-17 17:38:29 +00001777 StructConstantsTy::MapTy::iterator I =
Chris Lattner69edc982006-09-28 00:35:06 +00001778 StructConstants->InsertOrGetItem(Lookup, Exists);
Chris Lattner8760ec72005-10-04 01:17:50 +00001779
1780 if (Exists) {
1781 Replacement = I->second;
1782 } else {
1783 // Okay, the new shape doesn't exist in the system yet. Instead of
1784 // creating a new constant struct, inserting it, replaceallusesof'ing the
1785 // old with the new, then deleting the old... just update the current one
1786 // in place!
Chris Lattner69edc982006-09-28 00:35:06 +00001787 StructConstants->MoveConstantToNewSlot(this, I);
Chris Lattner8760ec72005-10-04 01:17:50 +00001788
Chris Lattnerdff59112005-10-04 18:47:09 +00001789 // Update to the new value.
1790 setOperand(OperandToUpdate, ToC);
Chris Lattner8760ec72005-10-04 01:17:50 +00001791 return;
1792 }
Chris Lattnerc4062ba2005-10-03 21:58:36 +00001793 }
1794
Chris Lattnerc4062ba2005-10-03 21:58:36 +00001795 assert(Replacement != this && "I didn't contain From!");
1796
Chris Lattner7a1450d2005-10-04 18:13:04 +00001797 // Everyone using this now uses the replacement.
1798 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00001799
1800 // Delete the old constant!
1801 destroyConstant();
1802}
1803
1804void ConstantPacked::replaceUsesOfWithOnConstant(Value *From, Value *To,
Chris Lattner7a1450d2005-10-04 18:13:04 +00001805 Use *U) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00001806 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1807
1808 std::vector<Constant*> Values;
1809 Values.reserve(getNumOperands()); // Build replacement array...
1810 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1811 Constant *Val = getOperand(i);
1812 if (Val == From) Val = cast<Constant>(To);
1813 Values.push_back(Val);
1814 }
1815
1816 Constant *Replacement = ConstantPacked::get(getType(), Values);
1817 assert(Replacement != this && "I didn't contain From!");
1818
Chris Lattner7a1450d2005-10-04 18:13:04 +00001819 // Everyone using this now uses the replacement.
1820 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00001821
1822 // Delete the old constant!
1823 destroyConstant();
1824}
1825
1826void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
Chris Lattner7a1450d2005-10-04 18:13:04 +00001827 Use *U) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00001828 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
1829 Constant *To = cast<Constant>(ToV);
1830
1831 Constant *Replacement = 0;
1832 if (getOpcode() == Instruction::GetElementPtr) {
1833 std::vector<Constant*> Indices;
1834 Constant *Pointer = getOperand(0);
1835 Indices.reserve(getNumOperands()-1);
1836 if (Pointer == From) Pointer = To;
1837
1838 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1839 Constant *Val = getOperand(i);
1840 if (Val == From) Val = To;
1841 Indices.push_back(Val);
1842 }
1843 Replacement = ConstantExpr::getGetElementPtr(Pointer, Indices);
1844 } else if (getOpcode() == Instruction::Cast) {
1845 assert(getOperand(0) == From && "Cast only has one use!");
1846 Replacement = ConstantExpr::getCast(To, getType());
1847 } else if (getOpcode() == Instruction::Select) {
1848 Constant *C1 = getOperand(0);
1849 Constant *C2 = getOperand(1);
1850 Constant *C3 = getOperand(2);
1851 if (C1 == From) C1 = To;
1852 if (C2 == From) C2 = To;
1853 if (C3 == From) C3 = To;
1854 Replacement = ConstantExpr::getSelect(C1, C2, C3);
Robert Bocchino23004482006-01-10 19:05:34 +00001855 } else if (getOpcode() == Instruction::ExtractElement) {
1856 Constant *C1 = getOperand(0);
1857 Constant *C2 = getOperand(1);
1858 if (C1 == From) C1 = To;
1859 if (C2 == From) C2 = To;
1860 Replacement = ConstantExpr::getExtractElement(C1, C2);
Chris Lattnera93b4b52006-04-08 05:09:48 +00001861 } else if (getOpcode() == Instruction::InsertElement) {
1862 Constant *C1 = getOperand(0);
1863 Constant *C2 = getOperand(1);
1864 Constant *C3 = getOperand(1);
1865 if (C1 == From) C1 = To;
1866 if (C2 == From) C2 = To;
1867 if (C3 == From) C3 = To;
1868 Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
1869 } else if (getOpcode() == Instruction::ShuffleVector) {
1870 Constant *C1 = getOperand(0);
1871 Constant *C2 = getOperand(1);
1872 Constant *C3 = getOperand(2);
1873 if (C1 == From) C1 = To;
1874 if (C2 == From) C2 = To;
1875 if (C3 == From) C3 = To;
1876 Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00001877 } else if (getNumOperands() == 2) {
1878 Constant *C1 = getOperand(0);
1879 Constant *C2 = getOperand(1);
1880 if (C1 == From) C1 = To;
1881 if (C2 == From) C2 = To;
1882 Replacement = ConstantExpr::get(getOpcode(), C1, C2);
1883 } else {
1884 assert(0 && "Unknown ConstantExpr type!");
1885 return;
1886 }
1887
1888 assert(Replacement != this && "I didn't contain From!");
1889
Chris Lattner7a1450d2005-10-04 18:13:04 +00001890 // Everyone using this now uses the replacement.
1891 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00001892
1893 // Delete the old constant!
1894 destroyConstant();
1895}
1896
1897
Jim Laskey2698f0d2006-03-08 18:11:07 +00001898/// getStringValue - Turn an LLVM constant pointer that eventually points to a
1899/// global into a string value. Return an empty string if we can't do it.
Evan Cheng38280c02006-03-10 23:52:03 +00001900/// Parameter Chop determines if the result is chopped at the first null
1901/// terminator.
Jim Laskey2698f0d2006-03-08 18:11:07 +00001902///
Evan Cheng38280c02006-03-10 23:52:03 +00001903std::string Constant::getStringValue(bool Chop, unsigned Offset) {
Jim Laskey2698f0d2006-03-08 18:11:07 +00001904 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(this)) {
1905 if (GV->hasInitializer() && isa<ConstantArray>(GV->getInitializer())) {
1906 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
1907 if (Init->isString()) {
1908 std::string Result = Init->getAsString();
1909 if (Offset < Result.size()) {
1910 // If we are pointing INTO The string, erase the beginning...
1911 Result.erase(Result.begin(), Result.begin()+Offset);
1912
1913 // Take off the null terminator, and any string fragments after it.
Evan Cheng38280c02006-03-10 23:52:03 +00001914 if (Chop) {
1915 std::string::size_type NullPos = Result.find_first_of((char)0);
1916 if (NullPos != std::string::npos)
1917 Result.erase(Result.begin()+NullPos, Result.end());
1918 }
Jim Laskey2698f0d2006-03-08 18:11:07 +00001919 return Result;
1920 }
1921 }
1922 }
1923 } else if (Constant *C = dyn_cast<Constant>(this)) {
1924 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
Evan Cheng2c5e5302006-03-11 00:13:10 +00001925 return GV->getStringValue(Chop, Offset);
Jim Laskey2698f0d2006-03-08 18:11:07 +00001926 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1927 if (CE->getOpcode() == Instruction::GetElementPtr) {
1928 // Turn a gep into the specified offset.
1929 if (CE->getNumOperands() == 3 &&
1930 cast<Constant>(CE->getOperand(1))->isNullValue() &&
1931 isa<ConstantInt>(CE->getOperand(2))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00001932 Offset += cast<ConstantInt>(CE->getOperand(2))->getZExtValue();
Evan Cheng2c5e5302006-03-11 00:13:10 +00001933 return CE->getOperand(0)->getStringValue(Chop, Offset);
Jim Laskey2698f0d2006-03-08 18:11:07 +00001934 }
1935 }
1936 }
1937 }
1938 return "";
1939}
1940