blob: d3f9b7f45b7545f3bf6014b602d0b1896c257856 [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"
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +000019#include "llvm/MDNode.h"
Chris Lattnerd7a73302001-10-13 06:57:33 +000020#include "llvm/Module.h"
Nick Lewycky49f89192009-04-04 07:22:01 +000021#include "llvm/ADT/FoldingSet.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000022#include "llvm/ADT/StringExtras.h"
Nick Lewycky49f89192009-04-04 07:22:01 +000023#include "llvm/ADT/StringMap.h"
Chris Lattner3d27be12006-08-27 12:54:02 +000024#include "llvm/Support/Compiler.h"
Bill Wendling6a462f12006-11-17 08:03:48 +000025#include "llvm/Support/Debug.h"
Chris Lattner69edc982006-09-28 00:35:06 +000026#include "llvm/Support/ManagedStatic.h"
Bill Wendling6a462f12006-11-17 08:03:48 +000027#include "llvm/Support/MathExtras.h"
Chris Lattnera80bf0b2007-02-20 06:39:57 +000028#include "llvm/ADT/DenseMap.h"
Chris Lattnerb5d70302007-02-19 20:01:23 +000029#include "llvm/ADT/SmallVector.h"
Chris Lattner2f7c9632001-06-06 20:29:01 +000030#include <algorithm>
Reid Spencer3aaaa0b2007-02-05 20:47:22 +000031#include <map>
Chris Lattner189d19f2003-11-21 20:23:48 +000032using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000033
Chris Lattner2f7c9632001-06-06 20:29:01 +000034//===----------------------------------------------------------------------===//
Chris Lattner3462ae32001-12-03 22:26:30 +000035// Constant Class
Chris Lattner2f7c9632001-06-06 20:29:01 +000036//===----------------------------------------------------------------------===//
37
Chris Lattner3462ae32001-12-03 22:26:30 +000038void Constant::destroyConstantImpl() {
39 // When a Constant is destroyed, there may be lingering
Chris Lattnerd7a73302001-10-13 06:57:33 +000040 // references to the constant by other constants in the constant pool. These
Misha Brukmanbe372b92003-08-21 22:14:26 +000041 // constants are implicitly dependent on the module that is being deleted,
Chris Lattnerd7a73302001-10-13 06:57:33 +000042 // but they don't know that. Because we only find out when the CPV is
43 // deleted, we must now notify all of our users (that should only be
Chris Lattner3462ae32001-12-03 22:26:30 +000044 // Constants) that they are, in fact, invalid now and should be deleted.
Chris Lattnerd7a73302001-10-13 06:57:33 +000045 //
46 while (!use_empty()) {
47 Value *V = use_back();
48#ifndef NDEBUG // Only in -g mode...
Chris Lattnerd9f4ac662002-07-18 00:14:50 +000049 if (!isa<Constant>(V))
Bill Wendling6a462f12006-11-17 08:03:48 +000050 DOUT << "While deleting: " << *this
51 << "\n\nUse still stuck around after Def is destroyed: "
52 << *V << "\n\n";
Chris Lattnerd7a73302001-10-13 06:57:33 +000053#endif
Vikram S. Adve4e537b22002-07-14 23:13:17 +000054 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
Reid Spencer1ebe1ab2004-07-17 23:48:33 +000055 Constant *CV = cast<Constant>(V);
56 CV->destroyConstant();
Chris Lattnerd7a73302001-10-13 06:57:33 +000057
58 // The constant should remove itself from our use list...
Vikram S. Adve4e537b22002-07-14 23:13:17 +000059 assert((use_empty() || use_back() != V) && "Constant not removed!");
Chris Lattnerd7a73302001-10-13 06:57:33 +000060 }
61
62 // Value has no outstanding references it is safe to delete it now...
63 delete this;
Chris Lattner38569342001-10-01 20:11:19 +000064}
Chris Lattner2f7c9632001-06-06 20:29:01 +000065
Chris Lattner23dd1f62006-10-20 00:27:06 +000066/// canTrap - Return true if evaluation of this constant could trap. This is
67/// true for things like constant expressions that could divide by zero.
68bool Constant::canTrap() const {
69 assert(getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
70 // The only thing that could possibly trap are constant exprs.
71 const ConstantExpr *CE = dyn_cast<ConstantExpr>(this);
72 if (!CE) return false;
73
74 // ConstantExpr traps if any operands can trap.
75 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
76 if (getOperand(i)->canTrap())
77 return true;
78
79 // Otherwise, only specific operations can trap.
80 switch (CE->getOpcode()) {
81 default:
82 return false;
Reid Spencer7e80b0b2006-10-26 06:15:43 +000083 case Instruction::UDiv:
84 case Instruction::SDiv:
85 case Instruction::FDiv:
Reid Spencer7eb55b32006-11-02 01:53:59 +000086 case Instruction::URem:
87 case Instruction::SRem:
88 case Instruction::FRem:
Chris Lattner23dd1f62006-10-20 00:27:06 +000089 // Div and rem can trap if the RHS is not known to be non-zero.
90 if (!isa<ConstantInt>(getOperand(1)) || getOperand(1)->isNullValue())
91 return true;
92 return false;
93 }
94}
95
Anton Korobeynikov7437b592009-03-29 17:13:18 +000096/// ContainsRelocations - Return true if the constant value contains relocations
97/// which cannot be resolved at compile time. Kind argument is used to filter
98/// only 'interesting' sorts of relocations.
99bool Constant::ContainsRelocations(unsigned Kind) const {
100 if (const GlobalValue* GV = dyn_cast<GlobalValue>(this)) {
101 bool isLocal = GV->hasLocalLinkage();
102 if ((Kind & Reloc::Local) && isLocal) {
103 // Global has local linkage and 'local' kind of relocations are
104 // requested
105 return true;
106 }
107
108 if ((Kind & Reloc::Global) && !isLocal) {
109 // Global has non-local linkage and 'global' kind of relocations are
110 // requested
111 return true;
112 }
Anton Korobeynikov255a3cb2009-03-30 15:28:21 +0000113
114 return false;
Anton Korobeynikov7437b592009-03-29 17:13:18 +0000115 }
116
Evan Chengf9e003b2007-03-08 00:59:12 +0000117 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
Anton Korobeynikovd5e8e932009-03-30 15:28:00 +0000118 if (getOperand(i)->ContainsRelocations(Kind))
Evan Chengf9e003b2007-03-08 00:59:12 +0000119 return true;
Anton Korobeynikov7437b592009-03-29 17:13:18 +0000120
Evan Chengf9e003b2007-03-08 00:59:12 +0000121 return false;
122}
123
Chris Lattnerb1585a92002-08-13 17:50:20 +0000124// Static constructor to create a '0' constant of arbitrary type...
125Constant *Constant::getNullValue(const Type *Ty) {
Dale Johannesen98d3a082007-09-14 22:26:36 +0000126 static uint64_t zero[2] = {0, 0};
Chris Lattner6b727592004-06-17 18:19:28 +0000127 switch (Ty->getTypeID()) {
Chris Lattnerdbcb0d32007-02-20 05:46:39 +0000128 case Type::IntegerTyID:
129 return ConstantInt::get(Ty, 0);
130 case Type::FloatTyID:
Chris Lattnerb5b3e312008-04-09 00:45:01 +0000131 return ConstantFP::get(APFloat(APInt(32, 0)));
Chris Lattnerdbcb0d32007-02-20 05:46:39 +0000132 case Type::DoubleTyID:
Chris Lattnerb5b3e312008-04-09 00:45:01 +0000133 return ConstantFP::get(APFloat(APInt(64, 0)));
Dale Johannesenbdad8092007-08-09 22:51:36 +0000134 case Type::X86_FP80TyID:
Chris Lattnerb5b3e312008-04-09 00:45:01 +0000135 return ConstantFP::get(APFloat(APInt(80, 2, zero)));
Dale Johannesenbdad8092007-08-09 22:51:36 +0000136 case Type::FP128TyID:
Chris Lattnerb5b3e312008-04-09 00:45:01 +0000137 return ConstantFP::get(APFloat(APInt(128, 2, zero), true));
Dale Johannesen98d3a082007-09-14 22:26:36 +0000138 case Type::PPC_FP128TyID:
Chris Lattnerb5b3e312008-04-09 00:45:01 +0000139 return ConstantFP::get(APFloat(APInt(128, 2, zero)));
Misha Brukmanb1c93172005-04-21 23:48:37 +0000140 case Type::PointerTyID:
Chris Lattnerb1585a92002-08-13 17:50:20 +0000141 return ConstantPointerNull::get(cast<PointerType>(Ty));
Chris Lattner9fba3da2004-02-15 05:53:04 +0000142 case Type::StructTyID:
143 case Type::ArrayTyID:
Reid Spencerd84d35b2007-02-15 02:26:10 +0000144 case Type::VectorTyID:
Chris Lattner9fba3da2004-02-15 05:53:04 +0000145 return ConstantAggregateZero::get(Ty);
Chris Lattnerb1585a92002-08-13 17:50:20 +0000146 default:
Reid Spencercf394bf2004-07-04 11:51:24 +0000147 // Function, Label, or Opaque type?
148 assert(!"Cannot create a null constant of that type!");
Chris Lattnerb1585a92002-08-13 17:50:20 +0000149 return 0;
150 }
151}
152
Chris Lattner72e39582007-06-15 06:10:53 +0000153Constant *Constant::getAllOnesValue(const Type *Ty) {
154 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty))
155 return ConstantInt::get(APInt::getAllOnesValue(ITy->getBitWidth()));
156 return ConstantVector::getAllOnesValue(cast<VectorType>(Ty));
157}
Chris Lattnerb1585a92002-08-13 17:50:20 +0000158
159// Static constructor to create an integral constant with all bits set
Zhou Sheng75b871f2007-01-11 12:24:14 +0000160ConstantInt *ConstantInt::getAllOnesValue(const Type *Ty) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000161 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty))
Reid Spencerd1bbfa52007-03-01 19:30:34 +0000162 return ConstantInt::get(APInt::getAllOnesValue(ITy->getBitWidth()));
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000163 return 0;
Chris Lattnerb1585a92002-08-13 17:50:20 +0000164}
165
Dan Gohman30978072007-05-24 14:36:04 +0000166/// @returns the value for a vector integer constant of the given type that
Chris Lattnerecab54c2007-01-04 01:49:26 +0000167/// has all its bits set to true.
168/// @brief Get the all ones value
Reid Spencerd84d35b2007-02-15 02:26:10 +0000169ConstantVector *ConstantVector::getAllOnesValue(const VectorType *Ty) {
Chris Lattnerecab54c2007-01-04 01:49:26 +0000170 std::vector<Constant*> Elts;
171 Elts.resize(Ty->getNumElements(),
Zhou Sheng75b871f2007-01-11 12:24:14 +0000172 ConstantInt::getAllOnesValue(Ty->getElementType()));
Dan Gohman30978072007-05-24 14:36:04 +0000173 assert(Elts[0] && "Not a vector integer type!");
Reid Spencerd84d35b2007-02-15 02:26:10 +0000174 return cast<ConstantVector>(ConstantVector::get(Elts));
Chris Lattnerecab54c2007-01-04 01:49:26 +0000175}
176
177
Chris Lattner2105d662008-07-10 00:28:11 +0000178/// getVectorElements - This method, which is only valid on constant of vector
179/// type, returns the elements of the vector in the specified smallvector.
Chris Lattnerc5098a22008-07-14 05:10:41 +0000180/// This handles breaking down a vector undef into undef elements, etc. For
181/// constant exprs and other cases we can't handle, we return an empty vector.
Chris Lattner2105d662008-07-10 00:28:11 +0000182void Constant::getVectorElements(SmallVectorImpl<Constant*> &Elts) const {
183 assert(isa<VectorType>(getType()) && "Not a vector constant!");
184
185 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this)) {
186 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i)
187 Elts.push_back(CV->getOperand(i));
188 return;
189 }
190
191 const VectorType *VT = cast<VectorType>(getType());
192 if (isa<ConstantAggregateZero>(this)) {
193 Elts.assign(VT->getNumElements(),
194 Constant::getNullValue(VT->getElementType()));
195 return;
196 }
197
Chris Lattnerc5098a22008-07-14 05:10:41 +0000198 if (isa<UndefValue>(this)) {
199 Elts.assign(VT->getNumElements(), UndefValue::get(VT->getElementType()));
200 return;
201 }
202
203 // Unknown type, must be constant expr etc.
Chris Lattner2105d662008-07-10 00:28:11 +0000204}
205
206
207
Chris Lattner2f7c9632001-06-06 20:29:01 +0000208//===----------------------------------------------------------------------===//
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000209// ConstantInt
Chris Lattner2f7c9632001-06-06 20:29:01 +0000210//===----------------------------------------------------------------------===//
211
Reid Spencerb31bffe2007-02-26 23:54:03 +0000212ConstantInt::ConstantInt(const IntegerType *Ty, const APInt& V)
Chris Lattner5db2f472007-02-20 05:55:46 +0000213 : Constant(Ty, ConstantIntVal, 0, 0), Val(V) {
Reid Spencerb31bffe2007-02-26 23:54:03 +0000214 assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
Chris Lattner2f7c9632001-06-06 20:29:01 +0000215}
216
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000217ConstantInt *ConstantInt::TheTrueVal = 0;
218ConstantInt *ConstantInt::TheFalseVal = 0;
219
220namespace llvm {
221 void CleanupTrueFalse(void *) {
222 ConstantInt::ResetTrueFalse();
223 }
224}
225
226static ManagedCleanup<llvm::CleanupTrueFalse> TrueFalseCleanup;
227
228ConstantInt *ConstantInt::CreateTrueFalseVals(bool WhichOne) {
229 assert(TheTrueVal == 0 && TheFalseVal == 0);
230 TheTrueVal = get(Type::Int1Ty, 1);
231 TheFalseVal = get(Type::Int1Ty, 0);
232
233 // Ensure that llvm_shutdown nulls out TheTrueVal/TheFalseVal.
234 TrueFalseCleanup.Register();
235
236 return WhichOne ? TheTrueVal : TheFalseVal;
237}
238
239
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000240namespace {
Reid Spencerb31bffe2007-02-26 23:54:03 +0000241 struct DenseMapAPIntKeyInfo {
242 struct KeyTy {
243 APInt val;
244 const Type* type;
245 KeyTy(const APInt& V, const Type* Ty) : val(V), type(Ty) {}
246 KeyTy(const KeyTy& that) : val(that.val), type(that.type) {}
247 bool operator==(const KeyTy& that) const {
248 return type == that.type && this->val == that.val;
249 }
250 bool operator!=(const KeyTy& that) const {
251 return !this->operator==(that);
252 }
253 };
254 static inline KeyTy getEmptyKey() { return KeyTy(APInt(1,0), 0); }
255 static inline KeyTy getTombstoneKey() { return KeyTy(APInt(1,1), 0); }
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000256 static unsigned getHashValue(const KeyTy &Key) {
Chris Lattner0625bd62007-09-17 18:34:04 +0000257 return DenseMapInfo<void*>::getHashValue(Key.type) ^
Reid Spencerb31bffe2007-02-26 23:54:03 +0000258 Key.val.getHashValue();
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000259 }
Chris Lattner0625bd62007-09-17 18:34:04 +0000260 static bool isEqual(const KeyTy &LHS, const KeyTy &RHS) {
261 return LHS == RHS;
262 }
Dale Johannesena719a602007-08-24 00:56:33 +0000263 static bool isPod() { return false; }
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000264 };
265}
266
267
Reid Spencerb31bffe2007-02-26 23:54:03 +0000268typedef DenseMap<DenseMapAPIntKeyInfo::KeyTy, ConstantInt*,
269 DenseMapAPIntKeyInfo> IntMapTy;
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000270static ManagedStatic<IntMapTy> IntConstants;
271
Reid Spencer362fb292007-03-19 20:39:08 +0000272ConstantInt *ConstantInt::get(const Type *Ty, uint64_t V, bool isSigned) {
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000273 const IntegerType *ITy = cast<IntegerType>(Ty);
Reid Spencer362fb292007-03-19 20:39:08 +0000274 return get(APInt(ITy->getBitWidth(), V, isSigned));
Reid Spencerb31bffe2007-02-26 23:54:03 +0000275}
276
Reid Spencerd1bbfa52007-03-01 19:30:34 +0000277// Get a ConstantInt from an APInt. Note that the value stored in the DenseMap
Dan Gohmanb3efe032008-02-07 02:30:40 +0000278// as the key, is a DenseMapAPIntKeyInfo::KeyTy which has provided the
Reid Spencerb31bffe2007-02-26 23:54:03 +0000279// operator== and operator!= to ensure that the DenseMap doesn't attempt to
280// compare APInt's of different widths, which would violate an APInt class
281// invariant which generates an assertion.
Reid Spencerd1bbfa52007-03-01 19:30:34 +0000282ConstantInt *ConstantInt::get(const APInt& V) {
283 // Get the corresponding integer type for the bit width of the value.
284 const IntegerType *ITy = IntegerType::get(V.getBitWidth());
Reid Spencerb31bffe2007-02-26 23:54:03 +0000285 // get an existing value or the insertion position
Reid Spencerd1bbfa52007-03-01 19:30:34 +0000286 DenseMapAPIntKeyInfo::KeyTy Key(V, ITy);
Reid Spencerb31bffe2007-02-26 23:54:03 +0000287 ConstantInt *&Slot = (*IntConstants)[Key];
288 // if it exists, return it.
289 if (Slot)
290 return Slot;
291 // otherwise create a new one, insert it, and return it.
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000292 return Slot = new ConstantInt(ITy, V);
293}
294
295//===----------------------------------------------------------------------===//
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000296// ConstantFP
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000297//===----------------------------------------------------------------------===//
298
Chris Lattner98bd9392008-04-09 06:38:30 +0000299static const fltSemantics *TypeToFloatSemantics(const Type *Ty) {
300 if (Ty == Type::FloatTy)
301 return &APFloat::IEEEsingle;
302 if (Ty == Type::DoubleTy)
303 return &APFloat::IEEEdouble;
304 if (Ty == Type::X86_FP80Ty)
305 return &APFloat::x87DoubleExtended;
306 else if (Ty == Type::FP128Ty)
307 return &APFloat::IEEEquad;
308
309 assert(Ty == Type::PPC_FP128Ty && "Unknown FP format");
310 return &APFloat::PPCDoubleDouble;
311}
312
Dale Johannesend246b2c2007-08-30 00:23:21 +0000313ConstantFP::ConstantFP(const Type *Ty, const APFloat& V)
314 : Constant(Ty, ConstantFPVal, 0, 0), Val(V) {
Chris Lattner98bd9392008-04-09 06:38:30 +0000315 assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
316 "FP type Mismatch");
Chris Lattner2f7c9632001-06-06 20:29:01 +0000317}
318
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000319bool ConstantFP::isNullValue() const {
Dale Johannesena719a602007-08-24 00:56:33 +0000320 return Val.isZero() && !Val.isNegative();
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000321}
322
Dale Johannesen98d3a082007-09-14 22:26:36 +0000323ConstantFP *ConstantFP::getNegativeZero(const Type *Ty) {
324 APFloat apf = cast <ConstantFP>(Constant::getNullValue(Ty))->getValueAPF();
325 apf.changeSign();
Chris Lattnerb5b3e312008-04-09 00:45:01 +0000326 return ConstantFP::get(apf);
Dale Johannesen98d3a082007-09-14 22:26:36 +0000327}
328
Dale Johannesend246b2c2007-08-30 00:23:21 +0000329bool ConstantFP::isExactlyValue(const APFloat& V) const {
330 return Val.bitwiseIsEqual(V);
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000331}
332
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000333namespace {
Dale Johannesena719a602007-08-24 00:56:33 +0000334 struct DenseMapAPFloatKeyInfo {
Dale Johannesenbdea32d2007-08-24 22:09:56 +0000335 struct KeyTy {
336 APFloat val;
337 KeyTy(const APFloat& V) : val(V){}
338 KeyTy(const KeyTy& that) : val(that.val) {}
339 bool operator==(const KeyTy& that) const {
340 return this->val.bitwiseIsEqual(that.val);
341 }
342 bool operator!=(const KeyTy& that) const {
343 return !this->operator==(that);
344 }
345 };
346 static inline KeyTy getEmptyKey() {
347 return KeyTy(APFloat(APFloat::Bogus,1));
Reid Spencerb31bffe2007-02-26 23:54:03 +0000348 }
Dale Johannesenbdea32d2007-08-24 22:09:56 +0000349 static inline KeyTy getTombstoneKey() {
350 return KeyTy(APFloat(APFloat::Bogus,2));
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000351 }
Dale Johannesenbdea32d2007-08-24 22:09:56 +0000352 static unsigned getHashValue(const KeyTy &Key) {
353 return Key.val.getHashValue();
Dale Johannesena719a602007-08-24 00:56:33 +0000354 }
Chris Lattner0625bd62007-09-17 18:34:04 +0000355 static bool isEqual(const KeyTy &LHS, const KeyTy &RHS) {
356 return LHS == RHS;
357 }
Dale Johannesena719a602007-08-24 00:56:33 +0000358 static bool isPod() { return false; }
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000359 };
360}
361
362//---- ConstantFP::get() implementation...
363//
Dale Johannesenbdea32d2007-08-24 22:09:56 +0000364typedef DenseMap<DenseMapAPFloatKeyInfo::KeyTy, ConstantFP*,
Dale Johannesena719a602007-08-24 00:56:33 +0000365 DenseMapAPFloatKeyInfo> FPMapTy;
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000366
Dale Johannesena719a602007-08-24 00:56:33 +0000367static ManagedStatic<FPMapTy> FPConstants;
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000368
Chris Lattnerb5b3e312008-04-09 00:45:01 +0000369ConstantFP *ConstantFP::get(const APFloat &V) {
Dale Johannesend246b2c2007-08-30 00:23:21 +0000370 DenseMapAPFloatKeyInfo::KeyTy Key(V);
371 ConstantFP *&Slot = (*FPConstants)[Key];
372 if (Slot) return Slot;
Chris Lattnerb5b3e312008-04-09 00:45:01 +0000373
374 const Type *Ty;
375 if (&V.getSemantics() == &APFloat::IEEEsingle)
376 Ty = Type::FloatTy;
377 else if (&V.getSemantics() == &APFloat::IEEEdouble)
378 Ty = Type::DoubleTy;
379 else if (&V.getSemantics() == &APFloat::x87DoubleExtended)
380 Ty = Type::X86_FP80Ty;
381 else if (&V.getSemantics() == &APFloat::IEEEquad)
382 Ty = Type::FP128Ty;
383 else {
384 assert(&V.getSemantics() == &APFloat::PPCDoubleDouble&&"Unknown FP format");
385 Ty = Type::PPC_FP128Ty;
386 }
387
Dale Johannesend246b2c2007-08-30 00:23:21 +0000388 return Slot = new ConstantFP(Ty, V);
389}
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000390
Chris Lattner98bd9392008-04-09 06:38:30 +0000391/// get() - This returns a constant fp for the specified value in the
392/// specified type. This should only be used for simple constant values like
393/// 2.0/1.0 etc, that are known-valid both as double and as the target format.
394ConstantFP *ConstantFP::get(const Type *Ty, double V) {
395 APFloat FV(V);
Dale Johannesen4f0bd682008-10-09 23:00:39 +0000396 bool ignored;
397 FV.convert(*TypeToFloatSemantics(Ty), APFloat::rmNearestTiesToEven, &ignored);
Chris Lattner98bd9392008-04-09 06:38:30 +0000398 return get(FV);
399}
400
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000401//===----------------------------------------------------------------------===//
402// ConstantXXX Classes
403//===----------------------------------------------------------------------===//
404
405
Chris Lattner3462ae32001-12-03 22:26:30 +0000406ConstantArray::ConstantArray(const ArrayType *T,
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000407 const std::vector<Constant*> &V)
Gabor Greiff6caff662008-05-10 08:32:32 +0000408 : Constant(T, ConstantArrayVal,
409 OperandTraits<ConstantArray>::op_end(this) - V.size(),
410 V.size()) {
Alkis Evlogimenos0507ffe2004-09-15 02:32:15 +0000411 assert(V.size() == T->getNumElements() &&
412 "Invalid initializer vector for constant array");
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000413 Use *OL = OperandList;
Chris Lattner0144fad2005-10-03 21:56:24 +0000414 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
415 I != E; ++I, ++OL) {
Chris Lattner20a24452005-10-07 05:23:36 +0000416 Constant *C = *I;
417 assert((C->getType() == T->getElementType() ||
Alkis Evlogimenoscb031d92004-09-10 04:16:59 +0000418 (T->isAbstract() &&
Chris Lattner20a24452005-10-07 05:23:36 +0000419 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
Alkis Evlogimenoscb031d92004-09-10 04:16:59 +0000420 "Initializer for array element doesn't match array element type!");
Gabor Greif2d3024d2008-05-26 21:33:52 +0000421 *OL = C;
Chris Lattner2f7c9632001-06-06 20:29:01 +0000422 }
423}
424
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000425
Chris Lattner3462ae32001-12-03 22:26:30 +0000426ConstantStruct::ConstantStruct(const StructType *T,
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000427 const std::vector<Constant*> &V)
Gabor Greiff6caff662008-05-10 08:32:32 +0000428 : Constant(T, ConstantStructVal,
429 OperandTraits<ConstantStruct>::op_end(this) - V.size(),
430 V.size()) {
Chris Lattnerac6db752004-02-09 04:37:31 +0000431 assert(V.size() == T->getNumElements() &&
Vikram S. Adve4e537b22002-07-14 23:13:17 +0000432 "Invalid initializer vector for constant structure");
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000433 Use *OL = OperandList;
Chris Lattner0144fad2005-10-03 21:56:24 +0000434 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
435 I != E; ++I, ++OL) {
Chris Lattner20a24452005-10-07 05:23:36 +0000436 Constant *C = *I;
437 assert((C->getType() == T->getElementType(I-V.begin()) ||
Chris Lattner0144fad2005-10-03 21:56:24 +0000438 ((T->getElementType(I-V.begin())->isAbstract() ||
Chris Lattner20a24452005-10-07 05:23:36 +0000439 C->getType()->isAbstract()) &&
Chris Lattner0144fad2005-10-03 21:56:24 +0000440 T->getElementType(I-V.begin())->getTypeID() ==
Chris Lattner20a24452005-10-07 05:23:36 +0000441 C->getType()->getTypeID())) &&
Chris Lattner93c8f142003-06-02 17:42:47 +0000442 "Initializer for struct element doesn't match struct element type!");
Gabor Greif2d3024d2008-05-26 21:33:52 +0000443 *OL = C;
Chris Lattner2f7c9632001-06-06 20:29:01 +0000444 }
445}
446
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000447
Reid Spencerd84d35b2007-02-15 02:26:10 +0000448ConstantVector::ConstantVector(const VectorType *T,
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000449 const std::vector<Constant*> &V)
Gabor Greiff6caff662008-05-10 08:32:32 +0000450 : Constant(T, ConstantVectorVal,
451 OperandTraits<ConstantVector>::op_end(this) - V.size(),
452 V.size()) {
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000453 Use *OL = OperandList;
Chris Lattner0144fad2005-10-03 21:56:24 +0000454 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
455 I != E; ++I, ++OL) {
Chris Lattner20a24452005-10-07 05:23:36 +0000456 Constant *C = *I;
457 assert((C->getType() == T->getElementType() ||
Alkis Evlogimenoscb031d92004-09-10 04:16:59 +0000458 (T->isAbstract() &&
Chris Lattner20a24452005-10-07 05:23:36 +0000459 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
Dan Gohman30978072007-05-24 14:36:04 +0000460 "Initializer for vector element doesn't match vector element type!");
Gabor Greif2d3024d2008-05-26 21:33:52 +0000461 *OL = C;
Brian Gaeke02209042004-08-20 06:00:58 +0000462 }
463}
464
Vikram S. Adve4e537b22002-07-14 23:13:17 +0000465
Gabor Greiff6caff662008-05-10 08:32:32 +0000466namespace llvm {
Gordon Henriksen14a55692007-12-10 02:14:30 +0000467// We declare several classes private to this file, so use an anonymous
468// namespace
469namespace {
Reid Spencer10fbf0e2006-12-03 05:48:19 +0000470
Gordon Henriksen14a55692007-12-10 02:14:30 +0000471/// UnaryConstantExpr - This class is private to Constants.cpp, and is used
472/// behind the scenes to implement unary constant exprs.
473class VISIBILITY_HIDDEN UnaryConstantExpr : public ConstantExpr {
Gabor Greife9ecc682008-04-06 20:25:17 +0000474 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
Gordon Henriksen14a55692007-12-10 02:14:30 +0000475public:
Gabor Greife9ecc682008-04-06 20:25:17 +0000476 // allocate space for exactly one operand
477 void *operator new(size_t s) {
478 return User::operator new(s, 1);
479 }
Gordon Henriksen14a55692007-12-10 02:14:30 +0000480 UnaryConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
Gabor Greiff6caff662008-05-10 08:32:32 +0000481 : ConstantExpr(Ty, Opcode, &Op<0>(), 1) {
482 Op<0>() = C;
483 }
484 /// Transparently provide more efficient getOperand methods.
485 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Gordon Henriksen14a55692007-12-10 02:14:30 +0000486};
Reid Spencer10fbf0e2006-12-03 05:48:19 +0000487
Gordon Henriksen14a55692007-12-10 02:14:30 +0000488/// BinaryConstantExpr - This class is private to Constants.cpp, and is used
489/// behind the scenes to implement binary constant exprs.
490class VISIBILITY_HIDDEN BinaryConstantExpr : public ConstantExpr {
Gabor Greife9ecc682008-04-06 20:25:17 +0000491 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
Gordon Henriksen14a55692007-12-10 02:14:30 +0000492public:
Gabor Greife9ecc682008-04-06 20:25:17 +0000493 // allocate space for exactly two operands
494 void *operator new(size_t s) {
495 return User::operator new(s, 2);
496 }
Gordon Henriksen14a55692007-12-10 02:14:30 +0000497 BinaryConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
Gabor Greiff6caff662008-05-10 08:32:32 +0000498 : ConstantExpr(C1->getType(), Opcode, &Op<0>(), 2) {
Gabor Greif2d3024d2008-05-26 21:33:52 +0000499 Op<0>() = C1;
500 Op<1>() = C2;
Gordon Henriksen14a55692007-12-10 02:14:30 +0000501 }
Gabor Greiff6caff662008-05-10 08:32:32 +0000502 /// Transparently provide more efficient getOperand methods.
503 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Gordon Henriksen14a55692007-12-10 02:14:30 +0000504};
Vikram S. Adve4e537b22002-07-14 23:13:17 +0000505
Gordon Henriksen14a55692007-12-10 02:14:30 +0000506/// SelectConstantExpr - This class is private to Constants.cpp, and is used
507/// behind the scenes to implement select constant exprs.
508class VISIBILITY_HIDDEN SelectConstantExpr : public ConstantExpr {
Gabor Greife9ecc682008-04-06 20:25:17 +0000509 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
Gordon Henriksen14a55692007-12-10 02:14:30 +0000510public:
Gabor Greife9ecc682008-04-06 20:25:17 +0000511 // allocate space for exactly three operands
512 void *operator new(size_t s) {
513 return User::operator new(s, 3);
514 }
Gordon Henriksen14a55692007-12-10 02:14:30 +0000515 SelectConstantExpr(Constant *C1, Constant *C2, Constant *C3)
Gabor Greiff6caff662008-05-10 08:32:32 +0000516 : ConstantExpr(C2->getType(), Instruction::Select, &Op<0>(), 3) {
Gabor Greif2d3024d2008-05-26 21:33:52 +0000517 Op<0>() = C1;
518 Op<1>() = C2;
519 Op<2>() = C3;
Gordon Henriksen14a55692007-12-10 02:14:30 +0000520 }
Gabor Greiff6caff662008-05-10 08:32:32 +0000521 /// Transparently provide more efficient getOperand methods.
522 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Gordon Henriksen14a55692007-12-10 02:14:30 +0000523};
Chris Lattnerd0df99c2005-01-29 00:34:39 +0000524
Gordon Henriksen14a55692007-12-10 02:14:30 +0000525/// ExtractElementConstantExpr - This class is private to
526/// Constants.cpp, and is used behind the scenes to implement
527/// extractelement constant exprs.
528class VISIBILITY_HIDDEN ExtractElementConstantExpr : public ConstantExpr {
Gabor Greife9ecc682008-04-06 20:25:17 +0000529 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
Gordon Henriksen14a55692007-12-10 02:14:30 +0000530public:
Gabor Greife9ecc682008-04-06 20:25:17 +0000531 // allocate space for exactly two operands
532 void *operator new(size_t s) {
533 return User::operator new(s, 2);
534 }
Gordon Henriksen14a55692007-12-10 02:14:30 +0000535 ExtractElementConstantExpr(Constant *C1, Constant *C2)
536 : ConstantExpr(cast<VectorType>(C1->getType())->getElementType(),
Gabor Greiff6caff662008-05-10 08:32:32 +0000537 Instruction::ExtractElement, &Op<0>(), 2) {
Gabor Greif2d3024d2008-05-26 21:33:52 +0000538 Op<0>() = C1;
539 Op<1>() = C2;
Gordon Henriksen14a55692007-12-10 02:14:30 +0000540 }
Gabor Greiff6caff662008-05-10 08:32:32 +0000541 /// Transparently provide more efficient getOperand methods.
542 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Gordon Henriksen14a55692007-12-10 02:14:30 +0000543};
Robert Bocchino23004482006-01-10 19:05:34 +0000544
Gordon Henriksen14a55692007-12-10 02:14:30 +0000545/// InsertElementConstantExpr - This class is private to
546/// Constants.cpp, and is used behind the scenes to implement
547/// insertelement constant exprs.
548class VISIBILITY_HIDDEN InsertElementConstantExpr : public ConstantExpr {
Gabor Greife9ecc682008-04-06 20:25:17 +0000549 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
Gordon Henriksen14a55692007-12-10 02:14:30 +0000550public:
Gabor Greife9ecc682008-04-06 20:25:17 +0000551 // allocate space for exactly three operands
552 void *operator new(size_t s) {
553 return User::operator new(s, 3);
554 }
Gordon Henriksen14a55692007-12-10 02:14:30 +0000555 InsertElementConstantExpr(Constant *C1, Constant *C2, Constant *C3)
556 : ConstantExpr(C1->getType(), Instruction::InsertElement,
Gabor Greiff6caff662008-05-10 08:32:32 +0000557 &Op<0>(), 3) {
Gabor Greif2d3024d2008-05-26 21:33:52 +0000558 Op<0>() = C1;
559 Op<1>() = C2;
560 Op<2>() = C3;
Gordon Henriksen14a55692007-12-10 02:14:30 +0000561 }
Gabor Greiff6caff662008-05-10 08:32:32 +0000562 /// Transparently provide more efficient getOperand methods.
563 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Gordon Henriksen14a55692007-12-10 02:14:30 +0000564};
Robert Bocchinoca27f032006-01-17 20:07:22 +0000565
Gordon Henriksen14a55692007-12-10 02:14:30 +0000566/// ShuffleVectorConstantExpr - This class is private to
567/// Constants.cpp, and is used behind the scenes to implement
568/// shufflevector constant exprs.
569class VISIBILITY_HIDDEN ShuffleVectorConstantExpr : public ConstantExpr {
Gabor Greife9ecc682008-04-06 20:25:17 +0000570 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
Gordon Henriksen14a55692007-12-10 02:14:30 +0000571public:
Gabor Greife9ecc682008-04-06 20:25:17 +0000572 // allocate space for exactly three operands
573 void *operator new(size_t s) {
574 return User::operator new(s, 3);
575 }
Gordon Henriksen14a55692007-12-10 02:14:30 +0000576 ShuffleVectorConstantExpr(Constant *C1, Constant *C2, Constant *C3)
Nate Begeman94aa38d2009-02-12 21:28:33 +0000577 : ConstantExpr(VectorType::get(
578 cast<VectorType>(C1->getType())->getElementType(),
579 cast<VectorType>(C3->getType())->getNumElements()),
580 Instruction::ShuffleVector,
Gabor Greiff6caff662008-05-10 08:32:32 +0000581 &Op<0>(), 3) {
Gabor Greif2d3024d2008-05-26 21:33:52 +0000582 Op<0>() = C1;
583 Op<1>() = C2;
584 Op<2>() = C3;
Gordon Henriksen14a55692007-12-10 02:14:30 +0000585 }
Gabor Greiff6caff662008-05-10 08:32:32 +0000586 /// Transparently provide more efficient getOperand methods.
587 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Gordon Henriksen14a55692007-12-10 02:14:30 +0000588};
589
Dan Gohman12fce772008-05-15 19:50:34 +0000590/// ExtractValueConstantExpr - This class is private to
591/// Constants.cpp, and is used behind the scenes to implement
592/// extractvalue constant exprs.
593class VISIBILITY_HIDDEN ExtractValueConstantExpr : public ConstantExpr {
Dan Gohman1ecaf452008-05-31 00:58:22 +0000594 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
Dan Gohman12fce772008-05-15 19:50:34 +0000595public:
Dan Gohman1ecaf452008-05-31 00:58:22 +0000596 // allocate space for exactly one operand
597 void *operator new(size_t s) {
598 return User::operator new(s, 1);
Dan Gohman12fce772008-05-15 19:50:34 +0000599 }
Dan Gohman1ecaf452008-05-31 00:58:22 +0000600 ExtractValueConstantExpr(Constant *Agg,
601 const SmallVector<unsigned, 4> &IdxList,
602 const Type *DestTy)
603 : ConstantExpr(DestTy, Instruction::ExtractValue, &Op<0>(), 1),
604 Indices(IdxList) {
605 Op<0>() = Agg;
606 }
607
Dan Gohman7bb04502008-05-31 19:09:08 +0000608 /// Indices - These identify which value to extract.
Dan Gohman1ecaf452008-05-31 00:58:22 +0000609 const SmallVector<unsigned, 4> Indices;
610
Dan Gohman12fce772008-05-15 19:50:34 +0000611 /// Transparently provide more efficient getOperand methods.
612 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
613};
614
615/// InsertValueConstantExpr - This class is private to
616/// Constants.cpp, and is used behind the scenes to implement
617/// insertvalue constant exprs.
618class VISIBILITY_HIDDEN InsertValueConstantExpr : public ConstantExpr {
Dan Gohman1ecaf452008-05-31 00:58:22 +0000619 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
Dan Gohman12fce772008-05-15 19:50:34 +0000620public:
Dan Gohman1ecaf452008-05-31 00:58:22 +0000621 // allocate space for exactly one operand
622 void *operator new(size_t s) {
623 return User::operator new(s, 2);
Dan Gohman12fce772008-05-15 19:50:34 +0000624 }
Dan Gohman1ecaf452008-05-31 00:58:22 +0000625 InsertValueConstantExpr(Constant *Agg, Constant *Val,
626 const SmallVector<unsigned, 4> &IdxList,
627 const Type *DestTy)
628 : ConstantExpr(DestTy, Instruction::InsertValue, &Op<0>(), 2),
629 Indices(IdxList) {
630 Op<0>() = Agg;
631 Op<1>() = Val;
632 }
633
Dan Gohman7bb04502008-05-31 19:09:08 +0000634 /// Indices - These identify the position for the insertion.
Dan Gohman1ecaf452008-05-31 00:58:22 +0000635 const SmallVector<unsigned, 4> Indices;
636
Dan Gohman12fce772008-05-15 19:50:34 +0000637 /// Transparently provide more efficient getOperand methods.
638 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
639};
640
641
Gordon Henriksen14a55692007-12-10 02:14:30 +0000642/// GetElementPtrConstantExpr - This class is private to Constants.cpp, and is
643/// used behind the scenes to implement getelementpr constant exprs.
Gabor Greife9ecc682008-04-06 20:25:17 +0000644class VISIBILITY_HIDDEN GetElementPtrConstantExpr : public ConstantExpr {
Gordon Henriksen14a55692007-12-10 02:14:30 +0000645 GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
Gabor Greiff6caff662008-05-10 08:32:32 +0000646 const Type *DestTy);
Gabor Greife9ecc682008-04-06 20:25:17 +0000647public:
Gabor Greif697e94c2008-05-15 10:04:30 +0000648 static GetElementPtrConstantExpr *Create(Constant *C,
649 const std::vector<Constant*>&IdxList,
Gabor Greiff6caff662008-05-10 08:32:32 +0000650 const Type *DestTy) {
Gabor Greif697e94c2008-05-15 10:04:30 +0000651 return new(IdxList.size() + 1)
652 GetElementPtrConstantExpr(C, IdxList, DestTy);
Gabor Greife9ecc682008-04-06 20:25:17 +0000653 }
Gabor Greiff6caff662008-05-10 08:32:32 +0000654 /// Transparently provide more efficient getOperand methods.
655 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Gordon Henriksen14a55692007-12-10 02:14:30 +0000656};
657
658// CompareConstantExpr - This class is private to Constants.cpp, and is used
659// behind the scenes to implement ICmp and FCmp constant expressions. This is
660// needed in order to store the predicate value for these instructions.
661struct VISIBILITY_HIDDEN CompareConstantExpr : public ConstantExpr {
Gabor Greife9ecc682008-04-06 20:25:17 +0000662 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
663 // allocate space for exactly two operands
664 void *operator new(size_t s) {
665 return User::operator new(s, 2);
666 }
Gordon Henriksen14a55692007-12-10 02:14:30 +0000667 unsigned short predicate;
Nate Begemand2195702008-05-12 19:01:56 +0000668 CompareConstantExpr(const Type *ty, Instruction::OtherOps opc,
669 unsigned short pred, Constant* LHS, Constant* RHS)
670 : ConstantExpr(ty, opc, &Op<0>(), 2), predicate(pred) {
Gabor Greif2d3024d2008-05-26 21:33:52 +0000671 Op<0>() = LHS;
672 Op<1>() = RHS;
Gordon Henriksen14a55692007-12-10 02:14:30 +0000673 }
Gabor Greiff6caff662008-05-10 08:32:32 +0000674 /// Transparently provide more efficient getOperand methods.
675 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Gordon Henriksen14a55692007-12-10 02:14:30 +0000676};
677
678} // end anonymous namespace
679
Gabor Greiff6caff662008-05-10 08:32:32 +0000680template <>
681struct OperandTraits<UnaryConstantExpr> : FixedNumOperandTraits<1> {
682};
683DEFINE_TRANSPARENT_OPERAND_ACCESSORS(UnaryConstantExpr, Value)
684
685template <>
686struct OperandTraits<BinaryConstantExpr> : FixedNumOperandTraits<2> {
687};
688DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BinaryConstantExpr, Value)
689
690template <>
691struct OperandTraits<SelectConstantExpr> : FixedNumOperandTraits<3> {
692};
693DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SelectConstantExpr, Value)
694
695template <>
696struct OperandTraits<ExtractElementConstantExpr> : FixedNumOperandTraits<2> {
697};
698DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractElementConstantExpr, Value)
699
700template <>
701struct OperandTraits<InsertElementConstantExpr> : FixedNumOperandTraits<3> {
702};
703DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertElementConstantExpr, Value)
704
705template <>
706struct OperandTraits<ShuffleVectorConstantExpr> : FixedNumOperandTraits<3> {
707};
708DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ShuffleVectorConstantExpr, Value)
709
Dan Gohman12fce772008-05-15 19:50:34 +0000710template <>
Dan Gohman1ecaf452008-05-31 00:58:22 +0000711struct OperandTraits<ExtractValueConstantExpr> : FixedNumOperandTraits<1> {
Dan Gohman12fce772008-05-15 19:50:34 +0000712};
Dan Gohman12fce772008-05-15 19:50:34 +0000713DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractValueConstantExpr, Value)
714
715template <>
Dan Gohman1ecaf452008-05-31 00:58:22 +0000716struct OperandTraits<InsertValueConstantExpr> : FixedNumOperandTraits<2> {
Dan Gohman12fce772008-05-15 19:50:34 +0000717};
Dan Gohman12fce772008-05-15 19:50:34 +0000718DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertValueConstantExpr, Value)
719
Gabor Greiff6caff662008-05-10 08:32:32 +0000720template <>
721struct OperandTraits<GetElementPtrConstantExpr> : VariadicOperandTraits<1> {
722};
723
724GetElementPtrConstantExpr::GetElementPtrConstantExpr
725 (Constant *C,
726 const std::vector<Constant*> &IdxList,
727 const Type *DestTy)
728 : ConstantExpr(DestTy, Instruction::GetElementPtr,
729 OperandTraits<GetElementPtrConstantExpr>::op_end(this)
730 - (IdxList.size()+1),
731 IdxList.size()+1) {
Gabor Greif2d3024d2008-05-26 21:33:52 +0000732 OperandList[0] = C;
Gabor Greiff6caff662008-05-10 08:32:32 +0000733 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
Gabor Greif2d3024d2008-05-26 21:33:52 +0000734 OperandList[i+1] = IdxList[i];
Gabor Greiff6caff662008-05-10 08:32:32 +0000735}
736
737DEFINE_TRANSPARENT_OPERAND_ACCESSORS(GetElementPtrConstantExpr, Value)
738
739
740template <>
741struct OperandTraits<CompareConstantExpr> : FixedNumOperandTraits<2> {
742};
743DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CompareConstantExpr, Value)
744
745
746} // End llvm namespace
747
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000748
749// Utility function for determining if a ConstantExpr is a CastOp or not. This
750// can't be inline because we don't want to #include Instruction.h into
751// Constant.h
752bool ConstantExpr::isCast() const {
753 return Instruction::isCast(getOpcode());
754}
755
Reid Spenceree3c9912006-12-04 05:19:50 +0000756bool ConstantExpr::isCompare() const {
Chris Lattnereab49262008-07-14 05:17:31 +0000757 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp ||
758 getOpcode() == Instruction::VICmp || getOpcode() == Instruction::VFCmp;
Reid Spenceree3c9912006-12-04 05:19:50 +0000759}
760
Dan Gohman1ecaf452008-05-31 00:58:22 +0000761bool ConstantExpr::hasIndices() const {
762 return getOpcode() == Instruction::ExtractValue ||
763 getOpcode() == Instruction::InsertValue;
764}
765
766const SmallVector<unsigned, 4> &ConstantExpr::getIndices() const {
767 if (const ExtractValueConstantExpr *EVCE =
768 dyn_cast<ExtractValueConstantExpr>(this))
769 return EVCE->Indices;
Dan Gohmana469bdb2008-06-23 16:39:44 +0000770
771 return cast<InsertValueConstantExpr>(this)->Indices;
Dan Gohman1ecaf452008-05-31 00:58:22 +0000772}
773
Chris Lattner817175f2004-03-29 02:37:53 +0000774/// ConstantExpr::get* - Return some common constants without having to
775/// specify the full Instruction::OPCODE identifier.
776///
777Constant *ConstantExpr::getNeg(Constant *C) {
Reid Spencer2eadb532007-01-21 00:29:26 +0000778 return get(Instruction::Sub,
779 ConstantExpr::getZeroValueForNegationExpr(C->getType()),
780 C);
Chris Lattner817175f2004-03-29 02:37:53 +0000781}
782Constant *ConstantExpr::getNot(Constant *C) {
Dale Johannesen47a5ef32008-08-21 21:20:09 +0000783 assert((isa<IntegerType>(C->getType()) ||
784 cast<VectorType>(C->getType())->getElementType()->isInteger()) &&
785 "Cannot NOT a nonintegral value!");
Chris Lattner817175f2004-03-29 02:37:53 +0000786 return get(Instruction::Xor, C,
Dale Johannesen47a5ef32008-08-21 21:20:09 +0000787 Constant::getAllOnesValue(C->getType()));
Chris Lattner817175f2004-03-29 02:37:53 +0000788}
789Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2) {
790 return get(Instruction::Add, C1, C2);
791}
792Constant *ConstantExpr::getSub(Constant *C1, Constant *C2) {
793 return get(Instruction::Sub, C1, C2);
794}
795Constant *ConstantExpr::getMul(Constant *C1, Constant *C2) {
796 return get(Instruction::Mul, C1, C2);
797}
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000798Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2) {
799 return get(Instruction::UDiv, C1, C2);
800}
801Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2) {
802 return get(Instruction::SDiv, C1, C2);
803}
804Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
805 return get(Instruction::FDiv, C1, C2);
Chris Lattner817175f2004-03-29 02:37:53 +0000806}
Reid Spencer7eb55b32006-11-02 01:53:59 +0000807Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
808 return get(Instruction::URem, C1, C2);
809}
810Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
811 return get(Instruction::SRem, C1, C2);
812}
813Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
814 return get(Instruction::FRem, C1, C2);
Chris Lattner817175f2004-03-29 02:37:53 +0000815}
816Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
817 return get(Instruction::And, C1, C2);
818}
819Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
820 return get(Instruction::Or, C1, C2);
821}
822Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
823 return get(Instruction::Xor, C1, C2);
824}
Reid Spencer10fbf0e2006-12-03 05:48:19 +0000825unsigned ConstantExpr::getPredicate() const {
Nate Begemand2195702008-05-12 19:01:56 +0000826 assert(getOpcode() == Instruction::FCmp ||
827 getOpcode() == Instruction::ICmp ||
828 getOpcode() == Instruction::VFCmp ||
829 getOpcode() == Instruction::VICmp);
Chris Lattneref650092007-10-18 16:26:24 +0000830 return ((const CompareConstantExpr*)this)->predicate;
Reid Spencer10fbf0e2006-12-03 05:48:19 +0000831}
Chris Lattner817175f2004-03-29 02:37:53 +0000832Constant *ConstantExpr::getShl(Constant *C1, Constant *C2) {
833 return get(Instruction::Shl, C1, C2);
834}
Reid Spencerfdff9382006-11-08 06:47:33 +0000835Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2) {
836 return get(Instruction::LShr, C1, C2);
Chris Lattner817175f2004-03-29 02:37:53 +0000837}
Reid Spencerfdff9382006-11-08 06:47:33 +0000838Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2) {
839 return get(Instruction::AShr, C1, C2);
Chris Lattnerdb8bdba2004-05-25 05:32:43 +0000840}
Chris Lattner60e0dd72001-10-03 06:12:09 +0000841
Chris Lattner7c1018a2006-07-14 19:37:40 +0000842/// getWithOperandReplaced - Return a constant expression identical to this
843/// one, but with the specified operand set to the specified value.
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000844Constant *
845ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
Chris Lattner7c1018a2006-07-14 19:37:40 +0000846 assert(OpNo < getNumOperands() && "Operand num is out of range!");
847 assert(Op->getType() == getOperand(OpNo)->getType() &&
848 "Replacing operand with value of different type!");
Chris Lattner227816342006-07-14 22:20:01 +0000849 if (getOperand(OpNo) == Op)
850 return const_cast<ConstantExpr*>(this);
Chris Lattner7c1018a2006-07-14 19:37:40 +0000851
Chris Lattner227816342006-07-14 22:20:01 +0000852 Constant *Op0, *Op1, *Op2;
Chris Lattner7c1018a2006-07-14 19:37:40 +0000853 switch (getOpcode()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000854 case Instruction::Trunc:
855 case Instruction::ZExt:
856 case Instruction::SExt:
857 case Instruction::FPTrunc:
858 case Instruction::FPExt:
859 case Instruction::UIToFP:
860 case Instruction::SIToFP:
861 case Instruction::FPToUI:
862 case Instruction::FPToSI:
863 case Instruction::PtrToInt:
864 case Instruction::IntToPtr:
865 case Instruction::BitCast:
866 return ConstantExpr::getCast(getOpcode(), Op, getType());
Chris Lattner227816342006-07-14 22:20:01 +0000867 case Instruction::Select:
868 Op0 = (OpNo == 0) ? Op : getOperand(0);
869 Op1 = (OpNo == 1) ? Op : getOperand(1);
870 Op2 = (OpNo == 2) ? Op : getOperand(2);
871 return ConstantExpr::getSelect(Op0, Op1, Op2);
872 case Instruction::InsertElement:
873 Op0 = (OpNo == 0) ? Op : getOperand(0);
874 Op1 = (OpNo == 1) ? Op : getOperand(1);
875 Op2 = (OpNo == 2) ? Op : getOperand(2);
876 return ConstantExpr::getInsertElement(Op0, Op1, Op2);
877 case Instruction::ExtractElement:
878 Op0 = (OpNo == 0) ? Op : getOperand(0);
879 Op1 = (OpNo == 1) ? Op : getOperand(1);
880 return ConstantExpr::getExtractElement(Op0, Op1);
881 case Instruction::ShuffleVector:
882 Op0 = (OpNo == 0) ? Op : getOperand(0);
883 Op1 = (OpNo == 1) ? Op : getOperand(1);
884 Op2 = (OpNo == 2) ? Op : getOperand(2);
885 return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Chris Lattner7c1018a2006-07-14 19:37:40 +0000886 case Instruction::GetElementPtr: {
Chris Lattnerb5d70302007-02-19 20:01:23 +0000887 SmallVector<Constant*, 8> Ops;
Dan Gohman12fce772008-05-15 19:50:34 +0000888 Ops.resize(getNumOperands()-1);
Chris Lattner7c1018a2006-07-14 19:37:40 +0000889 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
Dan Gohman12fce772008-05-15 19:50:34 +0000890 Ops[i-1] = getOperand(i);
Chris Lattner7c1018a2006-07-14 19:37:40 +0000891 if (OpNo == 0)
Chris Lattnerb5d70302007-02-19 20:01:23 +0000892 return ConstantExpr::getGetElementPtr(Op, &Ops[0], Ops.size());
Chris Lattner7c1018a2006-07-14 19:37:40 +0000893 Ops[OpNo-1] = Op;
Chris Lattnerb5d70302007-02-19 20:01:23 +0000894 return ConstantExpr::getGetElementPtr(getOperand(0), &Ops[0], Ops.size());
Chris Lattner7c1018a2006-07-14 19:37:40 +0000895 }
Chris Lattner7c1018a2006-07-14 19:37:40 +0000896 default:
897 assert(getNumOperands() == 2 && "Must be binary operator?");
Chris Lattner227816342006-07-14 22:20:01 +0000898 Op0 = (OpNo == 0) ? Op : getOperand(0);
899 Op1 = (OpNo == 1) ? Op : getOperand(1);
900 return ConstantExpr::get(getOpcode(), Op0, Op1);
901 }
902}
903
904/// getWithOperands - This returns the current constant expression with the
905/// operands replaced with the specified values. The specified operands must
906/// match count and type with the existing ones.
907Constant *ConstantExpr::
Chris Lattnerb078e282008-08-20 22:27:40 +0000908getWithOperands(Constant* const *Ops, unsigned NumOps) const {
909 assert(NumOps == getNumOperands() && "Operand count mismatch!");
Chris Lattner227816342006-07-14 22:20:01 +0000910 bool AnyChange = false;
Chris Lattnerb078e282008-08-20 22:27:40 +0000911 for (unsigned i = 0; i != NumOps; ++i) {
Chris Lattner227816342006-07-14 22:20:01 +0000912 assert(Ops[i]->getType() == getOperand(i)->getType() &&
913 "Operand type mismatch!");
914 AnyChange |= Ops[i] != getOperand(i);
915 }
916 if (!AnyChange) // No operands changed, return self.
917 return const_cast<ConstantExpr*>(this);
918
919 switch (getOpcode()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000920 case Instruction::Trunc:
921 case Instruction::ZExt:
922 case Instruction::SExt:
923 case Instruction::FPTrunc:
924 case Instruction::FPExt:
925 case Instruction::UIToFP:
926 case Instruction::SIToFP:
927 case Instruction::FPToUI:
928 case Instruction::FPToSI:
929 case Instruction::PtrToInt:
930 case Instruction::IntToPtr:
931 case Instruction::BitCast:
932 return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
Chris Lattner227816342006-07-14 22:20:01 +0000933 case Instruction::Select:
934 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
935 case Instruction::InsertElement:
936 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
937 case Instruction::ExtractElement:
938 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
939 case Instruction::ShuffleVector:
940 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
Chris Lattnerb5d70302007-02-19 20:01:23 +0000941 case Instruction::GetElementPtr:
Chris Lattnerb078e282008-08-20 22:27:40 +0000942 return ConstantExpr::getGetElementPtr(Ops[0], &Ops[1], NumOps-1);
Reid Spencer266e42b2006-12-23 06:05:41 +0000943 case Instruction::ICmp:
944 case Instruction::FCmp:
Nate Begeman098cc6f2008-07-25 17:56:27 +0000945 case Instruction::VICmp:
946 case Instruction::VFCmp:
Reid Spencer266e42b2006-12-23 06:05:41 +0000947 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
Chris Lattner227816342006-07-14 22:20:01 +0000948 default:
949 assert(getNumOperands() == 2 && "Must be binary operator?");
950 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1]);
Chris Lattner7c1018a2006-07-14 19:37:40 +0000951 }
952}
953
Chris Lattner2f7c9632001-06-06 20:29:01 +0000954
955//===----------------------------------------------------------------------===//
Chris Lattner2f7c9632001-06-06 20:29:01 +0000956// isValueValidForType implementations
957
Reid Spencere7334722006-12-19 01:28:19 +0000958bool ConstantInt::isValueValidForType(const Type *Ty, uint64_t Val) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000959 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000960 if (Ty == Type::Int1Ty)
961 return Val == 0 || Val == 1;
Reid Spencerd7a00d72007-02-05 23:47:56 +0000962 if (NumBits >= 64)
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000963 return true; // always true, has to fit in largest type
964 uint64_t Max = (1ll << NumBits) - 1;
965 return Val <= Max;
Reid Spencere7334722006-12-19 01:28:19 +0000966}
967
Reid Spencere0fc4df2006-10-20 07:07:24 +0000968bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000969 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000970 if (Ty == Type::Int1Ty)
Reid Spencera94d3942007-01-19 21:13:56 +0000971 return Val == 0 || Val == 1 || Val == -1;
Reid Spencerd7a00d72007-02-05 23:47:56 +0000972 if (NumBits >= 64)
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000973 return true; // always true, has to fit in largest type
974 int64_t Min = -(1ll << (NumBits-1));
975 int64_t Max = (1ll << (NumBits-1)) - 1;
976 return (Val >= Min && Val <= Max);
Chris Lattner2f7c9632001-06-06 20:29:01 +0000977}
978
Dale Johannesend246b2c2007-08-30 00:23:21 +0000979bool ConstantFP::isValueValidForType(const Type *Ty, const APFloat& Val) {
980 // convert modifies in place, so make a copy.
981 APFloat Val2 = APFloat(Val);
Dale Johannesen4f0bd682008-10-09 23:00:39 +0000982 bool losesInfo;
Chris Lattner6b727592004-06-17 18:19:28 +0000983 switch (Ty->getTypeID()) {
Chris Lattner2f7c9632001-06-06 20:29:01 +0000984 default:
985 return false; // These can't be represented as floating point!
986
Dale Johannesend246b2c2007-08-30 00:23:21 +0000987 // FIXME rounding mode needs to be more flexible
Dale Johannesen4f0bd682008-10-09 23:00:39 +0000988 case Type::FloatTyID: {
989 if (&Val2.getSemantics() == &APFloat::IEEEsingle)
990 return true;
991 Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &losesInfo);
992 return !losesInfo;
993 }
994 case Type::DoubleTyID: {
995 if (&Val2.getSemantics() == &APFloat::IEEEsingle ||
996 &Val2.getSemantics() == &APFloat::IEEEdouble)
997 return true;
998 Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &losesInfo);
999 return !losesInfo;
1000 }
Dale Johannesenbdad8092007-08-09 22:51:36 +00001001 case Type::X86_FP80TyID:
Dale Johannesen028084e2007-09-12 03:30:33 +00001002 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
1003 &Val2.getSemantics() == &APFloat::IEEEdouble ||
1004 &Val2.getSemantics() == &APFloat::x87DoubleExtended;
Dale Johannesenbdad8092007-08-09 22:51:36 +00001005 case Type::FP128TyID:
Dale Johannesen028084e2007-09-12 03:30:33 +00001006 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
1007 &Val2.getSemantics() == &APFloat::IEEEdouble ||
1008 &Val2.getSemantics() == &APFloat::IEEEquad;
Dale Johannesen007aa372007-10-11 18:07:22 +00001009 case Type::PPC_FP128TyID:
1010 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
1011 &Val2.getSemantics() == &APFloat::IEEEdouble ||
1012 &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
Chris Lattner2f7c9632001-06-06 20:29:01 +00001013 }
Chris Lattneraa2372562006-05-24 17:04:05 +00001014}
Chris Lattner9655e542001-07-20 19:16:02 +00001015
Chris Lattner49d855c2001-09-07 16:46:31 +00001016//===----------------------------------------------------------------------===//
Chris Lattner49d855c2001-09-07 16:46:31 +00001017// Factory Function Implementation
1018
Gabor Greiff6caff662008-05-10 08:32:32 +00001019
1020// The number of operands for each ConstantCreator::create method is
1021// determined by the ConstantTraits template.
Chris Lattner98fa07b2003-05-23 20:03:32 +00001022// ConstantCreator - A class that is used to create constants by
1023// ValueMap*. This class should be partially specialized if there is
1024// something strange that needs to be done to interface to the ctor for the
1025// constant.
1026//
Chris Lattner189d19f2003-11-21 20:23:48 +00001027namespace llvm {
Gabor Greiff6caff662008-05-10 08:32:32 +00001028 template<class ValType>
1029 struct ConstantTraits;
1030
1031 template<typename T, typename Alloc>
1032 struct VISIBILITY_HIDDEN ConstantTraits< std::vector<T, Alloc> > {
1033 static unsigned uses(const std::vector<T, Alloc>& v) {
1034 return v.size();
1035 }
1036 };
1037
Chris Lattner189d19f2003-11-21 20:23:48 +00001038 template<class ConstantClass, class TypeClass, class ValType>
Chris Lattner02157b02006-06-28 21:38:54 +00001039 struct VISIBILITY_HIDDEN ConstantCreator {
Chris Lattner189d19f2003-11-21 20:23:48 +00001040 static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
Gabor Greiff6caff662008-05-10 08:32:32 +00001041 return new(ConstantTraits<ValType>::uses(V)) ConstantClass(Ty, V);
Chris Lattner189d19f2003-11-21 20:23:48 +00001042 }
1043 };
Misha Brukmanb1c93172005-04-21 23:48:37 +00001044
Chris Lattner189d19f2003-11-21 20:23:48 +00001045 template<class ConstantClass, class TypeClass>
Chris Lattner02157b02006-06-28 21:38:54 +00001046 struct VISIBILITY_HIDDEN ConvertConstantType {
Chris Lattner189d19f2003-11-21 20:23:48 +00001047 static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
1048 assert(0 && "This type cannot be converted!\n");
1049 abort();
1050 }
1051 };
Chris Lattnerb50d1352003-10-05 00:17:43 +00001052
Chris Lattner935aa922005-10-04 17:48:46 +00001053 template<class ValType, class TypeClass, class ConstantClass,
1054 bool HasLargeKey = false /*true for arrays and structs*/ >
Chris Lattner02157b02006-06-28 21:38:54 +00001055 class VISIBILITY_HIDDEN ValueMap : public AbstractTypeUser {
Chris Lattnerb64419a2005-10-03 22:51:37 +00001056 public:
Jim Laskeyc03caef2006-07-17 17:38:29 +00001057 typedef std::pair<const Type*, ValType> MapKey;
1058 typedef std::map<MapKey, Constant *> MapTy;
1059 typedef std::map<Constant*, typename MapTy::iterator> InverseMapTy;
1060 typedef std::map<const Type*, typename MapTy::iterator> AbstractTypeMapTy;
Chris Lattnerb64419a2005-10-03 22:51:37 +00001061 private:
Chris Lattner5bbf60a52005-10-04 16:52:46 +00001062 /// Map - This is the main map from the element descriptor to the Constants.
1063 /// This is the primary way we avoid creating two of the same shape
1064 /// constant.
Chris Lattnerb50d1352003-10-05 00:17:43 +00001065 MapTy Map;
Chris Lattner935aa922005-10-04 17:48:46 +00001066
1067 /// InverseMap - If "HasLargeKey" is true, this contains an inverse mapping
1068 /// from the constants to their element in Map. This is important for
1069 /// removal of constants from the array, which would otherwise have to scan
1070 /// through the map with very large keys.
Jim Laskeyc03caef2006-07-17 17:38:29 +00001071 InverseMapTy InverseMap;
Chris Lattnerb50d1352003-10-05 00:17:43 +00001072
Jim Laskeyc03caef2006-07-17 17:38:29 +00001073 /// AbstractTypeMap - Map for abstract type constants.
1074 ///
Chris Lattnerb50d1352003-10-05 00:17:43 +00001075 AbstractTypeMapTy AbstractTypeMap;
Chris Lattner99a669b2004-11-19 16:39:44 +00001076
Chris Lattner98fa07b2003-05-23 20:03:32 +00001077 public:
Jim Laskeyc03caef2006-07-17 17:38:29 +00001078 typename MapTy::iterator map_end() { return Map.end(); }
Chris Lattnerb64419a2005-10-03 22:51:37 +00001079
1080 /// InsertOrGetItem - Return an iterator for the specified element.
1081 /// If the element exists in the map, the returned iterator points to the
1082 /// entry and Exists=true. If not, the iterator points to the newly
1083 /// inserted entry and returns Exists=false. Newly inserted entries have
1084 /// I->second == 0, and should be filled in.
Jim Laskeyc03caef2006-07-17 17:38:29 +00001085 typename MapTy::iterator InsertOrGetItem(std::pair<MapKey, Constant *>
1086 &InsertVal,
Chris Lattnerb64419a2005-10-03 22:51:37 +00001087 bool &Exists) {
Jim Laskeyc03caef2006-07-17 17:38:29 +00001088 std::pair<typename MapTy::iterator, bool> IP = Map.insert(InsertVal);
Chris Lattnerb64419a2005-10-03 22:51:37 +00001089 Exists = !IP.second;
1090 return IP.first;
1091 }
Chris Lattner5bbf60a52005-10-04 16:52:46 +00001092
Chris Lattner935aa922005-10-04 17:48:46 +00001093private:
Jim Laskeyc03caef2006-07-17 17:38:29 +00001094 typename MapTy::iterator FindExistingElement(ConstantClass *CP) {
Chris Lattner935aa922005-10-04 17:48:46 +00001095 if (HasLargeKey) {
Jim Laskeyc03caef2006-07-17 17:38:29 +00001096 typename InverseMapTy::iterator IMI = InverseMap.find(CP);
Chris Lattner935aa922005-10-04 17:48:46 +00001097 assert(IMI != InverseMap.end() && IMI->second != Map.end() &&
1098 IMI->second->second == CP &&
1099 "InverseMap corrupt!");
1100 return IMI->second;
1101 }
1102
Jim Laskeyc03caef2006-07-17 17:38:29 +00001103 typename MapTy::iterator I =
Dan Gohmane955c482008-08-05 14:45:15 +00001104 Map.find(MapKey(static_cast<const TypeClass*>(CP->getRawType()),
1105 getValType(CP)));
Chris Lattner5bbf60a52005-10-04 16:52:46 +00001106 if (I == Map.end() || I->second != CP) {
1107 // FIXME: This should not use a linear scan. If this gets to be a
1108 // performance problem, someone should look at this.
1109 for (I = Map.begin(); I != Map.end() && I->second != CP; ++I)
1110 /* empty */;
1111 }
Chris Lattner935aa922005-10-04 17:48:46 +00001112 return I;
1113 }
1114public:
1115
Chris Lattnerb64419a2005-10-03 22:51:37 +00001116 /// getOrCreate - Return the specified constant from the map, creating it if
1117 /// necessary.
Chris Lattner98fa07b2003-05-23 20:03:32 +00001118 ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
Chris Lattnerb50d1352003-10-05 00:17:43 +00001119 MapKey Lookup(Ty, V);
Dan Gohman3707f1d2008-07-11 20:58:19 +00001120 typename MapTy::iterator I = Map.find(Lookup);
Reid Spencere0fc4df2006-10-20 07:07:24 +00001121 // Is it in the map?
Dan Gohman3707f1d2008-07-11 20:58:19 +00001122 if (I != Map.end())
Reid Spencere0fc4df2006-10-20 07:07:24 +00001123 return static_cast<ConstantClass *>(I->second);
Chris Lattner98fa07b2003-05-23 20:03:32 +00001124
1125 // If no preexisting value, create one now...
1126 ConstantClass *Result =
1127 ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
1128
Chris Lattnerf97ab6d2008-08-23 03:48:35 +00001129 assert(Result->getType() == Ty && "Type specified is not correct!");
Chris Lattnerb50d1352003-10-05 00:17:43 +00001130 I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
1131
Chris Lattner935aa922005-10-04 17:48:46 +00001132 if (HasLargeKey) // Remember the reverse mapping if needed.
1133 InverseMap.insert(std::make_pair(Result, I));
1134
Chris Lattnerb50d1352003-10-05 00:17:43 +00001135 // If the type of the constant is abstract, make sure that an entry exists
1136 // for it in the AbstractTypeMap.
1137 if (Ty->isAbstract()) {
Dan Gohman3707f1d2008-07-11 20:58:19 +00001138 typename AbstractTypeMapTy::iterator TI = AbstractTypeMap.find(Ty);
Chris Lattnerb50d1352003-10-05 00:17:43 +00001139
Dan Gohman3707f1d2008-07-11 20:58:19 +00001140 if (TI == AbstractTypeMap.end()) {
Chris Lattnerb50d1352003-10-05 00:17:43 +00001141 // Add ourselves to the ATU list of the type.
1142 cast<DerivedType>(Ty)->addAbstractTypeUser(this);
1143
1144 AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
1145 }
1146 }
Chris Lattner98fa07b2003-05-23 20:03:32 +00001147 return Result;
1148 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001149
Chris Lattner98fa07b2003-05-23 20:03:32 +00001150 void remove(ConstantClass *CP) {
Jim Laskeyc03caef2006-07-17 17:38:29 +00001151 typename MapTy::iterator I = FindExistingElement(CP);
Chris Lattnerb50d1352003-10-05 00:17:43 +00001152 assert(I != Map.end() && "Constant not found in constant table!");
Chris Lattner3e650af2004-08-04 04:48:01 +00001153 assert(I->second == CP && "Didn't find correct element?");
Chris Lattnerb50d1352003-10-05 00:17:43 +00001154
Chris Lattner935aa922005-10-04 17:48:46 +00001155 if (HasLargeKey) // Remember the reverse mapping if needed.
1156 InverseMap.erase(CP);
1157
Chris Lattnerb50d1352003-10-05 00:17:43 +00001158 // Now that we found the entry, make sure this isn't the entry that
1159 // the AbstractTypeMap points to.
Jim Laskeyc03caef2006-07-17 17:38:29 +00001160 const TypeClass *Ty = static_cast<const TypeClass *>(I->first.first);
Chris Lattnerb50d1352003-10-05 00:17:43 +00001161 if (Ty->isAbstract()) {
1162 assert(AbstractTypeMap.count(Ty) &&
1163 "Abstract type not in AbstractTypeMap?");
Jim Laskeyc03caef2006-07-17 17:38:29 +00001164 typename MapTy::iterator &ATMEntryIt = AbstractTypeMap[Ty];
Chris Lattnerb50d1352003-10-05 00:17:43 +00001165 if (ATMEntryIt == I) {
1166 // Yes, we are removing the representative entry for this type.
1167 // See if there are any other entries of the same type.
Jim Laskeyc03caef2006-07-17 17:38:29 +00001168 typename MapTy::iterator TmpIt = ATMEntryIt;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001169
Chris Lattnerb50d1352003-10-05 00:17:43 +00001170 // First check the entry before this one...
1171 if (TmpIt != Map.begin()) {
1172 --TmpIt;
1173 if (TmpIt->first.first != Ty) // Not the same type, move back...
1174 ++TmpIt;
1175 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001176
Chris Lattnerb50d1352003-10-05 00:17:43 +00001177 // If we didn't find the same type, try to move forward...
1178 if (TmpIt == ATMEntryIt) {
1179 ++TmpIt;
1180 if (TmpIt == Map.end() || TmpIt->first.first != Ty)
1181 --TmpIt; // No entry afterwards with the same type
1182 }
1183
1184 // If there is another entry in the map of the same abstract type,
1185 // update the AbstractTypeMap entry now.
1186 if (TmpIt != ATMEntryIt) {
1187 ATMEntryIt = TmpIt;
1188 } else {
1189 // Otherwise, we are removing the last instance of this type
1190 // from the table. Remove from the ATM, and from user list.
1191 cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
1192 AbstractTypeMap.erase(Ty);
1193 }
Chris Lattner98fa07b2003-05-23 20:03:32 +00001194 }
Chris Lattnerb50d1352003-10-05 00:17:43 +00001195 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001196
Chris Lattnerb50d1352003-10-05 00:17:43 +00001197 Map.erase(I);
1198 }
1199
Chris Lattner3b793c62005-10-04 21:35:50 +00001200
1201 /// MoveConstantToNewSlot - If we are about to change C to be the element
1202 /// specified by I, update our internal data structures to reflect this
1203 /// fact.
Jim Laskeyc03caef2006-07-17 17:38:29 +00001204 void MoveConstantToNewSlot(ConstantClass *C, typename MapTy::iterator I) {
Chris Lattner3b793c62005-10-04 21:35:50 +00001205 // First, remove the old location of the specified constant in the map.
Jim Laskeyc03caef2006-07-17 17:38:29 +00001206 typename MapTy::iterator OldI = FindExistingElement(C);
Chris Lattner3b793c62005-10-04 21:35:50 +00001207 assert(OldI != Map.end() && "Constant not found in constant table!");
1208 assert(OldI->second == C && "Didn't find correct element?");
1209
1210 // If this constant is the representative element for its abstract type,
1211 // update the AbstractTypeMap so that the representative element is I.
1212 if (C->getType()->isAbstract()) {
1213 typename AbstractTypeMapTy::iterator ATI =
1214 AbstractTypeMap.find(C->getType());
1215 assert(ATI != AbstractTypeMap.end() &&
1216 "Abstract type not in AbstractTypeMap?");
1217 if (ATI->second == OldI)
1218 ATI->second = I;
1219 }
1220
1221 // Remove the old entry from the map.
1222 Map.erase(OldI);
1223
1224 // Update the inverse map so that we know that this constant is now
1225 // located at descriptor I.
1226 if (HasLargeKey) {
1227 assert(I->second == C && "Bad inversemap entry!");
1228 InverseMap[C] = I;
1229 }
1230 }
1231
Chris Lattnerb50d1352003-10-05 00:17:43 +00001232 void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00001233 typename AbstractTypeMapTy::iterator I =
Jim Laskeyc03caef2006-07-17 17:38:29 +00001234 AbstractTypeMap.find(cast<Type>(OldTy));
Chris Lattnerb50d1352003-10-05 00:17:43 +00001235
1236 assert(I != AbstractTypeMap.end() &&
1237 "Abstract type not in AbstractTypeMap?");
1238
1239 // Convert a constant at a time until the last one is gone. The last one
1240 // leaving will remove() itself, causing the AbstractTypeMapEntry to be
1241 // eliminated eventually.
1242 do {
1243 ConvertConstantType<ConstantClass,
Jim Laskeyc03caef2006-07-17 17:38:29 +00001244 TypeClass>::convert(
1245 static_cast<ConstantClass *>(I->second->second),
Chris Lattnerb50d1352003-10-05 00:17:43 +00001246 cast<TypeClass>(NewTy));
1247
Jim Laskeyc03caef2006-07-17 17:38:29 +00001248 I = AbstractTypeMap.find(cast<Type>(OldTy));
Chris Lattnerb50d1352003-10-05 00:17:43 +00001249 } while (I != AbstractTypeMap.end());
1250 }
1251
1252 // If the type became concrete without being refined to any other existing
1253 // type, we just remove ourselves from the ATU list.
1254 void typeBecameConcrete(const DerivedType *AbsTy) {
1255 AbsTy->removeAbstractTypeUser(this);
1256 }
1257
1258 void dump() const {
Bill Wendling6a462f12006-11-17 08:03:48 +00001259 DOUT << "Constant.cpp: ValueMap\n";
Chris Lattner98fa07b2003-05-23 20:03:32 +00001260 }
1261 };
1262}
1263
Chris Lattnera84df0a22006-09-28 23:36:21 +00001264
Chris Lattner28173502007-02-20 06:11:36 +00001265
Chris Lattner9fba3da2004-02-15 05:53:04 +00001266//---- ConstantAggregateZero::get() implementation...
1267//
1268namespace llvm {
1269 // ConstantAggregateZero does not take extra "value" argument...
1270 template<class ValType>
1271 struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
1272 static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
1273 return new ConstantAggregateZero(Ty);
1274 }
1275 };
1276
1277 template<>
1278 struct ConvertConstantType<ConstantAggregateZero, Type> {
1279 static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
1280 // Make everyone now use a constant of the new type...
1281 Constant *New = ConstantAggregateZero::get(NewTy);
1282 assert(New != OldC && "Didn't replace constant??");
1283 OldC->uncheckedReplaceAllUsesWith(New);
1284 OldC->destroyConstant(); // This constant is now dead, destroy it.
1285 }
1286 };
1287}
1288
Chris Lattner69edc982006-09-28 00:35:06 +00001289static ManagedStatic<ValueMap<char, Type,
1290 ConstantAggregateZero> > AggZeroConstants;
Chris Lattner9fba3da2004-02-15 05:53:04 +00001291
Chris Lattner3e650af2004-08-04 04:48:01 +00001292static char getValType(ConstantAggregateZero *CPZ) { return 0; }
1293
Dan Gohman8214fc12008-12-08 07:10:54 +00001294ConstantAggregateZero *ConstantAggregateZero::get(const Type *Ty) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001295 assert((isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) &&
Chris Lattnerbfd0b6d2006-06-10 04:16:23 +00001296 "Cannot create an aggregate zero of non-aggregate type!");
Chris Lattner69edc982006-09-28 00:35:06 +00001297 return AggZeroConstants->getOrCreate(Ty, 0);
Chris Lattner9fba3da2004-02-15 05:53:04 +00001298}
1299
Dan Gohman92b551b2009-03-03 02:55:14 +00001300/// destroyConstant - Remove the constant from the constant table...
1301///
Chris Lattner9fba3da2004-02-15 05:53:04 +00001302void ConstantAggregateZero::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00001303 AggZeroConstants->remove(this);
Chris Lattner9fba3da2004-02-15 05:53:04 +00001304 destroyConstantImpl();
1305}
1306
Chris Lattner3462ae32001-12-03 22:26:30 +00001307//---- ConstantArray::get() implementation...
Chris Lattner49d855c2001-09-07 16:46:31 +00001308//
Chris Lattner189d19f2003-11-21 20:23:48 +00001309namespace llvm {
1310 template<>
1311 struct ConvertConstantType<ConstantArray, ArrayType> {
1312 static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
1313 // Make everyone now use a constant of the new type...
1314 std::vector<Constant*> C;
1315 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1316 C.push_back(cast<Constant>(OldC->getOperand(i)));
1317 Constant *New = ConstantArray::get(NewTy, C);
1318 assert(New != OldC && "Didn't replace constant??");
1319 OldC->uncheckedReplaceAllUsesWith(New);
1320 OldC->destroyConstant(); // This constant is now dead, destroy it.
1321 }
1322 };
1323}
Chris Lattnerb50d1352003-10-05 00:17:43 +00001324
Chris Lattner3e650af2004-08-04 04:48:01 +00001325static std::vector<Constant*> getValType(ConstantArray *CA) {
1326 std::vector<Constant*> Elements;
1327 Elements.reserve(CA->getNumOperands());
1328 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1329 Elements.push_back(cast<Constant>(CA->getOperand(i)));
1330 return Elements;
1331}
1332
Chris Lattnerb64419a2005-10-03 22:51:37 +00001333typedef ValueMap<std::vector<Constant*>, ArrayType,
Chris Lattner935aa922005-10-04 17:48:46 +00001334 ConstantArray, true /*largekey*/> ArrayConstantsTy;
Chris Lattner69edc982006-09-28 00:35:06 +00001335static ManagedStatic<ArrayConstantsTy> ArrayConstants;
Chris Lattner49d855c2001-09-07 16:46:31 +00001336
Chris Lattner015e8212004-02-15 04:14:47 +00001337Constant *ConstantArray::get(const ArrayType *Ty,
Chris Lattner9fba3da2004-02-15 05:53:04 +00001338 const std::vector<Constant*> &V) {
1339 // If this is an all-zero array, return a ConstantAggregateZero object
1340 if (!V.empty()) {
1341 Constant *C = V[0];
1342 if (!C->isNullValue())
Chris Lattner69edc982006-09-28 00:35:06 +00001343 return ArrayConstants->getOrCreate(Ty, V);
Chris Lattner9fba3da2004-02-15 05:53:04 +00001344 for (unsigned i = 1, e = V.size(); i != e; ++i)
1345 if (V[i] != C)
Chris Lattner69edc982006-09-28 00:35:06 +00001346 return ArrayConstants->getOrCreate(Ty, V);
Chris Lattner9fba3da2004-02-15 05:53:04 +00001347 }
1348 return ConstantAggregateZero::get(Ty);
Chris Lattner49d855c2001-09-07 16:46:31 +00001349}
1350
Dan Gohman92b551b2009-03-03 02:55:14 +00001351/// destroyConstant - Remove the constant from the constant table...
1352///
Chris Lattner98fa07b2003-05-23 20:03:32 +00001353void ConstantArray::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00001354 ArrayConstants->remove(this);
Chris Lattner98fa07b2003-05-23 20:03:32 +00001355 destroyConstantImpl();
1356}
1357
Reid Spencer6f614532006-05-30 08:23:18 +00001358/// ConstantArray::get(const string&) - Return an array that is initialized to
1359/// contain the specified string. If length is zero then a null terminator is
1360/// added to the specified string so that it may be used in a natural way.
1361/// Otherwise, the length parameter specifies how much of the string to use
1362/// and it won't be null terminated.
1363///
Reid Spencer82ebaba2006-05-30 18:15:07 +00001364Constant *ConstantArray::get(const std::string &Str, bool AddNull) {
Chris Lattner7f74a562002-01-20 22:54:45 +00001365 std::vector<Constant*> ElementVals;
Reid Spencer82ebaba2006-05-30 18:15:07 +00001366 for (unsigned i = 0; i < Str.length(); ++i)
Reid Spencer8d9336d2006-12-31 05:26:44 +00001367 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, Str[i]));
Chris Lattner8f80fe02001-10-14 23:54:12 +00001368
1369 // Add a null terminator to the string...
Reid Spencer82ebaba2006-05-30 18:15:07 +00001370 if (AddNull) {
Reid Spencer8d9336d2006-12-31 05:26:44 +00001371 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, 0));
Reid Spencer6f614532006-05-30 08:23:18 +00001372 }
Chris Lattner8f80fe02001-10-14 23:54:12 +00001373
Reid Spencer8d9336d2006-12-31 05:26:44 +00001374 ArrayType *ATy = ArrayType::get(Type::Int8Ty, ElementVals.size());
Chris Lattner3462ae32001-12-03 22:26:30 +00001375 return ConstantArray::get(ATy, ElementVals);
Vikram S. Adve34410432001-10-14 23:17:20 +00001376}
1377
Reid Spencer2546b762007-01-26 07:37:34 +00001378/// isString - This method returns true if the array is an array of i8, and
1379/// if the elements of the array are all ConstantInt's.
Chris Lattnere8dfcca2004-01-14 17:06:38 +00001380bool ConstantArray::isString() const {
Reid Spencer2546b762007-01-26 07:37:34 +00001381 // Check the element type for i8...
Reid Spencer8d9336d2006-12-31 05:26:44 +00001382 if (getType()->getElementType() != Type::Int8Ty)
Chris Lattnere8dfcca2004-01-14 17:06:38 +00001383 return false;
1384 // Check the elements to make sure they are all integers, not constant
1385 // expressions.
1386 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1387 if (!isa<ConstantInt>(getOperand(i)))
1388 return false;
1389 return true;
1390}
1391
Evan Cheng3763c5b2006-10-26 19:15:05 +00001392/// isCString - This method returns true if the array is a string (see
Dan Gohman92b551b2009-03-03 02:55:14 +00001393/// isString) and it ends in a null byte \\0 and does not contains any other
Evan Cheng3763c5b2006-10-26 19:15:05 +00001394/// null bytes except its terminator.
1395bool ConstantArray::isCString() const {
Reid Spencer2546b762007-01-26 07:37:34 +00001396 // Check the element type for i8...
Reid Spencer8d9336d2006-12-31 05:26:44 +00001397 if (getType()->getElementType() != Type::Int8Ty)
Evan Chenge974da62006-10-26 21:48:03 +00001398 return false;
1399 Constant *Zero = Constant::getNullValue(getOperand(0)->getType());
1400 // Last element must be a null.
1401 if (getOperand(getNumOperands()-1) != Zero)
1402 return false;
1403 // Other elements must be non-null integers.
1404 for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
1405 if (!isa<ConstantInt>(getOperand(i)))
Evan Cheng3763c5b2006-10-26 19:15:05 +00001406 return false;
Evan Chenge974da62006-10-26 21:48:03 +00001407 if (getOperand(i) == Zero)
1408 return false;
1409 }
Evan Cheng3763c5b2006-10-26 19:15:05 +00001410 return true;
1411}
1412
1413
Dan Gohman92b551b2009-03-03 02:55:14 +00001414/// getAsString - If the sub-element type of this array is i8
1415/// then this method converts the array to an std::string and returns it.
1416/// Otherwise, it asserts out.
1417///
Chris Lattner81fabb02002-08-26 17:53:56 +00001418std::string ConstantArray::getAsString() const {
Chris Lattnere8dfcca2004-01-14 17:06:38 +00001419 assert(isString() && "Not a string!");
Chris Lattner81fabb02002-08-26 17:53:56 +00001420 std::string Result;
Owen Anderson79c69bc2008-06-24 21:58:29 +00001421 Result.reserve(getNumOperands());
Chris Lattner6077c312003-07-23 15:22:26 +00001422 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
Owen Andersonee9c30d2008-06-25 01:05:05 +00001423 Result.push_back((char)cast<ConstantInt>(getOperand(i))->getZExtValue());
Chris Lattner81fabb02002-08-26 17:53:56 +00001424 return Result;
1425}
1426
1427
Chris Lattner3462ae32001-12-03 22:26:30 +00001428//---- ConstantStruct::get() implementation...
Chris Lattner49d855c2001-09-07 16:46:31 +00001429//
Chris Lattnerb50d1352003-10-05 00:17:43 +00001430
Chris Lattner189d19f2003-11-21 20:23:48 +00001431namespace llvm {
1432 template<>
1433 struct ConvertConstantType<ConstantStruct, StructType> {
1434 static void convert(ConstantStruct *OldC, const StructType *NewTy) {
1435 // Make everyone now use a constant of the new type...
1436 std::vector<Constant*> C;
1437 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1438 C.push_back(cast<Constant>(OldC->getOperand(i)));
1439 Constant *New = ConstantStruct::get(NewTy, C);
1440 assert(New != OldC && "Didn't replace constant??");
Misha Brukmanb1c93172005-04-21 23:48:37 +00001441
Chris Lattner189d19f2003-11-21 20:23:48 +00001442 OldC->uncheckedReplaceAllUsesWith(New);
1443 OldC->destroyConstant(); // This constant is now dead, destroy it.
1444 }
1445 };
1446}
Chris Lattnerb50d1352003-10-05 00:17:43 +00001447
Chris Lattner8760ec72005-10-04 01:17:50 +00001448typedef ValueMap<std::vector<Constant*>, StructType,
Chris Lattner935aa922005-10-04 17:48:46 +00001449 ConstantStruct, true /*largekey*/> StructConstantsTy;
Chris Lattner69edc982006-09-28 00:35:06 +00001450static ManagedStatic<StructConstantsTy> StructConstants;
Chris Lattner49d855c2001-09-07 16:46:31 +00001451
Chris Lattner3e650af2004-08-04 04:48:01 +00001452static std::vector<Constant*> getValType(ConstantStruct *CS) {
1453 std::vector<Constant*> Elements;
1454 Elements.reserve(CS->getNumOperands());
1455 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1456 Elements.push_back(cast<Constant>(CS->getOperand(i)));
1457 return Elements;
1458}
1459
Chris Lattner015e8212004-02-15 04:14:47 +00001460Constant *ConstantStruct::get(const StructType *Ty,
1461 const std::vector<Constant*> &V) {
Chris Lattner9fba3da2004-02-15 05:53:04 +00001462 // Create a ConstantAggregateZero value if all elements are zeros...
1463 for (unsigned i = 0, e = V.size(); i != e; ++i)
1464 if (!V[i]->isNullValue())
Chris Lattner69edc982006-09-28 00:35:06 +00001465 return StructConstants->getOrCreate(Ty, V);
Chris Lattner9fba3da2004-02-15 05:53:04 +00001466
1467 return ConstantAggregateZero::get(Ty);
Chris Lattner49d855c2001-09-07 16:46:31 +00001468}
Chris Lattner883ad0b2001-10-03 15:39:36 +00001469
Andrew Lenharthdcb3c972006-12-08 18:06:16 +00001470Constant *ConstantStruct::get(const std::vector<Constant*> &V, bool packed) {
Chris Lattnerd6108ca2004-07-12 20:35:11 +00001471 std::vector<const Type*> StructEls;
1472 StructEls.reserve(V.size());
1473 for (unsigned i = 0, e = V.size(); i != e; ++i)
1474 StructEls.push_back(V[i]->getType());
Andrew Lenharthdcb3c972006-12-08 18:06:16 +00001475 return get(StructType::get(StructEls, packed), V);
Chris Lattnerd6108ca2004-07-12 20:35:11 +00001476}
1477
Chris Lattnerd7a73302001-10-13 06:57:33 +00001478// destroyConstant - Remove the constant from the constant table...
Chris Lattner883ad0b2001-10-03 15:39:36 +00001479//
Chris Lattner3462ae32001-12-03 22:26:30 +00001480void ConstantStruct::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00001481 StructConstants->remove(this);
Chris Lattnerd7a73302001-10-13 06:57:33 +00001482 destroyConstantImpl();
1483}
Chris Lattner883ad0b2001-10-03 15:39:36 +00001484
Reid Spencerd84d35b2007-02-15 02:26:10 +00001485//---- ConstantVector::get() implementation...
Brian Gaeke02209042004-08-20 06:00:58 +00001486//
1487namespace llvm {
1488 template<>
Reid Spencerd84d35b2007-02-15 02:26:10 +00001489 struct ConvertConstantType<ConstantVector, VectorType> {
1490 static void convert(ConstantVector *OldC, const VectorType *NewTy) {
Brian Gaeke02209042004-08-20 06:00:58 +00001491 // Make everyone now use a constant of the new type...
1492 std::vector<Constant*> C;
1493 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1494 C.push_back(cast<Constant>(OldC->getOperand(i)));
Reid Spencerd84d35b2007-02-15 02:26:10 +00001495 Constant *New = ConstantVector::get(NewTy, C);
Brian Gaeke02209042004-08-20 06:00:58 +00001496 assert(New != OldC && "Didn't replace constant??");
1497 OldC->uncheckedReplaceAllUsesWith(New);
1498 OldC->destroyConstant(); // This constant is now dead, destroy it.
1499 }
1500 };
1501}
1502
Reid Spencerd84d35b2007-02-15 02:26:10 +00001503static std::vector<Constant*> getValType(ConstantVector *CP) {
Brian Gaeke02209042004-08-20 06:00:58 +00001504 std::vector<Constant*> Elements;
1505 Elements.reserve(CP->getNumOperands());
1506 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1507 Elements.push_back(CP->getOperand(i));
1508 return Elements;
1509}
1510
Reid Spencerd84d35b2007-02-15 02:26:10 +00001511static ManagedStatic<ValueMap<std::vector<Constant*>, VectorType,
Reid Spencer09575ba2007-02-15 03:39:18 +00001512 ConstantVector> > VectorConstants;
Brian Gaeke02209042004-08-20 06:00:58 +00001513
Reid Spencerd84d35b2007-02-15 02:26:10 +00001514Constant *ConstantVector::get(const VectorType *Ty,
Brian Gaeke02209042004-08-20 06:00:58 +00001515 const std::vector<Constant*> &V) {
Chris Lattnerd977c072008-07-10 00:44:03 +00001516 assert(!V.empty() && "Vectors can't be empty");
1517 // If this is an all-undef or alll-zero vector, return a
1518 // ConstantAggregateZero or UndefValue.
1519 Constant *C = V[0];
1520 bool isZero = C->isNullValue();
1521 bool isUndef = isa<UndefValue>(C);
1522
1523 if (isZero || isUndef) {
Brian Gaeke02209042004-08-20 06:00:58 +00001524 for (unsigned i = 1, e = V.size(); i != e; ++i)
Chris Lattnerd977c072008-07-10 00:44:03 +00001525 if (V[i] != C) {
1526 isZero = isUndef = false;
1527 break;
1528 }
Brian Gaeke02209042004-08-20 06:00:58 +00001529 }
Chris Lattnerd977c072008-07-10 00:44:03 +00001530
1531 if (isZero)
1532 return ConstantAggregateZero::get(Ty);
1533 if (isUndef)
1534 return UndefValue::get(Ty);
1535 return VectorConstants->getOrCreate(Ty, V);
Brian Gaeke02209042004-08-20 06:00:58 +00001536}
1537
Reid Spencerd84d35b2007-02-15 02:26:10 +00001538Constant *ConstantVector::get(const std::vector<Constant*> &V) {
Brian Gaeke02209042004-08-20 06:00:58 +00001539 assert(!V.empty() && "Cannot infer type if V is empty");
Reid Spencerd84d35b2007-02-15 02:26:10 +00001540 return get(VectorType::get(V.front()->getType(),V.size()), V);
Brian Gaeke02209042004-08-20 06:00:58 +00001541}
1542
1543// destroyConstant - Remove the constant from the constant table...
1544//
Reid Spencerd84d35b2007-02-15 02:26:10 +00001545void ConstantVector::destroyConstant() {
Reid Spencer09575ba2007-02-15 03:39:18 +00001546 VectorConstants->remove(this);
Brian Gaeke02209042004-08-20 06:00:58 +00001547 destroyConstantImpl();
1548}
1549
Dan Gohman30978072007-05-24 14:36:04 +00001550/// This function will return true iff every element in this vector constant
Jim Laskeyf0478822007-01-12 22:39:14 +00001551/// is set to all ones.
1552/// @returns true iff this constant's emements are all set to all ones.
1553/// @brief Determine if the value is all ones.
Reid Spencerd84d35b2007-02-15 02:26:10 +00001554bool ConstantVector::isAllOnesValue() const {
Jim Laskeyf0478822007-01-12 22:39:14 +00001555 // Check out first element.
1556 const Constant *Elt = getOperand(0);
1557 const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1558 if (!CI || !CI->isAllOnesValue()) return false;
1559 // Then make sure all remaining elements point to the same value.
1560 for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
1561 if (getOperand(I) != Elt) return false;
1562 }
1563 return true;
1564}
1565
Dan Gohman07159202007-10-17 17:51:30 +00001566/// getSplatValue - If this is a splat constant, where all of the
1567/// elements have the same value, return that value. Otherwise return null.
1568Constant *ConstantVector::getSplatValue() {
1569 // Check out first element.
1570 Constant *Elt = getOperand(0);
1571 // Then make sure all remaining elements point to the same value.
1572 for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
1573 if (getOperand(I) != Elt) return 0;
1574 return Elt;
1575}
1576
Chris Lattner3462ae32001-12-03 22:26:30 +00001577//---- ConstantPointerNull::get() implementation...
Chris Lattnerd7a73302001-10-13 06:57:33 +00001578//
Chris Lattner98fa07b2003-05-23 20:03:32 +00001579
Chris Lattner189d19f2003-11-21 20:23:48 +00001580namespace llvm {
1581 // ConstantPointerNull does not take extra "value" argument...
1582 template<class ValType>
1583 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1584 static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1585 return new ConstantPointerNull(Ty);
1586 }
1587 };
Chris Lattner98fa07b2003-05-23 20:03:32 +00001588
Chris Lattner189d19f2003-11-21 20:23:48 +00001589 template<>
1590 struct ConvertConstantType<ConstantPointerNull, PointerType> {
1591 static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1592 // Make everyone now use a constant of the new type...
1593 Constant *New = ConstantPointerNull::get(NewTy);
1594 assert(New != OldC && "Didn't replace constant??");
1595 OldC->uncheckedReplaceAllUsesWith(New);
1596 OldC->destroyConstant(); // This constant is now dead, destroy it.
1597 }
1598 };
1599}
Chris Lattnerb50d1352003-10-05 00:17:43 +00001600
Chris Lattner69edc982006-09-28 00:35:06 +00001601static ManagedStatic<ValueMap<char, PointerType,
1602 ConstantPointerNull> > NullPtrConstants;
Chris Lattnerd7a73302001-10-13 06:57:33 +00001603
Chris Lattner3e650af2004-08-04 04:48:01 +00001604static char getValType(ConstantPointerNull *) {
1605 return 0;
1606}
1607
1608
Chris Lattner3462ae32001-12-03 22:26:30 +00001609ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
Chris Lattner69edc982006-09-28 00:35:06 +00001610 return NullPtrConstants->getOrCreate(Ty, 0);
Chris Lattner883ad0b2001-10-03 15:39:36 +00001611}
1612
Chris Lattner0c6e0b92002-08-18 00:40:04 +00001613// destroyConstant - Remove the constant from the constant table...
1614//
1615void ConstantPointerNull::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00001616 NullPtrConstants->remove(this);
Chris Lattner0c6e0b92002-08-18 00:40:04 +00001617 destroyConstantImpl();
1618}
1619
1620
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001621//---- UndefValue::get() implementation...
1622//
1623
1624namespace llvm {
1625 // UndefValue does not take extra "value" argument...
1626 template<class ValType>
1627 struct ConstantCreator<UndefValue, Type, ValType> {
1628 static UndefValue *create(const Type *Ty, const ValType &V) {
1629 return new UndefValue(Ty);
1630 }
1631 };
1632
1633 template<>
1634 struct ConvertConstantType<UndefValue, Type> {
1635 static void convert(UndefValue *OldC, const Type *NewTy) {
1636 // Make everyone now use a constant of the new type.
1637 Constant *New = UndefValue::get(NewTy);
1638 assert(New != OldC && "Didn't replace constant??");
1639 OldC->uncheckedReplaceAllUsesWith(New);
1640 OldC->destroyConstant(); // This constant is now dead, destroy it.
1641 }
1642 };
1643}
1644
Chris Lattner69edc982006-09-28 00:35:06 +00001645static ManagedStatic<ValueMap<char, Type, UndefValue> > UndefValueConstants;
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001646
1647static char getValType(UndefValue *) {
1648 return 0;
1649}
1650
1651
1652UndefValue *UndefValue::get(const Type *Ty) {
Chris Lattner69edc982006-09-28 00:35:06 +00001653 return UndefValueConstants->getOrCreate(Ty, 0);
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001654}
1655
1656// destroyConstant - Remove the constant from the constant table.
1657//
1658void UndefValue::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00001659 UndefValueConstants->remove(this);
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001660 destroyConstantImpl();
1661}
1662
Nick Lewycky49f89192009-04-04 07:22:01 +00001663//---- MDString::get() implementation
1664//
1665
1666MDString::MDString(const char *begin, const char *end)
1667 : Constant(Type::EmptyStructTy, MDStringVal, 0, 0),
1668 StrBegin(begin), StrEnd(end) {}
1669
1670static ManagedStatic<StringMap<MDString*> > MDStringCache;
1671
1672MDString *MDString::get(const char *StrBegin, const char *StrEnd) {
1673 StringMapEntry<MDString *> &Entry = MDStringCache->GetOrCreateValue(StrBegin,
1674 StrEnd);
1675 MDString *&S = Entry.getValue();
1676 if (!S) S = new MDString(Entry.getKeyData(),
1677 Entry.getKeyData() + Entry.getKeyLength());
1678 return S;
1679}
1680
1681void MDString::destroyConstant() {
1682 MDStringCache->erase(MDStringCache->find(StrBegin, StrEnd));
1683 destroyConstantImpl();
1684}
1685
1686//---- MDNode::get() implementation
1687//
1688
1689static ManagedStatic<FoldingSet<MDNode> > MDNodeSet;
1690
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00001691MDNode::MDNode(Value*const* Vals, unsigned NumVals)
1692 : Constant(Type::EmptyStructTy, MDNodeVal, 0, 0) {
1693 for (unsigned i = 0; i != NumVals; ++i)
1694 Node.push_back(ElementVH(Vals[i], this));
Nick Lewycky49f89192009-04-04 07:22:01 +00001695}
1696
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00001697void MDNode::Profile(FoldingSetNodeID &ID) const {
1698 for (const_elem_iterator I = elem_begin(), E = elem_end(); I != E; ++I)
Nick Lewycky49f89192009-04-04 07:22:01 +00001699 ID.AddPointer(*I);
1700}
1701
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00001702MDNode *MDNode::get(Value*const* Vals, unsigned NumVals) {
Nick Lewycky49f89192009-04-04 07:22:01 +00001703 FoldingSetNodeID ID;
1704 for (unsigned i = 0; i != NumVals; ++i)
1705 ID.AddPointer(Vals[i]);
1706
1707 void *InsertPoint;
1708 if (MDNode *N = MDNodeSet->FindNodeOrInsertPos(ID, InsertPoint))
1709 return N;
1710
1711 // InsertPoint will have been set by the FindNodeOrInsertPos call.
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00001712 MDNode *N = new(0) MDNode(Vals, NumVals);
Nick Lewycky49f89192009-04-04 07:22:01 +00001713 MDNodeSet->InsertNode(N, InsertPoint);
1714 return N;
1715}
1716
1717void MDNode::destroyConstant() {
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00001718 MDNodeSet->RemoveNode(this);
Nick Lewycky49f89192009-04-04 07:22:01 +00001719 destroyConstantImpl();
1720}
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001721
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001722//---- ConstantExpr::get() implementations...
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001723//
Reid Spencer8d9336d2006-12-31 05:26:44 +00001724
Dan Gohmand78c4002008-05-13 00:00:25 +00001725namespace {
1726
Reid Spenceree3c9912006-12-04 05:19:50 +00001727struct ExprMapKeyType {
Dan Gohman1ecaf452008-05-31 00:58:22 +00001728 typedef SmallVector<unsigned, 4> IndexList;
1729
1730 ExprMapKeyType(unsigned opc,
1731 const std::vector<Constant*> &ops,
1732 unsigned short pred = 0,
1733 const IndexList &inds = IndexList())
1734 : opcode(opc), predicate(pred), operands(ops), indices(inds) {}
Reid Spencerdba6aa42006-12-04 18:38:05 +00001735 uint16_t opcode;
1736 uint16_t predicate;
Reid Spenceree3c9912006-12-04 05:19:50 +00001737 std::vector<Constant*> operands;
Dan Gohman1ecaf452008-05-31 00:58:22 +00001738 IndexList indices;
Reid Spenceree3c9912006-12-04 05:19:50 +00001739 bool operator==(const ExprMapKeyType& that) const {
1740 return this->opcode == that.opcode &&
1741 this->predicate == that.predicate &&
Bill Wendling97f7de82008-10-26 00:19:56 +00001742 this->operands == that.operands &&
Dan Gohman1ecaf452008-05-31 00:58:22 +00001743 this->indices == that.indices;
Reid Spenceree3c9912006-12-04 05:19:50 +00001744 }
1745 bool operator<(const ExprMapKeyType & that) const {
1746 return this->opcode < that.opcode ||
1747 (this->opcode == that.opcode && this->predicate < that.predicate) ||
1748 (this->opcode == that.opcode && this->predicate == that.predicate &&
Dan Gohman1ecaf452008-05-31 00:58:22 +00001749 this->operands < that.operands) ||
1750 (this->opcode == that.opcode && this->predicate == that.predicate &&
1751 this->operands == that.operands && this->indices < that.indices);
Reid Spenceree3c9912006-12-04 05:19:50 +00001752 }
1753
1754 bool operator!=(const ExprMapKeyType& that) const {
1755 return !(*this == that);
1756 }
1757};
Chris Lattner98fa07b2003-05-23 20:03:32 +00001758
Dan Gohmand78c4002008-05-13 00:00:25 +00001759}
1760
Chris Lattner189d19f2003-11-21 20:23:48 +00001761namespace llvm {
1762 template<>
1763 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
Reid Spencer10fbf0e2006-12-03 05:48:19 +00001764 static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V,
1765 unsigned short pred = 0) {
Reid Spenceree3c9912006-12-04 05:19:50 +00001766 if (Instruction::isCast(V.opcode))
1767 return new UnaryConstantExpr(V.opcode, V.operands[0], Ty);
1768 if ((V.opcode >= Instruction::BinaryOpsBegin &&
Reid Spencer2341c222007-02-02 02:16:23 +00001769 V.opcode < Instruction::BinaryOpsEnd))
Reid Spenceree3c9912006-12-04 05:19:50 +00001770 return new BinaryConstantExpr(V.opcode, V.operands[0], V.operands[1]);
1771 if (V.opcode == Instruction::Select)
1772 return new SelectConstantExpr(V.operands[0], V.operands[1],
1773 V.operands[2]);
1774 if (V.opcode == Instruction::ExtractElement)
1775 return new ExtractElementConstantExpr(V.operands[0], V.operands[1]);
1776 if (V.opcode == Instruction::InsertElement)
1777 return new InsertElementConstantExpr(V.operands[0], V.operands[1],
1778 V.operands[2]);
1779 if (V.opcode == Instruction::ShuffleVector)
1780 return new ShuffleVectorConstantExpr(V.operands[0], V.operands[1],
1781 V.operands[2]);
Dan Gohman1ecaf452008-05-31 00:58:22 +00001782 if (V.opcode == Instruction::InsertValue)
1783 return new InsertValueConstantExpr(V.operands[0], V.operands[1],
1784 V.indices, Ty);
1785 if (V.opcode == Instruction::ExtractValue)
1786 return new ExtractValueConstantExpr(V.operands[0], V.indices, Ty);
Reid Spenceree3c9912006-12-04 05:19:50 +00001787 if (V.opcode == Instruction::GetElementPtr) {
1788 std::vector<Constant*> IdxList(V.operands.begin()+1, V.operands.end());
Gabor Greife9ecc682008-04-06 20:25:17 +00001789 return GetElementPtrConstantExpr::Create(V.operands[0], IdxList, Ty);
Reid Spenceree3c9912006-12-04 05:19:50 +00001790 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001791
Reid Spenceree3c9912006-12-04 05:19:50 +00001792 // The compare instructions are weird. We have to encode the predicate
1793 // value and it is combined with the instruction opcode by multiplying
1794 // the opcode by one hundred. We must decode this to get the predicate.
1795 if (V.opcode == Instruction::ICmp)
Nate Begemand2195702008-05-12 19:01:56 +00001796 return new CompareConstantExpr(Ty, Instruction::ICmp, V.predicate,
Reid Spenceree3c9912006-12-04 05:19:50 +00001797 V.operands[0], V.operands[1]);
1798 if (V.opcode == Instruction::FCmp)
Nate Begemand2195702008-05-12 19:01:56 +00001799 return new CompareConstantExpr(Ty, Instruction::FCmp, V.predicate,
1800 V.operands[0], V.operands[1]);
1801 if (V.opcode == Instruction::VICmp)
1802 return new CompareConstantExpr(Ty, Instruction::VICmp, V.predicate,
1803 V.operands[0], V.operands[1]);
1804 if (V.opcode == Instruction::VFCmp)
1805 return new CompareConstantExpr(Ty, Instruction::VFCmp, V.predicate,
Reid Spenceree3c9912006-12-04 05:19:50 +00001806 V.operands[0], V.operands[1]);
1807 assert(0 && "Invalid ConstantExpr!");
Jeff Cohen9f469632006-12-15 21:47:01 +00001808 return 0;
Chris Lattnerb50d1352003-10-05 00:17:43 +00001809 }
Chris Lattner189d19f2003-11-21 20:23:48 +00001810 };
Chris Lattnerb50d1352003-10-05 00:17:43 +00001811
Chris Lattner189d19f2003-11-21 20:23:48 +00001812 template<>
1813 struct ConvertConstantType<ConstantExpr, Type> {
1814 static void convert(ConstantExpr *OldC, const Type *NewTy) {
1815 Constant *New;
1816 switch (OldC->getOpcode()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001817 case Instruction::Trunc:
1818 case Instruction::ZExt:
1819 case Instruction::SExt:
1820 case Instruction::FPTrunc:
1821 case Instruction::FPExt:
1822 case Instruction::UIToFP:
1823 case Instruction::SIToFP:
1824 case Instruction::FPToUI:
1825 case Instruction::FPToSI:
1826 case Instruction::PtrToInt:
1827 case Instruction::IntToPtr:
1828 case Instruction::BitCast:
Reid Spencerbb65ebf2006-12-12 23:36:14 +00001829 New = ConstantExpr::getCast(OldC->getOpcode(), OldC->getOperand(0),
1830 NewTy);
Chris Lattner189d19f2003-11-21 20:23:48 +00001831 break;
Chris Lattner6e415c02004-03-12 05:54:04 +00001832 case Instruction::Select:
1833 New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1834 OldC->getOperand(1),
1835 OldC->getOperand(2));
1836 break;
Chris Lattner189d19f2003-11-21 20:23:48 +00001837 default:
1838 assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
Reid Spencer7eb55b32006-11-02 01:53:59 +00001839 OldC->getOpcode() < Instruction::BinaryOpsEnd);
Chris Lattner189d19f2003-11-21 20:23:48 +00001840 New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1841 OldC->getOperand(1));
1842 break;
1843 case Instruction::GetElementPtr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00001844 // Make everyone now use a constant of the new type...
Chris Lattner13128ab2004-10-11 22:52:25 +00001845 std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
Chris Lattner302116a2007-01-31 04:40:28 +00001846 New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0),
1847 &Idx[0], Idx.size());
Chris Lattner189d19f2003-11-21 20:23:48 +00001848 break;
1849 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001850
Chris Lattner189d19f2003-11-21 20:23:48 +00001851 assert(New != OldC && "Didn't replace constant??");
1852 OldC->uncheckedReplaceAllUsesWith(New);
1853 OldC->destroyConstant(); // This constant is now dead, destroy it.
1854 }
1855 };
1856} // end namespace llvm
Chris Lattnerb50d1352003-10-05 00:17:43 +00001857
1858
Chris Lattner3e650af2004-08-04 04:48:01 +00001859static ExprMapKeyType getValType(ConstantExpr *CE) {
1860 std::vector<Constant*> Operands;
1861 Operands.reserve(CE->getNumOperands());
1862 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
1863 Operands.push_back(cast<Constant>(CE->getOperand(i)));
Reid Spenceree3c9912006-12-04 05:19:50 +00001864 return ExprMapKeyType(CE->getOpcode(), Operands,
Dan Gohman1ecaf452008-05-31 00:58:22 +00001865 CE->isCompare() ? CE->getPredicate() : 0,
1866 CE->hasIndices() ?
1867 CE->getIndices() : SmallVector<unsigned, 4>());
Chris Lattner3e650af2004-08-04 04:48:01 +00001868}
1869
Chris Lattner69edc982006-09-28 00:35:06 +00001870static ManagedStatic<ValueMap<ExprMapKeyType, Type,
1871 ConstantExpr> > ExprConstants;
Vikram S. Adve4c485332002-07-15 18:19:33 +00001872
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001873/// This is a utility function to handle folding of casts and lookup of the
Duncan Sands7d6c8ae2008-03-30 19:38:55 +00001874/// cast in the ExprConstants map. It is used by the various get* methods below.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001875static inline Constant *getFoldedCast(
1876 Instruction::CastOps opc, Constant *C, const Type *Ty) {
Chris Lattner815ae2b2003-10-07 22:19:19 +00001877 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001878 // Fold a few common cases
1879 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
1880 return FC;
Chris Lattneracdbe712003-04-17 19:24:48 +00001881
Vikram S. Adve4c485332002-07-15 18:19:33 +00001882 // Look up the constant in the table first to ensure uniqueness
Chris Lattner2b383d2e2003-05-13 21:37:02 +00001883 std::vector<Constant*> argVec(1, C);
Reid Spenceree3c9912006-12-04 05:19:50 +00001884 ExprMapKeyType Key(opc, argVec);
Chris Lattner69edc982006-09-28 00:35:06 +00001885 return ExprConstants->getOrCreate(Ty, Key);
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001886}
Reid Spencerf37dc652006-12-05 19:14:13 +00001887
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001888Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
1889 Instruction::CastOps opc = Instruction::CastOps(oc);
1890 assert(Instruction::isCast(opc) && "opcode out of range");
1891 assert(C && Ty && "Null arguments to getCast");
1892 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1893
1894 switch (opc) {
1895 default:
1896 assert(0 && "Invalid cast opcode");
1897 break;
1898 case Instruction::Trunc: return getTrunc(C, Ty);
Reid Spencerbb65ebf2006-12-12 23:36:14 +00001899 case Instruction::ZExt: return getZExt(C, Ty);
1900 case Instruction::SExt: return getSExt(C, Ty);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001901 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
1902 case Instruction::FPExt: return getFPExtend(C, Ty);
1903 case Instruction::UIToFP: return getUIToFP(C, Ty);
1904 case Instruction::SIToFP: return getSIToFP(C, Ty);
1905 case Instruction::FPToUI: return getFPToUI(C, Ty);
1906 case Instruction::FPToSI: return getFPToSI(C, Ty);
1907 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1908 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1909 case Instruction::BitCast: return getBitCast(C, Ty);
Chris Lattner1ece6f82005-01-01 15:59:57 +00001910 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001911 return 0;
Reid Spencerf37dc652006-12-05 19:14:13 +00001912}
1913
Reid Spencer5c140882006-12-04 20:17:56 +00001914Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
1915 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1916 return getCast(Instruction::BitCast, C, Ty);
1917 return getCast(Instruction::ZExt, C, Ty);
1918}
1919
1920Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
1921 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1922 return getCast(Instruction::BitCast, C, Ty);
1923 return getCast(Instruction::SExt, C, Ty);
1924}
1925
1926Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
1927 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1928 return getCast(Instruction::BitCast, C, Ty);
1929 return getCast(Instruction::Trunc, C, Ty);
1930}
1931
Reid Spencerbc245a02006-12-05 03:25:26 +00001932Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
1933 assert(isa<PointerType>(S->getType()) && "Invalid cast");
Chris Lattner03c49532007-01-15 02:27:26 +00001934 assert((Ty->isInteger() || isa<PointerType>(Ty)) && "Invalid cast");
Reid Spencerbc245a02006-12-05 03:25:26 +00001935
Chris Lattner03c49532007-01-15 02:27:26 +00001936 if (Ty->isInteger())
Reid Spencerbc245a02006-12-05 03:25:26 +00001937 return getCast(Instruction::PtrToInt, S, Ty);
1938 return getCast(Instruction::BitCast, S, Ty);
1939}
1940
Reid Spencer56521c42006-12-12 00:51:07 +00001941Constant *ConstantExpr::getIntegerCast(Constant *C, const Type *Ty,
1942 bool isSigned) {
Chris Lattner03c49532007-01-15 02:27:26 +00001943 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
Reid Spencer56521c42006-12-12 00:51:07 +00001944 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1945 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1946 Instruction::CastOps opcode =
1947 (SrcBits == DstBits ? Instruction::BitCast :
1948 (SrcBits > DstBits ? Instruction::Trunc :
1949 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1950 return getCast(opcode, C, Ty);
1951}
1952
1953Constant *ConstantExpr::getFPCast(Constant *C, const Type *Ty) {
1954 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1955 "Invalid cast");
1956 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1957 unsigned DstBits = Ty->getPrimitiveSizeInBits();
Reid Spencerca104e82006-12-12 05:38:50 +00001958 if (SrcBits == DstBits)
1959 return C; // Avoid a useless cast
Reid Spencer56521c42006-12-12 00:51:07 +00001960 Instruction::CastOps opcode =
Reid Spencerca104e82006-12-12 05:38:50 +00001961 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
Reid Spencer56521c42006-12-12 00:51:07 +00001962 return getCast(opcode, C, Ty);
1963}
1964
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001965Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
Chris Lattner03c49532007-01-15 02:27:26 +00001966 assert(C->getType()->isInteger() && "Trunc operand must be integer");
1967 assert(Ty->isInteger() && "Trunc produces only integral");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001968 assert(C->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()&&
1969 "SrcTy must be larger than DestTy for Trunc!");
1970
1971 return getFoldedCast(Instruction::Trunc, C, Ty);
1972}
1973
Reid Spencerbb65ebf2006-12-12 23:36:14 +00001974Constant *ConstantExpr::getSExt(Constant *C, const Type *Ty) {
Chris Lattner03c49532007-01-15 02:27:26 +00001975 assert(C->getType()->isInteger() && "SEXt operand must be integral");
1976 assert(Ty->isInteger() && "SExt produces only integer");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001977 assert(C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1978 "SrcTy must be smaller than DestTy for SExt!");
1979
1980 return getFoldedCast(Instruction::SExt, C, Ty);
Chris Lattnerdd284742004-04-04 23:20:30 +00001981}
1982
Reid Spencerbb65ebf2006-12-12 23:36:14 +00001983Constant *ConstantExpr::getZExt(Constant *C, const Type *Ty) {
Chris Lattner03c49532007-01-15 02:27:26 +00001984 assert(C->getType()->isInteger() && "ZEXt operand must be integral");
1985 assert(Ty->isInteger() && "ZExt produces only integer");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001986 assert(C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1987 "SrcTy must be smaller than DestTy for ZExt!");
1988
1989 return getFoldedCast(Instruction::ZExt, C, Ty);
1990}
1991
1992Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
1993 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1994 C->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()&&
1995 "This is an illegal floating point truncation!");
1996 return getFoldedCast(Instruction::FPTrunc, C, Ty);
1997}
1998
1999Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
2000 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
2001 C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
2002 "This is an illegal floating point extension!");
2003 return getFoldedCast(Instruction::FPExt, C, Ty);
2004}
2005
2006Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
Devang Pateld26344d2008-11-03 23:20:04 +00002007#ifndef NDEBUG
Nate Begemand4d45c22007-11-17 03:58:34 +00002008 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2009 bool toVec = Ty->getTypeID() == Type::VectorTyID;
Devang Pateld26344d2008-11-03 23:20:04 +00002010#endif
Nate Begemand4d45c22007-11-17 03:58:34 +00002011 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2012 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
2013 "This is an illegal uint to floating point cast!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002014 return getFoldedCast(Instruction::UIToFP, C, Ty);
2015}
2016
2017Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
Devang Pateld26344d2008-11-03 23:20:04 +00002018#ifndef NDEBUG
Nate Begemand4d45c22007-11-17 03:58:34 +00002019 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2020 bool toVec = Ty->getTypeID() == Type::VectorTyID;
Devang Pateld26344d2008-11-03 23:20:04 +00002021#endif
Nate Begemand4d45c22007-11-17 03:58:34 +00002022 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2023 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002024 "This is an illegal sint to floating point cast!");
2025 return getFoldedCast(Instruction::SIToFP, C, Ty);
2026}
2027
2028Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
Devang Pateld26344d2008-11-03 23:20:04 +00002029#ifndef NDEBUG
Nate Begemand4d45c22007-11-17 03:58:34 +00002030 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2031 bool toVec = Ty->getTypeID() == Type::VectorTyID;
Devang Pateld26344d2008-11-03 23:20:04 +00002032#endif
Nate Begemand4d45c22007-11-17 03:58:34 +00002033 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2034 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
2035 "This is an illegal floating point to uint cast!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002036 return getFoldedCast(Instruction::FPToUI, C, Ty);
2037}
2038
2039Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
Devang Pateld26344d2008-11-03 23:20:04 +00002040#ifndef NDEBUG
Nate Begemand4d45c22007-11-17 03:58:34 +00002041 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2042 bool toVec = Ty->getTypeID() == Type::VectorTyID;
Devang Pateld26344d2008-11-03 23:20:04 +00002043#endif
Nate Begemand4d45c22007-11-17 03:58:34 +00002044 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2045 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
2046 "This is an illegal floating point to sint cast!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002047 return getFoldedCast(Instruction::FPToSI, C, Ty);
2048}
2049
2050Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
2051 assert(isa<PointerType>(C->getType()) && "PtrToInt source must be pointer");
Chris Lattner03c49532007-01-15 02:27:26 +00002052 assert(DstTy->isInteger() && "PtrToInt destination must be integral");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002053 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
2054}
2055
2056Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
Chris Lattner03c49532007-01-15 02:27:26 +00002057 assert(C->getType()->isInteger() && "IntToPtr source must be integral");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002058 assert(isa<PointerType>(DstTy) && "IntToPtr destination must be a pointer");
2059 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
2060}
2061
2062Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
2063 // BitCast implies a no-op cast of type only. No bits change. However, you
2064 // can't cast pointers to anything but pointers.
Devang Pateld26344d2008-11-03 23:20:04 +00002065#ifndef NDEBUG
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002066 const Type *SrcTy = C->getType();
2067 assert((isa<PointerType>(SrcTy) == isa<PointerType>(DstTy)) &&
Reid Spencer5c140882006-12-04 20:17:56 +00002068 "BitCast cannot cast pointer to non-pointer and vice versa");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002069
2070 // Now we know we're not dealing with mismatched pointer casts (ptr->nonptr
2071 // or nonptr->ptr). For all the other types, the cast is okay if source and
2072 // destination bit widths are identical.
2073 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
2074 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
Devang Pateld26344d2008-11-03 23:20:04 +00002075#endif
Chris Lattnere4086012009-03-08 04:06:26 +00002076 assert(SrcBitSize == DstBitSize && "BitCast requires types of same width");
Chris Lattnercbeda872009-03-21 06:55:54 +00002077
2078 // It is common to ask for a bitcast of a value to its own type, handle this
2079 // speedily.
2080 if (C->getType() == DstTy) return C;
2081
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002082 return getFoldedCast(Instruction::BitCast, C, DstTy);
Chris Lattnerdd284742004-04-04 23:20:30 +00002083}
2084
Duncan Sandsd334aca2009-05-21 15:52:21 +00002085Constant *ConstantExpr::getAlignOf(const Type *Ty) {
2086 // alignof is implemented as: (i64) gep ({i8,Ty}*)null, 0, 1
2087 const Type *AligningTy = StructType::get(Type::Int8Ty, Ty, NULL);
2088 Constant *NullPtr = getNullValue(AligningTy->getPointerTo());
2089 Constant *Zero = ConstantInt::get(Type::Int32Ty, 0);
2090 Constant *One = ConstantInt::get(Type::Int32Ty, 1);
2091 Constant *Indices[2] = { Zero, One };
2092 Constant *GEP = getGetElementPtr(NullPtr, Indices, 2);
2093 return getCast(Instruction::PtrToInt, GEP, Type::Int32Ty);
2094}
2095
Alkis Evlogimenosda5de052004-10-24 01:41:10 +00002096Constant *ConstantExpr::getSizeOf(const Type *Ty) {
Gordon Henriksen7ce31762007-10-06 14:29:36 +00002097 // sizeof is implemented as: (i64) gep (Ty*)null, 1
Chris Lattnerb5d70302007-02-19 20:01:23 +00002098 Constant *GEPIdx = ConstantInt::get(Type::Int32Ty, 1);
2099 Constant *GEP =
Christopher Lambedf07882007-12-17 01:12:55 +00002100 getGetElementPtr(getNullValue(PointerType::getUnqual(Ty)), &GEPIdx, 1);
Chris Lattnerb5d70302007-02-19 20:01:23 +00002101 return getCast(Instruction::PtrToInt, GEP, Type::Int64Ty);
Alkis Evlogimenos9160d5f2005-03-19 11:40:31 +00002102}
2103
Chris Lattnerb50d1352003-10-05 00:17:43 +00002104Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
Reid Spencera009d0d2006-12-04 21:35:24 +00002105 Constant *C1, Constant *C2) {
Chris Lattner38a9bcd2003-05-21 17:49:25 +00002106 // Check the operands for consistency first
Reid Spencer7eb55b32006-11-02 01:53:59 +00002107 assert(Opcode >= Instruction::BinaryOpsBegin &&
2108 Opcode < Instruction::BinaryOpsEnd &&
Chris Lattner38a9bcd2003-05-21 17:49:25 +00002109 "Invalid opcode in binary constant expression");
2110 assert(C1->getType() == C2->getType() &&
2111 "Operand types in binary constant expression should match");
Chris Lattnerb50d1352003-10-05 00:17:43 +00002112
Reid Spencer542964f2007-01-11 18:21:29 +00002113 if (ReqTy == C1->getType() || ReqTy == Type::Int1Ty)
Chris Lattnerb50d1352003-10-05 00:17:43 +00002114 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
2115 return FC; // Fold a few common cases...
Chris Lattneracdbe712003-04-17 19:24:48 +00002116
Chris Lattner2b383d2e2003-05-13 21:37:02 +00002117 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
Reid Spencera009d0d2006-12-04 21:35:24 +00002118 ExprMapKeyType Key(Opcode, argVec);
Chris Lattner69edc982006-09-28 00:35:06 +00002119 return ExprConstants->getOrCreate(ReqTy, Key);
Vikram S. Adve4e537b22002-07-14 23:13:17 +00002120}
2121
Reid Spencer266e42b2006-12-23 06:05:41 +00002122Constant *ConstantExpr::getCompareTy(unsigned short predicate,
Nate Begeman098cc6f2008-07-25 17:56:27 +00002123 Constant *C1, Constant *C2) {
2124 bool isVectorType = C1->getType()->getTypeID() == Type::VectorTyID;
Reid Spencer266e42b2006-12-23 06:05:41 +00002125 switch (predicate) {
2126 default: assert(0 && "Invalid CmpInst predicate");
Nate Begemanc96e2e42008-07-25 17:35:37 +00002127 case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
2128 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
2129 case CmpInst::FCMP_ONE: case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
2130 case CmpInst::FCMP_UEQ: case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
2131 case CmpInst::FCMP_ULT: case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
2132 case CmpInst::FCMP_TRUE:
Nate Begeman098cc6f2008-07-25 17:56:27 +00002133 return isVectorType ? getVFCmp(predicate, C1, C2)
2134 : getFCmp(predicate, C1, C2);
Nate Begemanc96e2e42008-07-25 17:35:37 +00002135 case CmpInst::ICMP_EQ: case CmpInst::ICMP_NE: case CmpInst::ICMP_UGT:
2136 case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
2137 case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
2138 case CmpInst::ICMP_SLE:
Nate Begeman098cc6f2008-07-25 17:56:27 +00002139 return isVectorType ? getVICmp(predicate, C1, C2)
2140 : getICmp(predicate, C1, C2);
Reid Spencer266e42b2006-12-23 06:05:41 +00002141 }
Reid Spencera009d0d2006-12-04 21:35:24 +00002142}
2143
2144Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00002145#ifndef NDEBUG
2146 switch (Opcode) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00002147 case Instruction::Add:
2148 case Instruction::Sub:
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002149 case Instruction::Mul:
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00002150 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Chris Lattner03c49532007-01-15 02:27:26 +00002151 assert((C1->getType()->isInteger() || C1->getType()->isFloatingPoint() ||
Reid Spencerd84d35b2007-02-15 02:26:10 +00002152 isa<VectorType>(C1->getType())) &&
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00002153 "Tried to create an arithmetic operation on a non-arithmetic type!");
2154 break;
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002155 case Instruction::UDiv:
2156 case Instruction::SDiv:
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 Spencer7e80b0b2006-10-26 06:15:43 +00002160 "Tried to create an arithmetic operation on a non-arithmetic type!");
2161 break;
2162 case Instruction::FDiv:
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 Spencer7e80b0b2006-10-26 06:15:43 +00002166 && "Tried to create an arithmetic operation on a non-arithmetic type!");
2167 break;
Reid Spencer7eb55b32006-11-02 01:53:59 +00002168 case Instruction::URem:
2169 case Instruction::SRem:
2170 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00002171 assert((C1->getType()->isInteger() || (isa<VectorType>(C1->getType()) &&
2172 cast<VectorType>(C1->getType())->getElementType()->isInteger())) &&
Reid Spencer7eb55b32006-11-02 01:53:59 +00002173 "Tried to create an arithmetic operation on a non-arithmetic type!");
2174 break;
2175 case Instruction::FRem:
2176 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00002177 assert((C1->getType()->isFloatingPoint() || (isa<VectorType>(C1->getType())
2178 && cast<VectorType>(C1->getType())->getElementType()->isFloatingPoint()))
Reid Spencer7eb55b32006-11-02 01:53:59 +00002179 && "Tried to create an arithmetic operation on a non-arithmetic type!");
2180 break;
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00002181 case Instruction::And:
2182 case Instruction::Or:
2183 case Instruction::Xor:
2184 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00002185 assert((C1->getType()->isInteger() || isa<VectorType>(C1->getType())) &&
Misha Brukman3852f652005-01-27 06:46:38 +00002186 "Tried to create a logical operation on a non-integral type!");
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00002187 break;
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00002188 case Instruction::Shl:
Reid Spencerfdff9382006-11-08 06:47:33 +00002189 case Instruction::LShr:
2190 case Instruction::AShr:
Reid Spencer2341c222007-02-02 02:16:23 +00002191 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Dan Gohman79975d52009-03-14 17:09:17 +00002192 assert(C1->getType()->isIntOrIntVector() &&
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00002193 "Tried to create a shift operation on a non-integer type!");
2194 break;
2195 default:
2196 break;
2197 }
2198#endif
2199
Reid Spencera009d0d2006-12-04 21:35:24 +00002200 return getTy(C1->getType(), Opcode, C1, C2);
2201}
2202
Reid Spencer266e42b2006-12-23 06:05:41 +00002203Constant *ConstantExpr::getCompare(unsigned short pred,
Reid Spencera009d0d2006-12-04 21:35:24 +00002204 Constant *C1, Constant *C2) {
2205 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Reid Spencer266e42b2006-12-23 06:05:41 +00002206 return getCompareTy(pred, C1, C2);
Chris Lattner29ca2c62004-08-04 18:50:09 +00002207}
2208
Chris Lattner6e415c02004-03-12 05:54:04 +00002209Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
2210 Constant *V1, Constant *V2) {
Chris Lattner41632132008-12-29 00:16:12 +00002211 assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
Chris Lattner6e415c02004-03-12 05:54:04 +00002212
2213 if (ReqTy == V1->getType())
2214 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
2215 return SC; // Fold common cases
2216
2217 std::vector<Constant*> argVec(3, C);
2218 argVec[1] = V1;
2219 argVec[2] = V2;
Reid Spenceree3c9912006-12-04 05:19:50 +00002220 ExprMapKeyType Key(Instruction::Select, argVec);
Chris Lattner69edc982006-09-28 00:35:06 +00002221 return ExprConstants->getOrCreate(ReqTy, Key);
Chris Lattner6e415c02004-03-12 05:54:04 +00002222}
2223
Chris Lattnerb50d1352003-10-05 00:17:43 +00002224Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
Chris Lattner302116a2007-01-31 04:40:28 +00002225 Value* const *Idxs,
2226 unsigned NumIdx) {
Dan Gohman12fce772008-05-15 19:50:34 +00002227 assert(GetElementPtrInst::getIndexedType(C->getType(), Idxs,
2228 Idxs+NumIdx) ==
2229 cast<PointerType>(ReqTy)->getElementType() &&
2230 "GEP indices invalid!");
Chris Lattner04b60fe2004-02-16 20:46:13 +00002231
Chris Lattner302116a2007-01-31 04:40:28 +00002232 if (Constant *FC = ConstantFoldGetElementPtr(C, (Constant**)Idxs, NumIdx))
Chris Lattneracdbe712003-04-17 19:24:48 +00002233 return FC; // Fold a few common cases...
Chris Lattner04b60fe2004-02-16 20:46:13 +00002234
Chris Lattnerb50d1352003-10-05 00:17:43 +00002235 assert(isa<PointerType>(C->getType()) &&
Chris Lattner98fa07b2003-05-23 20:03:32 +00002236 "Non-pointer type for constant GetElementPtr expression");
Vikram S. Adve4c485332002-07-15 18:19:33 +00002237 // Look up the constant in the table first to ensure uniqueness
Chris Lattner13128ab2004-10-11 22:52:25 +00002238 std::vector<Constant*> ArgVec;
Chris Lattner302116a2007-01-31 04:40:28 +00002239 ArgVec.reserve(NumIdx+1);
Chris Lattner13128ab2004-10-11 22:52:25 +00002240 ArgVec.push_back(C);
Chris Lattner302116a2007-01-31 04:40:28 +00002241 for (unsigned i = 0; i != NumIdx; ++i)
2242 ArgVec.push_back(cast<Constant>(Idxs[i]));
2243 const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec);
Chris Lattner69edc982006-09-28 00:35:06 +00002244 return ExprConstants->getOrCreate(ReqTy, Key);
Vikram S. Adve4c485332002-07-15 18:19:33 +00002245}
2246
Chris Lattner302116a2007-01-31 04:40:28 +00002247Constant *ConstantExpr::getGetElementPtr(Constant *C, Value* const *Idxs,
2248 unsigned NumIdx) {
Chris Lattnerb50d1352003-10-05 00:17:43 +00002249 // Get the result type of the getelementptr!
Chris Lattner302116a2007-01-31 04:40:28 +00002250 const Type *Ty =
Dan Gohman12fce772008-05-15 19:50:34 +00002251 GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx);
Chris Lattnerb50d1352003-10-05 00:17:43 +00002252 assert(Ty && "GEP indices invalid!");
Christopher Lamb54dd24c2007-12-11 08:59:05 +00002253 unsigned As = cast<PointerType>(C->getType())->getAddressSpace();
2254 return getGetElementPtrTy(PointerType::get(Ty, As), C, Idxs, NumIdx);
Chris Lattner13128ab2004-10-11 22:52:25 +00002255}
2256
Chris Lattner302116a2007-01-31 04:40:28 +00002257Constant *ConstantExpr::getGetElementPtr(Constant *C, Constant* const *Idxs,
2258 unsigned NumIdx) {
2259 return getGetElementPtr(C, (Value* const *)Idxs, NumIdx);
Chris Lattnerb50d1352003-10-05 00:17:43 +00002260}
2261
Chris Lattner302116a2007-01-31 04:40:28 +00002262
Reid Spenceree3c9912006-12-04 05:19:50 +00002263Constant *
2264ConstantExpr::getICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2265 assert(LHS->getType() == RHS->getType());
2266 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
2267 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
2268
Reid Spencer266e42b2006-12-23 06:05:41 +00002269 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
Reid Spenceree3c9912006-12-04 05:19:50 +00002270 return FC; // Fold a few common cases...
2271
2272 // Look up the constant in the table first to ensure uniqueness
2273 std::vector<Constant*> ArgVec;
2274 ArgVec.push_back(LHS);
2275 ArgVec.push_back(RHS);
Reid Spencerb1537492006-12-24 18:42:29 +00002276 // Get the key type with both the opcode and predicate
Reid Spenceree3c9912006-12-04 05:19:50 +00002277 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
Reid Spencer542964f2007-01-11 18:21:29 +00002278 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
Reid Spenceree3c9912006-12-04 05:19:50 +00002279}
2280
2281Constant *
2282ConstantExpr::getFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2283 assert(LHS->getType() == RHS->getType());
2284 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
2285
Reid Spencer266e42b2006-12-23 06:05:41 +00002286 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
Reid Spenceree3c9912006-12-04 05:19:50 +00002287 return FC; // Fold a few common cases...
2288
2289 // Look up the constant in the table first to ensure uniqueness
2290 std::vector<Constant*> ArgVec;
2291 ArgVec.push_back(LHS);
2292 ArgVec.push_back(RHS);
Reid Spencerb1537492006-12-24 18:42:29 +00002293 // Get the key type with both the opcode and predicate
Reid Spenceree3c9912006-12-04 05:19:50 +00002294 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
Reid Spencer542964f2007-01-11 18:21:29 +00002295 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
Reid Spenceree3c9912006-12-04 05:19:50 +00002296}
2297
Nate Begemand2195702008-05-12 19:01:56 +00002298Constant *
2299ConstantExpr::getVICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
Chris Lattnereab49262008-07-14 05:17:31 +00002300 assert(isa<VectorType>(LHS->getType()) && LHS->getType() == RHS->getType() &&
Nate Begemand2195702008-05-12 19:01:56 +00002301 "Tried to create vicmp operation on non-vector type!");
Nate Begemand2195702008-05-12 19:01:56 +00002302 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
2303 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid VICmp Predicate");
2304
Nate Begemanac7f3d92008-05-12 19:23:22 +00002305 const VectorType *VTy = cast<VectorType>(LHS->getType());
Nate Begemand2195702008-05-12 19:01:56 +00002306 const Type *EltTy = VTy->getElementType();
2307 unsigned NumElts = VTy->getNumElements();
2308
Chris Lattnereab49262008-07-14 05:17:31 +00002309 // See if we can fold the element-wise comparison of the LHS and RHS.
2310 SmallVector<Constant *, 16> LHSElts, RHSElts;
2311 LHS->getVectorElements(LHSElts);
2312 RHS->getVectorElements(RHSElts);
2313
2314 if (!LHSElts.empty() && !RHSElts.empty()) {
2315 SmallVector<Constant *, 16> Elts;
2316 for (unsigned i = 0; i != NumElts; ++i) {
2317 Constant *FC = ConstantFoldCompareInstruction(pred, LHSElts[i],
2318 RHSElts[i]);
2319 if (ConstantInt *FCI = dyn_cast_or_null<ConstantInt>(FC)) {
2320 if (FCI->getZExtValue())
2321 Elts.push_back(ConstantInt::getAllOnesValue(EltTy));
2322 else
2323 Elts.push_back(ConstantInt::get(EltTy, 0ULL));
2324 } else if (FC && isa<UndefValue>(FC)) {
2325 Elts.push_back(UndefValue::get(EltTy));
2326 } else {
2327 break;
2328 }
Nate Begemand2195702008-05-12 19:01:56 +00002329 }
Chris Lattnereab49262008-07-14 05:17:31 +00002330 if (Elts.size() == NumElts)
2331 return ConstantVector::get(&Elts[0], Elts.size());
Nate Begemand2195702008-05-12 19:01:56 +00002332 }
Nate Begemand2195702008-05-12 19:01:56 +00002333
2334 // Look up the constant in the table first to ensure uniqueness
2335 std::vector<Constant*> ArgVec;
2336 ArgVec.push_back(LHS);
2337 ArgVec.push_back(RHS);
2338 // Get the key type with both the opcode and predicate
2339 const ExprMapKeyType Key(Instruction::VICmp, ArgVec, pred);
2340 return ExprConstants->getOrCreate(LHS->getType(), Key);
2341}
2342
2343Constant *
2344ConstantExpr::getVFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2345 assert(isa<VectorType>(LHS->getType()) &&
2346 "Tried to create vfcmp operation on non-vector type!");
2347 assert(LHS->getType() == RHS->getType());
2348 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid VFCmp Predicate");
2349
2350 const VectorType *VTy = cast<VectorType>(LHS->getType());
2351 unsigned NumElts = VTy->getNumElements();
2352 const Type *EltTy = VTy->getElementType();
2353 const Type *REltTy = IntegerType::get(EltTy->getPrimitiveSizeInBits());
2354 const Type *ResultTy = VectorType::get(REltTy, NumElts);
2355
Chris Lattnereab49262008-07-14 05:17:31 +00002356 // See if we can fold the element-wise comparison of the LHS and RHS.
2357 SmallVector<Constant *, 16> LHSElts, RHSElts;
2358 LHS->getVectorElements(LHSElts);
2359 RHS->getVectorElements(RHSElts);
2360
2361 if (!LHSElts.empty() && !RHSElts.empty()) {
2362 SmallVector<Constant *, 16> Elts;
2363 for (unsigned i = 0; i != NumElts; ++i) {
2364 Constant *FC = ConstantFoldCompareInstruction(pred, LHSElts[i],
2365 RHSElts[i]);
2366 if (ConstantInt *FCI = dyn_cast_or_null<ConstantInt>(FC)) {
2367 if (FCI->getZExtValue())
2368 Elts.push_back(ConstantInt::getAllOnesValue(REltTy));
2369 else
2370 Elts.push_back(ConstantInt::get(REltTy, 0ULL));
2371 } else if (FC && isa<UndefValue>(FC)) {
2372 Elts.push_back(UndefValue::get(REltTy));
2373 } else {
2374 break;
2375 }
Nate Begemand2195702008-05-12 19:01:56 +00002376 }
Chris Lattnereab49262008-07-14 05:17:31 +00002377 if (Elts.size() == NumElts)
2378 return ConstantVector::get(&Elts[0], Elts.size());
Nate Begemand2195702008-05-12 19:01:56 +00002379 }
Nate Begemand2195702008-05-12 19:01:56 +00002380
2381 // Look up the constant in the table first to ensure uniqueness
2382 std::vector<Constant*> ArgVec;
2383 ArgVec.push_back(LHS);
2384 ArgVec.push_back(RHS);
2385 // Get the key type with both the opcode and predicate
2386 const ExprMapKeyType Key(Instruction::VFCmp, ArgVec, pred);
2387 return ExprConstants->getOrCreate(ResultTy, Key);
2388}
2389
Robert Bocchino23004482006-01-10 19:05:34 +00002390Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
2391 Constant *Idx) {
Robert Bocchinode7f1c92006-01-10 20:03:46 +00002392 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
2393 return FC; // Fold a few common cases...
Robert Bocchino23004482006-01-10 19:05:34 +00002394 // Look up the constant in the table first to ensure uniqueness
2395 std::vector<Constant*> ArgVec(1, Val);
2396 ArgVec.push_back(Idx);
Reid Spenceree3c9912006-12-04 05:19:50 +00002397 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
Chris Lattner69edc982006-09-28 00:35:06 +00002398 return ExprConstants->getOrCreate(ReqTy, Key);
Robert Bocchino23004482006-01-10 19:05:34 +00002399}
2400
2401Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00002402 assert(isa<VectorType>(Val->getType()) &&
Reid Spencer09575ba2007-02-15 03:39:18 +00002403 "Tried to create extractelement operation on non-vector type!");
Reid Spencer8d9336d2006-12-31 05:26:44 +00002404 assert(Idx->getType() == Type::Int32Ty &&
Reid Spencer2546b762007-01-26 07:37:34 +00002405 "Extractelement index must be i32 type!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00002406 return getExtractElementTy(cast<VectorType>(Val->getType())->getElementType(),
Robert Bocchino23004482006-01-10 19:05:34 +00002407 Val, Idx);
2408}
Chris Lattnerb50d1352003-10-05 00:17:43 +00002409
Robert Bocchinoca27f032006-01-17 20:07:22 +00002410Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
2411 Constant *Elt, Constant *Idx) {
2412 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
2413 return FC; // Fold a few common cases...
2414 // Look up the constant in the table first to ensure uniqueness
2415 std::vector<Constant*> ArgVec(1, Val);
2416 ArgVec.push_back(Elt);
2417 ArgVec.push_back(Idx);
Reid Spenceree3c9912006-12-04 05:19:50 +00002418 const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
Chris Lattner69edc982006-09-28 00:35:06 +00002419 return ExprConstants->getOrCreate(ReqTy, Key);
Robert Bocchinoca27f032006-01-17 20:07:22 +00002420}
2421
2422Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
2423 Constant *Idx) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00002424 assert(isa<VectorType>(Val->getType()) &&
Reid Spencer09575ba2007-02-15 03:39:18 +00002425 "Tried to create insertelement operation on non-vector type!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00002426 assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType()
Robert Bocchinoca27f032006-01-17 20:07:22 +00002427 && "Insertelement types must match!");
Reid Spencer8d9336d2006-12-31 05:26:44 +00002428 assert(Idx->getType() == Type::Int32Ty &&
Reid Spencer2546b762007-01-26 07:37:34 +00002429 "Insertelement index must be i32 type!");
Gordon Henriksenb52d1ed2008-08-30 15:41:51 +00002430 return getInsertElementTy(Val->getType(), Val, Elt, Idx);
Robert Bocchinoca27f032006-01-17 20:07:22 +00002431}
2432
Chris Lattnerbbe0a422006-04-08 01:18:18 +00002433Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
2434 Constant *V2, Constant *Mask) {
2435 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
2436 return FC; // Fold a few common cases...
2437 // Look up the constant in the table first to ensure uniqueness
2438 std::vector<Constant*> ArgVec(1, V1);
2439 ArgVec.push_back(V2);
2440 ArgVec.push_back(Mask);
Reid Spenceree3c9912006-12-04 05:19:50 +00002441 const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
Chris Lattner69edc982006-09-28 00:35:06 +00002442 return ExprConstants->getOrCreate(ReqTy, Key);
Chris Lattnerbbe0a422006-04-08 01:18:18 +00002443}
2444
2445Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
2446 Constant *Mask) {
2447 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
2448 "Invalid shuffle vector constant expr operands!");
Nate Begeman94aa38d2009-02-12 21:28:33 +00002449
2450 unsigned NElts = cast<VectorType>(Mask->getType())->getNumElements();
2451 const Type *EltTy = cast<VectorType>(V1->getType())->getElementType();
2452 const Type *ShufTy = VectorType::get(EltTy, NElts);
2453 return getShuffleVectorTy(ShufTy, V1, V2, Mask);
Chris Lattnerbbe0a422006-04-08 01:18:18 +00002454}
2455
Dan Gohman12fce772008-05-15 19:50:34 +00002456Constant *ConstantExpr::getInsertValueTy(const Type *ReqTy, Constant *Agg,
2457 Constant *Val,
Dan Gohman1ecaf452008-05-31 00:58:22 +00002458 const unsigned *Idxs, unsigned NumIdx) {
Dan Gohman12fce772008-05-15 19:50:34 +00002459 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
2460 Idxs+NumIdx) == Val->getType() &&
2461 "insertvalue indices invalid!");
2462 assert(Agg->getType() == ReqTy &&
2463 "insertvalue type invalid!");
Dan Gohman0752bff2008-05-23 00:36:11 +00002464 assert(Agg->getType()->isFirstClassType() &&
2465 "Non-first-class type for constant InsertValue expression");
Dan Gohmand5d24f62008-07-21 23:30:30 +00002466 Constant *FC = ConstantFoldInsertValueInstruction(Agg, Val, Idxs, NumIdx);
2467 assert(FC && "InsertValue constant expr couldn't be folded!");
2468 return FC;
Dan Gohman12fce772008-05-15 19:50:34 +00002469}
2470
2471Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
Dan Gohman1ecaf452008-05-31 00:58:22 +00002472 const unsigned *IdxList, unsigned NumIdx) {
Dan Gohman0752bff2008-05-23 00:36:11 +00002473 assert(Agg->getType()->isFirstClassType() &&
2474 "Tried to create insertelement operation on non-first-class type!");
Dan Gohman12fce772008-05-15 19:50:34 +00002475
Dan Gohman0752bff2008-05-23 00:36:11 +00002476 const Type *ReqTy = Agg->getType();
Devang Pateld26344d2008-11-03 23:20:04 +00002477#ifndef NDEBUG
Dan Gohman0752bff2008-05-23 00:36:11 +00002478 const Type *ValTy =
Dan Gohman12fce772008-05-15 19:50:34 +00002479 ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
Devang Pateld26344d2008-11-03 23:20:04 +00002480#endif
Dan Gohman0752bff2008-05-23 00:36:11 +00002481 assert(ValTy == Val->getType() && "insertvalue indices invalid!");
Dan Gohman12fce772008-05-15 19:50:34 +00002482 return getInsertValueTy(ReqTy, Agg, Val, IdxList, NumIdx);
2483}
2484
2485Constant *ConstantExpr::getExtractValueTy(const Type *ReqTy, Constant *Agg,
Dan Gohman1ecaf452008-05-31 00:58:22 +00002486 const unsigned *Idxs, unsigned NumIdx) {
Dan Gohman12fce772008-05-15 19:50:34 +00002487 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
2488 Idxs+NumIdx) == ReqTy &&
2489 "extractvalue indices invalid!");
Dan Gohman0752bff2008-05-23 00:36:11 +00002490 assert(Agg->getType()->isFirstClassType() &&
2491 "Non-first-class type for constant extractvalue expression");
Dan Gohmand5d24f62008-07-21 23:30:30 +00002492 Constant *FC = ConstantFoldExtractValueInstruction(Agg, Idxs, NumIdx);
2493 assert(FC && "ExtractValue constant expr couldn't be folded!");
2494 return FC;
Dan Gohman12fce772008-05-15 19:50:34 +00002495}
2496
2497Constant *ConstantExpr::getExtractValue(Constant *Agg,
Dan Gohman1ecaf452008-05-31 00:58:22 +00002498 const unsigned *IdxList, unsigned NumIdx) {
Dan Gohman0752bff2008-05-23 00:36:11 +00002499 assert(Agg->getType()->isFirstClassType() &&
2500 "Tried to create extractelement operation on non-first-class type!");
Dan Gohman12fce772008-05-15 19:50:34 +00002501
2502 const Type *ReqTy =
2503 ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
2504 assert(ReqTy && "extractvalue indices invalid!");
2505 return getExtractValueTy(ReqTy, Agg, IdxList, NumIdx);
2506}
2507
Reid Spencer2eadb532007-01-21 00:29:26 +00002508Constant *ConstantExpr::getZeroValueForNegationExpr(const Type *Ty) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00002509 if (const VectorType *PTy = dyn_cast<VectorType>(Ty))
Reid Spencer6598ca82007-01-21 02:29:10 +00002510 if (PTy->getElementType()->isFloatingPoint()) {
2511 std::vector<Constant*> zeros(PTy->getNumElements(),
Dale Johannesen98d3a082007-09-14 22:26:36 +00002512 ConstantFP::getNegativeZero(PTy->getElementType()));
Reid Spencerd84d35b2007-02-15 02:26:10 +00002513 return ConstantVector::get(PTy, zeros);
Reid Spencer6598ca82007-01-21 02:29:10 +00002514 }
Reid Spencer2eadb532007-01-21 00:29:26 +00002515
Dale Johannesen98d3a082007-09-14 22:26:36 +00002516 if (Ty->isFloatingPoint())
2517 return ConstantFP::getNegativeZero(Ty);
Reid Spencer2eadb532007-01-21 00:29:26 +00002518
2519 return Constant::getNullValue(Ty);
2520}
2521
Vikram S. Adve4c485332002-07-15 18:19:33 +00002522// destroyConstant - Remove the constant from the constant table...
2523//
2524void ConstantExpr::destroyConstant() {
Chris Lattner69edc982006-09-28 00:35:06 +00002525 ExprConstants->remove(this);
Vikram S. Adve4c485332002-07-15 18:19:33 +00002526 destroyConstantImpl();
Vikram S. Adve4e537b22002-07-14 23:13:17 +00002527}
2528
Chris Lattner3cd8c562002-07-30 18:54:25 +00002529const char *ConstantExpr::getOpcodeName() const {
2530 return Instruction::getOpcodeName(getOpcode());
Vikram S. Adve4e537b22002-07-14 23:13:17 +00002531}
Reid Spencer1ebe1ab2004-07-17 23:48:33 +00002532
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002533//===----------------------------------------------------------------------===//
2534// replaceUsesOfWithOnConstant implementations
2535
Chris Lattner913849b2007-08-21 00:55:23 +00002536/// replaceUsesOfWithOnConstant - Update this constant array to change uses of
2537/// 'From' to be uses of 'To'. This must update the uniquing data structures
2538/// etc.
2539///
2540/// Note that we intentionally replace all uses of From with To here. Consider
2541/// a large array that uses 'From' 1000 times. By handling this case all here,
2542/// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
2543/// single invocation handles all 1000 uses. Handling them one at a time would
2544/// work, but would be really slow because it would have to unique each updated
2545/// array instance.
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002546void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
Chris Lattner7a1450d2005-10-04 18:13:04 +00002547 Use *U) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002548 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
Chris Lattner8760ec72005-10-04 01:17:50 +00002549 Constant *ToC = cast<Constant>(To);
Chris Lattnerdff59112005-10-04 18:47:09 +00002550
Jim Laskeyc03caef2006-07-17 17:38:29 +00002551 std::pair<ArrayConstantsTy::MapKey, Constant*> Lookup;
Chris Lattnerb64419a2005-10-03 22:51:37 +00002552 Lookup.first.first = getType();
2553 Lookup.second = this;
Chris Lattnerdff59112005-10-04 18:47:09 +00002554
Chris Lattnerb64419a2005-10-03 22:51:37 +00002555 std::vector<Constant*> &Values = Lookup.first.second;
2556 Values.reserve(getNumOperands()); // Build replacement array.
Chris Lattnerdff59112005-10-04 18:47:09 +00002557
Chris Lattner8760ec72005-10-04 01:17:50 +00002558 // Fill values with the modified operands of the constant array. Also,
2559 // compute whether this turns into an all-zeros array.
Chris Lattnerdff59112005-10-04 18:47:09 +00002560 bool isAllZeros = false;
Chris Lattner913849b2007-08-21 00:55:23 +00002561 unsigned NumUpdated = 0;
Chris Lattnerdff59112005-10-04 18:47:09 +00002562 if (!ToC->isNullValue()) {
Chris Lattner913849b2007-08-21 00:55:23 +00002563 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2564 Constant *Val = cast<Constant>(O->get());
2565 if (Val == From) {
2566 Val = ToC;
2567 ++NumUpdated;
2568 }
2569 Values.push_back(Val);
2570 }
Chris Lattnerdff59112005-10-04 18:47:09 +00002571 } else {
2572 isAllZeros = true;
2573 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2574 Constant *Val = cast<Constant>(O->get());
Chris Lattner913849b2007-08-21 00:55:23 +00002575 if (Val == From) {
2576 Val = ToC;
2577 ++NumUpdated;
2578 }
Chris Lattnerdff59112005-10-04 18:47:09 +00002579 Values.push_back(Val);
2580 if (isAllZeros) isAllZeros = Val->isNullValue();
2581 }
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002582 }
2583
Chris Lattnerb64419a2005-10-03 22:51:37 +00002584 Constant *Replacement = 0;
2585 if (isAllZeros) {
2586 Replacement = ConstantAggregateZero::get(getType());
2587 } else {
2588 // Check to see if we have this array type already.
2589 bool Exists;
Jim Laskeyc03caef2006-07-17 17:38:29 +00002590 ArrayConstantsTy::MapTy::iterator I =
Chris Lattner69edc982006-09-28 00:35:06 +00002591 ArrayConstants->InsertOrGetItem(Lookup, Exists);
Chris Lattnerb64419a2005-10-03 22:51:37 +00002592
2593 if (Exists) {
2594 Replacement = I->second;
2595 } else {
2596 // Okay, the new shape doesn't exist in the system yet. Instead of
2597 // creating a new constant array, inserting it, replaceallusesof'ing the
2598 // old with the new, then deleting the old... just update the current one
2599 // in place!
Chris Lattner69edc982006-09-28 00:35:06 +00002600 ArrayConstants->MoveConstantToNewSlot(this, I);
Chris Lattnerb64419a2005-10-03 22:51:37 +00002601
Chris Lattner913849b2007-08-21 00:55:23 +00002602 // Update to the new value. Optimize for the case when we have a single
2603 // operand that we're changing, but handle bulk updates efficiently.
2604 if (NumUpdated == 1) {
2605 unsigned OperandToUpdate = U-OperandList;
2606 assert(getOperand(OperandToUpdate) == From &&
2607 "ReplaceAllUsesWith broken!");
2608 setOperand(OperandToUpdate, ToC);
2609 } else {
2610 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2611 if (getOperand(i) == From)
2612 setOperand(i, ToC);
2613 }
Chris Lattnerb64419a2005-10-03 22:51:37 +00002614 return;
2615 }
2616 }
2617
2618 // Otherwise, I do need to replace this with an existing value.
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002619 assert(Replacement != this && "I didn't contain From!");
2620
Chris Lattner7a1450d2005-10-04 18:13:04 +00002621 // Everyone using this now uses the replacement.
2622 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002623
2624 // Delete the old constant!
2625 destroyConstant();
2626}
2627
2628void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
Chris Lattner7a1450d2005-10-04 18:13:04 +00002629 Use *U) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002630 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
Chris Lattner8760ec72005-10-04 01:17:50 +00002631 Constant *ToC = cast<Constant>(To);
2632
Chris Lattnerdff59112005-10-04 18:47:09 +00002633 unsigned OperandToUpdate = U-OperandList;
2634 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
2635
Jim Laskeyc03caef2006-07-17 17:38:29 +00002636 std::pair<StructConstantsTy::MapKey, Constant*> Lookup;
Chris Lattner8760ec72005-10-04 01:17:50 +00002637 Lookup.first.first = getType();
2638 Lookup.second = this;
2639 std::vector<Constant*> &Values = Lookup.first.second;
2640 Values.reserve(getNumOperands()); // Build replacement struct.
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002641
Chris Lattnerdff59112005-10-04 18:47:09 +00002642
Chris Lattner8760ec72005-10-04 01:17:50 +00002643 // Fill values with the modified operands of the constant struct. Also,
2644 // compute whether this turns into an all-zeros struct.
Chris Lattnerdff59112005-10-04 18:47:09 +00002645 bool isAllZeros = false;
2646 if (!ToC->isNullValue()) {
2647 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
2648 Values.push_back(cast<Constant>(O->get()));
2649 } else {
2650 isAllZeros = true;
2651 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2652 Constant *Val = cast<Constant>(O->get());
2653 Values.push_back(Val);
2654 if (isAllZeros) isAllZeros = Val->isNullValue();
2655 }
Chris Lattner8760ec72005-10-04 01:17:50 +00002656 }
Chris Lattnerdff59112005-10-04 18:47:09 +00002657 Values[OperandToUpdate] = ToC;
2658
Chris Lattner8760ec72005-10-04 01:17:50 +00002659 Constant *Replacement = 0;
2660 if (isAllZeros) {
2661 Replacement = ConstantAggregateZero::get(getType());
2662 } else {
2663 // Check to see if we have this array type already.
2664 bool Exists;
Jim Laskeyc03caef2006-07-17 17:38:29 +00002665 StructConstantsTy::MapTy::iterator I =
Chris Lattner69edc982006-09-28 00:35:06 +00002666 StructConstants->InsertOrGetItem(Lookup, Exists);
Chris Lattner8760ec72005-10-04 01:17:50 +00002667
2668 if (Exists) {
2669 Replacement = I->second;
2670 } else {
2671 // Okay, the new shape doesn't exist in the system yet. Instead of
2672 // creating a new constant struct, inserting it, replaceallusesof'ing the
2673 // old with the new, then deleting the old... just update the current one
2674 // in place!
Chris Lattner69edc982006-09-28 00:35:06 +00002675 StructConstants->MoveConstantToNewSlot(this, I);
Chris Lattner8760ec72005-10-04 01:17:50 +00002676
Chris Lattnerdff59112005-10-04 18:47:09 +00002677 // Update to the new value.
2678 setOperand(OperandToUpdate, ToC);
Chris Lattner8760ec72005-10-04 01:17:50 +00002679 return;
2680 }
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002681 }
2682
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002683 assert(Replacement != this && "I didn't contain From!");
2684
Chris Lattner7a1450d2005-10-04 18:13:04 +00002685 // Everyone using this now uses the replacement.
2686 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002687
2688 // Delete the old constant!
2689 destroyConstant();
2690}
2691
Reid Spencerd84d35b2007-02-15 02:26:10 +00002692void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
Chris Lattner7a1450d2005-10-04 18:13:04 +00002693 Use *U) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002694 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2695
2696 std::vector<Constant*> Values;
2697 Values.reserve(getNumOperands()); // Build replacement array...
2698 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2699 Constant *Val = getOperand(i);
2700 if (Val == From) Val = cast<Constant>(To);
2701 Values.push_back(Val);
2702 }
2703
Reid Spencerd84d35b2007-02-15 02:26:10 +00002704 Constant *Replacement = ConstantVector::get(getType(), Values);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002705 assert(Replacement != this && "I didn't contain From!");
2706
Chris Lattner7a1450d2005-10-04 18:13:04 +00002707 // Everyone using this now uses the replacement.
2708 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002709
2710 // Delete the old constant!
2711 destroyConstant();
2712}
2713
2714void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
Chris Lattner7a1450d2005-10-04 18:13:04 +00002715 Use *U) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002716 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2717 Constant *To = cast<Constant>(ToV);
2718
2719 Constant *Replacement = 0;
2720 if (getOpcode() == Instruction::GetElementPtr) {
Chris Lattnerb5d70302007-02-19 20:01:23 +00002721 SmallVector<Constant*, 8> Indices;
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002722 Constant *Pointer = getOperand(0);
2723 Indices.reserve(getNumOperands()-1);
2724 if (Pointer == From) Pointer = To;
2725
2726 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2727 Constant *Val = getOperand(i);
2728 if (Val == From) Val = To;
2729 Indices.push_back(Val);
2730 }
Chris Lattnerb5d70302007-02-19 20:01:23 +00002731 Replacement = ConstantExpr::getGetElementPtr(Pointer,
2732 &Indices[0], Indices.size());
Dan Gohman12fce772008-05-15 19:50:34 +00002733 } else if (getOpcode() == Instruction::ExtractValue) {
Dan Gohman12fce772008-05-15 19:50:34 +00002734 Constant *Agg = getOperand(0);
Dan Gohman12fce772008-05-15 19:50:34 +00002735 if (Agg == From) Agg = To;
2736
Dan Gohman1ecaf452008-05-31 00:58:22 +00002737 const SmallVector<unsigned, 4> &Indices = getIndices();
Dan Gohman12fce772008-05-15 19:50:34 +00002738 Replacement = ConstantExpr::getExtractValue(Agg,
2739 &Indices[0], Indices.size());
2740 } else if (getOpcode() == Instruction::InsertValue) {
Dan Gohman12fce772008-05-15 19:50:34 +00002741 Constant *Agg = getOperand(0);
2742 Constant *Val = getOperand(1);
Dan Gohman12fce772008-05-15 19:50:34 +00002743 if (Agg == From) Agg = To;
2744 if (Val == From) Val = To;
2745
Dan Gohman1ecaf452008-05-31 00:58:22 +00002746 const SmallVector<unsigned, 4> &Indices = getIndices();
Dan Gohman12fce772008-05-15 19:50:34 +00002747 Replacement = ConstantExpr::getInsertValue(Agg, Val,
2748 &Indices[0], Indices.size());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002749 } else if (isCast()) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002750 assert(getOperand(0) == From && "Cast only has one use!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002751 Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002752 } else if (getOpcode() == Instruction::Select) {
2753 Constant *C1 = getOperand(0);
2754 Constant *C2 = getOperand(1);
2755 Constant *C3 = getOperand(2);
2756 if (C1 == From) C1 = To;
2757 if (C2 == From) C2 = To;
2758 if (C3 == From) C3 = To;
2759 Replacement = ConstantExpr::getSelect(C1, C2, C3);
Robert Bocchino23004482006-01-10 19:05:34 +00002760 } else if (getOpcode() == Instruction::ExtractElement) {
2761 Constant *C1 = getOperand(0);
2762 Constant *C2 = getOperand(1);
2763 if (C1 == From) C1 = To;
2764 if (C2 == From) C2 = To;
2765 Replacement = ConstantExpr::getExtractElement(C1, C2);
Chris Lattnera93b4b52006-04-08 05:09:48 +00002766 } else if (getOpcode() == Instruction::InsertElement) {
2767 Constant *C1 = getOperand(0);
2768 Constant *C2 = getOperand(1);
2769 Constant *C3 = getOperand(1);
2770 if (C1 == From) C1 = To;
2771 if (C2 == From) C2 = To;
2772 if (C3 == From) C3 = To;
2773 Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2774 } else if (getOpcode() == Instruction::ShuffleVector) {
2775 Constant *C1 = getOperand(0);
2776 Constant *C2 = getOperand(1);
2777 Constant *C3 = getOperand(2);
2778 if (C1 == From) C1 = To;
2779 if (C2 == From) C2 = To;
2780 if (C3 == From) C3 = To;
2781 Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
Reid Spenceree3c9912006-12-04 05:19:50 +00002782 } else if (isCompare()) {
2783 Constant *C1 = getOperand(0);
2784 Constant *C2 = getOperand(1);
2785 if (C1 == From) C1 = To;
2786 if (C2 == From) C2 = To;
2787 if (getOpcode() == Instruction::ICmp)
2788 Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
Chris Lattnereab49262008-07-14 05:17:31 +00002789 else if (getOpcode() == Instruction::FCmp)
Reid Spenceree3c9912006-12-04 05:19:50 +00002790 Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
Chris Lattnereab49262008-07-14 05:17:31 +00002791 else if (getOpcode() == Instruction::VICmp)
2792 Replacement = ConstantExpr::getVICmp(getPredicate(), C1, C2);
2793 else {
2794 assert(getOpcode() == Instruction::VFCmp);
2795 Replacement = ConstantExpr::getVFCmp(getPredicate(), C1, C2);
2796 }
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002797 } else if (getNumOperands() == 2) {
2798 Constant *C1 = getOperand(0);
2799 Constant *C2 = getOperand(1);
2800 if (C1 == From) C1 = To;
2801 if (C2 == From) C2 = To;
2802 Replacement = ConstantExpr::get(getOpcode(), C1, C2);
2803 } else {
2804 assert(0 && "Unknown ConstantExpr type!");
2805 return;
2806 }
2807
2808 assert(Replacement != this && "I didn't contain From!");
2809
Chris Lattner7a1450d2005-10-04 18:13:04 +00002810 // Everyone using this now uses the replacement.
2811 uncheckedReplaceAllUsesWith(Replacement);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002812
2813 // Delete the old constant!
2814 destroyConstant();
Matthijs Kooijmanba5d7ef2008-07-03 07:46:41 +00002815}
Nick Lewycky49f89192009-04-04 07:22:01 +00002816
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00002817void MDNode::replaceElement(Value *From, Value *To) {
2818 SmallVector<Value*, 4> Values;
2819 Values.reserve(getNumElements()); // Build replacement array...
2820 for (unsigned i = 0, e = getNumElements(); i != e; ++i) {
2821 Value *Val = getElement(i);
2822 if (Val == From) Val = To;
Nick Lewycky49f89192009-04-04 07:22:01 +00002823 Values.push_back(Val);
2824 }
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00002825
2826 MDNode *Replacement = MDNode::get(&Values[0], Values.size());
Nick Lewycky49f89192009-04-04 07:22:01 +00002827 assert(Replacement != this && "I didn't contain From!");
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00002828
Nick Lewycky49f89192009-04-04 07:22:01 +00002829 uncheckedReplaceAllUsesWith(Replacement);
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00002830
Nick Lewycky49f89192009-04-04 07:22:01 +00002831 destroyConstant();
2832}