blob: 2afaa6c7b3794a47b9306987b2bd057813d007f4 [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//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner2f7c9632001-06-06 20:29:01 +00009//
Chris Lattner3462ae32001-12-03 22:26:30 +000010// This file implements the Constant* classes...
Chris Lattner2f7c9632001-06-06 20:29:01 +000011//
12//===----------------------------------------------------------------------===//
13
Chris Lattnerca142372002-04-28 19:55:58 +000014#include "llvm/Constants.h"
Chris Lattner33e93b82007-02-27 03:05:06 +000015#include "ConstantFold.h"
Chris Lattner2f7c9632001-06-06 20:29:01 +000016#include "llvm/DerivedTypes.h"
Reid Spencer1ebe1ab2004-07-17 23:48:33 +000017#include "llvm/GlobalValue.h"
Misha Brukman63b38bd2004-07-29 17:30:56 +000018#include "llvm/Instructions.h"
Chris Lattnerd7a73302001-10-13 06:57:33 +000019#include "llvm/Module.h"
Nick Lewycky49f89192009-04-04 07:22:01 +000020#include "llvm/ADT/FoldingSet.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000021#include "llvm/ADT/StringExtras.h"
Nick Lewycky49f89192009-04-04 07:22:01 +000022#include "llvm/ADT/StringMap.h"
Chris Lattner3d27be12006-08-27 12:54:02 +000023#include "llvm/Support/Compiler.h"
Bill Wendling6a462f12006-11-17 08:03:48 +000024#include "llvm/Support/Debug.h"
Chris Lattner69edc982006-09-28 00:35:06 +000025#include "llvm/Support/ManagedStatic.h"
Bill Wendling6a462f12006-11-17 08:03:48 +000026#include "llvm/Support/MathExtras.h"
Chris Lattnera80bf0b2007-02-20 06:39:57 +000027#include "llvm/ADT/DenseMap.h"
Chris Lattnerb5d70302007-02-19 20:01:23 +000028#include "llvm/ADT/SmallVector.h"
Chris Lattner2f7c9632001-06-06 20:29:01 +000029#include <algorithm>
Reid Spencer3aaaa0b2007-02-05 20:47:22 +000030#include <map>
Chris Lattner189d19f2003-11-21 20:23:48 +000031using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000032
Chris Lattner2f7c9632001-06-06 20:29:01 +000033//===----------------------------------------------------------------------===//
Chris Lattner3462ae32001-12-03 22:26:30 +000034// Constant Class
Chris Lattner2f7c9632001-06-06 20:29:01 +000035//===----------------------------------------------------------------------===//
36
Chris Lattner3462ae32001-12-03 22:26:30 +000037void Constant::destroyConstantImpl() {
38 // When a Constant is destroyed, there may be lingering
Chris Lattnerd7a73302001-10-13 06:57:33 +000039 // references to the constant by other constants in the constant pool. These
Misha Brukmanbe372b92003-08-21 22:14:26 +000040 // constants are implicitly dependent on the module that is being deleted,
Chris Lattnerd7a73302001-10-13 06:57:33 +000041 // but they don't know that. Because we only find out when the CPV is
42 // deleted, we must now notify all of our users (that should only be
Chris Lattner3462ae32001-12-03 22:26:30 +000043 // Constants) that they are, in fact, invalid now and should be deleted.
Chris Lattnerd7a73302001-10-13 06:57:33 +000044 //
45 while (!use_empty()) {
46 Value *V = use_back();
47#ifndef NDEBUG // Only in -g mode...
Chris Lattnerd9f4ac662002-07-18 00:14:50 +000048 if (!isa<Constant>(V))
Bill Wendling6a462f12006-11-17 08:03:48 +000049 DOUT << "While deleting: " << *this
50 << "\n\nUse still stuck around after Def is destroyed: "
51 << *V << "\n\n";
Chris Lattnerd7a73302001-10-13 06:57:33 +000052#endif
Vikram S. Adve4e537b22002-07-14 23:13:17 +000053 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
Reid Spencer1ebe1ab2004-07-17 23:48:33 +000054 Constant *CV = cast<Constant>(V);
55 CV->destroyConstant();
Chris Lattnerd7a73302001-10-13 06:57:33 +000056
57 // The constant should remove itself from our use list...
Vikram S. Adve4e537b22002-07-14 23:13:17 +000058 assert((use_empty() || use_back() != V) && "Constant not removed!");
Chris Lattnerd7a73302001-10-13 06:57:33 +000059 }
60
61 // Value has no outstanding references it is safe to delete it now...
62 delete this;
Chris Lattner38569342001-10-01 20:11:19 +000063}
Chris Lattner2f7c9632001-06-06 20:29:01 +000064
Chris Lattner23dd1f62006-10-20 00:27:06 +000065/// canTrap - Return true if evaluation of this constant could trap. This is
66/// true for things like constant expressions that could divide by zero.
67bool Constant::canTrap() const {
68 assert(getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
69 // The only thing that could possibly trap are constant exprs.
70 const ConstantExpr *CE = dyn_cast<ConstantExpr>(this);
71 if (!CE) return false;
72
73 // ConstantExpr traps if any operands can trap.
74 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
75 if (getOperand(i)->canTrap())
76 return true;
77
78 // Otherwise, only specific operations can trap.
79 switch (CE->getOpcode()) {
80 default:
81 return false;
Reid Spencer7e80b0b2006-10-26 06:15:43 +000082 case Instruction::UDiv:
83 case Instruction::SDiv:
84 case Instruction::FDiv:
Reid Spencer7eb55b32006-11-02 01:53:59 +000085 case Instruction::URem:
86 case Instruction::SRem:
87 case Instruction::FRem:
Chris Lattner23dd1f62006-10-20 00:27:06 +000088 // Div and rem can trap if the RHS is not known to be non-zero.
89 if (!isa<ConstantInt>(getOperand(1)) || getOperand(1)->isNullValue())
90 return true;
91 return false;
92 }
93}
94
Anton Korobeynikov7437b592009-03-29 17:13:18 +000095/// ContainsRelocations - Return true if the constant value contains relocations
96/// which cannot be resolved at compile time. Kind argument is used to filter
97/// only 'interesting' sorts of relocations.
98bool Constant::ContainsRelocations(unsigned Kind) const {
99 if (const GlobalValue* GV = dyn_cast<GlobalValue>(this)) {
100 bool isLocal = GV->hasLocalLinkage();
101 if ((Kind & Reloc::Local) && isLocal) {
102 // Global has local linkage and 'local' kind of relocations are
103 // requested
104 return true;
105 }
106
107 if ((Kind & Reloc::Global) && !isLocal) {
108 // Global has non-local linkage and 'global' kind of relocations are
109 // requested
110 return true;
111 }
Anton Korobeynikov255a3cb2009-03-30 15:28:21 +0000112
113 return false;
Anton Korobeynikov7437b592009-03-29 17:13:18 +0000114 }
115
Evan Chengf9e003b2007-03-08 00:59:12 +0000116 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
Anton Korobeynikovd5e8e932009-03-30 15:28:00 +0000117 if (getOperand(i)->ContainsRelocations(Kind))
Evan Chengf9e003b2007-03-08 00:59:12 +0000118 return true;
Anton Korobeynikov7437b592009-03-29 17:13:18 +0000119
Evan Chengf9e003b2007-03-08 00:59:12 +0000120 return false;
121}
122
Chris Lattnerb1585a92002-08-13 17:50:20 +0000123// Static constructor to create a '0' constant of arbitrary type...
124Constant *Constant::getNullValue(const Type *Ty) {
Dale Johannesen98d3a082007-09-14 22:26:36 +0000125 static uint64_t zero[2] = {0, 0};
Chris Lattner6b727592004-06-17 18:19:28 +0000126 switch (Ty->getTypeID()) {
Chris Lattnerdbcb0d32007-02-20 05:46:39 +0000127 case Type::IntegerTyID:
128 return ConstantInt::get(Ty, 0);
129 case Type::FloatTyID:
Chris Lattnerb5b3e312008-04-09 00:45:01 +0000130 return ConstantFP::get(APFloat(APInt(32, 0)));
Chris Lattnerdbcb0d32007-02-20 05:46:39 +0000131 case Type::DoubleTyID:
Chris Lattnerb5b3e312008-04-09 00:45:01 +0000132 return ConstantFP::get(APFloat(APInt(64, 0)));
Dale Johannesenbdad8092007-08-09 22:51:36 +0000133 case Type::X86_FP80TyID:
Chris Lattnerb5b3e312008-04-09 00:45:01 +0000134 return ConstantFP::get(APFloat(APInt(80, 2, zero)));
Dale Johannesenbdad8092007-08-09 22:51:36 +0000135 case Type::FP128TyID:
Chris Lattnerb5b3e312008-04-09 00:45:01 +0000136 return ConstantFP::get(APFloat(APInt(128, 2, zero), true));
Dale Johannesen98d3a082007-09-14 22:26:36 +0000137 case Type::PPC_FP128TyID:
Chris Lattnerb5b3e312008-04-09 00:45:01 +0000138 return ConstantFP::get(APFloat(APInt(128, 2, zero)));
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 Lattner9fba3da2004-02-15 05:53:04 +0000141 case Type::StructTyID:
142 case Type::ArrayTyID:
Reid Spencerd84d35b2007-02-15 02:26:10 +0000143 case Type::VectorTyID:
Chris Lattner9fba3da2004-02-15 05:53:04 +0000144 return ConstantAggregateZero::get(Ty);
Chris Lattnerb1585a92002-08-13 17:50:20 +0000145 default:
Reid Spencercf394bf2004-07-04 11:51:24 +0000146 // Function, Label, or Opaque type?
147 assert(!"Cannot create a null constant of that type!");
Chris Lattnerb1585a92002-08-13 17:50:20 +0000148 return 0;
149 }
150}
151
Chris Lattner72e39582007-06-15 06:10:53 +0000152Constant *Constant::getAllOnesValue(const Type *Ty) {
153 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty))
154 return ConstantInt::get(APInt::getAllOnesValue(ITy->getBitWidth()));
155 return ConstantVector::getAllOnesValue(cast<VectorType>(Ty));
156}
Chris Lattnerb1585a92002-08-13 17:50:20 +0000157
158// Static constructor to create an integral constant with all bits set
Zhou Sheng75b871f2007-01-11 12:24:14 +0000159ConstantInt *ConstantInt::getAllOnesValue(const Type *Ty) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000160 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty))
Reid Spencerd1bbfa52007-03-01 19:30:34 +0000161 return ConstantInt::get(APInt::getAllOnesValue(ITy->getBitWidth()));
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000162 return 0;
Chris Lattnerb1585a92002-08-13 17:50:20 +0000163}
164
Dan Gohman30978072007-05-24 14:36:04 +0000165/// @returns the value for a vector integer constant of the given type that
Chris Lattnerecab54c2007-01-04 01:49:26 +0000166/// has all its bits set to true.
167/// @brief Get the all ones value
Reid Spencerd84d35b2007-02-15 02:26:10 +0000168ConstantVector *ConstantVector::getAllOnesValue(const VectorType *Ty) {
Chris Lattnerecab54c2007-01-04 01:49:26 +0000169 std::vector<Constant*> Elts;
170 Elts.resize(Ty->getNumElements(),
Zhou Sheng75b871f2007-01-11 12:24:14 +0000171 ConstantInt::getAllOnesValue(Ty->getElementType()));
Dan Gohman30978072007-05-24 14:36:04 +0000172 assert(Elts[0] && "Not a vector integer type!");
Reid Spencerd84d35b2007-02-15 02:26:10 +0000173 return cast<ConstantVector>(ConstantVector::get(Elts));
Chris Lattnerecab54c2007-01-04 01:49:26 +0000174}
175
176
Chris Lattner2105d662008-07-10 00:28:11 +0000177/// getVectorElements - This method, which is only valid on constant of vector
178/// type, returns the elements of the vector in the specified smallvector.
Chris Lattnerc5098a22008-07-14 05:10:41 +0000179/// This handles breaking down a vector undef into undef elements, etc. For
180/// constant exprs and other cases we can't handle, we return an empty vector.
Chris Lattner2105d662008-07-10 00:28:11 +0000181void Constant::getVectorElements(SmallVectorImpl<Constant*> &Elts) const {
182 assert(isa<VectorType>(getType()) && "Not a vector constant!");
183
184 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this)) {
185 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i)
186 Elts.push_back(CV->getOperand(i));
187 return;
188 }
189
190 const VectorType *VT = cast<VectorType>(getType());
191 if (isa<ConstantAggregateZero>(this)) {
192 Elts.assign(VT->getNumElements(),
193 Constant::getNullValue(VT->getElementType()));
194 return;
195 }
196
Chris Lattnerc5098a22008-07-14 05:10:41 +0000197 if (isa<UndefValue>(this)) {
198 Elts.assign(VT->getNumElements(), UndefValue::get(VT->getElementType()));
199 return;
200 }
201
202 // Unknown type, must be constant expr etc.
Chris Lattner2105d662008-07-10 00:28:11 +0000203}
204
205
206
Chris Lattner2f7c9632001-06-06 20:29:01 +0000207//===----------------------------------------------------------------------===//
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000208// ConstantInt
Chris Lattner2f7c9632001-06-06 20:29:01 +0000209//===----------------------------------------------------------------------===//
210
Reid Spencerb31bffe2007-02-26 23:54:03 +0000211ConstantInt::ConstantInt(const IntegerType *Ty, const APInt& V)
Chris Lattner5db2f472007-02-20 05:55:46 +0000212 : Constant(Ty, ConstantIntVal, 0, 0), Val(V) {
Reid Spencerb31bffe2007-02-26 23:54:03 +0000213 assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
Chris Lattner2f7c9632001-06-06 20:29:01 +0000214}
215
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000216ConstantInt *ConstantInt::TheTrueVal = 0;
217ConstantInt *ConstantInt::TheFalseVal = 0;
218
219namespace llvm {
220 void CleanupTrueFalse(void *) {
221 ConstantInt::ResetTrueFalse();
222 }
223}
224
225static ManagedCleanup<llvm::CleanupTrueFalse> TrueFalseCleanup;
226
227ConstantInt *ConstantInt::CreateTrueFalseVals(bool WhichOne) {
228 assert(TheTrueVal == 0 && TheFalseVal == 0);
229 TheTrueVal = get(Type::Int1Ty, 1);
230 TheFalseVal = get(Type::Int1Ty, 0);
231
232 // Ensure that llvm_shutdown nulls out TheTrueVal/TheFalseVal.
233 TrueFalseCleanup.Register();
234
235 return WhichOne ? TheTrueVal : TheFalseVal;
236}
237
238
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000239namespace {
Reid Spencerb31bffe2007-02-26 23:54:03 +0000240 struct DenseMapAPIntKeyInfo {
241 struct KeyTy {
242 APInt val;
243 const Type* type;
244 KeyTy(const APInt& V, const Type* Ty) : val(V), type(Ty) {}
245 KeyTy(const KeyTy& that) : val(that.val), type(that.type) {}
246 bool operator==(const KeyTy& that) const {
247 return type == that.type && this->val == that.val;
248 }
249 bool operator!=(const KeyTy& that) const {
250 return !this->operator==(that);
251 }
252 };
253 static inline KeyTy getEmptyKey() { return KeyTy(APInt(1,0), 0); }
254 static inline KeyTy getTombstoneKey() { return KeyTy(APInt(1,1), 0); }
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000255 static unsigned getHashValue(const KeyTy &Key) {
Chris Lattner0625bd62007-09-17 18:34:04 +0000256 return DenseMapInfo<void*>::getHashValue(Key.type) ^
Reid Spencerb31bffe2007-02-26 23:54:03 +0000257 Key.val.getHashValue();
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000258 }
Chris Lattner0625bd62007-09-17 18:34:04 +0000259 static bool isEqual(const KeyTy &LHS, const KeyTy &RHS) {
260 return LHS == RHS;
261 }
Dale Johannesena719a602007-08-24 00:56:33 +0000262 static bool isPod() { return false; }
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000263 };
264}
265
266
Reid Spencerb31bffe2007-02-26 23:54:03 +0000267typedef DenseMap<DenseMapAPIntKeyInfo::KeyTy, ConstantInt*,
268 DenseMapAPIntKeyInfo> IntMapTy;
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000269static ManagedStatic<IntMapTy> IntConstants;
270
Reid Spencer362fb292007-03-19 20:39:08 +0000271ConstantInt *ConstantInt::get(const Type *Ty, uint64_t V, bool isSigned) {
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000272 const IntegerType *ITy = cast<IntegerType>(Ty);
Reid Spencer362fb292007-03-19 20:39:08 +0000273 return get(APInt(ITy->getBitWidth(), V, isSigned));
Reid Spencerb31bffe2007-02-26 23:54:03 +0000274}
275
Reid Spencerd1bbfa52007-03-01 19:30:34 +0000276// Get a ConstantInt from an APInt. Note that the value stored in the DenseMap
Dan Gohmanb3efe032008-02-07 02:30:40 +0000277// as the key, is a DenseMapAPIntKeyInfo::KeyTy which has provided the
Reid Spencerb31bffe2007-02-26 23:54:03 +0000278// operator== and operator!= to ensure that the DenseMap doesn't attempt to
279// compare APInt's of different widths, which would violate an APInt class
280// invariant which generates an assertion.
Reid Spencerd1bbfa52007-03-01 19:30:34 +0000281ConstantInt *ConstantInt::get(const APInt& V) {
282 // Get the corresponding integer type for the bit width of the value.
283 const IntegerType *ITy = IntegerType::get(V.getBitWidth());
Reid Spencerb31bffe2007-02-26 23:54:03 +0000284 // get an existing value or the insertion position
Reid Spencerd1bbfa52007-03-01 19:30:34 +0000285 DenseMapAPIntKeyInfo::KeyTy Key(V, ITy);
Reid Spencerb31bffe2007-02-26 23:54:03 +0000286 ConstantInt *&Slot = (*IntConstants)[Key];
287 // if it exists, return it.
288 if (Slot)
289 return Slot;
290 // otherwise create a new one, insert it, and return it.
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000291 return Slot = new ConstantInt(ITy, V);
292}
293
294//===----------------------------------------------------------------------===//
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000295// ConstantFP
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000296//===----------------------------------------------------------------------===//
297
Chris Lattner98bd9392008-04-09 06:38:30 +0000298static const fltSemantics *TypeToFloatSemantics(const Type *Ty) {
299 if (Ty == Type::FloatTy)
300 return &APFloat::IEEEsingle;
301 if (Ty == Type::DoubleTy)
302 return &APFloat::IEEEdouble;
303 if (Ty == Type::X86_FP80Ty)
304 return &APFloat::x87DoubleExtended;
305 else if (Ty == Type::FP128Ty)
306 return &APFloat::IEEEquad;
307
308 assert(Ty == Type::PPC_FP128Ty && "Unknown FP format");
309 return &APFloat::PPCDoubleDouble;
310}
311
Dale Johannesend246b2c2007-08-30 00:23:21 +0000312ConstantFP::ConstantFP(const Type *Ty, const APFloat& V)
313 : Constant(Ty, ConstantFPVal, 0, 0), Val(V) {
Chris Lattner98bd9392008-04-09 06:38:30 +0000314 assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
315 "FP type Mismatch");
Chris Lattner2f7c9632001-06-06 20:29:01 +0000316}
317
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000318bool ConstantFP::isNullValue() const {
Dale Johannesena719a602007-08-24 00:56:33 +0000319 return Val.isZero() && !Val.isNegative();
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000320}
321
Dale Johannesen98d3a082007-09-14 22:26:36 +0000322ConstantFP *ConstantFP::getNegativeZero(const Type *Ty) {
323 APFloat apf = cast <ConstantFP>(Constant::getNullValue(Ty))->getValueAPF();
324 apf.changeSign();
Chris Lattnerb5b3e312008-04-09 00:45:01 +0000325 return ConstantFP::get(apf);
Dale Johannesen98d3a082007-09-14 22:26:36 +0000326}
327
Dale Johannesend246b2c2007-08-30 00:23:21 +0000328bool ConstantFP::isExactlyValue(const APFloat& V) const {
329 return Val.bitwiseIsEqual(V);
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000330}
331
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000332namespace {
Dale Johannesena719a602007-08-24 00:56:33 +0000333 struct DenseMapAPFloatKeyInfo {
Dale Johannesenbdea32d2007-08-24 22:09:56 +0000334 struct KeyTy {
335 APFloat val;
336 KeyTy(const APFloat& V) : val(V){}
337 KeyTy(const KeyTy& that) : val(that.val) {}
338 bool operator==(const KeyTy& that) const {
339 return this->val.bitwiseIsEqual(that.val);
340 }
341 bool operator!=(const KeyTy& that) const {
342 return !this->operator==(that);
343 }
344 };
345 static inline KeyTy getEmptyKey() {
346 return KeyTy(APFloat(APFloat::Bogus,1));
Reid Spencerb31bffe2007-02-26 23:54:03 +0000347 }
Dale Johannesenbdea32d2007-08-24 22:09:56 +0000348 static inline KeyTy getTombstoneKey() {
349 return KeyTy(APFloat(APFloat::Bogus,2));
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000350 }
Dale Johannesenbdea32d2007-08-24 22:09:56 +0000351 static unsigned getHashValue(const KeyTy &Key) {
352 return Key.val.getHashValue();
Dale Johannesena719a602007-08-24 00:56:33 +0000353 }
Chris Lattner0625bd62007-09-17 18:34:04 +0000354 static bool isEqual(const KeyTy &LHS, const KeyTy &RHS) {
355 return LHS == RHS;
356 }
Dale Johannesena719a602007-08-24 00:56:33 +0000357 static bool isPod() { return false; }
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000358 };
359}
360
361//---- ConstantFP::get() implementation...
362//
Dale Johannesenbdea32d2007-08-24 22:09:56 +0000363typedef DenseMap<DenseMapAPFloatKeyInfo::KeyTy, ConstantFP*,
Dale Johannesena719a602007-08-24 00:56:33 +0000364 DenseMapAPFloatKeyInfo> FPMapTy;
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000365
Dale Johannesena719a602007-08-24 00:56:33 +0000366static ManagedStatic<FPMapTy> FPConstants;
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000367
Chris Lattnerb5b3e312008-04-09 00:45:01 +0000368ConstantFP *ConstantFP::get(const APFloat &V) {
Dale Johannesend246b2c2007-08-30 00:23:21 +0000369 DenseMapAPFloatKeyInfo::KeyTy Key(V);
370 ConstantFP *&Slot = (*FPConstants)[Key];
371 if (Slot) return Slot;
Chris Lattnerb5b3e312008-04-09 00:45:01 +0000372
373 const Type *Ty;
374 if (&V.getSemantics() == &APFloat::IEEEsingle)
375 Ty = Type::FloatTy;
376 else if (&V.getSemantics() == &APFloat::IEEEdouble)
377 Ty = Type::DoubleTy;
378 else if (&V.getSemantics() == &APFloat::x87DoubleExtended)
379 Ty = Type::X86_FP80Ty;
380 else if (&V.getSemantics() == &APFloat::IEEEquad)
381 Ty = Type::FP128Ty;
382 else {
383 assert(&V.getSemantics() == &APFloat::PPCDoubleDouble&&"Unknown FP format");
384 Ty = Type::PPC_FP128Ty;
385 }
386
Dale Johannesend246b2c2007-08-30 00:23:21 +0000387 return Slot = new ConstantFP(Ty, V);
388}
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000389
Chris Lattner98bd9392008-04-09 06:38:30 +0000390/// get() - This returns a constant fp for the specified value in the
391/// specified type. This should only be used for simple constant values like
392/// 2.0/1.0 etc, that are known-valid both as double and as the target format.
393ConstantFP *ConstantFP::get(const Type *Ty, double V) {
394 APFloat FV(V);
Dale Johannesen4f0bd682008-10-09 23:00:39 +0000395 bool ignored;
396 FV.convert(*TypeToFloatSemantics(Ty), APFloat::rmNearestTiesToEven, &ignored);
Chris Lattner98bd9392008-04-09 06:38:30 +0000397 return get(FV);
398}
399
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000400//===----------------------------------------------------------------------===//
401// ConstantXXX Classes
402//===----------------------------------------------------------------------===//
403
404
Chris Lattner3462ae32001-12-03 22:26:30 +0000405ConstantArray::ConstantArray(const ArrayType *T,
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000406 const std::vector<Constant*> &V)
Gabor Greiff6caff662008-05-10 08:32:32 +0000407 : Constant(T, ConstantArrayVal,
408 OperandTraits<ConstantArray>::op_end(this) - V.size(),
409 V.size()) {
Alkis Evlogimenos0507ffe2004-09-15 02:32:15 +0000410 assert(V.size() == T->getNumElements() &&
411 "Invalid initializer vector for constant array");
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000412 Use *OL = OperandList;
Chris Lattner0144fad2005-10-03 21:56:24 +0000413 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
414 I != E; ++I, ++OL) {
Chris Lattner20a24452005-10-07 05:23:36 +0000415 Constant *C = *I;
416 assert((C->getType() == T->getElementType() ||
Alkis Evlogimenoscb031d92004-09-10 04:16:59 +0000417 (T->isAbstract() &&
Chris Lattner20a24452005-10-07 05:23:36 +0000418 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
Alkis Evlogimenoscb031d92004-09-10 04:16:59 +0000419 "Initializer for array element doesn't match array element type!");
Gabor Greif2d3024d2008-05-26 21:33:52 +0000420 *OL = C;
Chris Lattner2f7c9632001-06-06 20:29:01 +0000421 }
422}
423
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000424
Chris Lattner3462ae32001-12-03 22:26:30 +0000425ConstantStruct::ConstantStruct(const StructType *T,
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000426 const std::vector<Constant*> &V)
Gabor Greiff6caff662008-05-10 08:32:32 +0000427 : Constant(T, ConstantStructVal,
428 OperandTraits<ConstantStruct>::op_end(this) - V.size(),
429 V.size()) {
Chris Lattnerac6db752004-02-09 04:37:31 +0000430 assert(V.size() == T->getNumElements() &&
Vikram S. Adve4e537b22002-07-14 23:13:17 +0000431 "Invalid initializer vector for constant structure");
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000432 Use *OL = OperandList;
Chris Lattner0144fad2005-10-03 21:56:24 +0000433 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
434 I != E; ++I, ++OL) {
Chris Lattner20a24452005-10-07 05:23:36 +0000435 Constant *C = *I;
436 assert((C->getType() == T->getElementType(I-V.begin()) ||
Chris Lattner0144fad2005-10-03 21:56:24 +0000437 ((T->getElementType(I-V.begin())->isAbstract() ||
Chris Lattner20a24452005-10-07 05:23:36 +0000438 C->getType()->isAbstract()) &&
Chris Lattner0144fad2005-10-03 21:56:24 +0000439 T->getElementType(I-V.begin())->getTypeID() ==
Chris Lattner20a24452005-10-07 05:23:36 +0000440 C->getType()->getTypeID())) &&
Chris Lattner93c8f142003-06-02 17:42:47 +0000441 "Initializer for struct element doesn't match struct element type!");
Gabor Greif2d3024d2008-05-26 21:33:52 +0000442 *OL = C;
Chris Lattner2f7c9632001-06-06 20:29:01 +0000443 }
444}
445
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000446
Reid Spencerd84d35b2007-02-15 02:26:10 +0000447ConstantVector::ConstantVector(const VectorType *T,
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000448 const std::vector<Constant*> &V)
Gabor Greiff6caff662008-05-10 08:32:32 +0000449 : Constant(T, ConstantVectorVal,
450 OperandTraits<ConstantVector>::op_end(this) - V.size(),
451 V.size()) {
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000452 Use *OL = OperandList;
Chris Lattner0144fad2005-10-03 21:56:24 +0000453 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
454 I != E; ++I, ++OL) {
Chris Lattner20a24452005-10-07 05:23:36 +0000455 Constant *C = *I;
456 assert((C->getType() == T->getElementType() ||
Alkis Evlogimenoscb031d92004-09-10 04:16:59 +0000457 (T->isAbstract() &&
Chris Lattner20a24452005-10-07 05:23:36 +0000458 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
Dan Gohman30978072007-05-24 14:36:04 +0000459 "Initializer for vector element doesn't match vector element type!");
Gabor Greif2d3024d2008-05-26 21:33:52 +0000460 *OL = C;
Brian Gaeke02209042004-08-20 06:00:58 +0000461 }
462}
463
Vikram S. Adve4e537b22002-07-14 23:13:17 +0000464
Gabor Greiff6caff662008-05-10 08:32:32 +0000465namespace llvm {
Gordon Henriksen14a55692007-12-10 02:14:30 +0000466// We declare several classes private to this file, so use an anonymous
467// namespace
468namespace {
Reid Spencer10fbf0e2006-12-03 05:48:19 +0000469
Gordon Henriksen14a55692007-12-10 02:14:30 +0000470/// UnaryConstantExpr - This class is private to Constants.cpp, and is used
471/// behind the scenes to implement unary constant exprs.
472class VISIBILITY_HIDDEN UnaryConstantExpr : public ConstantExpr {
Gabor Greife9ecc682008-04-06 20:25:17 +0000473 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
Gordon Henriksen14a55692007-12-10 02:14:30 +0000474public:
Gabor Greife9ecc682008-04-06 20:25:17 +0000475 // allocate space for exactly one operand
476 void *operator new(size_t s) {
477 return User::operator new(s, 1);
478 }
Gordon Henriksen14a55692007-12-10 02:14:30 +0000479 UnaryConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
Gabor Greiff6caff662008-05-10 08:32:32 +0000480 : ConstantExpr(Ty, Opcode, &Op<0>(), 1) {
481 Op<0>() = C;
482 }
483 /// Transparently provide more efficient getOperand methods.
484 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Gordon Henriksen14a55692007-12-10 02:14:30 +0000485};
Reid Spencer10fbf0e2006-12-03 05:48:19 +0000486
Gordon Henriksen14a55692007-12-10 02:14:30 +0000487/// BinaryConstantExpr - This class is private to Constants.cpp, and is used
488/// behind the scenes to implement binary constant exprs.
489class VISIBILITY_HIDDEN BinaryConstantExpr : public ConstantExpr {
Gabor Greife9ecc682008-04-06 20:25:17 +0000490 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
Gordon Henriksen14a55692007-12-10 02:14:30 +0000491public:
Gabor Greife9ecc682008-04-06 20:25:17 +0000492 // allocate space for exactly two operands
493 void *operator new(size_t s) {
494 return User::operator new(s, 2);
495 }
Gordon Henriksen14a55692007-12-10 02:14:30 +0000496 BinaryConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
Gabor Greiff6caff662008-05-10 08:32:32 +0000497 : ConstantExpr(C1->getType(), Opcode, &Op<0>(), 2) {
Gabor Greif2d3024d2008-05-26 21:33:52 +0000498 Op<0>() = C1;
499 Op<1>() = C2;
Gordon Henriksen14a55692007-12-10 02:14:30 +0000500 }
Gabor Greiff6caff662008-05-10 08:32:32 +0000501 /// Transparently provide more efficient getOperand methods.
502 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Gordon Henriksen14a55692007-12-10 02:14:30 +0000503};
Vikram S. Adve4e537b22002-07-14 23:13:17 +0000504
Gordon Henriksen14a55692007-12-10 02:14:30 +0000505/// SelectConstantExpr - This class is private to Constants.cpp, and is used
506/// behind the scenes to implement select constant exprs.
507class VISIBILITY_HIDDEN SelectConstantExpr : public ConstantExpr {
Gabor Greife9ecc682008-04-06 20:25:17 +0000508 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
Gordon Henriksen14a55692007-12-10 02:14:30 +0000509public:
Gabor Greife9ecc682008-04-06 20:25:17 +0000510 // allocate space for exactly three operands
511 void *operator new(size_t s) {
512 return User::operator new(s, 3);
513 }
Gordon Henriksen14a55692007-12-10 02:14:30 +0000514 SelectConstantExpr(Constant *C1, Constant *C2, Constant *C3)
Gabor Greiff6caff662008-05-10 08:32:32 +0000515 : ConstantExpr(C2->getType(), Instruction::Select, &Op<0>(), 3) {
Gabor Greif2d3024d2008-05-26 21:33:52 +0000516 Op<0>() = C1;
517 Op<1>() = C2;
518 Op<2>() = C3;
Gordon Henriksen14a55692007-12-10 02:14:30 +0000519 }
Gabor Greiff6caff662008-05-10 08:32:32 +0000520 /// Transparently provide more efficient getOperand methods.
521 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Gordon Henriksen14a55692007-12-10 02:14:30 +0000522};
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000523
Gordon Henriksen14a55692007-12-10 02:14:30 +0000524/// ExtractElementConstantExpr - This class is private to
525/// Constants.cpp, and is used behind the scenes to implement
526/// extractelement constant exprs.
527class VISIBILITY_HIDDEN ExtractElementConstantExpr : public ConstantExpr {
Gabor Greife9ecc682008-04-06 20:25:17 +0000528 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
Gordon Henriksen14a55692007-12-10 02:14:30 +0000529public:
Gabor Greife9ecc682008-04-06 20:25:17 +0000530 // allocate space for exactly two operands
531 void *operator new(size_t s) {
532 return User::operator new(s, 2);
533 }
Gordon Henriksen14a55692007-12-10 02:14:30 +0000534 ExtractElementConstantExpr(Constant *C1, Constant *C2)
535 : ConstantExpr(cast<VectorType>(C1->getType())->getElementType(),
Gabor Greiff6caff662008-05-10 08:32:32 +0000536 Instruction::ExtractElement, &Op<0>(), 2) {
Gabor Greif2d3024d2008-05-26 21:33:52 +0000537 Op<0>() = C1;
538 Op<1>() = C2;
Gordon Henriksen14a55692007-12-10 02:14:30 +0000539 }
Gabor Greiff6caff662008-05-10 08:32:32 +0000540 /// Transparently provide more efficient getOperand methods.
541 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Gordon Henriksen14a55692007-12-10 02:14:30 +0000542};
Robert Bocchino23004482006-01-10 19:05:34 +0000543
Gordon Henriksen14a55692007-12-10 02:14:30 +0000544/// InsertElementConstantExpr - This class is private to
545/// Constants.cpp, and is used behind the scenes to implement
546/// insertelement constant exprs.
547class VISIBILITY_HIDDEN InsertElementConstantExpr : public ConstantExpr {
Gabor Greife9ecc682008-04-06 20:25:17 +0000548 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
Gordon Henriksen14a55692007-12-10 02:14:30 +0000549public:
Gabor Greife9ecc682008-04-06 20:25:17 +0000550 // allocate space for exactly three operands
551 void *operator new(size_t s) {
552 return User::operator new(s, 3);
553 }
Gordon Henriksen14a55692007-12-10 02:14:30 +0000554 InsertElementConstantExpr(Constant *C1, Constant *C2, Constant *C3)
555 : ConstantExpr(C1->getType(), Instruction::InsertElement,
Gabor Greiff6caff662008-05-10 08:32:32 +0000556 &Op<0>(), 3) {
Gabor Greif2d3024d2008-05-26 21:33:52 +0000557 Op<0>() = C1;
558 Op<1>() = C2;
559 Op<2>() = C3;
Gordon Henriksen14a55692007-12-10 02:14:30 +0000560 }
Gabor Greiff6caff662008-05-10 08:32:32 +0000561 /// Transparently provide more efficient getOperand methods.
562 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Gordon Henriksen14a55692007-12-10 02:14:30 +0000563};
Robert Bocchinoca27f032006-01-17 20:07:22 +0000564
Gordon Henriksen14a55692007-12-10 02:14:30 +0000565/// ShuffleVectorConstantExpr - This class is private to
566/// Constants.cpp, and is used behind the scenes to implement
567/// shufflevector constant exprs.
568class VISIBILITY_HIDDEN ShuffleVectorConstantExpr : public ConstantExpr {
Gabor Greife9ecc682008-04-06 20:25:17 +0000569 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
Gordon Henriksen14a55692007-12-10 02:14:30 +0000570public:
Gabor Greife9ecc682008-04-06 20:25:17 +0000571 // allocate space for exactly three operands
572 void *operator new(size_t s) {
573 return User::operator new(s, 3);
574 }
Gordon Henriksen14a55692007-12-10 02:14:30 +0000575 ShuffleVectorConstantExpr(Constant *C1, Constant *C2, Constant *C3)
Nate Begeman94aa38d2009-02-12 21:28:33 +0000576 : ConstantExpr(VectorType::get(
577 cast<VectorType>(C1->getType())->getElementType(),
578 cast<VectorType>(C3->getType())->getNumElements()),
579 Instruction::ShuffleVector,
Gabor Greiff6caff662008-05-10 08:32:32 +0000580 &Op<0>(), 3) {
Gabor Greif2d3024d2008-05-26 21:33:52 +0000581 Op<0>() = C1;
582 Op<1>() = C2;
583 Op<2>() = C3;
Gordon Henriksen14a55692007-12-10 02:14:30 +0000584 }
Gabor Greiff6caff662008-05-10 08:32:32 +0000585 /// Transparently provide more efficient getOperand methods.
586 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Gordon Henriksen14a55692007-12-10 02:14:30 +0000587};
588
Dan Gohman12fce772008-05-15 19:50:34 +0000589/// ExtractValueConstantExpr - This class is private to
590/// Constants.cpp, and is used behind the scenes to implement
591/// extractvalue constant exprs.
592class VISIBILITY_HIDDEN ExtractValueConstantExpr : public ConstantExpr {
Dan Gohman1ecaf452008-05-31 00:58:22 +0000593 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
Dan Gohman12fce772008-05-15 19:50:34 +0000594public:
Dan Gohman1ecaf452008-05-31 00:58:22 +0000595 // allocate space for exactly one operand
596 void *operator new(size_t s) {
597 return User::operator new(s, 1);
Dan Gohman12fce772008-05-15 19:50:34 +0000598 }
Dan Gohman1ecaf452008-05-31 00:58:22 +0000599 ExtractValueConstantExpr(Constant *Agg,
600 const SmallVector<unsigned, 4> &IdxList,
601 const Type *DestTy)
602 : ConstantExpr(DestTy, Instruction::ExtractValue, &Op<0>(), 1),
603 Indices(IdxList) {
604 Op<0>() = Agg;
605 }
606
Dan Gohman7bb04502008-05-31 19:09:08 +0000607 /// Indices - These identify which value to extract.
Dan Gohman1ecaf452008-05-31 00:58:22 +0000608 const SmallVector<unsigned, 4> Indices;
609
Dan Gohman12fce772008-05-15 19:50:34 +0000610 /// Transparently provide more efficient getOperand methods.
611 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
612};
613
614/// InsertValueConstantExpr - This class is private to
615/// Constants.cpp, and is used behind the scenes to implement
616/// insertvalue constant exprs.
617class VISIBILITY_HIDDEN InsertValueConstantExpr : public ConstantExpr {
Dan Gohman1ecaf452008-05-31 00:58:22 +0000618 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
Dan Gohman12fce772008-05-15 19:50:34 +0000619public:
Dan Gohman1ecaf452008-05-31 00:58:22 +0000620 // allocate space for exactly one operand
621 void *operator new(size_t s) {
622 return User::operator new(s, 2);
Dan Gohman12fce772008-05-15 19:50:34 +0000623 }
Dan Gohman1ecaf452008-05-31 00:58:22 +0000624 InsertValueConstantExpr(Constant *Agg, Constant *Val,
625 const SmallVector<unsigned, 4> &IdxList,
626 const Type *DestTy)
627 : ConstantExpr(DestTy, Instruction::InsertValue, &Op<0>(), 2),
628 Indices(IdxList) {
629 Op<0>() = Agg;
630 Op<1>() = Val;
631 }
632
Dan Gohman7bb04502008-05-31 19:09:08 +0000633 /// Indices - These identify the position for the insertion.
Dan Gohman1ecaf452008-05-31 00:58:22 +0000634 const SmallVector<unsigned, 4> Indices;
635
Dan Gohman12fce772008-05-15 19:50:34 +0000636 /// Transparently provide more efficient getOperand methods.
637 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
638};
639
640
Gordon Henriksen14a55692007-12-10 02:14:30 +0000641/// GetElementPtrConstantExpr - This class is private to Constants.cpp, and is
642/// used behind the scenes to implement getelementpr constant exprs.
Gabor Greife9ecc682008-04-06 20:25:17 +0000643class VISIBILITY_HIDDEN GetElementPtrConstantExpr : public ConstantExpr {
Gordon Henriksen14a55692007-12-10 02:14:30 +0000644 GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
Gabor Greiff6caff662008-05-10 08:32:32 +0000645 const Type *DestTy);
Gabor Greife9ecc682008-04-06 20:25:17 +0000646public:
Gabor Greif697e94c2008-05-15 10:04:30 +0000647 static GetElementPtrConstantExpr *Create(Constant *C,
648 const std::vector<Constant*>&IdxList,
Gabor Greiff6caff662008-05-10 08:32:32 +0000649 const Type *DestTy) {
Gabor Greif697e94c2008-05-15 10:04:30 +0000650 return new(IdxList.size() + 1)
651 GetElementPtrConstantExpr(C, IdxList, DestTy);
Gabor Greife9ecc682008-04-06 20:25:17 +0000652 }
Gabor Greiff6caff662008-05-10 08:32:32 +0000653 /// Transparently provide more efficient getOperand methods.
654 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Gordon Henriksen14a55692007-12-10 02:14:30 +0000655};
656
657// CompareConstantExpr - This class is private to Constants.cpp, and is used
658// behind the scenes to implement ICmp and FCmp constant expressions. This is
659// needed in order to store the predicate value for these instructions.
660struct VISIBILITY_HIDDEN CompareConstantExpr : public ConstantExpr {
Gabor Greife9ecc682008-04-06 20:25:17 +0000661 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
662 // allocate space for exactly two operands
663 void *operator new(size_t s) {
664 return User::operator new(s, 2);
665 }
Gordon Henriksen14a55692007-12-10 02:14:30 +0000666 unsigned short predicate;
Nate Begemand2195702008-05-12 19:01:56 +0000667 CompareConstantExpr(const Type *ty, Instruction::OtherOps opc,
668 unsigned short pred, Constant* LHS, Constant* RHS)
669 : ConstantExpr(ty, opc, &Op<0>(), 2), predicate(pred) {
Gabor Greif2d3024d2008-05-26 21:33:52 +0000670 Op<0>() = LHS;
671 Op<1>() = RHS;
Gordon Henriksen14a55692007-12-10 02:14:30 +0000672 }
Gabor Greiff6caff662008-05-10 08:32:32 +0000673 /// Transparently provide more efficient getOperand methods.
674 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Gordon Henriksen14a55692007-12-10 02:14:30 +0000675};
676
677} // end anonymous namespace
678
Gabor Greiff6caff662008-05-10 08:32:32 +0000679template <>
680struct OperandTraits<UnaryConstantExpr> : FixedNumOperandTraits<1> {
681};
682DEFINE_TRANSPARENT_OPERAND_ACCESSORS(UnaryConstantExpr, Value)
683
684template <>
685struct OperandTraits<BinaryConstantExpr> : FixedNumOperandTraits<2> {
686};
687DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BinaryConstantExpr, Value)
688
689template <>
690struct OperandTraits<SelectConstantExpr> : FixedNumOperandTraits<3> {
691};
692DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SelectConstantExpr, Value)
693
694template <>
695struct OperandTraits<ExtractElementConstantExpr> : FixedNumOperandTraits<2> {
696};
697DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractElementConstantExpr, Value)
698
699template <>
700struct OperandTraits<InsertElementConstantExpr> : FixedNumOperandTraits<3> {
701};
702DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertElementConstantExpr, Value)
703
704template <>
705struct OperandTraits<ShuffleVectorConstantExpr> : FixedNumOperandTraits<3> {
706};
707DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ShuffleVectorConstantExpr, Value)
708
Dan Gohman12fce772008-05-15 19:50:34 +0000709template <>
Dan Gohman1ecaf452008-05-31 00:58:22 +0000710struct OperandTraits<ExtractValueConstantExpr> : FixedNumOperandTraits<1> {
Dan Gohman12fce772008-05-15 19:50:34 +0000711};
Dan Gohman12fce772008-05-15 19:50:34 +0000712DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractValueConstantExpr, Value)
713
714template <>
Dan Gohman1ecaf452008-05-31 00:58:22 +0000715struct OperandTraits<InsertValueConstantExpr> : FixedNumOperandTraits<2> {
Dan Gohman12fce772008-05-15 19:50:34 +0000716};
Dan Gohman12fce772008-05-15 19:50:34 +0000717DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertValueConstantExpr, Value)
718
Gabor Greiff6caff662008-05-10 08:32:32 +0000719template <>
720struct OperandTraits<GetElementPtrConstantExpr> : VariadicOperandTraits<1> {
721};
722
723GetElementPtrConstantExpr::GetElementPtrConstantExpr
724 (Constant *C,
725 const std::vector<Constant*> &IdxList,
726 const Type *DestTy)
727 : ConstantExpr(DestTy, Instruction::GetElementPtr,
728 OperandTraits<GetElementPtrConstantExpr>::op_end(this)
729 - (IdxList.size()+1),
730 IdxList.size()+1) {
Gabor Greif2d3024d2008-05-26 21:33:52 +0000731 OperandList[0] = C;
Gabor Greiff6caff662008-05-10 08:32:32 +0000732 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
Gabor Greif2d3024d2008-05-26 21:33:52 +0000733 OperandList[i+1] = IdxList[i];
Gabor Greiff6caff662008-05-10 08:32:32 +0000734}
735
736DEFINE_TRANSPARENT_OPERAND_ACCESSORS(GetElementPtrConstantExpr, Value)
737
738
739template <>
740struct OperandTraits<CompareConstantExpr> : FixedNumOperandTraits<2> {
741};
742DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CompareConstantExpr, Value)
743
744
745} // End llvm namespace
746
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000747
748// Utility function for determining if a ConstantExpr is a CastOp or not. This
749// can't be inline because we don't want to #include Instruction.h into
750// Constant.h
751bool ConstantExpr::isCast() const {
752 return Instruction::isCast(getOpcode());
753}
754
Reid Spenceree3c9912006-12-04 05:19:50 +0000755bool ConstantExpr::isCompare() const {
Chris Lattnereab49262008-07-14 05:17:31 +0000756 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp ||
757 getOpcode() == Instruction::VICmp || getOpcode() == Instruction::VFCmp;
Reid Spenceree3c9912006-12-04 05:19:50 +0000758}
759
Dan Gohman1ecaf452008-05-31 00:58:22 +0000760bool ConstantExpr::hasIndices() const {
761 return getOpcode() == Instruction::ExtractValue ||
762 getOpcode() == Instruction::InsertValue;
763}
764
765const SmallVector<unsigned, 4> &ConstantExpr::getIndices() const {
766 if (const ExtractValueConstantExpr *EVCE =
767 dyn_cast<ExtractValueConstantExpr>(this))
768 return EVCE->Indices;
Dan Gohmana469bdb2008-06-23 16:39:44 +0000769
770 return cast<InsertValueConstantExpr>(this)->Indices;
Dan Gohman1ecaf452008-05-31 00:58:22 +0000771}
772
Chris Lattner817175f2004-03-29 02:37:53 +0000773/// ConstantExpr::get* - Return some common constants without having to
774/// specify the full Instruction::OPCODE identifier.
775///
776Constant *ConstantExpr::getNeg(Constant *C) {
Reid Spencer2eadb532007-01-21 00:29:26 +0000777 return get(Instruction::Sub,
778 ConstantExpr::getZeroValueForNegationExpr(C->getType()),
779 C);
Chris Lattner817175f2004-03-29 02:37:53 +0000780}
781Constant *ConstantExpr::getNot(Constant *C) {
Dale Johannesen47a5ef32008-08-21 21:20:09 +0000782 assert((isa<IntegerType>(C->getType()) ||
783 cast<VectorType>(C->getType())->getElementType()->isInteger()) &&
784 "Cannot NOT a nonintegral value!");
Chris Lattner817175f2004-03-29 02:37:53 +0000785 return get(Instruction::Xor, C,
Dale Johannesen47a5ef32008-08-21 21:20:09 +0000786 Constant::getAllOnesValue(C->getType()));
Chris Lattner817175f2004-03-29 02:37:53 +0000787}
788Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2) {
789 return get(Instruction::Add, C1, C2);
790}
791Constant *ConstantExpr::getSub(Constant *C1, Constant *C2) {
792 return get(Instruction::Sub, C1, C2);
793}
794Constant *ConstantExpr::getMul(Constant *C1, Constant *C2) {
795 return get(Instruction::Mul, C1, C2);
796}
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000797Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2) {
798 return get(Instruction::UDiv, C1, C2);
799}
800Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2) {
801 return get(Instruction::SDiv, C1, C2);
802}
803Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
804 return get(Instruction::FDiv, C1, C2);
Chris Lattner817175f2004-03-29 02:37:53 +0000805}
Reid Spencer7eb55b32006-11-02 01:53:59 +0000806Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
807 return get(Instruction::URem, C1, C2);
808}
809Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
810 return get(Instruction::SRem, C1, C2);
811}
812Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
813 return get(Instruction::FRem, C1, C2);
Chris Lattner817175f2004-03-29 02:37:53 +0000814}
815Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
816 return get(Instruction::And, C1, C2);
817}
818Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
819 return get(Instruction::Or, C1, C2);
820}
821Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
822 return get(Instruction::Xor, C1, C2);
823}
Reid Spencer10fbf0e2006-12-03 05:48:19 +0000824unsigned ConstantExpr::getPredicate() const {
Nate Begemand2195702008-05-12 19:01:56 +0000825 assert(getOpcode() == Instruction::FCmp ||
826 getOpcode() == Instruction::ICmp ||
827 getOpcode() == Instruction::VFCmp ||
828 getOpcode() == Instruction::VICmp);
Chris Lattneref650092007-10-18 16:26:24 +0000829 return ((const CompareConstantExpr*)this)->predicate;
Reid Spencer10fbf0e2006-12-03 05:48:19 +0000830}
Chris Lattner817175f2004-03-29 02:37:53 +0000831Constant *ConstantExpr::getShl(Constant *C1, Constant *C2) {
832 return get(Instruction::Shl, C1, C2);
833}
Reid Spencerfdff9382006-11-08 06:47:33 +0000834Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2) {
835 return get(Instruction::LShr, C1, C2);
Chris Lattner817175f2004-03-29 02:37:53 +0000836}
Reid Spencerfdff9382006-11-08 06:47:33 +0000837Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2) {
838 return get(Instruction::AShr, C1, C2);
Chris Lattnerdb8bdba2004-05-25 05:32:43 +0000839}
Chris Lattner60e0dd72001-10-03 06:12:09 +0000840
Chris Lattner7c1018a2006-07-14 19:37:40 +0000841/// getWithOperandReplaced - Return a constant expression identical to this
842/// one, but with the specified operand set to the specified value.
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000843Constant *
844ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
Chris Lattner7c1018a2006-07-14 19:37:40 +0000845 assert(OpNo < getNumOperands() && "Operand num is out of range!");
846 assert(Op->getType() == getOperand(OpNo)->getType() &&
847 "Replacing operand with value of different type!");
Chris Lattner227816342006-07-14 22:20:01 +0000848 if (getOperand(OpNo) == Op)
849 return const_cast<ConstantExpr*>(this);
Chris Lattner7c1018a2006-07-14 19:37:40 +0000850
Chris Lattner227816342006-07-14 22:20:01 +0000851 Constant *Op0, *Op1, *Op2;
Chris Lattner7c1018a2006-07-14 19:37:40 +0000852 switch (getOpcode()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000853 case Instruction::Trunc:
854 case Instruction::ZExt:
855 case Instruction::SExt:
856 case Instruction::FPTrunc:
857 case Instruction::FPExt:
858 case Instruction::UIToFP:
859 case Instruction::SIToFP:
860 case Instruction::FPToUI:
861 case Instruction::FPToSI:
862 case Instruction::PtrToInt:
863 case Instruction::IntToPtr:
864 case Instruction::BitCast:
865 return ConstantExpr::getCast(getOpcode(), Op, getType());
Chris Lattner227816342006-07-14 22:20:01 +0000866 case Instruction::Select:
867 Op0 = (OpNo == 0) ? Op : getOperand(0);
868 Op1 = (OpNo == 1) ? Op : getOperand(1);
869 Op2 = (OpNo == 2) ? Op : getOperand(2);
870 return ConstantExpr::getSelect(Op0, Op1, Op2);
871 case Instruction::InsertElement:
872 Op0 = (OpNo == 0) ? Op : getOperand(0);
873 Op1 = (OpNo == 1) ? Op : getOperand(1);
874 Op2 = (OpNo == 2) ? Op : getOperand(2);
875 return ConstantExpr::getInsertElement(Op0, Op1, Op2);
876 case Instruction::ExtractElement:
877 Op0 = (OpNo == 0) ? Op : getOperand(0);
878 Op1 = (OpNo == 1) ? Op : getOperand(1);
879 return ConstantExpr::getExtractElement(Op0, Op1);
880 case Instruction::ShuffleVector:
881 Op0 = (OpNo == 0) ? Op : getOperand(0);
882 Op1 = (OpNo == 1) ? Op : getOperand(1);
883 Op2 = (OpNo == 2) ? Op : getOperand(2);
884 return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Chris Lattner7c1018a2006-07-14 19:37:40 +0000885 case Instruction::GetElementPtr: {
Chris Lattnerb5d70302007-02-19 20:01:23 +0000886 SmallVector<Constant*, 8> Ops;
Dan Gohman12fce772008-05-15 19:50:34 +0000887 Ops.resize(getNumOperands()-1);
Chris Lattner7c1018a2006-07-14 19:37:40 +0000888 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
Dan Gohman12fce772008-05-15 19:50:34 +0000889 Ops[i-1] = getOperand(i);
Chris Lattner7c1018a2006-07-14 19:37:40 +0000890 if (OpNo == 0)
Chris Lattnerb5d70302007-02-19 20:01:23 +0000891 return ConstantExpr::getGetElementPtr(Op, &Ops[0], Ops.size());
Chris Lattner7c1018a2006-07-14 19:37:40 +0000892 Ops[OpNo-1] = Op;
Chris Lattnerb5d70302007-02-19 20:01:23 +0000893 return ConstantExpr::getGetElementPtr(getOperand(0), &Ops[0], Ops.size());
Chris Lattner7c1018a2006-07-14 19:37:40 +0000894 }
Chris Lattner7c1018a2006-07-14 19:37:40 +0000895 default:
896 assert(getNumOperands() == 2 && "Must be binary operator?");
Chris Lattner227816342006-07-14 22:20:01 +0000897 Op0 = (OpNo == 0) ? Op : getOperand(0);
898 Op1 = (OpNo == 1) ? Op : getOperand(1);
899 return ConstantExpr::get(getOpcode(), Op0, Op1);
900 }
901}
902
903/// getWithOperands - This returns the current constant expression with the
904/// operands replaced with the specified values. The specified operands must
905/// match count and type with the existing ones.
906Constant *ConstantExpr::
Chris Lattnerb078e282008-08-20 22:27:40 +0000907getWithOperands(Constant* const *Ops, unsigned NumOps) const {
908 assert(NumOps == getNumOperands() && "Operand count mismatch!");
Chris Lattner227816342006-07-14 22:20:01 +0000909 bool AnyChange = false;
Chris Lattnerb078e282008-08-20 22:27:40 +0000910 for (unsigned i = 0; i != NumOps; ++i) {
Chris Lattner227816342006-07-14 22:20:01 +0000911 assert(Ops[i]->getType() == getOperand(i)->getType() &&
912 "Operand type mismatch!");
913 AnyChange |= Ops[i] != getOperand(i);
914 }
915 if (!AnyChange) // No operands changed, return self.
916 return const_cast<ConstantExpr*>(this);
917
918 switch (getOpcode()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000919 case Instruction::Trunc:
920 case Instruction::ZExt:
921 case Instruction::SExt:
922 case Instruction::FPTrunc:
923 case Instruction::FPExt:
924 case Instruction::UIToFP:
925 case Instruction::SIToFP:
926 case Instruction::FPToUI:
927 case Instruction::FPToSI:
928 case Instruction::PtrToInt:
929 case Instruction::IntToPtr:
930 case Instruction::BitCast:
931 return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
Chris Lattner227816342006-07-14 22:20:01 +0000932 case Instruction::Select:
933 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
934 case Instruction::InsertElement:
935 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
936 case Instruction::ExtractElement:
937 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
938 case Instruction::ShuffleVector:
939 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
Chris Lattnerb5d70302007-02-19 20:01:23 +0000940 case Instruction::GetElementPtr:
Chris Lattnerb078e282008-08-20 22:27:40 +0000941 return ConstantExpr::getGetElementPtr(Ops[0], &Ops[1], NumOps-1);
Reid Spencer266e42b2006-12-23 06:05:41 +0000942 case Instruction::ICmp:
943 case Instruction::FCmp:
Nate Begeman098cc6f2008-07-25 17:56:27 +0000944 case Instruction::VICmp:
945 case Instruction::VFCmp:
Reid Spencer266e42b2006-12-23 06:05:41 +0000946 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
Chris Lattner227816342006-07-14 22:20:01 +0000947 default:
948 assert(getNumOperands() == 2 && "Must be binary operator?");
949 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1]);
Chris Lattner7c1018a2006-07-14 19:37:40 +0000950 }
951}
952
Chris Lattner2f7c9632001-06-06 20:29:01 +0000953
954//===----------------------------------------------------------------------===//
Chris Lattner2f7c9632001-06-06 20:29:01 +0000955// isValueValidForType implementations
956
Reid Spencere7334722006-12-19 01:28:19 +0000957bool ConstantInt::isValueValidForType(const Type *Ty, uint64_t Val) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000958 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000959 if (Ty == Type::Int1Ty)
960 return Val == 0 || Val == 1;
Reid Spencerd7a00d72007-02-05 23:47:56 +0000961 if (NumBits >= 64)
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000962 return true; // always true, has to fit in largest type
963 uint64_t Max = (1ll << NumBits) - 1;
964 return Val <= Max;
Reid Spencere7334722006-12-19 01:28:19 +0000965}
966
Reid Spencere0fc4df2006-10-20 07:07:24 +0000967bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000968 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000969 if (Ty == Type::Int1Ty)
Reid Spencera94d3942007-01-19 21:13:56 +0000970 return Val == 0 || Val == 1 || Val == -1;
Reid Spencerd7a00d72007-02-05 23:47:56 +0000971 if (NumBits >= 64)
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000972 return true; // always true, has to fit in largest type
973 int64_t Min = -(1ll << (NumBits-1));
974 int64_t Max = (1ll << (NumBits-1)) - 1;
975 return (Val >= Min && Val <= Max);
Chris Lattner2f7c9632001-06-06 20:29:01 +0000976}
977
Dale Johannesend246b2c2007-08-30 00:23:21 +0000978bool ConstantFP::isValueValidForType(const Type *Ty, const APFloat& Val) {
979 // convert modifies in place, so make a copy.
980 APFloat Val2 = APFloat(Val);
Dale Johannesen4f0bd682008-10-09 23:00:39 +0000981 bool losesInfo;
Chris Lattner6b727592004-06-17 18:19:28 +0000982 switch (Ty->getTypeID()) {
Chris Lattner2f7c9632001-06-06 20:29:01 +0000983 default:
984 return false; // These can't be represented as floating point!
985
Dale Johannesend246b2c2007-08-30 00:23:21 +0000986 // FIXME rounding mode needs to be more flexible
Dale Johannesen4f0bd682008-10-09 23:00:39 +0000987 case Type::FloatTyID: {
988 if (&Val2.getSemantics() == &APFloat::IEEEsingle)
989 return true;
990 Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &losesInfo);
991 return !losesInfo;
992 }
993 case Type::DoubleTyID: {
994 if (&Val2.getSemantics() == &APFloat::IEEEsingle ||
995 &Val2.getSemantics() == &APFloat::IEEEdouble)
996 return true;
997 Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &losesInfo);
998 return !losesInfo;
999 }
Dale Johannesenbdad8092007-08-09 22:51:36 +00001000 case Type::X86_FP80TyID:
Dale Johannesen028084e2007-09-12 03:30:33 +00001001 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
1002 &Val2.getSemantics() == &APFloat::IEEEdouble ||
1003 &Val2.getSemantics() == &APFloat::x87DoubleExtended;
Dale Johannesenbdad8092007-08-09 22:51:36 +00001004 case Type::FP128TyID:
Dale Johannesen028084e2007-09-12 03:30:33 +00001005 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
1006 &Val2.getSemantics() == &APFloat::IEEEdouble ||
1007 &Val2.getSemantics() == &APFloat::IEEEquad;
Dale Johannesen007aa372007-10-11 18:07:22 +00001008 case Type::PPC_FP128TyID:
1009 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
1010 &Val2.getSemantics() == &APFloat::IEEEdouble ||
1011 &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
Chris Lattner2f7c9632001-06-06 20:29:01 +00001012 }
Chris Lattneraa2372562006-05-24 17:04:05 +00001013}
Chris Lattner9655e542001-07-20 19:16:02 +00001014
Chris Lattner49d855c2001-09-07 16:46:31 +00001015//===----------------------------------------------------------------------===//
Chris Lattner49d855c2001-09-07 16:46:31 +00001016// Factory Function Implementation
1017
Gabor Greiff6caff662008-05-10 08:32:32 +00001018
1019// The number of operands for each ConstantCreator::create method is
1020// determined by the ConstantTraits template.
Chris Lattner98fa07b2003-05-23 20:03:32 +00001021// ConstantCreator - A class that is used to create constants by
1022// ValueMap*. This class should be partially specialized if there is
1023// something strange that needs to be done to interface to the ctor for the
1024// constant.
1025//
Chris Lattner189d19f2003-11-21 20:23:48 +00001026namespace llvm {
Gabor Greiff6caff662008-05-10 08:32:32 +00001027 template<class ValType>
1028 struct ConstantTraits;
1029
1030 template<typename T, typename Alloc>
1031 struct VISIBILITY_HIDDEN ConstantTraits< std::vector<T, Alloc> > {
1032 static unsigned uses(const std::vector<T, Alloc>& v) {
1033 return v.size();
1034 }
1035 };
1036
Chris Lattner189d19f2003-11-21 20:23:48 +00001037 template<class ConstantClass, class TypeClass, class ValType>
Chris Lattner02157b02006-06-28 21:38:54 +00001038 struct VISIBILITY_HIDDEN ConstantCreator {
Chris Lattner189d19f2003-11-21 20:23:48 +00001039 static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
Gabor Greiff6caff662008-05-10 08:32:32 +00001040 return new(ConstantTraits<ValType>::uses(V)) ConstantClass(Ty, V);
Chris Lattner189d19f2003-11-21 20:23:48 +00001041 }
1042 };
Misha Brukmanb1c93172005-04-21 23:48:37 +00001043
Chris Lattner189d19f2003-11-21 20:23:48 +00001044 template<class ConstantClass, class TypeClass>
Chris Lattner02157b02006-06-28 21:38:54 +00001045 struct VISIBILITY_HIDDEN ConvertConstantType {
Chris Lattner189d19f2003-11-21 20:23:48 +00001046 static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
1047 assert(0 && "This type cannot be converted!\n");
1048 abort();
1049 }
1050 };
Chris Lattnerb50d1352003-10-05 00:17:43 +00001051
Chris Lattner935aa922005-10-04 17:48:46 +00001052 template<class ValType, class TypeClass, class ConstantClass,
1053 bool HasLargeKey = false /*true for arrays and structs*/ >
Chris Lattner02157b02006-06-28 21:38:54 +00001054 class VISIBILITY_HIDDEN ValueMap : public AbstractTypeUser {
Chris Lattnerb64419a2005-10-03 22:51:37 +00001055 public:
Jim Laskeyc03caef2006-07-17 17:38:29 +00001056 typedef std::pair<const Type*, ValType> MapKey;
1057 typedef std::map<MapKey, Constant *> MapTy;
1058 typedef std::map<Constant*, typename MapTy::iterator> InverseMapTy;
1059 typedef std::map<const Type*, typename MapTy::iterator> AbstractTypeMapTy;
Chris Lattnerb64419a2005-10-03 22:51:37 +00001060 private:
Chris Lattner5bbf60a52005-10-04 16:52:46 +00001061 /// Map - This is the main map from the element descriptor to the Constants.
1062 /// This is the primary way we avoid creating two of the same shape
1063 /// constant.
Chris Lattnerb50d1352003-10-05 00:17:43 +00001064 MapTy Map;
Chris Lattner935aa922005-10-04 17:48:46 +00001065
1066 /// InverseMap - If "HasLargeKey" is true, this contains an inverse mapping
1067 /// from the constants to their element in Map. This is important for
1068 /// removal of constants from the array, which would otherwise have to scan
1069 /// through the map with very large keys.
Jim Laskeyc03caef2006-07-17 17:38:29 +00001070 InverseMapTy InverseMap;
Chris Lattnerb50d1352003-10-05 00:17:43 +00001071
Jim Laskeyc03caef2006-07-17 17:38:29 +00001072 /// AbstractTypeMap - Map for abstract type constants.
1073 ///
Chris Lattnerb50d1352003-10-05 00:17:43 +00001074 AbstractTypeMapTy AbstractTypeMap;
Chris Lattner99a669b2004-11-19 16:39:44 +00001075
Chris Lattner98fa07b2003-05-23 20:03:32 +00001076 public:
Jim Laskeyc03caef2006-07-17 17:38:29 +00001077 typename MapTy::iterator map_end() { return Map.end(); }
Chris Lattnerb64419a2005-10-03 22:51:37 +00001078
1079 /// InsertOrGetItem - Return an iterator for the specified element.
1080 /// If the element exists in the map, the returned iterator points to the
1081 /// entry and Exists=true. If not, the iterator points to the newly
1082 /// inserted entry and returns Exists=false. Newly inserted entries have
1083 /// I->second == 0, and should be filled in.
Jim Laskeyc03caef2006-07-17 17:38:29 +00001084 typename MapTy::iterator InsertOrGetItem(std::pair<MapKey, Constant *>
1085 &InsertVal,
Chris Lattnerb64419a2005-10-03 22:51:37 +00001086 bool &Exists) {
Jim Laskeyc03caef2006-07-17 17:38:29 +00001087 std::pair<typename MapTy::iterator, bool> IP = Map.insert(InsertVal);
Chris Lattnerb64419a2005-10-03 22:51:37 +00001088 Exists = !IP.second;
1089 return IP.first;
1090 }
Chris Lattner5bbf60a52005-10-04 16:52:46 +00001091
Chris Lattner935aa922005-10-04 17:48:46 +00001092private:
Jim Laskeyc03caef2006-07-17 17:38:29 +00001093 typename MapTy::iterator FindExistingElement(ConstantClass *CP) {
Chris Lattner935aa922005-10-04 17:48:46 +00001094 if (HasLargeKey) {
Jim Laskeyc03caef2006-07-17 17:38:29 +00001095 typename InverseMapTy::iterator IMI = InverseMap.find(CP);
Chris Lattner935aa922005-10-04 17:48:46 +00001096 assert(IMI != InverseMap.end() && IMI->second != Map.end() &&
1097 IMI->second->second == CP &&
1098 "InverseMap corrupt!");
1099 return IMI->second;
1100 }
1101
Jim Laskeyc03caef2006-07-17 17:38:29 +00001102 typename MapTy::iterator I =
Dan Gohmane955c482008-08-05 14:45:15 +00001103 Map.find(MapKey(static_cast<const TypeClass*>(CP->getRawType()),
1104 getValType(CP)));
Chris Lattner5bbf60a52005-10-04 16:52:46 +00001105 if (I == Map.end() || I->second != CP) {
1106 // FIXME: This should not use a linear scan. If this gets to be a
1107 // performance problem, someone should look at this.
1108 for (I = Map.begin(); I != Map.end() && I->second != CP; ++I)
1109 /* empty */;
1110 }
Chris Lattner935aa922005-10-04 17:48:46 +00001111 return I;
1112 }
1113public:
1114
Chris Lattnerb64419a2005-10-03 22:51:37 +00001115 /// getOrCreate - Return the specified constant from the map, creating it if
1116 /// necessary.
Chris Lattner98fa07b2003-05-23 20:03:32 +00001117 ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
Chris Lattnerb50d1352003-10-05 00:17:43 +00001118 MapKey Lookup(Ty, V);
Dan Gohman3707f1d2008-07-11 20:58:19 +00001119 typename MapTy::iterator I = Map.find(Lookup);
Reid Spencere0fc4df2006-10-20 07:07:24 +00001120 // Is it in the map?
Dan Gohman3707f1d2008-07-11 20:58:19 +00001121 if (I != Map.end())
Reid Spencere0fc4df2006-10-20 07:07:24 +00001122 return static_cast<ConstantClass *>(I->second);
Chris Lattner98fa07b2003-05-23 20:03:32 +00001123
1124 // If no preexisting value, create one now...
1125 ConstantClass *Result =
1126 ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
1127
Chris Lattnerf97ab6d2008-08-23 03:48:35 +00001128 assert(Result->getType() == Ty && "Type specified is not correct!");
Chris Lattnerb50d1352003-10-05 00:17:43 +00001129 I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
1130
Chris Lattner935aa922005-10-04 17:48:46 +00001131 if (HasLargeKey) // Remember the reverse mapping if needed.
1132 InverseMap.insert(std::make_pair(Result, I));
1133
Chris Lattnerb50d1352003-10-05 00:17:43 +00001134 // If the type of the constant is abstract, make sure that an entry exists
1135 // for it in the AbstractTypeMap.
1136 if (Ty->isAbstract()) {
Dan Gohman3707f1d2008-07-11 20:58:19 +00001137 typename AbstractTypeMapTy::iterator TI = AbstractTypeMap.find(Ty);
Chris Lattnerb50d1352003-10-05 00:17:43 +00001138
Dan Gohman3707f1d2008-07-11 20:58:19 +00001139 if (TI == AbstractTypeMap.end()) {
Chris Lattnerb50d1352003-10-05 00:17:43 +00001140 // Add ourselves to the ATU list of the type.
1141 cast<DerivedType>(Ty)->addAbstractTypeUser(this);
1142
1143 AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
1144 }
1145 }
Chris Lattner98fa07b2003-05-23 20:03:32 +00001146 return Result;
1147 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001148
Chris Lattner98fa07b2003-05-23 20:03:32 +00001149 void remove(ConstantClass *CP) {
Jim Laskeyc03caef2006-07-17 17:38:29 +00001150 typename MapTy::iterator I = FindExistingElement(CP);
Chris Lattnerb50d1352003-10-05 00:17:43 +00001151 assert(I != Map.end() && "Constant not found in constant table!");
Chris Lattner3e650af2004-08-04 04:48:01 +00001152 assert(I->second == CP && "Didn't find correct element?");
Chris Lattnerb50d1352003-10-05 00:17:43 +00001153
Chris Lattner935aa922005-10-04 17:48:46 +00001154 if (HasLargeKey) // Remember the reverse mapping if needed.
1155 InverseMap.erase(CP);
1156
Chris Lattnerb50d1352003-10-05 00:17:43 +00001157 // Now that we found the entry, make sure this isn't the entry that
1158 // the AbstractTypeMap points to.
Jim Laskeyc03caef2006-07-17 17:38:29 +00001159 const TypeClass *Ty = static_cast<const TypeClass *>(I->first.first);
Chris Lattnerb50d1352003-10-05 00:17:43 +00001160 if (Ty->isAbstract()) {
1161 assert(AbstractTypeMap.count(Ty) &&
1162 "Abstract type not in AbstractTypeMap?");
Jim Laskeyc03caef2006-07-17 17:38:29 +00001163 typename MapTy::iterator &ATMEntryIt = AbstractTypeMap[Ty];
Chris Lattnerb50d1352003-10-05 00:17:43 +00001164 if (ATMEntryIt == I) {
1165 // Yes, we are removing the representative entry for this type.
1166 // See if there are any other entries of the same type.
Jim Laskeyc03caef2006-07-17 17:38:29 +00001167 typename MapTy::iterator TmpIt = ATMEntryIt;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001168
Chris Lattnerb50d1352003-10-05 00:17:43 +00001169 // First check the entry before this one...
1170 if (TmpIt != Map.begin()) {
1171 --TmpIt;
1172 if (TmpIt->first.first != Ty) // Not the same type, move back...
1173 ++TmpIt;
1174 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001175
Chris Lattnerb50d1352003-10-05 00:17:43 +00001176 // If we didn't find the same type, try to move forward...
1177 if (TmpIt == ATMEntryIt) {
1178 ++TmpIt;
1179 if (TmpIt == Map.end() || TmpIt->first.first != Ty)
1180 --TmpIt; // No entry afterwards with the same type
1181 }
1182
1183 // If there is another entry in the map of the same abstract type,
1184 // update the AbstractTypeMap entry now.
1185 if (TmpIt != ATMEntryIt) {
1186 ATMEntryIt = TmpIt;
1187 } else {
1188 // Otherwise, we are removing the last instance of this type
1189 // from the table. Remove from the ATM, and from user list.
1190 cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
1191 AbstractTypeMap.erase(Ty);
1192 }
Chris Lattner98fa07b2003-05-23 20:03:32 +00001193 }
Chris Lattnerb50d1352003-10-05 00:17:43 +00001194 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001195
Chris Lattnerb50d1352003-10-05 00:17:43 +00001196 Map.erase(I);
1197 }
1198
Chris Lattner3b793c62005-10-04 21:35:50 +00001199
1200 /// MoveConstantToNewSlot - If we are about to change C to be the element
1201 /// specified by I, update our internal data structures to reflect this
1202 /// fact.
Jim Laskeyc03caef2006-07-17 17:38:29 +00001203 void MoveConstantToNewSlot(ConstantClass *C, typename MapTy::iterator I) {
Chris Lattner3b793c62005-10-04 21:35:50 +00001204 // First, remove the old location of the specified constant in the map.
Jim Laskeyc03caef2006-07-17 17:38:29 +00001205 typename MapTy::iterator OldI = FindExistingElement(C);
Chris Lattner3b793c62005-10-04 21:35:50 +00001206 assert(OldI != Map.end() && "Constant not found in constant table!");
1207 assert(OldI->second == C && "Didn't find correct element?");
1208
1209 // If this constant is the representative element for its abstract type,
1210 // update the AbstractTypeMap so that the representative element is I.
1211 if (C->getType()->isAbstract()) {
1212 typename AbstractTypeMapTy::iterator ATI =
1213 AbstractTypeMap.find(C->getType());
1214 assert(ATI != AbstractTypeMap.end() &&
1215 "Abstract type not in AbstractTypeMap?");
1216 if (ATI->second == OldI)
1217 ATI->second = I;
1218 }
1219
1220 // Remove the old entry from the map.
1221 Map.erase(OldI);
1222
1223 // Update the inverse map so that we know that this constant is now
1224 // located at descriptor I.
1225 if (HasLargeKey) {
1226 assert(I->second == C && "Bad inversemap entry!");
1227 InverseMap[C] = I;
1228 }
1229 }
1230
Chris Lattnerb50d1352003-10-05 00:17:43 +00001231 void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00001232 typename AbstractTypeMapTy::iterator I =
Jim Laskeyc03caef2006-07-17 17:38:29 +00001233 AbstractTypeMap.find(cast<Type>(OldTy));
Chris Lattnerb50d1352003-10-05 00:17:43 +00001234
1235 assert(I != AbstractTypeMap.end() &&
1236 "Abstract type not in AbstractTypeMap?");
1237
1238 // Convert a constant at a time until the last one is gone. The last one
1239 // leaving will remove() itself, causing the AbstractTypeMapEntry to be
1240 // eliminated eventually.
1241 do {
1242 ConvertConstantType<ConstantClass,
Jim Laskeyc03caef2006-07-17 17:38:29 +00001243 TypeClass>::convert(
1244 static_cast<ConstantClass *>(I->second->second),
Chris Lattnerb50d1352003-10-05 00:17:43 +00001245 cast<TypeClass>(NewTy));
1246
Jim Laskeyc03caef2006-07-17 17:38:29 +00001247 I = AbstractTypeMap.find(cast<Type>(OldTy));
Chris Lattnerb50d1352003-10-05 00:17:43 +00001248 } while (I != AbstractTypeMap.end());
1249 }
1250
1251 // If the type became concrete without being refined to any other existing
1252 // type, we just remove ourselves from the ATU list.
1253 void typeBecameConcrete(const DerivedType *AbsTy) {
1254 AbsTy->removeAbstractTypeUser(this);
1255 }
1256
1257 void dump() const {
Bill Wendling6a462f12006-11-17 08:03:48 +00001258 DOUT << "Constant.cpp: ValueMap\n";
Chris Lattner98fa07b2003-05-23 20:03:32 +00001259 }
1260 };
1261}
1262
Chris Lattnera84df0a22006-09-28 23:36:21 +00001263
Chris Lattner28173502007-02-20 06:11:36 +00001264
Chris Lattner9fba3da2004-02-15 05:53:04 +00001265//---- ConstantAggregateZero::get() implementation...
1266//
1267namespace llvm {
1268 // ConstantAggregateZero does not take extra "value" argument...
1269 template<class ValType>
1270 struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
1271 static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
1272 return new ConstantAggregateZero(Ty);
1273 }
1274 };
1275
1276 template<>
1277 struct ConvertConstantType<ConstantAggregateZero, Type> {
1278 static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
1279 // Make everyone now use a constant of the new type...
1280 Constant *New = ConstantAggregateZero::get(NewTy);
1281 assert(New != OldC && "Didn't replace constant??");
1282 OldC->uncheckedReplaceAllUsesWith(New);
1283 OldC->destroyConstant(); // This constant is now dead, destroy it.
1284 }
1285 };
1286}
1287
Chris Lattner69edc982006-09-28 00:35:06 +00001288static ManagedStatic<ValueMap<char, Type,
1289 ConstantAggregateZero> > AggZeroConstants;
Chris Lattner9fba3da2004-02-15 05:53:04 +00001290
Chris Lattner3e650af2004-08-04 04:48:01 +00001291static char getValType(ConstantAggregateZero *CPZ) { return 0; }
1292
Dan Gohman8214fc12008-12-08 07:10:54 +00001293ConstantAggregateZero *ConstantAggregateZero::get(const Type *Ty) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001294 assert((isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) &&
Chris Lattnerbfd0b6d2006-06-10 04:16:23 +00001295 "Cannot create an aggregate zero of non-aggregate type!");
Chris Lattner69edc982006-09-28 00:35:06 +00001296 return AggZeroConstants->getOrCreate(Ty, 0);
Chris Lattner9fba3da2004-02-15 05:53:04 +00001297}
1298
Dan Gohman92b551b2009-03-03 02:55:14 +00001299/// destroyConstant - Remove the constant from the constant table...
1300///
Chris Lattner9fba3da2004-02-15 05:53:04 +00001301void ConstantAggregateZero::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00001302 AggZeroConstants->remove(this);
Chris Lattner9fba3da2004-02-15 05:53:04 +00001303 destroyConstantImpl();
1304}
1305
Chris Lattner3462ae32001-12-03 22:26:30 +00001306//---- ConstantArray::get() implementation...
Chris Lattner49d855c2001-09-07 16:46:31 +00001307//
Chris Lattner189d19f2003-11-21 20:23:48 +00001308namespace llvm {
1309 template<>
1310 struct ConvertConstantType<ConstantArray, ArrayType> {
1311 static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
1312 // Make everyone now use a constant of the new type...
1313 std::vector<Constant*> C;
1314 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1315 C.push_back(cast<Constant>(OldC->getOperand(i)));
1316 Constant *New = ConstantArray::get(NewTy, C);
1317 assert(New != OldC && "Didn't replace constant??");
1318 OldC->uncheckedReplaceAllUsesWith(New);
1319 OldC->destroyConstant(); // This constant is now dead, destroy it.
1320 }
1321 };
1322}
Chris Lattnerb50d1352003-10-05 00:17:43 +00001323
Chris Lattner3e650af2004-08-04 04:48:01 +00001324static std::vector<Constant*> getValType(ConstantArray *CA) {
1325 std::vector<Constant*> Elements;
1326 Elements.reserve(CA->getNumOperands());
1327 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1328 Elements.push_back(cast<Constant>(CA->getOperand(i)));
1329 return Elements;
1330}
1331
Chris Lattnerb64419a2005-10-03 22:51:37 +00001332typedef ValueMap<std::vector<Constant*>, ArrayType,
Chris Lattner935aa922005-10-04 17:48:46 +00001333 ConstantArray, true /*largekey*/> ArrayConstantsTy;
Chris Lattner69edc982006-09-28 00:35:06 +00001334static ManagedStatic<ArrayConstantsTy> ArrayConstants;
Chris Lattner49d855c2001-09-07 16:46:31 +00001335
Chris Lattner015e8212004-02-15 04:14:47 +00001336Constant *ConstantArray::get(const ArrayType *Ty,
Chris Lattner9fba3da2004-02-15 05:53:04 +00001337 const std::vector<Constant*> &V) {
1338 // If this is an all-zero array, return a ConstantAggregateZero object
1339 if (!V.empty()) {
1340 Constant *C = V[0];
1341 if (!C->isNullValue())
Chris Lattner69edc982006-09-28 00:35:06 +00001342 return ArrayConstants->getOrCreate(Ty, V);
Chris Lattner9fba3da2004-02-15 05:53:04 +00001343 for (unsigned i = 1, e = V.size(); i != e; ++i)
1344 if (V[i] != C)
Chris Lattner69edc982006-09-28 00:35:06 +00001345 return ArrayConstants->getOrCreate(Ty, V);
Chris Lattner9fba3da2004-02-15 05:53:04 +00001346 }
1347 return ConstantAggregateZero::get(Ty);
Chris Lattner49d855c2001-09-07 16:46:31 +00001348}
1349
Dan Gohman92b551b2009-03-03 02:55:14 +00001350/// destroyConstant - Remove the constant from the constant table...
1351///
Chris Lattner98fa07b2003-05-23 20:03:32 +00001352void ConstantArray::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00001353 ArrayConstants->remove(this);
Chris Lattner98fa07b2003-05-23 20:03:32 +00001354 destroyConstantImpl();
1355}
1356
Reid Spencer6f614532006-05-30 08:23:18 +00001357/// ConstantArray::get(const string&) - Return an array that is initialized to
1358/// contain the specified string. If length is zero then a null terminator is
1359/// added to the specified string so that it may be used in a natural way.
1360/// Otherwise, the length parameter specifies how much of the string to use
1361/// and it won't be null terminated.
1362///
Reid Spencer82ebaba2006-05-30 18:15:07 +00001363Constant *ConstantArray::get(const std::string &Str, bool AddNull) {
Chris Lattner7f74a562002-01-20 22:54:45 +00001364 std::vector<Constant*> ElementVals;
Reid Spencer82ebaba2006-05-30 18:15:07 +00001365 for (unsigned i = 0; i < Str.length(); ++i)
Reid Spencer8d9336d2006-12-31 05:26:44 +00001366 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, Str[i]));
Chris Lattner8f80fe02001-10-14 23:54:12 +00001367
1368 // Add a null terminator to the string...
Reid Spencer82ebaba2006-05-30 18:15:07 +00001369 if (AddNull) {
Reid Spencer8d9336d2006-12-31 05:26:44 +00001370 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, 0));
Reid Spencer6f614532006-05-30 08:23:18 +00001371 }
Chris Lattner8f80fe02001-10-14 23:54:12 +00001372
Reid Spencer8d9336d2006-12-31 05:26:44 +00001373 ArrayType *ATy = ArrayType::get(Type::Int8Ty, ElementVals.size());
Chris Lattner3462ae32001-12-03 22:26:30 +00001374 return ConstantArray::get(ATy, ElementVals);
Vikram S. Adve34410432001-10-14 23:17:20 +00001375}
1376
Reid Spencer2546b762007-01-26 07:37:34 +00001377/// isString - This method returns true if the array is an array of i8, and
1378/// if the elements of the array are all ConstantInt's.
Chris Lattnere8dfcca2004-01-14 17:06:38 +00001379bool ConstantArray::isString() const {
Reid Spencer2546b762007-01-26 07:37:34 +00001380 // Check the element type for i8...
Reid Spencer8d9336d2006-12-31 05:26:44 +00001381 if (getType()->getElementType() != Type::Int8Ty)
Chris Lattnere8dfcca2004-01-14 17:06:38 +00001382 return false;
1383 // Check the elements to make sure they are all integers, not constant
1384 // expressions.
1385 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1386 if (!isa<ConstantInt>(getOperand(i)))
1387 return false;
1388 return true;
1389}
1390
Evan Cheng3763c5b2006-10-26 19:15:05 +00001391/// isCString - This method returns true if the array is a string (see
Dan Gohman92b551b2009-03-03 02:55:14 +00001392/// isString) and it ends in a null byte \\0 and does not contains any other
Evan Cheng3763c5b2006-10-26 19:15:05 +00001393/// null bytes except its terminator.
1394bool ConstantArray::isCString() const {
Reid Spencer2546b762007-01-26 07:37:34 +00001395 // Check the element type for i8...
Reid Spencer8d9336d2006-12-31 05:26:44 +00001396 if (getType()->getElementType() != Type::Int8Ty)
Evan Chenge974da62006-10-26 21:48:03 +00001397 return false;
1398 Constant *Zero = Constant::getNullValue(getOperand(0)->getType());
1399 // Last element must be a null.
1400 if (getOperand(getNumOperands()-1) != Zero)
1401 return false;
1402 // Other elements must be non-null integers.
1403 for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
1404 if (!isa<ConstantInt>(getOperand(i)))
Evan Cheng3763c5b2006-10-26 19:15:05 +00001405 return false;
Evan Chenge974da62006-10-26 21:48:03 +00001406 if (getOperand(i) == Zero)
1407 return false;
1408 }
Evan Cheng3763c5b2006-10-26 19:15:05 +00001409 return true;
1410}
1411
1412
Dan Gohman92b551b2009-03-03 02:55:14 +00001413/// getAsString - If the sub-element type of this array is i8
1414/// then this method converts the array to an std::string and returns it.
1415/// Otherwise, it asserts out.
1416///
Chris Lattner81fabb02002-08-26 17:53:56 +00001417std::string ConstantArray::getAsString() const {
Chris Lattnere8dfcca2004-01-14 17:06:38 +00001418 assert(isString() && "Not a string!");
Chris Lattner81fabb02002-08-26 17:53:56 +00001419 std::string Result;
Owen Anderson79c69bc2008-06-24 21:58:29 +00001420 Result.reserve(getNumOperands());
Chris Lattner6077c312003-07-23 15:22:26 +00001421 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
Owen Andersonee9c30d2008-06-25 01:05:05 +00001422 Result.push_back((char)cast<ConstantInt>(getOperand(i))->getZExtValue());
Chris Lattner81fabb02002-08-26 17:53:56 +00001423 return Result;
1424}
1425
1426
Chris Lattner3462ae32001-12-03 22:26:30 +00001427//---- ConstantStruct::get() implementation...
Chris Lattner49d855c2001-09-07 16:46:31 +00001428//
Chris Lattnerb50d1352003-10-05 00:17:43 +00001429
Chris Lattner189d19f2003-11-21 20:23:48 +00001430namespace llvm {
1431 template<>
1432 struct ConvertConstantType<ConstantStruct, StructType> {
1433 static void convert(ConstantStruct *OldC, const StructType *NewTy) {
1434 // Make everyone now use a constant of the new type...
1435 std::vector<Constant*> C;
1436 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1437 C.push_back(cast<Constant>(OldC->getOperand(i)));
1438 Constant *New = ConstantStruct::get(NewTy, C);
1439 assert(New != OldC && "Didn't replace constant??");
Misha Brukmanb1c93172005-04-21 23:48:37 +00001440
Chris Lattner189d19f2003-11-21 20:23:48 +00001441 OldC->uncheckedReplaceAllUsesWith(New);
1442 OldC->destroyConstant(); // This constant is now dead, destroy it.
1443 }
1444 };
1445}
Chris Lattnerb50d1352003-10-05 00:17:43 +00001446
Chris Lattner8760ec72005-10-04 01:17:50 +00001447typedef ValueMap<std::vector<Constant*>, StructType,
Chris Lattner935aa922005-10-04 17:48:46 +00001448 ConstantStruct, true /*largekey*/> StructConstantsTy;
Chris Lattner69edc982006-09-28 00:35:06 +00001449static ManagedStatic<StructConstantsTy> StructConstants;
Chris Lattner49d855c2001-09-07 16:46:31 +00001450
Chris Lattner3e650af2004-08-04 04:48:01 +00001451static std::vector<Constant*> getValType(ConstantStruct *CS) {
1452 std::vector<Constant*> Elements;
1453 Elements.reserve(CS->getNumOperands());
1454 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1455 Elements.push_back(cast<Constant>(CS->getOperand(i)));
1456 return Elements;
1457}
1458
Chris Lattner015e8212004-02-15 04:14:47 +00001459Constant *ConstantStruct::get(const StructType *Ty,
1460 const std::vector<Constant*> &V) {
Chris Lattner9fba3da2004-02-15 05:53:04 +00001461 // Create a ConstantAggregateZero value if all elements are zeros...
1462 for (unsigned i = 0, e = V.size(); i != e; ++i)
1463 if (!V[i]->isNullValue())
Chris Lattner69edc982006-09-28 00:35:06 +00001464 return StructConstants->getOrCreate(Ty, V);
Chris Lattner9fba3da2004-02-15 05:53:04 +00001465
1466 return ConstantAggregateZero::get(Ty);
Chris Lattner49d855c2001-09-07 16:46:31 +00001467}
Chris Lattner883ad0b2001-10-03 15:39:36 +00001468
Andrew Lenharthdcb3c972006-12-08 18:06:16 +00001469Constant *ConstantStruct::get(const std::vector<Constant*> &V, bool packed) {
Chris Lattnerd6108ca2004-07-12 20:35:11 +00001470 std::vector<const Type*> StructEls;
1471 StructEls.reserve(V.size());
1472 for (unsigned i = 0, e = V.size(); i != e; ++i)
1473 StructEls.push_back(V[i]->getType());
Andrew Lenharthdcb3c972006-12-08 18:06:16 +00001474 return get(StructType::get(StructEls, packed), V);
Chris Lattnerd6108ca2004-07-12 20:35:11 +00001475}
1476
Chris Lattnerd7a73302001-10-13 06:57:33 +00001477// destroyConstant - Remove the constant from the constant table...
Chris Lattner883ad0b2001-10-03 15:39:36 +00001478//
Chris Lattner3462ae32001-12-03 22:26:30 +00001479void ConstantStruct::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00001480 StructConstants->remove(this);
Chris Lattnerd7a73302001-10-13 06:57:33 +00001481 destroyConstantImpl();
1482}
Chris Lattner883ad0b2001-10-03 15:39:36 +00001483
Reid Spencerd84d35b2007-02-15 02:26:10 +00001484//---- ConstantVector::get() implementation...
Brian Gaeke02209042004-08-20 06:00:58 +00001485//
1486namespace llvm {
1487 template<>
Reid Spencerd84d35b2007-02-15 02:26:10 +00001488 struct ConvertConstantType<ConstantVector, VectorType> {
1489 static void convert(ConstantVector *OldC, const VectorType *NewTy) {
Brian Gaeke02209042004-08-20 06:00:58 +00001490 // Make everyone now use a constant of the new type...
1491 std::vector<Constant*> C;
1492 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1493 C.push_back(cast<Constant>(OldC->getOperand(i)));
Reid Spencerd84d35b2007-02-15 02:26:10 +00001494 Constant *New = ConstantVector::get(NewTy, C);
Brian Gaeke02209042004-08-20 06:00:58 +00001495 assert(New != OldC && "Didn't replace constant??");
1496 OldC->uncheckedReplaceAllUsesWith(New);
1497 OldC->destroyConstant(); // This constant is now dead, destroy it.
1498 }
1499 };
1500}
1501
Reid Spencerd84d35b2007-02-15 02:26:10 +00001502static std::vector<Constant*> getValType(ConstantVector *CP) {
Brian Gaeke02209042004-08-20 06:00:58 +00001503 std::vector<Constant*> Elements;
1504 Elements.reserve(CP->getNumOperands());
1505 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1506 Elements.push_back(CP->getOperand(i));
1507 return Elements;
1508}
1509
Reid Spencerd84d35b2007-02-15 02:26:10 +00001510static ManagedStatic<ValueMap<std::vector<Constant*>, VectorType,
Reid Spencer09575ba2007-02-15 03:39:18 +00001511 ConstantVector> > VectorConstants;
Brian Gaeke02209042004-08-20 06:00:58 +00001512
Reid Spencerd84d35b2007-02-15 02:26:10 +00001513Constant *ConstantVector::get(const VectorType *Ty,
Brian Gaeke02209042004-08-20 06:00:58 +00001514 const std::vector<Constant*> &V) {
Chris Lattnerd977c072008-07-10 00:44:03 +00001515 assert(!V.empty() && "Vectors can't be empty");
1516 // If this is an all-undef or alll-zero vector, return a
1517 // ConstantAggregateZero or UndefValue.
1518 Constant *C = V[0];
1519 bool isZero = C->isNullValue();
1520 bool isUndef = isa<UndefValue>(C);
1521
1522 if (isZero || isUndef) {
Brian Gaeke02209042004-08-20 06:00:58 +00001523 for (unsigned i = 1, e = V.size(); i != e; ++i)
Chris Lattnerd977c072008-07-10 00:44:03 +00001524 if (V[i] != C) {
1525 isZero = isUndef = false;
1526 break;
1527 }
Brian Gaeke02209042004-08-20 06:00:58 +00001528 }
Chris Lattnerd977c072008-07-10 00:44:03 +00001529
1530 if (isZero)
1531 return ConstantAggregateZero::get(Ty);
1532 if (isUndef)
1533 return UndefValue::get(Ty);
1534 return VectorConstants->getOrCreate(Ty, V);
Brian Gaeke02209042004-08-20 06:00:58 +00001535}
1536
Reid Spencerd84d35b2007-02-15 02:26:10 +00001537Constant *ConstantVector::get(const std::vector<Constant*> &V) {
Brian Gaeke02209042004-08-20 06:00:58 +00001538 assert(!V.empty() && "Cannot infer type if V is empty");
Reid Spencerd84d35b2007-02-15 02:26:10 +00001539 return get(VectorType::get(V.front()->getType(),V.size()), V);
Brian Gaeke02209042004-08-20 06:00:58 +00001540}
1541
1542// destroyConstant - Remove the constant from the constant table...
1543//
Reid Spencerd84d35b2007-02-15 02:26:10 +00001544void ConstantVector::destroyConstant() {
Reid Spencer09575ba2007-02-15 03:39:18 +00001545 VectorConstants->remove(this);
Brian Gaeke02209042004-08-20 06:00:58 +00001546 destroyConstantImpl();
1547}
1548
Dan Gohman30978072007-05-24 14:36:04 +00001549/// This function will return true iff every element in this vector constant
Jim Laskeyf0478822007-01-12 22:39:14 +00001550/// is set to all ones.
1551/// @returns true iff this constant's emements are all set to all ones.
1552/// @brief Determine if the value is all ones.
Reid Spencerd84d35b2007-02-15 02:26:10 +00001553bool ConstantVector::isAllOnesValue() const {
Jim Laskeyf0478822007-01-12 22:39:14 +00001554 // Check out first element.
1555 const Constant *Elt = getOperand(0);
1556 const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1557 if (!CI || !CI->isAllOnesValue()) return false;
1558 // Then make sure all remaining elements point to the same value.
1559 for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
1560 if (getOperand(I) != Elt) return false;
1561 }
1562 return true;
1563}
1564
Dan Gohman07159202007-10-17 17:51:30 +00001565/// getSplatValue - If this is a splat constant, where all of the
1566/// elements have the same value, return that value. Otherwise return null.
1567Constant *ConstantVector::getSplatValue() {
1568 // Check out first element.
1569 Constant *Elt = getOperand(0);
1570 // Then make sure all remaining elements point to the same value.
1571 for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
1572 if (getOperand(I) != Elt) return 0;
1573 return Elt;
1574}
1575
Chris Lattner3462ae32001-12-03 22:26:30 +00001576//---- ConstantPointerNull::get() implementation...
Chris Lattnerd7a73302001-10-13 06:57:33 +00001577//
Chris Lattner98fa07b2003-05-23 20:03:32 +00001578
Chris Lattner189d19f2003-11-21 20:23:48 +00001579namespace llvm {
1580 // ConstantPointerNull does not take extra "value" argument...
1581 template<class ValType>
1582 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1583 static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1584 return new ConstantPointerNull(Ty);
1585 }
1586 };
Chris Lattner98fa07b2003-05-23 20:03:32 +00001587
Chris Lattner189d19f2003-11-21 20:23:48 +00001588 template<>
1589 struct ConvertConstantType<ConstantPointerNull, PointerType> {
1590 static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1591 // Make everyone now use a constant of the new type...
1592 Constant *New = ConstantPointerNull::get(NewTy);
1593 assert(New != OldC && "Didn't replace constant??");
1594 OldC->uncheckedReplaceAllUsesWith(New);
1595 OldC->destroyConstant(); // This constant is now dead, destroy it.
1596 }
1597 };
1598}
Chris Lattnerb50d1352003-10-05 00:17:43 +00001599
Chris Lattner69edc982006-09-28 00:35:06 +00001600static ManagedStatic<ValueMap<char, PointerType,
1601 ConstantPointerNull> > NullPtrConstants;
Chris Lattnerd7a73302001-10-13 06:57:33 +00001602
Chris Lattner3e650af2004-08-04 04:48:01 +00001603static char getValType(ConstantPointerNull *) {
1604 return 0;
1605}
1606
1607
Chris Lattner3462ae32001-12-03 22:26:30 +00001608ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
Chris Lattner69edc982006-09-28 00:35:06 +00001609 return NullPtrConstants->getOrCreate(Ty, 0);
Chris Lattner883ad0b2001-10-03 15:39:36 +00001610}
1611
Chris Lattner0c6e0b92002-08-18 00:40:04 +00001612// destroyConstant - Remove the constant from the constant table...
1613//
1614void ConstantPointerNull::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00001615 NullPtrConstants->remove(this);
Chris Lattner0c6e0b92002-08-18 00:40:04 +00001616 destroyConstantImpl();
1617}
1618
1619
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001620//---- UndefValue::get() implementation...
1621//
1622
1623namespace llvm {
1624 // UndefValue does not take extra "value" argument...
1625 template<class ValType>
1626 struct ConstantCreator<UndefValue, Type, ValType> {
1627 static UndefValue *create(const Type *Ty, const ValType &V) {
1628 return new UndefValue(Ty);
1629 }
1630 };
1631
1632 template<>
1633 struct ConvertConstantType<UndefValue, Type> {
1634 static void convert(UndefValue *OldC, const Type *NewTy) {
1635 // Make everyone now use a constant of the new type.
1636 Constant *New = UndefValue::get(NewTy);
1637 assert(New != OldC && "Didn't replace constant??");
1638 OldC->uncheckedReplaceAllUsesWith(New);
1639 OldC->destroyConstant(); // This constant is now dead, destroy it.
1640 }
1641 };
1642}
1643
Chris Lattner69edc982006-09-28 00:35:06 +00001644static ManagedStatic<ValueMap<char, Type, UndefValue> > UndefValueConstants;
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001645
1646static char getValType(UndefValue *) {
1647 return 0;
1648}
1649
1650
1651UndefValue *UndefValue::get(const Type *Ty) {
Chris Lattner69edc982006-09-28 00:35:06 +00001652 return UndefValueConstants->getOrCreate(Ty, 0);
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001653}
1654
1655// destroyConstant - Remove the constant from the constant table.
1656//
1657void UndefValue::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00001658 UndefValueConstants->remove(this);
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001659 destroyConstantImpl();
1660}
1661
Nick Lewycky49f89192009-04-04 07:22:01 +00001662//---- MDString::get() implementation
1663//
1664
1665MDString::MDString(const char *begin, const char *end)
1666 : Constant(Type::EmptyStructTy, MDStringVal, 0, 0),
1667 StrBegin(begin), StrEnd(end) {}
1668
1669static ManagedStatic<StringMap<MDString*> > MDStringCache;
1670
1671MDString *MDString::get(const char *StrBegin, const char *StrEnd) {
1672 StringMapEntry<MDString *> &Entry = MDStringCache->GetOrCreateValue(StrBegin,
1673 StrEnd);
1674 MDString *&S = Entry.getValue();
1675 if (!S) S = new MDString(Entry.getKeyData(),
1676 Entry.getKeyData() + Entry.getKeyLength());
1677 return S;
1678}
1679
1680void MDString::destroyConstant() {
1681 MDStringCache->erase(MDStringCache->find(StrBegin, StrEnd));
1682 destroyConstantImpl();
1683}
1684
1685//---- MDNode::get() implementation
1686//
1687
1688static ManagedStatic<FoldingSet<MDNode> > MDNodeSet;
1689
1690MDNode::MDNode(Constant*const* Vals, unsigned NumVals)
1691 : Constant(Type::EmptyStructTy, MDNodeVal,
1692 OperandTraits<MDNode>::op_end(this) - NumVals, NumVals) {
1693 std::copy(Vals, Vals + NumVals, OperandList);
1694}
1695
1696void MDNode::Profile(FoldingSetNodeID &ID) {
1697 for (op_iterator I = op_begin(), E = op_end(); I != E; ++I)
1698 ID.AddPointer(*I);
1699}
1700
1701MDNode *MDNode::get(Constant*const* Vals, unsigned NumVals) {
1702 FoldingSetNodeID ID;
1703 for (unsigned i = 0; i != NumVals; ++i)
1704 ID.AddPointer(Vals[i]);
1705
1706 void *InsertPoint;
1707 if (MDNode *N = MDNodeSet->FindNodeOrInsertPos(ID, InsertPoint))
1708 return N;
1709
1710 // InsertPoint will have been set by the FindNodeOrInsertPos call.
1711 MDNode *N = new(NumVals) MDNode(Vals, NumVals);
1712 MDNodeSet->InsertNode(N, InsertPoint);
1713 return N;
1714}
1715
1716void MDNode::destroyConstant() {
1717 destroyConstantImpl();
1718}
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001719
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001720//---- ConstantExpr::get() implementations...
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001721//
Reid Spencer8d9336d2006-12-31 05:26:44 +00001722
Dan Gohmand78c4002008-05-13 00:00:25 +00001723namespace {
1724
Reid Spenceree3c9912006-12-04 05:19:50 +00001725struct ExprMapKeyType {
Dan Gohman1ecaf452008-05-31 00:58:22 +00001726 typedef SmallVector<unsigned, 4> IndexList;
1727
1728 ExprMapKeyType(unsigned opc,
1729 const std::vector<Constant*> &ops,
1730 unsigned short pred = 0,
1731 const IndexList &inds = IndexList())
1732 : opcode(opc), predicate(pred), operands(ops), indices(inds) {}
Reid Spencerdba6aa42006-12-04 18:38:05 +00001733 uint16_t opcode;
1734 uint16_t predicate;
Reid Spenceree3c9912006-12-04 05:19:50 +00001735 std::vector<Constant*> operands;
Dan Gohman1ecaf452008-05-31 00:58:22 +00001736 IndexList indices;
Reid Spenceree3c9912006-12-04 05:19:50 +00001737 bool operator==(const ExprMapKeyType& that) const {
1738 return this->opcode == that.opcode &&
1739 this->predicate == that.predicate &&
Bill Wendling97f7de82008-10-26 00:19:56 +00001740 this->operands == that.operands &&
Dan Gohman1ecaf452008-05-31 00:58:22 +00001741 this->indices == that.indices;
Reid Spenceree3c9912006-12-04 05:19:50 +00001742 }
1743 bool operator<(const ExprMapKeyType & that) const {
1744 return this->opcode < that.opcode ||
1745 (this->opcode == that.opcode && this->predicate < that.predicate) ||
1746 (this->opcode == that.opcode && this->predicate == that.predicate &&
Dan Gohman1ecaf452008-05-31 00:58:22 +00001747 this->operands < that.operands) ||
1748 (this->opcode == that.opcode && this->predicate == that.predicate &&
1749 this->operands == that.operands && this->indices < that.indices);
Reid Spenceree3c9912006-12-04 05:19:50 +00001750 }
1751
1752 bool operator!=(const ExprMapKeyType& that) const {
1753 return !(*this == that);
1754 }
1755};
Chris Lattner98fa07b2003-05-23 20:03:32 +00001756
Dan Gohmand78c4002008-05-13 00:00:25 +00001757}
1758
Chris Lattner189d19f2003-11-21 20:23:48 +00001759namespace llvm {
1760 template<>
1761 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
Reid Spencer10fbf0e2006-12-03 05:48:19 +00001762 static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V,
1763 unsigned short pred = 0) {
Reid Spenceree3c9912006-12-04 05:19:50 +00001764 if (Instruction::isCast(V.opcode))
1765 return new UnaryConstantExpr(V.opcode, V.operands[0], Ty);
1766 if ((V.opcode >= Instruction::BinaryOpsBegin &&
Reid Spencer2341c222007-02-02 02:16:23 +00001767 V.opcode < Instruction::BinaryOpsEnd))
Reid Spenceree3c9912006-12-04 05:19:50 +00001768 return new BinaryConstantExpr(V.opcode, V.operands[0], V.operands[1]);
1769 if (V.opcode == Instruction::Select)
1770 return new SelectConstantExpr(V.operands[0], V.operands[1],
1771 V.operands[2]);
1772 if (V.opcode == Instruction::ExtractElement)
1773 return new ExtractElementConstantExpr(V.operands[0], V.operands[1]);
1774 if (V.opcode == Instruction::InsertElement)
1775 return new InsertElementConstantExpr(V.operands[0], V.operands[1],
1776 V.operands[2]);
1777 if (V.opcode == Instruction::ShuffleVector)
1778 return new ShuffleVectorConstantExpr(V.operands[0], V.operands[1],
1779 V.operands[2]);
Dan Gohman1ecaf452008-05-31 00:58:22 +00001780 if (V.opcode == Instruction::InsertValue)
1781 return new InsertValueConstantExpr(V.operands[0], V.operands[1],
1782 V.indices, Ty);
1783 if (V.opcode == Instruction::ExtractValue)
1784 return new ExtractValueConstantExpr(V.operands[0], V.indices, Ty);
Reid Spenceree3c9912006-12-04 05:19:50 +00001785 if (V.opcode == Instruction::GetElementPtr) {
1786 std::vector<Constant*> IdxList(V.operands.begin()+1, V.operands.end());
Gabor Greife9ecc682008-04-06 20:25:17 +00001787 return GetElementPtrConstantExpr::Create(V.operands[0], IdxList, Ty);
Reid Spenceree3c9912006-12-04 05:19:50 +00001788 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001789
Reid Spenceree3c9912006-12-04 05:19:50 +00001790 // The compare instructions are weird. We have to encode the predicate
1791 // value and it is combined with the instruction opcode by multiplying
1792 // the opcode by one hundred. We must decode this to get the predicate.
1793 if (V.opcode == Instruction::ICmp)
Nate Begemand2195702008-05-12 19:01:56 +00001794 return new CompareConstantExpr(Ty, Instruction::ICmp, V.predicate,
Reid Spenceree3c9912006-12-04 05:19:50 +00001795 V.operands[0], V.operands[1]);
1796 if (V.opcode == Instruction::FCmp)
Nate Begemand2195702008-05-12 19:01:56 +00001797 return new CompareConstantExpr(Ty, Instruction::FCmp, V.predicate,
1798 V.operands[0], V.operands[1]);
1799 if (V.opcode == Instruction::VICmp)
1800 return new CompareConstantExpr(Ty, Instruction::VICmp, V.predicate,
1801 V.operands[0], V.operands[1]);
1802 if (V.opcode == Instruction::VFCmp)
1803 return new CompareConstantExpr(Ty, Instruction::VFCmp, V.predicate,
Reid Spenceree3c9912006-12-04 05:19:50 +00001804 V.operands[0], V.operands[1]);
1805 assert(0 && "Invalid ConstantExpr!");
Jeff Cohen9f469632006-12-15 21:47:01 +00001806 return 0;
Chris Lattnerb50d1352003-10-05 00:17:43 +00001807 }
Chris Lattner189d19f2003-11-21 20:23:48 +00001808 };
Chris Lattnerb50d1352003-10-05 00:17:43 +00001809
Chris Lattner189d19f2003-11-21 20:23:48 +00001810 template<>
1811 struct ConvertConstantType<ConstantExpr, Type> {
1812 static void convert(ConstantExpr *OldC, const Type *NewTy) {
1813 Constant *New;
1814 switch (OldC->getOpcode()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001815 case Instruction::Trunc:
1816 case Instruction::ZExt:
1817 case Instruction::SExt:
1818 case Instruction::FPTrunc:
1819 case Instruction::FPExt:
1820 case Instruction::UIToFP:
1821 case Instruction::SIToFP:
1822 case Instruction::FPToUI:
1823 case Instruction::FPToSI:
1824 case Instruction::PtrToInt:
1825 case Instruction::IntToPtr:
1826 case Instruction::BitCast:
Reid Spencerbb65ebf2006-12-12 23:36:14 +00001827 New = ConstantExpr::getCast(OldC->getOpcode(), OldC->getOperand(0),
1828 NewTy);
Chris Lattner189d19f2003-11-21 20:23:48 +00001829 break;
Chris Lattner6e415c02004-03-12 05:54:04 +00001830 case Instruction::Select:
1831 New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1832 OldC->getOperand(1),
1833 OldC->getOperand(2));
1834 break;
Chris Lattner189d19f2003-11-21 20:23:48 +00001835 default:
1836 assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
Reid Spencer7eb55b32006-11-02 01:53:59 +00001837 OldC->getOpcode() < Instruction::BinaryOpsEnd);
Chris Lattner189d19f2003-11-21 20:23:48 +00001838 New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1839 OldC->getOperand(1));
1840 break;
1841 case Instruction::GetElementPtr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00001842 // Make everyone now use a constant of the new type...
Chris Lattner13128ab2004-10-11 22:52:25 +00001843 std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
Chris Lattner302116a2007-01-31 04:40:28 +00001844 New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0),
1845 &Idx[0], Idx.size());
Chris Lattner189d19f2003-11-21 20:23:48 +00001846 break;
1847 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001848
Chris Lattner189d19f2003-11-21 20:23:48 +00001849 assert(New != OldC && "Didn't replace constant??");
1850 OldC->uncheckedReplaceAllUsesWith(New);
1851 OldC->destroyConstant(); // This constant is now dead, destroy it.
1852 }
1853 };
1854} // end namespace llvm
Chris Lattnerb50d1352003-10-05 00:17:43 +00001855
1856
Chris Lattner3e650af2004-08-04 04:48:01 +00001857static ExprMapKeyType getValType(ConstantExpr *CE) {
1858 std::vector<Constant*> Operands;
1859 Operands.reserve(CE->getNumOperands());
1860 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
1861 Operands.push_back(cast<Constant>(CE->getOperand(i)));
Reid Spenceree3c9912006-12-04 05:19:50 +00001862 return ExprMapKeyType(CE->getOpcode(), Operands,
Dan Gohman1ecaf452008-05-31 00:58:22 +00001863 CE->isCompare() ? CE->getPredicate() : 0,
1864 CE->hasIndices() ?
1865 CE->getIndices() : SmallVector<unsigned, 4>());
Chris Lattner3e650af2004-08-04 04:48:01 +00001866}
1867
Chris Lattner69edc982006-09-28 00:35:06 +00001868static ManagedStatic<ValueMap<ExprMapKeyType, Type,
1869 ConstantExpr> > ExprConstants;
Vikram S. Adve4c485332002-07-15 18:19:33 +00001870
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001871/// This is a utility function to handle folding of casts and lookup of the
Duncan Sands7d6c8ae2008-03-30 19:38:55 +00001872/// cast in the ExprConstants map. It is used by the various get* methods below.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001873static inline Constant *getFoldedCast(
1874 Instruction::CastOps opc, Constant *C, const Type *Ty) {
Chris Lattner815ae2b2003-10-07 22:19:19 +00001875 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001876 // Fold a few common cases
1877 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
1878 return FC;
Chris Lattneracdbe712003-04-17 19:24:48 +00001879
Vikram S. Adve4c485332002-07-15 18:19:33 +00001880 // Look up the constant in the table first to ensure uniqueness
Chris Lattner2b383d2e2003-05-13 21:37:02 +00001881 std::vector<Constant*> argVec(1, C);
Reid Spenceree3c9912006-12-04 05:19:50 +00001882 ExprMapKeyType Key(opc, argVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001883 return ExprConstants->getOrCreate(Ty, Key);
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001884}
Reid Spencerf37dc652006-12-05 19:14:13 +00001885
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001886Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
1887 Instruction::CastOps opc = Instruction::CastOps(oc);
1888 assert(Instruction::isCast(opc) && "opcode out of range");
1889 assert(C && Ty && "Null arguments to getCast");
1890 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1891
1892 switch (opc) {
1893 default:
1894 assert(0 && "Invalid cast opcode");
1895 break;
1896 case Instruction::Trunc: return getTrunc(C, Ty);
Reid Spencerbb65ebf2006-12-12 23:36:14 +00001897 case Instruction::ZExt: return getZExt(C, Ty);
1898 case Instruction::SExt: return getSExt(C, Ty);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001899 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
1900 case Instruction::FPExt: return getFPExtend(C, Ty);
1901 case Instruction::UIToFP: return getUIToFP(C, Ty);
1902 case Instruction::SIToFP: return getSIToFP(C, Ty);
1903 case Instruction::FPToUI: return getFPToUI(C, Ty);
1904 case Instruction::FPToSI: return getFPToSI(C, Ty);
1905 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1906 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1907 case Instruction::BitCast: return getBitCast(C, Ty);
Chris Lattner1ece6f82005-01-01 15:59:57 +00001908 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001909 return 0;
Reid Spencerf37dc652006-12-05 19:14:13 +00001910}
1911
Reid Spencer5c140882006-12-04 20:17:56 +00001912Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
1913 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1914 return getCast(Instruction::BitCast, C, Ty);
1915 return getCast(Instruction::ZExt, C, Ty);
1916}
1917
1918Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
1919 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1920 return getCast(Instruction::BitCast, C, Ty);
1921 return getCast(Instruction::SExt, C, Ty);
1922}
1923
1924Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
1925 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1926 return getCast(Instruction::BitCast, C, Ty);
1927 return getCast(Instruction::Trunc, C, Ty);
1928}
1929
Reid Spencerbc245a02006-12-05 03:25:26 +00001930Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
1931 assert(isa<PointerType>(S->getType()) && "Invalid cast");
Chris Lattner03c49532007-01-15 02:27:26 +00001932 assert((Ty->isInteger() || isa<PointerType>(Ty)) && "Invalid cast");
Reid Spencerbc245a02006-12-05 03:25:26 +00001933
Chris Lattner03c49532007-01-15 02:27:26 +00001934 if (Ty->isInteger())
Reid Spencerbc245a02006-12-05 03:25:26 +00001935 return getCast(Instruction::PtrToInt, S, Ty);
1936 return getCast(Instruction::BitCast, S, Ty);
1937}
1938
Reid Spencer56521c42006-12-12 00:51:07 +00001939Constant *ConstantExpr::getIntegerCast(Constant *C, const Type *Ty,
1940 bool isSigned) {
Chris Lattner03c49532007-01-15 02:27:26 +00001941 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
Reid Spencer56521c42006-12-12 00:51:07 +00001942 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1943 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1944 Instruction::CastOps opcode =
1945 (SrcBits == DstBits ? Instruction::BitCast :
1946 (SrcBits > DstBits ? Instruction::Trunc :
1947 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1948 return getCast(opcode, C, Ty);
1949}
1950
1951Constant *ConstantExpr::getFPCast(Constant *C, const Type *Ty) {
1952 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1953 "Invalid cast");
1954 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1955 unsigned DstBits = Ty->getPrimitiveSizeInBits();
Reid Spencerca104e82006-12-12 05:38:50 +00001956 if (SrcBits == DstBits)
1957 return C; // Avoid a useless cast
Reid Spencer56521c42006-12-12 00:51:07 +00001958 Instruction::CastOps opcode =
Reid Spencerca104e82006-12-12 05:38:50 +00001959 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
Reid Spencer56521c42006-12-12 00:51:07 +00001960 return getCast(opcode, C, Ty);
1961}
1962
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001963Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
Chris Lattner03c49532007-01-15 02:27:26 +00001964 assert(C->getType()->isInteger() && "Trunc operand must be integer");
1965 assert(Ty->isInteger() && "Trunc produces only integral");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001966 assert(C->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()&&
1967 "SrcTy must be larger than DestTy for Trunc!");
1968
1969 return getFoldedCast(Instruction::Trunc, C, Ty);
1970}
1971
Reid Spencerbb65ebf2006-12-12 23:36:14 +00001972Constant *ConstantExpr::getSExt(Constant *C, const Type *Ty) {
Chris Lattner03c49532007-01-15 02:27:26 +00001973 assert(C->getType()->isInteger() && "SEXt operand must be integral");
1974 assert(Ty->isInteger() && "SExt produces only integer");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001975 assert(C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1976 "SrcTy must be smaller than DestTy for SExt!");
1977
1978 return getFoldedCast(Instruction::SExt, C, Ty);
Chris Lattnerdd284742004-04-04 23:20:30 +00001979}
1980
Reid Spencerbb65ebf2006-12-12 23:36:14 +00001981Constant *ConstantExpr::getZExt(Constant *C, const Type *Ty) {
Chris Lattner03c49532007-01-15 02:27:26 +00001982 assert(C->getType()->isInteger() && "ZEXt operand must be integral");
1983 assert(Ty->isInteger() && "ZExt produces only integer");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001984 assert(C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1985 "SrcTy must be smaller than DestTy for ZExt!");
1986
1987 return getFoldedCast(Instruction::ZExt, C, Ty);
1988}
1989
1990Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
1991 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1992 C->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()&&
1993 "This is an illegal floating point truncation!");
1994 return getFoldedCast(Instruction::FPTrunc, C, Ty);
1995}
1996
1997Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
1998 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1999 C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
2000 "This is an illegal floating point extension!");
2001 return getFoldedCast(Instruction::FPExt, C, Ty);
2002}
2003
2004Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
Devang Pateld26344d2008-11-03 23:20:04 +00002005#ifndef NDEBUG
Nate Begemand4d45c22007-11-17 03:58:34 +00002006 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2007 bool toVec = Ty->getTypeID() == Type::VectorTyID;
Devang Pateld26344d2008-11-03 23:20:04 +00002008#endif
Nate Begemand4d45c22007-11-17 03:58:34 +00002009 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2010 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
2011 "This is an illegal uint to floating point cast!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002012 return getFoldedCast(Instruction::UIToFP, C, Ty);
2013}
2014
2015Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
Devang Pateld26344d2008-11-03 23:20:04 +00002016#ifndef NDEBUG
Nate Begemand4d45c22007-11-17 03:58:34 +00002017 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2018 bool toVec = Ty->getTypeID() == Type::VectorTyID;
Devang Pateld26344d2008-11-03 23:20:04 +00002019#endif
Nate Begemand4d45c22007-11-17 03:58:34 +00002020 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2021 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002022 "This is an illegal sint to floating point cast!");
2023 return getFoldedCast(Instruction::SIToFP, C, Ty);
2024}
2025
2026Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
Devang Pateld26344d2008-11-03 23:20:04 +00002027#ifndef NDEBUG
Nate Begemand4d45c22007-11-17 03:58:34 +00002028 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2029 bool toVec = Ty->getTypeID() == Type::VectorTyID;
Devang Pateld26344d2008-11-03 23:20:04 +00002030#endif
Nate Begemand4d45c22007-11-17 03:58:34 +00002031 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2032 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
2033 "This is an illegal floating point to uint cast!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002034 return getFoldedCast(Instruction::FPToUI, C, Ty);
2035}
2036
2037Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
Devang Pateld26344d2008-11-03 23:20:04 +00002038#ifndef NDEBUG
Nate Begemand4d45c22007-11-17 03:58:34 +00002039 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2040 bool toVec = Ty->getTypeID() == Type::VectorTyID;
Devang Pateld26344d2008-11-03 23:20:04 +00002041#endif
Nate Begemand4d45c22007-11-17 03:58:34 +00002042 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2043 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
2044 "This is an illegal floating point to sint cast!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002045 return getFoldedCast(Instruction::FPToSI, C, Ty);
2046}
2047
2048Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
2049 assert(isa<PointerType>(C->getType()) && "PtrToInt source must be pointer");
Chris Lattner03c49532007-01-15 02:27:26 +00002050 assert(DstTy->isInteger() && "PtrToInt destination must be integral");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002051 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
2052}
2053
2054Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
Chris Lattner03c49532007-01-15 02:27:26 +00002055 assert(C->getType()->isInteger() && "IntToPtr source must be integral");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002056 assert(isa<PointerType>(DstTy) && "IntToPtr destination must be a pointer");
2057 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
2058}
2059
2060Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
2061 // BitCast implies a no-op cast of type only. No bits change. However, you
2062 // can't cast pointers to anything but pointers.
Devang Pateld26344d2008-11-03 23:20:04 +00002063#ifndef NDEBUG
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002064 const Type *SrcTy = C->getType();
2065 assert((isa<PointerType>(SrcTy) == isa<PointerType>(DstTy)) &&
Reid Spencer5c140882006-12-04 20:17:56 +00002066 "BitCast cannot cast pointer to non-pointer and vice versa");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002067
2068 // Now we know we're not dealing with mismatched pointer casts (ptr->nonptr
2069 // or nonptr->ptr). For all the other types, the cast is okay if source and
2070 // destination bit widths are identical.
2071 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
2072 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
Devang Pateld26344d2008-11-03 23:20:04 +00002073#endif
Chris Lattnere4086012009-03-08 04:06:26 +00002074 assert(SrcBitSize == DstBitSize && "BitCast requires types of same width");
Chris Lattnercbeda872009-03-21 06:55:54 +00002075
2076 // It is common to ask for a bitcast of a value to its own type, handle this
2077 // speedily.
2078 if (C->getType() == DstTy) return C;
2079
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002080 return getFoldedCast(Instruction::BitCast, C, DstTy);
Chris Lattnerdd284742004-04-04 23:20:30 +00002081}
2082
Alkis Evlogimenosda5de052004-10-24 01:41:10 +00002083Constant *ConstantExpr::getSizeOf(const Type *Ty) {
Gordon Henriksen7ce31762007-10-06 14:29:36 +00002084 // sizeof is implemented as: (i64) gep (Ty*)null, 1
Chris Lattnerb5d70302007-02-19 20:01:23 +00002085 Constant *GEPIdx = ConstantInt::get(Type::Int32Ty, 1);
2086 Constant *GEP =
Christopher Lambedf07882007-12-17 01:12:55 +00002087 getGetElementPtr(getNullValue(PointerType::getUnqual(Ty)), &GEPIdx, 1);
Chris Lattnerb5d70302007-02-19 20:01:23 +00002088 return getCast(Instruction::PtrToInt, GEP, Type::Int64Ty);
Alkis Evlogimenos9160d5f2005-03-19 11:40:31 +00002089}
2090
Chris Lattnerb50d1352003-10-05 00:17:43 +00002091Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
Reid Spencera009d0d2006-12-04 21:35:24 +00002092 Constant *C1, Constant *C2) {
Chris Lattner38a9bcd2003-05-21 17:49:25 +00002093 // Check the operands for consistency first
Reid Spencer7eb55b32006-11-02 01:53:59 +00002094 assert(Opcode >= Instruction::BinaryOpsBegin &&
2095 Opcode < Instruction::BinaryOpsEnd &&
Chris Lattner38a9bcd2003-05-21 17:49:25 +00002096 "Invalid opcode in binary constant expression");
2097 assert(C1->getType() == C2->getType() &&
2098 "Operand types in binary constant expression should match");
Chris Lattnerb50d1352003-10-05 00:17:43 +00002099
Reid Spencer542964f2007-01-11 18:21:29 +00002100 if (ReqTy == C1->getType() || ReqTy == Type::Int1Ty)
Chris Lattnerb50d1352003-10-05 00:17:43 +00002101 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
2102 return FC; // Fold a few common cases...
Chris Lattneracdbe712003-04-17 19:24:48 +00002103
Chris Lattner2b383d2e2003-05-13 21:37:02 +00002104 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
Reid Spencera009d0d2006-12-04 21:35:24 +00002105 ExprMapKeyType Key(Opcode, argVec);
Chris Lattner69edc982006-09-28 00:35:06 +00002106 return ExprConstants->getOrCreate(ReqTy, Key);
Vikram S. Adve4e537b22002-07-14 23:13:17 +00002107}
2108
Reid Spencer266e42b2006-12-23 06:05:41 +00002109Constant *ConstantExpr::getCompareTy(unsigned short predicate,
Nate Begeman098cc6f2008-07-25 17:56:27 +00002110 Constant *C1, Constant *C2) {
2111 bool isVectorType = C1->getType()->getTypeID() == Type::VectorTyID;
Reid Spencer266e42b2006-12-23 06:05:41 +00002112 switch (predicate) {
2113 default: assert(0 && "Invalid CmpInst predicate");
Nate Begemanc96e2e42008-07-25 17:35:37 +00002114 case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
2115 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
2116 case CmpInst::FCMP_ONE: case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
2117 case CmpInst::FCMP_UEQ: case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
2118 case CmpInst::FCMP_ULT: case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
2119 case CmpInst::FCMP_TRUE:
Nate Begeman098cc6f2008-07-25 17:56:27 +00002120 return isVectorType ? getVFCmp(predicate, C1, C2)
2121 : getFCmp(predicate, C1, C2);
Nate Begemanc96e2e42008-07-25 17:35:37 +00002122 case CmpInst::ICMP_EQ: case CmpInst::ICMP_NE: case CmpInst::ICMP_UGT:
2123 case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
2124 case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
2125 case CmpInst::ICMP_SLE:
Nate Begeman098cc6f2008-07-25 17:56:27 +00002126 return isVectorType ? getVICmp(predicate, C1, C2)
2127 : getICmp(predicate, C1, C2);
Reid Spencer266e42b2006-12-23 06:05:41 +00002128 }
Reid Spencera009d0d2006-12-04 21:35:24 +00002129}
2130
2131Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00002132#ifndef NDEBUG
2133 switch (Opcode) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00002134 case Instruction::Add:
2135 case Instruction::Sub:
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002136 case Instruction::Mul:
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00002137 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Chris Lattner03c49532007-01-15 02:27:26 +00002138 assert((C1->getType()->isInteger() || C1->getType()->isFloatingPoint() ||
Reid Spencerd84d35b2007-02-15 02:26:10 +00002139 isa<VectorType>(C1->getType())) &&
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00002140 "Tried to create an arithmetic operation on a non-arithmetic type!");
2141 break;
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002142 case Instruction::UDiv:
2143 case Instruction::SDiv:
2144 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00002145 assert((C1->getType()->isInteger() || (isa<VectorType>(C1->getType()) &&
2146 cast<VectorType>(C1->getType())->getElementType()->isInteger())) &&
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002147 "Tried to create an arithmetic operation on a non-arithmetic type!");
2148 break;
2149 case Instruction::FDiv:
2150 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00002151 assert((C1->getType()->isFloatingPoint() || (isa<VectorType>(C1->getType())
2152 && cast<VectorType>(C1->getType())->getElementType()->isFloatingPoint()))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002153 && "Tried to create an arithmetic operation on a non-arithmetic type!");
2154 break;
Reid Spencer7eb55b32006-11-02 01:53:59 +00002155 case Instruction::URem:
2156 case Instruction::SRem:
2157 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00002158 assert((C1->getType()->isInteger() || (isa<VectorType>(C1->getType()) &&
2159 cast<VectorType>(C1->getType())->getElementType()->isInteger())) &&
Reid Spencer7eb55b32006-11-02 01:53:59 +00002160 "Tried to create an arithmetic operation on a non-arithmetic type!");
2161 break;
2162 case Instruction::FRem:
2163 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00002164 assert((C1->getType()->isFloatingPoint() || (isa<VectorType>(C1->getType())
2165 && cast<VectorType>(C1->getType())->getElementType()->isFloatingPoint()))
Reid Spencer7eb55b32006-11-02 01:53:59 +00002166 && "Tried to create an arithmetic operation on a non-arithmetic type!");
2167 break;
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00002168 case Instruction::And:
2169 case Instruction::Or:
2170 case Instruction::Xor:
2171 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00002172 assert((C1->getType()->isInteger() || isa<VectorType>(C1->getType())) &&
Misha Brukman3852f652005-01-27 06:46:38 +00002173 "Tried to create a logical operation on a non-integral type!");
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00002174 break;
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00002175 case Instruction::Shl:
Reid Spencerfdff9382006-11-08 06:47:33 +00002176 case Instruction::LShr:
2177 case Instruction::AShr:
Reid Spencer2341c222007-02-02 02:16:23 +00002178 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Dan Gohman79975d52009-03-14 17:09:17 +00002179 assert(C1->getType()->isIntOrIntVector() &&
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00002180 "Tried to create a shift operation on a non-integer type!");
2181 break;
2182 default:
2183 break;
2184 }
2185#endif
2186
Reid Spencera009d0d2006-12-04 21:35:24 +00002187 return getTy(C1->getType(), Opcode, C1, C2);
2188}
2189
Reid Spencer266e42b2006-12-23 06:05:41 +00002190Constant *ConstantExpr::getCompare(unsigned short pred,
Reid Spencera009d0d2006-12-04 21:35:24 +00002191 Constant *C1, Constant *C2) {
2192 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Reid Spencer266e42b2006-12-23 06:05:41 +00002193 return getCompareTy(pred, C1, C2);
Chris Lattner29ca2c62004-08-04 18:50:09 +00002194}
2195
Chris Lattner6e415c02004-03-12 05:54:04 +00002196Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
2197 Constant *V1, Constant *V2) {
Chris Lattner41632132008-12-29 00:16:12 +00002198 assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
Chris Lattner6e415c02004-03-12 05:54:04 +00002199
2200 if (ReqTy == V1->getType())
2201 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
2202 return SC; // Fold common cases
2203
2204 std::vector<Constant*> argVec(3, C);
2205 argVec[1] = V1;
2206 argVec[2] = V2;
Reid Spenceree3c9912006-12-04 05:19:50 +00002207 ExprMapKeyType Key(Instruction::Select, argVec);
Chris Lattner69edc982006-09-28 00:35:06 +00002208 return ExprConstants->getOrCreate(ReqTy, Key);
Chris Lattner6e415c02004-03-12 05:54:04 +00002209}
2210
Chris Lattnerb50d1352003-10-05 00:17:43 +00002211Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
Chris Lattner302116a2007-01-31 04:40:28 +00002212 Value* const *Idxs,
2213 unsigned NumIdx) {
Dan Gohman12fce772008-05-15 19:50:34 +00002214 assert(GetElementPtrInst::getIndexedType(C->getType(), Idxs,
2215 Idxs+NumIdx) ==
2216 cast<PointerType>(ReqTy)->getElementType() &&
2217 "GEP indices invalid!");
Chris Lattner04b60fe2004-02-16 20:46:13 +00002218
Chris Lattner302116a2007-01-31 04:40:28 +00002219 if (Constant *FC = ConstantFoldGetElementPtr(C, (Constant**)Idxs, NumIdx))
Chris Lattneracdbe712003-04-17 19:24:48 +00002220 return FC; // Fold a few common cases...
Chris Lattner04b60fe2004-02-16 20:46:13 +00002221
Chris Lattnerb50d1352003-10-05 00:17:43 +00002222 assert(isa<PointerType>(C->getType()) &&
Chris Lattner98fa07b2003-05-23 20:03:32 +00002223 "Non-pointer type for constant GetElementPtr expression");
Vikram S. Adve4c485332002-07-15 18:19:33 +00002224 // Look up the constant in the table first to ensure uniqueness
Chris Lattner13128ab2004-10-11 22:52:25 +00002225 std::vector<Constant*> ArgVec;
Chris Lattner302116a2007-01-31 04:40:28 +00002226 ArgVec.reserve(NumIdx+1);
Chris Lattner13128ab2004-10-11 22:52:25 +00002227 ArgVec.push_back(C);
Chris Lattner302116a2007-01-31 04:40:28 +00002228 for (unsigned i = 0; i != NumIdx; ++i)
2229 ArgVec.push_back(cast<Constant>(Idxs[i]));
2230 const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec);
Chris Lattner69edc982006-09-28 00:35:06 +00002231 return ExprConstants->getOrCreate(ReqTy, Key);
Vikram S. Adve4c485332002-07-15 18:19:33 +00002232}
2233
Chris Lattner302116a2007-01-31 04:40:28 +00002234Constant *ConstantExpr::getGetElementPtr(Constant *C, Value* const *Idxs,
2235 unsigned NumIdx) {
Chris Lattnerb50d1352003-10-05 00:17:43 +00002236 // Get the result type of the getelementptr!
Chris Lattner302116a2007-01-31 04:40:28 +00002237 const Type *Ty =
Dan Gohman12fce772008-05-15 19:50:34 +00002238 GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx);
Chris Lattnerb50d1352003-10-05 00:17:43 +00002239 assert(Ty && "GEP indices invalid!");
Christopher Lamb54dd24c2007-12-11 08:59:05 +00002240 unsigned As = cast<PointerType>(C->getType())->getAddressSpace();
2241 return getGetElementPtrTy(PointerType::get(Ty, As), C, Idxs, NumIdx);
Chris Lattner13128ab2004-10-11 22:52:25 +00002242}
2243
Chris Lattner302116a2007-01-31 04:40:28 +00002244Constant *ConstantExpr::getGetElementPtr(Constant *C, Constant* const *Idxs,
2245 unsigned NumIdx) {
2246 return getGetElementPtr(C, (Value* const *)Idxs, NumIdx);
Chris Lattnerb50d1352003-10-05 00:17:43 +00002247}
2248
Chris Lattner302116a2007-01-31 04:40:28 +00002249
Reid Spenceree3c9912006-12-04 05:19:50 +00002250Constant *
2251ConstantExpr::getICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2252 assert(LHS->getType() == RHS->getType());
2253 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
2254 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
2255
Reid Spencer266e42b2006-12-23 06:05:41 +00002256 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
Reid Spenceree3c9912006-12-04 05:19:50 +00002257 return FC; // Fold a few common cases...
2258
2259 // Look up the constant in the table first to ensure uniqueness
2260 std::vector<Constant*> ArgVec;
2261 ArgVec.push_back(LHS);
2262 ArgVec.push_back(RHS);
Reid Spencerb1537492006-12-24 18:42:29 +00002263 // Get the key type with both the opcode and predicate
Reid Spenceree3c9912006-12-04 05:19:50 +00002264 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
Reid Spencer542964f2007-01-11 18:21:29 +00002265 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
Reid Spenceree3c9912006-12-04 05:19:50 +00002266}
2267
2268Constant *
2269ConstantExpr::getFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2270 assert(LHS->getType() == RHS->getType());
2271 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
2272
Reid Spencer266e42b2006-12-23 06:05:41 +00002273 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
Reid Spenceree3c9912006-12-04 05:19:50 +00002274 return FC; // Fold a few common cases...
2275
2276 // Look up the constant in the table first to ensure uniqueness
2277 std::vector<Constant*> ArgVec;
2278 ArgVec.push_back(LHS);
2279 ArgVec.push_back(RHS);
Reid Spencerb1537492006-12-24 18:42:29 +00002280 // Get the key type with both the opcode and predicate
Reid Spenceree3c9912006-12-04 05:19:50 +00002281 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
Reid Spencer542964f2007-01-11 18:21:29 +00002282 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
Reid Spenceree3c9912006-12-04 05:19:50 +00002283}
2284
Nate Begemand2195702008-05-12 19:01:56 +00002285Constant *
2286ConstantExpr::getVICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
Chris Lattnereab49262008-07-14 05:17:31 +00002287 assert(isa<VectorType>(LHS->getType()) && LHS->getType() == RHS->getType() &&
Nate Begemand2195702008-05-12 19:01:56 +00002288 "Tried to create vicmp operation on non-vector type!");
Nate Begemand2195702008-05-12 19:01:56 +00002289 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
2290 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid VICmp Predicate");
2291
Nate Begemanac7f3d92008-05-12 19:23:22 +00002292 const VectorType *VTy = cast<VectorType>(LHS->getType());
Nate Begemand2195702008-05-12 19:01:56 +00002293 const Type *EltTy = VTy->getElementType();
2294 unsigned NumElts = VTy->getNumElements();
2295
Chris Lattnereab49262008-07-14 05:17:31 +00002296 // See if we can fold the element-wise comparison of the LHS and RHS.
2297 SmallVector<Constant *, 16> LHSElts, RHSElts;
2298 LHS->getVectorElements(LHSElts);
2299 RHS->getVectorElements(RHSElts);
2300
2301 if (!LHSElts.empty() && !RHSElts.empty()) {
2302 SmallVector<Constant *, 16> Elts;
2303 for (unsigned i = 0; i != NumElts; ++i) {
2304 Constant *FC = ConstantFoldCompareInstruction(pred, LHSElts[i],
2305 RHSElts[i]);
2306 if (ConstantInt *FCI = dyn_cast_or_null<ConstantInt>(FC)) {
2307 if (FCI->getZExtValue())
2308 Elts.push_back(ConstantInt::getAllOnesValue(EltTy));
2309 else
2310 Elts.push_back(ConstantInt::get(EltTy, 0ULL));
2311 } else if (FC && isa<UndefValue>(FC)) {
2312 Elts.push_back(UndefValue::get(EltTy));
2313 } else {
2314 break;
2315 }
Nate Begemand2195702008-05-12 19:01:56 +00002316 }
Chris Lattnereab49262008-07-14 05:17:31 +00002317 if (Elts.size() == NumElts)
2318 return ConstantVector::get(&Elts[0], Elts.size());
Nate Begemand2195702008-05-12 19:01:56 +00002319 }
Nate Begemand2195702008-05-12 19:01:56 +00002320
2321 // Look up the constant in the table first to ensure uniqueness
2322 std::vector<Constant*> ArgVec;
2323 ArgVec.push_back(LHS);
2324 ArgVec.push_back(RHS);
2325 // Get the key type with both the opcode and predicate
2326 const ExprMapKeyType Key(Instruction::VICmp, ArgVec, pred);
2327 return ExprConstants->getOrCreate(LHS->getType(), Key);
2328}
2329
2330Constant *
2331ConstantExpr::getVFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2332 assert(isa<VectorType>(LHS->getType()) &&
2333 "Tried to create vfcmp operation on non-vector type!");
2334 assert(LHS->getType() == RHS->getType());
2335 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid VFCmp Predicate");
2336
2337 const VectorType *VTy = cast<VectorType>(LHS->getType());
2338 unsigned NumElts = VTy->getNumElements();
2339 const Type *EltTy = VTy->getElementType();
2340 const Type *REltTy = IntegerType::get(EltTy->getPrimitiveSizeInBits());
2341 const Type *ResultTy = VectorType::get(REltTy, NumElts);
2342
Chris Lattnereab49262008-07-14 05:17:31 +00002343 // See if we can fold the element-wise comparison of the LHS and RHS.
2344 SmallVector<Constant *, 16> LHSElts, RHSElts;
2345 LHS->getVectorElements(LHSElts);
2346 RHS->getVectorElements(RHSElts);
2347
2348 if (!LHSElts.empty() && !RHSElts.empty()) {
2349 SmallVector<Constant *, 16> Elts;
2350 for (unsigned i = 0; i != NumElts; ++i) {
2351 Constant *FC = ConstantFoldCompareInstruction(pred, LHSElts[i],
2352 RHSElts[i]);
2353 if (ConstantInt *FCI = dyn_cast_or_null<ConstantInt>(FC)) {
2354 if (FCI->getZExtValue())
2355 Elts.push_back(ConstantInt::getAllOnesValue(REltTy));
2356 else
2357 Elts.push_back(ConstantInt::get(REltTy, 0ULL));
2358 } else if (FC && isa<UndefValue>(FC)) {
2359 Elts.push_back(UndefValue::get(REltTy));
2360 } else {
2361 break;
2362 }
Nate Begemand2195702008-05-12 19:01:56 +00002363 }
Chris Lattnereab49262008-07-14 05:17:31 +00002364 if (Elts.size() == NumElts)
2365 return ConstantVector::get(&Elts[0], Elts.size());
Nate Begemand2195702008-05-12 19:01:56 +00002366 }
Nate Begemand2195702008-05-12 19:01:56 +00002367
2368 // Look up the constant in the table first to ensure uniqueness
2369 std::vector<Constant*> ArgVec;
2370 ArgVec.push_back(LHS);
2371 ArgVec.push_back(RHS);
2372 // Get the key type with both the opcode and predicate
2373 const ExprMapKeyType Key(Instruction::VFCmp, ArgVec, pred);
2374 return ExprConstants->getOrCreate(ResultTy, Key);
2375}
2376
Robert Bocchino23004482006-01-10 19:05:34 +00002377Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
2378 Constant *Idx) {
Robert Bocchinode7f1c92006-01-10 20:03:46 +00002379 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
2380 return FC; // Fold a few common cases...
Robert Bocchino23004482006-01-10 19:05:34 +00002381 // Look up the constant in the table first to ensure uniqueness
2382 std::vector<Constant*> ArgVec(1, Val);
2383 ArgVec.push_back(Idx);
Reid Spenceree3c9912006-12-04 05:19:50 +00002384 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
Chris Lattner69edc982006-09-28 00:35:06 +00002385 return ExprConstants->getOrCreate(ReqTy, Key);
Robert Bocchino23004482006-01-10 19:05:34 +00002386}
2387
2388Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00002389 assert(isa<VectorType>(Val->getType()) &&
Reid Spencer09575ba2007-02-15 03:39:18 +00002390 "Tried to create extractelement operation on non-vector type!");
Reid Spencer8d9336d2006-12-31 05:26:44 +00002391 assert(Idx->getType() == Type::Int32Ty &&
Reid Spencer2546b762007-01-26 07:37:34 +00002392 "Extractelement index must be i32 type!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00002393 return getExtractElementTy(cast<VectorType>(Val->getType())->getElementType(),
Robert Bocchino23004482006-01-10 19:05:34 +00002394 Val, Idx);
2395}
Chris Lattnerb50d1352003-10-05 00:17:43 +00002396
Robert Bocchinoca27f032006-01-17 20:07:22 +00002397Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
2398 Constant *Elt, Constant *Idx) {
2399 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
2400 return FC; // Fold a few common cases...
2401 // Look up the constant in the table first to ensure uniqueness
2402 std::vector<Constant*> ArgVec(1, Val);
2403 ArgVec.push_back(Elt);
2404 ArgVec.push_back(Idx);
Reid Spenceree3c9912006-12-04 05:19:50 +00002405 const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
Chris Lattner69edc982006-09-28 00:35:06 +00002406 return ExprConstants->getOrCreate(ReqTy, Key);
Robert Bocchinoca27f032006-01-17 20:07:22 +00002407}
2408
2409Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
2410 Constant *Idx) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00002411 assert(isa<VectorType>(Val->getType()) &&
Reid Spencer09575ba2007-02-15 03:39:18 +00002412 "Tried to create insertelement operation on non-vector type!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00002413 assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType()
Robert Bocchinoca27f032006-01-17 20:07:22 +00002414 && "Insertelement types must match!");
Reid Spencer8d9336d2006-12-31 05:26:44 +00002415 assert(Idx->getType() == Type::Int32Ty &&
Reid Spencer2546b762007-01-26 07:37:34 +00002416 "Insertelement index must be i32 type!");
Gordon Henriksenb52d1ed2008-08-30 15:41:51 +00002417 return getInsertElementTy(Val->getType(), Val, Elt, Idx);
Robert Bocchinoca27f032006-01-17 20:07:22 +00002418}
2419
Chris Lattnerbbe0a422006-04-08 01:18:18 +00002420Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
2421 Constant *V2, Constant *Mask) {
2422 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
2423 return FC; // Fold a few common cases...
2424 // Look up the constant in the table first to ensure uniqueness
2425 std::vector<Constant*> ArgVec(1, V1);
2426 ArgVec.push_back(V2);
2427 ArgVec.push_back(Mask);
Reid Spenceree3c9912006-12-04 05:19:50 +00002428 const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
Chris Lattner69edc982006-09-28 00:35:06 +00002429 return ExprConstants->getOrCreate(ReqTy, Key);
Chris Lattnerbbe0a422006-04-08 01:18:18 +00002430}
2431
2432Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
2433 Constant *Mask) {
2434 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
2435 "Invalid shuffle vector constant expr operands!");
Nate Begeman94aa38d2009-02-12 21:28:33 +00002436
2437 unsigned NElts = cast<VectorType>(Mask->getType())->getNumElements();
2438 const Type *EltTy = cast<VectorType>(V1->getType())->getElementType();
2439 const Type *ShufTy = VectorType::get(EltTy, NElts);
2440 return getShuffleVectorTy(ShufTy, V1, V2, Mask);
Chris Lattnerbbe0a422006-04-08 01:18:18 +00002441}
2442
Dan Gohman12fce772008-05-15 19:50:34 +00002443Constant *ConstantExpr::getInsertValueTy(const Type *ReqTy, Constant *Agg,
2444 Constant *Val,
Dan Gohman1ecaf452008-05-31 00:58:22 +00002445 const unsigned *Idxs, unsigned NumIdx) {
Dan Gohman12fce772008-05-15 19:50:34 +00002446 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
2447 Idxs+NumIdx) == Val->getType() &&
2448 "insertvalue indices invalid!");
2449 assert(Agg->getType() == ReqTy &&
2450 "insertvalue type invalid!");
Dan Gohman0752bff2008-05-23 00:36:11 +00002451 assert(Agg->getType()->isFirstClassType() &&
2452 "Non-first-class type for constant InsertValue expression");
Dan Gohmand5d24f62008-07-21 23:30:30 +00002453 Constant *FC = ConstantFoldInsertValueInstruction(Agg, Val, Idxs, NumIdx);
2454 assert(FC && "InsertValue constant expr couldn't be folded!");
2455 return FC;
Dan Gohman12fce772008-05-15 19:50:34 +00002456}
2457
2458Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
Dan Gohman1ecaf452008-05-31 00:58:22 +00002459 const unsigned *IdxList, unsigned NumIdx) {
Dan Gohman0752bff2008-05-23 00:36:11 +00002460 assert(Agg->getType()->isFirstClassType() &&
2461 "Tried to create insertelement operation on non-first-class type!");
Dan Gohman12fce772008-05-15 19:50:34 +00002462
Dan Gohman0752bff2008-05-23 00:36:11 +00002463 const Type *ReqTy = Agg->getType();
Devang Pateld26344d2008-11-03 23:20:04 +00002464#ifndef NDEBUG
Dan Gohman0752bff2008-05-23 00:36:11 +00002465 const Type *ValTy =
Dan Gohman12fce772008-05-15 19:50:34 +00002466 ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
Devang Pateld26344d2008-11-03 23:20:04 +00002467#endif
Dan Gohman0752bff2008-05-23 00:36:11 +00002468 assert(ValTy == Val->getType() && "insertvalue indices invalid!");
Dan Gohman12fce772008-05-15 19:50:34 +00002469 return getInsertValueTy(ReqTy, Agg, Val, IdxList, NumIdx);
2470}
2471
2472Constant *ConstantExpr::getExtractValueTy(const Type *ReqTy, Constant *Agg,
Dan Gohman1ecaf452008-05-31 00:58:22 +00002473 const unsigned *Idxs, unsigned NumIdx) {
Dan Gohman12fce772008-05-15 19:50:34 +00002474 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
2475 Idxs+NumIdx) == ReqTy &&
2476 "extractvalue indices invalid!");
Dan Gohman0752bff2008-05-23 00:36:11 +00002477 assert(Agg->getType()->isFirstClassType() &&
2478 "Non-first-class type for constant extractvalue expression");
Dan Gohmand5d24f62008-07-21 23:30:30 +00002479 Constant *FC = ConstantFoldExtractValueInstruction(Agg, Idxs, NumIdx);
2480 assert(FC && "ExtractValue constant expr couldn't be folded!");
2481 return FC;
Dan Gohman12fce772008-05-15 19:50:34 +00002482}
2483
2484Constant *ConstantExpr::getExtractValue(Constant *Agg,
Dan Gohman1ecaf452008-05-31 00:58:22 +00002485 const unsigned *IdxList, unsigned NumIdx) {
Dan Gohman0752bff2008-05-23 00:36:11 +00002486 assert(Agg->getType()->isFirstClassType() &&
2487 "Tried to create extractelement operation on non-first-class type!");
Dan Gohman12fce772008-05-15 19:50:34 +00002488
2489 const Type *ReqTy =
2490 ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
2491 assert(ReqTy && "extractvalue indices invalid!");
2492 return getExtractValueTy(ReqTy, Agg, IdxList, NumIdx);
2493}
2494
Reid Spencer2eadb532007-01-21 00:29:26 +00002495Constant *ConstantExpr::getZeroValueForNegationExpr(const Type *Ty) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00002496 if (const VectorType *PTy = dyn_cast<VectorType>(Ty))
Reid Spencer6598ca82007-01-21 02:29:10 +00002497 if (PTy->getElementType()->isFloatingPoint()) {
2498 std::vector<Constant*> zeros(PTy->getNumElements(),
Dale Johannesen98d3a082007-09-14 22:26:36 +00002499 ConstantFP::getNegativeZero(PTy->getElementType()));
Reid Spencerd84d35b2007-02-15 02:26:10 +00002500 return ConstantVector::get(PTy, zeros);
Reid Spencer6598ca82007-01-21 02:29:10 +00002501 }
Reid Spencer2eadb532007-01-21 00:29:26 +00002502
Dale Johannesen98d3a082007-09-14 22:26:36 +00002503 if (Ty->isFloatingPoint())
2504 return ConstantFP::getNegativeZero(Ty);
Reid Spencer2eadb532007-01-21 00:29:26 +00002505
2506 return Constant::getNullValue(Ty);
2507}
2508
Vikram S. Adve4c485332002-07-15 18:19:33 +00002509// destroyConstant - Remove the constant from the constant table...
2510//
2511void ConstantExpr::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00002512 ExprConstants->remove(this);
Vikram S. Adve4c485332002-07-15 18:19:33 +00002513 destroyConstantImpl();
Vikram S. Adve4e537b22002-07-14 23:13:17 +00002514}
2515
Chris Lattner3cd8c562002-07-30 18:54:25 +00002516const char *ConstantExpr::getOpcodeName() const {
2517 return Instruction::getOpcodeName(getOpcode());
Vikram S. Adve4e537b22002-07-14 23:13:17 +00002518}
Reid Spencer1ebe1ab2004-07-17 23:48:33 +00002519
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002520//===----------------------------------------------------------------------===//
2521// replaceUsesOfWithOnConstant implementations
2522
Chris Lattner913849b2007-08-21 00:55:23 +00002523/// replaceUsesOfWithOnConstant - Update this constant array to change uses of
2524/// 'From' to be uses of 'To'. This must update the uniquing data structures
2525/// etc.
2526///
2527/// Note that we intentionally replace all uses of From with To here. Consider
2528/// a large array that uses 'From' 1000 times. By handling this case all here,
2529/// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
2530/// single invocation handles all 1000 uses. Handling them one at a time would
2531/// work, but would be really slow because it would have to unique each updated
2532/// array instance.
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002533void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
Chris Lattner7a1450d2005-10-04 18:13:04 +00002534 Use *U) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002535 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
Chris Lattner8760ec72005-10-04 01:17:50 +00002536 Constant *ToC = cast<Constant>(To);
Chris Lattnerdff59112005-10-04 18:47:09 +00002537
Jim Laskeyc03caef2006-07-17 17:38:29 +00002538 std::pair<ArrayConstantsTy::MapKey, Constant*> Lookup;
Chris Lattnerb64419a2005-10-03 22:51:37 +00002539 Lookup.first.first = getType();
2540 Lookup.second = this;
Chris Lattnerdff59112005-10-04 18:47:09 +00002541
Chris Lattnerb64419a2005-10-03 22:51:37 +00002542 std::vector<Constant*> &Values = Lookup.first.second;
2543 Values.reserve(getNumOperands()); // Build replacement array.
Chris Lattnerdff59112005-10-04 18:47:09 +00002544
Chris Lattner8760ec72005-10-04 01:17:50 +00002545 // Fill values with the modified operands of the constant array. Also,
2546 // compute whether this turns into an all-zeros array.
Chris Lattnerdff59112005-10-04 18:47:09 +00002547 bool isAllZeros = false;
Chris Lattner913849b2007-08-21 00:55:23 +00002548 unsigned NumUpdated = 0;
Chris Lattnerdff59112005-10-04 18:47:09 +00002549 if (!ToC->isNullValue()) {
Chris Lattner913849b2007-08-21 00:55:23 +00002550 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2551 Constant *Val = cast<Constant>(O->get());
2552 if (Val == From) {
2553 Val = ToC;
2554 ++NumUpdated;
2555 }
2556 Values.push_back(Val);
2557 }
Chris Lattnerdff59112005-10-04 18:47:09 +00002558 } else {
2559 isAllZeros = true;
2560 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2561 Constant *Val = cast<Constant>(O->get());
Chris Lattner913849b2007-08-21 00:55:23 +00002562 if (Val == From) {
2563 Val = ToC;
2564 ++NumUpdated;
2565 }
Chris Lattnerdff59112005-10-04 18:47:09 +00002566 Values.push_back(Val);
2567 if (isAllZeros) isAllZeros = Val->isNullValue();
2568 }
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002569 }
2570
Chris Lattnerb64419a2005-10-03 22:51:37 +00002571 Constant *Replacement = 0;
2572 if (isAllZeros) {
2573 Replacement = ConstantAggregateZero::get(getType());
2574 } else {
2575 // Check to see if we have this array type already.
2576 bool Exists;
Jim Laskeyc03caef2006-07-17 17:38:29 +00002577 ArrayConstantsTy::MapTy::iterator I =
Chris Lattner69edc982006-09-28 00:35:06 +00002578 ArrayConstants->InsertOrGetItem(Lookup, Exists);
Chris Lattnerb64419a2005-10-03 22:51:37 +00002579
2580 if (Exists) {
2581 Replacement = I->second;
2582 } else {
2583 // Okay, the new shape doesn't exist in the system yet. Instead of
2584 // creating a new constant array, inserting it, replaceallusesof'ing the
2585 // old with the new, then deleting the old... just update the current one
2586 // in place!
Chris Lattner69edc982006-09-28 00:35:06 +00002587 ArrayConstants->MoveConstantToNewSlot(this, I);
Chris Lattnerb64419a2005-10-03 22:51:37 +00002588
Chris Lattner913849b2007-08-21 00:55:23 +00002589 // Update to the new value. Optimize for the case when we have a single
2590 // operand that we're changing, but handle bulk updates efficiently.
2591 if (NumUpdated == 1) {
2592 unsigned OperandToUpdate = U-OperandList;
2593 assert(getOperand(OperandToUpdate) == From &&
2594 "ReplaceAllUsesWith broken!");
2595 setOperand(OperandToUpdate, ToC);
2596 } else {
2597 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2598 if (getOperand(i) == From)
2599 setOperand(i, ToC);
2600 }
Chris Lattnerb64419a2005-10-03 22:51:37 +00002601 return;
2602 }
2603 }
2604
2605 // Otherwise, I do need to replace this with an existing value.
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002606 assert(Replacement != this && "I didn't contain From!");
2607
Chris Lattner7a1450d2005-10-04 18:13:04 +00002608 // Everyone using this now uses the replacement.
2609 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002610
2611 // Delete the old constant!
2612 destroyConstant();
2613}
2614
2615void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
Chris Lattner7a1450d2005-10-04 18:13:04 +00002616 Use *U) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002617 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
Chris Lattner8760ec72005-10-04 01:17:50 +00002618 Constant *ToC = cast<Constant>(To);
2619
Chris Lattnerdff59112005-10-04 18:47:09 +00002620 unsigned OperandToUpdate = U-OperandList;
2621 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
2622
Jim Laskeyc03caef2006-07-17 17:38:29 +00002623 std::pair<StructConstantsTy::MapKey, Constant*> Lookup;
Chris Lattner8760ec72005-10-04 01:17:50 +00002624 Lookup.first.first = getType();
2625 Lookup.second = this;
2626 std::vector<Constant*> &Values = Lookup.first.second;
2627 Values.reserve(getNumOperands()); // Build replacement struct.
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002628
Chris Lattnerdff59112005-10-04 18:47:09 +00002629
Chris Lattner8760ec72005-10-04 01:17:50 +00002630 // Fill values with the modified operands of the constant struct. Also,
2631 // compute whether this turns into an all-zeros struct.
Chris Lattnerdff59112005-10-04 18:47:09 +00002632 bool isAllZeros = false;
2633 if (!ToC->isNullValue()) {
2634 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
2635 Values.push_back(cast<Constant>(O->get()));
2636 } else {
2637 isAllZeros = true;
2638 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2639 Constant *Val = cast<Constant>(O->get());
2640 Values.push_back(Val);
2641 if (isAllZeros) isAllZeros = Val->isNullValue();
2642 }
Chris Lattner8760ec72005-10-04 01:17:50 +00002643 }
Chris Lattnerdff59112005-10-04 18:47:09 +00002644 Values[OperandToUpdate] = ToC;
2645
Chris Lattner8760ec72005-10-04 01:17:50 +00002646 Constant *Replacement = 0;
2647 if (isAllZeros) {
2648 Replacement = ConstantAggregateZero::get(getType());
2649 } else {
2650 // Check to see if we have this array type already.
2651 bool Exists;
Jim Laskeyc03caef2006-07-17 17:38:29 +00002652 StructConstantsTy::MapTy::iterator I =
Chris Lattner69edc982006-09-28 00:35:06 +00002653 StructConstants->InsertOrGetItem(Lookup, Exists);
Chris Lattner8760ec72005-10-04 01:17:50 +00002654
2655 if (Exists) {
2656 Replacement = I->second;
2657 } else {
2658 // Okay, the new shape doesn't exist in the system yet. Instead of
2659 // creating a new constant struct, inserting it, replaceallusesof'ing the
2660 // old with the new, then deleting the old... just update the current one
2661 // in place!
Chris Lattner69edc982006-09-28 00:35:06 +00002662 StructConstants->MoveConstantToNewSlot(this, I);
Chris Lattner8760ec72005-10-04 01:17:50 +00002663
Chris Lattnerdff59112005-10-04 18:47:09 +00002664 // Update to the new value.
2665 setOperand(OperandToUpdate, ToC);
Chris Lattner8760ec72005-10-04 01:17:50 +00002666 return;
2667 }
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002668 }
2669
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002670 assert(Replacement != this && "I didn't contain From!");
2671
Chris Lattner7a1450d2005-10-04 18:13:04 +00002672 // Everyone using this now uses the replacement.
2673 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002674
2675 // Delete the old constant!
2676 destroyConstant();
2677}
2678
Reid Spencerd84d35b2007-02-15 02:26:10 +00002679void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
Chris Lattner7a1450d2005-10-04 18:13:04 +00002680 Use *U) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002681 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2682
2683 std::vector<Constant*> Values;
2684 Values.reserve(getNumOperands()); // Build replacement array...
2685 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2686 Constant *Val = getOperand(i);
2687 if (Val == From) Val = cast<Constant>(To);
2688 Values.push_back(Val);
2689 }
2690
Reid Spencerd84d35b2007-02-15 02:26:10 +00002691 Constant *Replacement = ConstantVector::get(getType(), Values);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002692 assert(Replacement != this && "I didn't contain From!");
2693
Chris Lattner7a1450d2005-10-04 18:13:04 +00002694 // Everyone using this now uses the replacement.
2695 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002696
2697 // Delete the old constant!
2698 destroyConstant();
2699}
2700
2701void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
Chris Lattner7a1450d2005-10-04 18:13:04 +00002702 Use *U) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002703 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2704 Constant *To = cast<Constant>(ToV);
2705
2706 Constant *Replacement = 0;
2707 if (getOpcode() == Instruction::GetElementPtr) {
Chris Lattnerb5d70302007-02-19 20:01:23 +00002708 SmallVector<Constant*, 8> Indices;
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002709 Constant *Pointer = getOperand(0);
2710 Indices.reserve(getNumOperands()-1);
2711 if (Pointer == From) Pointer = To;
2712
2713 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2714 Constant *Val = getOperand(i);
2715 if (Val == From) Val = To;
2716 Indices.push_back(Val);
2717 }
Chris Lattnerb5d70302007-02-19 20:01:23 +00002718 Replacement = ConstantExpr::getGetElementPtr(Pointer,
2719 &Indices[0], Indices.size());
Dan Gohman12fce772008-05-15 19:50:34 +00002720 } else if (getOpcode() == Instruction::ExtractValue) {
Dan Gohman12fce772008-05-15 19:50:34 +00002721 Constant *Agg = getOperand(0);
Dan Gohman12fce772008-05-15 19:50:34 +00002722 if (Agg == From) Agg = To;
2723
Dan Gohman1ecaf452008-05-31 00:58:22 +00002724 const SmallVector<unsigned, 4> &Indices = getIndices();
Dan Gohman12fce772008-05-15 19:50:34 +00002725 Replacement = ConstantExpr::getExtractValue(Agg,
2726 &Indices[0], Indices.size());
2727 } else if (getOpcode() == Instruction::InsertValue) {
Dan Gohman12fce772008-05-15 19:50:34 +00002728 Constant *Agg = getOperand(0);
2729 Constant *Val = getOperand(1);
Dan Gohman12fce772008-05-15 19:50:34 +00002730 if (Agg == From) Agg = To;
2731 if (Val == From) Val = To;
2732
Dan Gohman1ecaf452008-05-31 00:58:22 +00002733 const SmallVector<unsigned, 4> &Indices = getIndices();
Dan Gohman12fce772008-05-15 19:50:34 +00002734 Replacement = ConstantExpr::getInsertValue(Agg, Val,
2735 &Indices[0], Indices.size());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002736 } else if (isCast()) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002737 assert(getOperand(0) == From && "Cast only has one use!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002738 Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002739 } else if (getOpcode() == Instruction::Select) {
2740 Constant *C1 = getOperand(0);
2741 Constant *C2 = getOperand(1);
2742 Constant *C3 = getOperand(2);
2743 if (C1 == From) C1 = To;
2744 if (C2 == From) C2 = To;
2745 if (C3 == From) C3 = To;
2746 Replacement = ConstantExpr::getSelect(C1, C2, C3);
Robert Bocchino23004482006-01-10 19:05:34 +00002747 } else if (getOpcode() == Instruction::ExtractElement) {
2748 Constant *C1 = getOperand(0);
2749 Constant *C2 = getOperand(1);
2750 if (C1 == From) C1 = To;
2751 if (C2 == From) C2 = To;
2752 Replacement = ConstantExpr::getExtractElement(C1, C2);
Chris Lattnera93b4b52006-04-08 05:09:48 +00002753 } else if (getOpcode() == Instruction::InsertElement) {
2754 Constant *C1 = getOperand(0);
2755 Constant *C2 = getOperand(1);
2756 Constant *C3 = getOperand(1);
2757 if (C1 == From) C1 = To;
2758 if (C2 == From) C2 = To;
2759 if (C3 == From) C3 = To;
2760 Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2761 } else if (getOpcode() == Instruction::ShuffleVector) {
2762 Constant *C1 = getOperand(0);
2763 Constant *C2 = getOperand(1);
2764 Constant *C3 = getOperand(2);
2765 if (C1 == From) C1 = To;
2766 if (C2 == From) C2 = To;
2767 if (C3 == From) C3 = To;
2768 Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
Reid Spenceree3c9912006-12-04 05:19:50 +00002769 } else if (isCompare()) {
2770 Constant *C1 = getOperand(0);
2771 Constant *C2 = getOperand(1);
2772 if (C1 == From) C1 = To;
2773 if (C2 == From) C2 = To;
2774 if (getOpcode() == Instruction::ICmp)
2775 Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
Chris Lattnereab49262008-07-14 05:17:31 +00002776 else if (getOpcode() == Instruction::FCmp)
Reid Spenceree3c9912006-12-04 05:19:50 +00002777 Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
Chris Lattnereab49262008-07-14 05:17:31 +00002778 else if (getOpcode() == Instruction::VICmp)
2779 Replacement = ConstantExpr::getVICmp(getPredicate(), C1, C2);
2780 else {
2781 assert(getOpcode() == Instruction::VFCmp);
2782 Replacement = ConstantExpr::getVFCmp(getPredicate(), C1, C2);
2783 }
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002784 } else if (getNumOperands() == 2) {
2785 Constant *C1 = getOperand(0);
2786 Constant *C2 = getOperand(1);
2787 if (C1 == From) C1 = To;
2788 if (C2 == From) C2 = To;
2789 Replacement = ConstantExpr::get(getOpcode(), C1, C2);
2790 } else {
2791 assert(0 && "Unknown ConstantExpr type!");
2792 return;
2793 }
2794
2795 assert(Replacement != this && "I didn't contain From!");
2796
Chris Lattner7a1450d2005-10-04 18:13:04 +00002797 // Everyone using this now uses the replacement.
2798 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002799
2800 // Delete the old constant!
2801 destroyConstant();
Matthijs Kooijmanba5d7ef2008-07-03 07:46:41 +00002802}
Nick Lewycky49f89192009-04-04 07:22:01 +00002803
2804void MDNode::replaceUsesOfWithOnConstant(Value *From, Value *To, Use *U) {
2805 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2806
2807 SmallVector<Constant*, 8> Values;
2808 Values.reserve(getNumOperands()); // Build replacement array...
2809 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2810 Constant *Val = getOperand(i);
2811 if (Val == From) Val = cast<Constant>(To);
2812 Values.push_back(Val);
2813 }
2814
2815 Constant *Replacement = MDNode::get(&Values[0], Values.size());
2816 assert(Replacement != this && "I didn't contain From!");
2817
2818 // Everyone using this now uses the replacement.
2819 uncheckedReplaceAllUsesWith(Replacement);
2820
2821 // Delete the old constant!
2822 destroyConstant();
2823}