Add support for vectors of pointers.
[oota-llvm.git] / lib / VMCore / Constants.cpp
1 //===-- Constants.cpp - Implement Constant nodes --------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the Constant* classes.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Constants.h"
15 #include "LLVMContextImpl.h"
16 #include "ConstantFold.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/GlobalValue.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/Module.h"
21 #include "llvm/Operator.h"
22 #include "llvm/ADT/FoldingSet.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/ADT/StringMap.h"
25 #include "llvm/Support/Compiler.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/ManagedStatic.h"
29 #include "llvm/Support/MathExtras.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include "llvm/Support/GetElementPtrTypeIterator.h"
32 #include "llvm/ADT/DenseMap.h"
33 #include "llvm/ADT/SmallVector.h"
34 #include "llvm/ADT/STLExtras.h"
35 #include <algorithm>
36 #include <cstdarg>
37 using namespace llvm;
38
39 //===----------------------------------------------------------------------===//
40 //                              Constant Class
41 //===----------------------------------------------------------------------===//
42
43 bool Constant::isNegativeZeroValue() const {
44   // Floating point values have an explicit -0.0 value.
45   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
46     return CFP->isZero() && CFP->isNegative();
47   
48   // Otherwise, just use +0.0.
49   return isNullValue();
50 }
51
52 bool Constant::isNullValue() const {
53   // 0 is null.
54   if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
55     return CI->isZero();
56   
57   // +0.0 is null.
58   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
59     return CFP->isZero() && !CFP->isNegative();
60
61   // constant zero is zero for aggregates and cpnull is null for pointers.
62   return isa<ConstantAggregateZero>(this) || isa<ConstantPointerNull>(this);
63 }
64
65 bool Constant::isAllOnesValue() const {
66   // Check for -1 integers
67   if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
68     return CI->isMinusOne();
69
70   // Check for FP which are bitcasted from -1 integers
71   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
72     return CFP->getValueAPF().bitcastToAPInt().isAllOnesValue();
73
74   // Check for constant vectors which are splats of -1 values.
75   if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
76     if (Constant *Splat = CV->getSplatValue())
77       return Splat->isAllOnesValue();
78
79   return false;
80 }
81
82 // Constructor to create a '0' constant of arbitrary type...
83 Constant *Constant::getNullValue(Type *Ty) {
84   switch (Ty->getTypeID()) {
85   case Type::IntegerTyID:
86     return ConstantInt::get(Ty, 0);
87   case Type::FloatTyID:
88     return ConstantFP::get(Ty->getContext(),
89                            APFloat::getZero(APFloat::IEEEsingle));
90   case Type::DoubleTyID:
91     return ConstantFP::get(Ty->getContext(),
92                            APFloat::getZero(APFloat::IEEEdouble));
93   case Type::X86_FP80TyID:
94     return ConstantFP::get(Ty->getContext(),
95                            APFloat::getZero(APFloat::x87DoubleExtended));
96   case Type::FP128TyID:
97     return ConstantFP::get(Ty->getContext(),
98                            APFloat::getZero(APFloat::IEEEquad));
99   case Type::PPC_FP128TyID:
100     return ConstantFP::get(Ty->getContext(),
101                            APFloat(APInt::getNullValue(128)));
102   case Type::PointerTyID:
103     return ConstantPointerNull::get(cast<PointerType>(Ty));
104   case Type::StructTyID:
105   case Type::ArrayTyID:
106   case Type::VectorTyID:
107     return ConstantAggregateZero::get(Ty);
108   default:
109     // Function, Label, or Opaque type?
110     assert(0 && "Cannot create a null constant of that type!");
111     return 0;
112   }
113 }
114
115 Constant *Constant::getIntegerValue(Type *Ty, const APInt &V) {
116   Type *ScalarTy = Ty->getScalarType();
117
118   // Create the base integer constant.
119   Constant *C = ConstantInt::get(Ty->getContext(), V);
120
121   // Convert an integer to a pointer, if necessary.
122   if (PointerType *PTy = dyn_cast<PointerType>(ScalarTy))
123     C = ConstantExpr::getIntToPtr(C, PTy);
124
125   // Broadcast a scalar to a vector, if necessary.
126   if (VectorType *VTy = dyn_cast<VectorType>(Ty))
127     C = ConstantVector::get(std::vector<Constant *>(VTy->getNumElements(), C));
128
129   return C;
130 }
131
132 Constant *Constant::getAllOnesValue(Type *Ty) {
133   if (IntegerType *ITy = dyn_cast<IntegerType>(Ty))
134     return ConstantInt::get(Ty->getContext(),
135                             APInt::getAllOnesValue(ITy->getBitWidth()));
136
137   if (Ty->isFloatingPointTy()) {
138     APFloat FL = APFloat::getAllOnesValue(Ty->getPrimitiveSizeInBits(),
139                                           !Ty->isPPC_FP128Ty());
140     return ConstantFP::get(Ty->getContext(), FL);
141   }
142
143   SmallVector<Constant*, 16> Elts;
144   VectorType *VTy = cast<VectorType>(Ty);
145   Elts.resize(VTy->getNumElements(), getAllOnesValue(VTy->getElementType()));
146   assert(Elts[0] && "Invalid AllOnes value!");
147   return cast<ConstantVector>(ConstantVector::get(Elts));
148 }
149
150 void Constant::destroyConstantImpl() {
151   // When a Constant is destroyed, there may be lingering
152   // references to the constant by other constants in the constant pool.  These
153   // constants are implicitly dependent on the module that is being deleted,
154   // but they don't know that.  Because we only find out when the CPV is
155   // deleted, we must now notify all of our users (that should only be
156   // Constants) that they are, in fact, invalid now and should be deleted.
157   //
158   while (!use_empty()) {
159     Value *V = use_back();
160 #ifndef NDEBUG      // Only in -g mode...
161     if (!isa<Constant>(V)) {
162       dbgs() << "While deleting: " << *this
163              << "\n\nUse still stuck around after Def is destroyed: "
164              << *V << "\n\n";
165     }
166 #endif
167     assert(isa<Constant>(V) && "References remain to Constant being destroyed");
168     Constant *CV = cast<Constant>(V);
169     CV->destroyConstant();
170
171     // The constant should remove itself from our use list...
172     assert((use_empty() || use_back() != V) && "Constant not removed!");
173   }
174
175   // Value has no outstanding references it is safe to delete it now...
176   delete this;
177 }
178
179 /// canTrap - Return true if evaluation of this constant could trap.  This is
180 /// true for things like constant expressions that could divide by zero.
181 bool Constant::canTrap() const {
182   assert(getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
183   // The only thing that could possibly trap are constant exprs.
184   const ConstantExpr *CE = dyn_cast<ConstantExpr>(this);
185   if (!CE) return false;
186   
187   // ConstantExpr traps if any operands can trap. 
188   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
189     if (CE->getOperand(i)->canTrap()) 
190       return true;
191
192   // Otherwise, only specific operations can trap.
193   switch (CE->getOpcode()) {
194   default:
195     return false;
196   case Instruction::UDiv:
197   case Instruction::SDiv:
198   case Instruction::FDiv:
199   case Instruction::URem:
200   case Instruction::SRem:
201   case Instruction::FRem:
202     // Div and rem can trap if the RHS is not known to be non-zero.
203     if (!isa<ConstantInt>(CE->getOperand(1)) ||CE->getOperand(1)->isNullValue())
204       return true;
205     return false;
206   }
207 }
208
209 /// isConstantUsed - Return true if the constant has users other than constant
210 /// exprs and other dangling things.
211 bool Constant::isConstantUsed() const {
212   for (const_use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
213     const Constant *UC = dyn_cast<Constant>(*UI);
214     if (UC == 0 || isa<GlobalValue>(UC))
215       return true;
216     
217     if (UC->isConstantUsed())
218       return true;
219   }
220   return false;
221 }
222
223
224
225 /// getRelocationInfo - This method classifies the entry according to
226 /// whether or not it may generate a relocation entry.  This must be
227 /// conservative, so if it might codegen to a relocatable entry, it should say
228 /// so.  The return values are:
229 /// 
230 ///  NoRelocation: This constant pool entry is guaranteed to never have a
231 ///     relocation applied to it (because it holds a simple constant like
232 ///     '4').
233 ///  LocalRelocation: This entry has relocations, but the entries are
234 ///     guaranteed to be resolvable by the static linker, so the dynamic
235 ///     linker will never see them.
236 ///  GlobalRelocations: This entry may have arbitrary relocations.
237 ///
238 /// FIXME: This really should not be in VMCore.
239 Constant::PossibleRelocationsTy Constant::getRelocationInfo() const {
240   if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
241     if (GV->hasLocalLinkage() || GV->hasHiddenVisibility())
242       return LocalRelocation;  // Local to this file/library.
243     return GlobalRelocations;    // Global reference.
244   }
245   
246   if (const BlockAddress *BA = dyn_cast<BlockAddress>(this))
247     return BA->getFunction()->getRelocationInfo();
248   
249   // While raw uses of blockaddress need to be relocated, differences between
250   // two of them don't when they are for labels in the same function.  This is a
251   // common idiom when creating a table for the indirect goto extension, so we
252   // handle it efficiently here.
253   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(this))
254     if (CE->getOpcode() == Instruction::Sub) {
255       ConstantExpr *LHS = dyn_cast<ConstantExpr>(CE->getOperand(0));
256       ConstantExpr *RHS = dyn_cast<ConstantExpr>(CE->getOperand(1));
257       if (LHS && RHS &&
258           LHS->getOpcode() == Instruction::PtrToInt &&
259           RHS->getOpcode() == Instruction::PtrToInt &&
260           isa<BlockAddress>(LHS->getOperand(0)) &&
261           isa<BlockAddress>(RHS->getOperand(0)) &&
262           cast<BlockAddress>(LHS->getOperand(0))->getFunction() ==
263             cast<BlockAddress>(RHS->getOperand(0))->getFunction())
264         return NoRelocation;
265     }
266   
267   PossibleRelocationsTy Result = NoRelocation;
268   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
269     Result = std::max(Result,
270                       cast<Constant>(getOperand(i))->getRelocationInfo());
271   
272   return Result;
273 }
274
275
276 /// getVectorElements - This method, which is only valid on constant of vector
277 /// type, returns the elements of the vector in the specified smallvector.
278 /// This handles breaking down a vector undef into undef elements, etc.  For
279 /// constant exprs and other cases we can't handle, we return an empty vector.
280 void Constant::getVectorElements(SmallVectorImpl<Constant*> &Elts) const {
281   assert(getType()->isVectorTy() && "Not a vector constant!");
282   
283   if (const ConstantVector *CV = dyn_cast<ConstantVector>(this)) {
284     for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i)
285       Elts.push_back(CV->getOperand(i));
286     return;
287   }
288   
289   VectorType *VT = cast<VectorType>(getType());
290   if (isa<ConstantAggregateZero>(this)) {
291     Elts.assign(VT->getNumElements(), 
292                 Constant::getNullValue(VT->getElementType()));
293     return;
294   }
295   
296   if (isa<UndefValue>(this)) {
297     Elts.assign(VT->getNumElements(), UndefValue::get(VT->getElementType()));
298     return;
299   }
300   
301   // Unknown type, must be constant expr etc.
302 }
303
304
305 /// removeDeadUsersOfConstant - If the specified constantexpr is dead, remove
306 /// it.  This involves recursively eliminating any dead users of the
307 /// constantexpr.
308 static bool removeDeadUsersOfConstant(const Constant *C) {
309   if (isa<GlobalValue>(C)) return false; // Cannot remove this
310   
311   while (!C->use_empty()) {
312     const Constant *User = dyn_cast<Constant>(C->use_back());
313     if (!User) return false; // Non-constant usage;
314     if (!removeDeadUsersOfConstant(User))
315       return false; // Constant wasn't dead
316   }
317   
318   const_cast<Constant*>(C)->destroyConstant();
319   return true;
320 }
321
322
323 /// removeDeadConstantUsers - If there are any dead constant users dangling
324 /// off of this constant, remove them.  This method is useful for clients
325 /// that want to check to see if a global is unused, but don't want to deal
326 /// with potentially dead constants hanging off of the globals.
327 void Constant::removeDeadConstantUsers() const {
328   Value::const_use_iterator I = use_begin(), E = use_end();
329   Value::const_use_iterator LastNonDeadUser = E;
330   while (I != E) {
331     const Constant *User = dyn_cast<Constant>(*I);
332     if (User == 0) {
333       LastNonDeadUser = I;
334       ++I;
335       continue;
336     }
337     
338     if (!removeDeadUsersOfConstant(User)) {
339       // If the constant wasn't dead, remember that this was the last live use
340       // and move on to the next constant.
341       LastNonDeadUser = I;
342       ++I;
343       continue;
344     }
345     
346     // If the constant was dead, then the iterator is invalidated.
347     if (LastNonDeadUser == E) {
348       I = use_begin();
349       if (I == E) break;
350     } else {
351       I = LastNonDeadUser;
352       ++I;
353     }
354   }
355 }
356
357
358
359 //===----------------------------------------------------------------------===//
360 //                                ConstantInt
361 //===----------------------------------------------------------------------===//
362
363 ConstantInt::ConstantInt(IntegerType *Ty, const APInt& V)
364   : Constant(Ty, ConstantIntVal, 0, 0), Val(V) {
365   assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
366 }
367
368 ConstantInt *ConstantInt::getTrue(LLVMContext &Context) {
369   LLVMContextImpl *pImpl = Context.pImpl;
370   if (!pImpl->TheTrueVal)
371     pImpl->TheTrueVal = ConstantInt::get(Type::getInt1Ty(Context), 1);
372   return pImpl->TheTrueVal;
373 }
374
375 ConstantInt *ConstantInt::getFalse(LLVMContext &Context) {
376   LLVMContextImpl *pImpl = Context.pImpl;
377   if (!pImpl->TheFalseVal)
378     pImpl->TheFalseVal = ConstantInt::get(Type::getInt1Ty(Context), 0);
379   return pImpl->TheFalseVal;
380 }
381
382 Constant *ConstantInt::getTrue(Type *Ty) {
383   VectorType *VTy = dyn_cast<VectorType>(Ty);
384   if (!VTy) {
385     assert(Ty->isIntegerTy(1) && "True must be i1 or vector of i1.");
386     return ConstantInt::getTrue(Ty->getContext());
387   }
388   assert(VTy->getElementType()->isIntegerTy(1) &&
389          "True must be vector of i1 or i1.");
390   SmallVector<Constant*, 16> Splat(VTy->getNumElements(),
391                                    ConstantInt::getTrue(Ty->getContext()));
392   return ConstantVector::get(Splat);
393 }
394
395 Constant *ConstantInt::getFalse(Type *Ty) {
396   VectorType *VTy = dyn_cast<VectorType>(Ty);
397   if (!VTy) {
398     assert(Ty->isIntegerTy(1) && "False must be i1 or vector of i1.");
399     return ConstantInt::getFalse(Ty->getContext());
400   }
401   assert(VTy->getElementType()->isIntegerTy(1) &&
402          "False must be vector of i1 or i1.");
403   SmallVector<Constant*, 16> Splat(VTy->getNumElements(),
404                                    ConstantInt::getFalse(Ty->getContext()));
405   return ConstantVector::get(Splat);
406 }
407
408
409 // Get a ConstantInt from an APInt. Note that the value stored in the DenseMap 
410 // as the key, is a DenseMapAPIntKeyInfo::KeyTy which has provided the
411 // operator== and operator!= to ensure that the DenseMap doesn't attempt to
412 // compare APInt's of different widths, which would violate an APInt class
413 // invariant which generates an assertion.
414 ConstantInt *ConstantInt::get(LLVMContext &Context, const APInt &V) {
415   // Get the corresponding integer type for the bit width of the value.
416   IntegerType *ITy = IntegerType::get(Context, V.getBitWidth());
417   // get an existing value or the insertion position
418   DenseMapAPIntKeyInfo::KeyTy Key(V, ITy);
419   ConstantInt *&Slot = Context.pImpl->IntConstants[Key]; 
420   if (!Slot) Slot = new ConstantInt(ITy, V);
421   return Slot;
422 }
423
424 Constant *ConstantInt::get(Type *Ty, uint64_t V, bool isSigned) {
425   Constant *C = get(cast<IntegerType>(Ty->getScalarType()), V, isSigned);
426
427   // For vectors, broadcast the value.
428   if (VectorType *VTy = dyn_cast<VectorType>(Ty))
429     return ConstantVector::get(SmallVector<Constant*,
430                                            16>(VTy->getNumElements(), C));
431
432   return C;
433 }
434
435 ConstantInt* ConstantInt::get(IntegerType* Ty, uint64_t V, 
436                               bool isSigned) {
437   return get(Ty->getContext(), APInt(Ty->getBitWidth(), V, isSigned));
438 }
439
440 ConstantInt* ConstantInt::getSigned(IntegerType* Ty, int64_t V) {
441   return get(Ty, V, true);
442 }
443
444 Constant *ConstantInt::getSigned(Type *Ty, int64_t V) {
445   return get(Ty, V, true);
446 }
447
448 Constant *ConstantInt::get(Type* Ty, const APInt& V) {
449   ConstantInt *C = get(Ty->getContext(), V);
450   assert(C->getType() == Ty->getScalarType() &&
451          "ConstantInt type doesn't match the type implied by its value!");
452
453   // For vectors, broadcast the value.
454   if (VectorType *VTy = dyn_cast<VectorType>(Ty))
455     return ConstantVector::get(
456       SmallVector<Constant *, 16>(VTy->getNumElements(), C));
457
458   return C;
459 }
460
461 ConstantInt* ConstantInt::get(IntegerType* Ty, StringRef Str,
462                               uint8_t radix) {
463   return get(Ty->getContext(), APInt(Ty->getBitWidth(), Str, radix));
464 }
465
466 //===----------------------------------------------------------------------===//
467 //                                ConstantFP
468 //===----------------------------------------------------------------------===//
469
470 static const fltSemantics *TypeToFloatSemantics(Type *Ty) {
471   if (Ty->isFloatTy())
472     return &APFloat::IEEEsingle;
473   if (Ty->isDoubleTy())
474     return &APFloat::IEEEdouble;
475   if (Ty->isX86_FP80Ty())
476     return &APFloat::x87DoubleExtended;
477   else if (Ty->isFP128Ty())
478     return &APFloat::IEEEquad;
479   
480   assert(Ty->isPPC_FP128Ty() && "Unknown FP format");
481   return &APFloat::PPCDoubleDouble;
482 }
483
484 /// get() - This returns a constant fp for the specified value in the
485 /// specified type.  This should only be used for simple constant values like
486 /// 2.0/1.0 etc, that are known-valid both as double and as the target format.
487 Constant *ConstantFP::get(Type* Ty, double V) {
488   LLVMContext &Context = Ty->getContext();
489   
490   APFloat FV(V);
491   bool ignored;
492   FV.convert(*TypeToFloatSemantics(Ty->getScalarType()),
493              APFloat::rmNearestTiesToEven, &ignored);
494   Constant *C = get(Context, FV);
495
496   // For vectors, broadcast the value.
497   if (VectorType *VTy = dyn_cast<VectorType>(Ty))
498     return ConstantVector::get(
499       SmallVector<Constant *, 16>(VTy->getNumElements(), C));
500
501   return C;
502 }
503
504
505 Constant *ConstantFP::get(Type* Ty, StringRef Str) {
506   LLVMContext &Context = Ty->getContext();
507
508   APFloat FV(*TypeToFloatSemantics(Ty->getScalarType()), Str);
509   Constant *C = get(Context, FV);
510
511   // For vectors, broadcast the value.
512   if (VectorType *VTy = dyn_cast<VectorType>(Ty))
513     return ConstantVector::get(
514       SmallVector<Constant *, 16>(VTy->getNumElements(), C));
515
516   return C; 
517 }
518
519
520 ConstantFP* ConstantFP::getNegativeZero(Type* Ty) {
521   LLVMContext &Context = Ty->getContext();
522   APFloat apf = cast <ConstantFP>(Constant::getNullValue(Ty))->getValueAPF();
523   apf.changeSign();
524   return get(Context, apf);
525 }
526
527
528 Constant *ConstantFP::getZeroValueForNegation(Type* Ty) {
529   if (VectorType *PTy = dyn_cast<VectorType>(Ty))
530     if (PTy->getElementType()->isFloatingPointTy()) {
531       SmallVector<Constant*, 16> zeros(PTy->getNumElements(),
532                            getNegativeZero(PTy->getElementType()));
533       return ConstantVector::get(zeros);
534     }
535
536   if (Ty->isFloatingPointTy()) 
537     return getNegativeZero(Ty);
538
539   return Constant::getNullValue(Ty);
540 }
541
542
543 // ConstantFP accessors.
544 ConstantFP* ConstantFP::get(LLVMContext &Context, const APFloat& V) {
545   DenseMapAPFloatKeyInfo::KeyTy Key(V);
546   
547   LLVMContextImpl* pImpl = Context.pImpl;
548   
549   ConstantFP *&Slot = pImpl->FPConstants[Key];
550     
551   if (!Slot) {
552     Type *Ty;
553     if (&V.getSemantics() == &APFloat::IEEEsingle)
554       Ty = Type::getFloatTy(Context);
555     else if (&V.getSemantics() == &APFloat::IEEEdouble)
556       Ty = Type::getDoubleTy(Context);
557     else if (&V.getSemantics() == &APFloat::x87DoubleExtended)
558       Ty = Type::getX86_FP80Ty(Context);
559     else if (&V.getSemantics() == &APFloat::IEEEquad)
560       Ty = Type::getFP128Ty(Context);
561     else {
562       assert(&V.getSemantics() == &APFloat::PPCDoubleDouble && 
563              "Unknown FP format");
564       Ty = Type::getPPC_FP128Ty(Context);
565     }
566     Slot = new ConstantFP(Ty, V);
567   }
568   
569   return Slot;
570 }
571
572 ConstantFP *ConstantFP::getInfinity(Type *Ty, bool Negative) {
573   const fltSemantics &Semantics = *TypeToFloatSemantics(Ty);
574   return ConstantFP::get(Ty->getContext(),
575                          APFloat::getInf(Semantics, Negative));
576 }
577
578 ConstantFP::ConstantFP(Type *Ty, const APFloat& V)
579   : Constant(Ty, ConstantFPVal, 0, 0), Val(V) {
580   assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
581          "FP type Mismatch");
582 }
583
584 bool ConstantFP::isExactlyValue(const APFloat &V) const {
585   return Val.bitwiseIsEqual(V);
586 }
587
588 //===----------------------------------------------------------------------===//
589 //                            ConstantXXX Classes
590 //===----------------------------------------------------------------------===//
591
592
593 ConstantArray::ConstantArray(ArrayType *T, ArrayRef<Constant *> V)
594   : Constant(T, ConstantArrayVal,
595              OperandTraits<ConstantArray>::op_end(this) - V.size(),
596              V.size()) {
597   assert(V.size() == T->getNumElements() &&
598          "Invalid initializer vector for constant array");
599   for (unsigned i = 0, e = V.size(); i != e; ++i)
600     assert(V[i]->getType() == T->getElementType() &&
601            "Initializer for array element doesn't match array element type!");
602   std::copy(V.begin(), V.end(), op_begin());
603 }
604
605 Constant *ConstantArray::get(ArrayType *Ty, ArrayRef<Constant*> V) {
606   for (unsigned i = 0, e = V.size(); i != e; ++i) {
607     assert(V[i]->getType() == Ty->getElementType() &&
608            "Wrong type in array element initializer");
609   }
610   LLVMContextImpl *pImpl = Ty->getContext().pImpl;
611   // If this is an all-zero array, return a ConstantAggregateZero object
612   if (!V.empty()) {
613     Constant *C = V[0];
614     if (!C->isNullValue())
615       return pImpl->ArrayConstants.getOrCreate(Ty, V);
616     
617     for (unsigned i = 1, e = V.size(); i != e; ++i)
618       if (V[i] != C)
619         return pImpl->ArrayConstants.getOrCreate(Ty, V);
620   }
621   
622   return ConstantAggregateZero::get(Ty);
623 }
624
625 /// ConstantArray::get(const string&) - Return an array that is initialized to
626 /// contain the specified string.  If length is zero then a null terminator is 
627 /// added to the specified string so that it may be used in a natural way. 
628 /// Otherwise, the length parameter specifies how much of the string to use 
629 /// and it won't be null terminated.
630 ///
631 Constant *ConstantArray::get(LLVMContext &Context, StringRef Str,
632                              bool AddNull) {
633   std::vector<Constant*> ElementVals;
634   ElementVals.reserve(Str.size() + size_t(AddNull));
635   for (unsigned i = 0; i < Str.size(); ++i)
636     ElementVals.push_back(ConstantInt::get(Type::getInt8Ty(Context), Str[i]));
637
638   // Add a null terminator to the string...
639   if (AddNull) {
640     ElementVals.push_back(ConstantInt::get(Type::getInt8Ty(Context), 0));
641   }
642
643   ArrayType *ATy = ArrayType::get(Type::getInt8Ty(Context), ElementVals.size());
644   return get(ATy, ElementVals);
645 }
646
647 /// getTypeForElements - Return an anonymous struct type to use for a constant
648 /// with the specified set of elements.  The list must not be empty.
649 StructType *ConstantStruct::getTypeForElements(LLVMContext &Context,
650                                                ArrayRef<Constant*> V,
651                                                bool Packed) {
652   SmallVector<Type*, 16> EltTypes;
653   for (unsigned i = 0, e = V.size(); i != e; ++i)
654     EltTypes.push_back(V[i]->getType());
655   
656   return StructType::get(Context, EltTypes, Packed);
657 }
658
659
660 StructType *ConstantStruct::getTypeForElements(ArrayRef<Constant*> V,
661                                                bool Packed) {
662   assert(!V.empty() &&
663          "ConstantStruct::getTypeForElements cannot be called on empty list");
664   return getTypeForElements(V[0]->getContext(), V, Packed);
665 }
666
667
668 ConstantStruct::ConstantStruct(StructType *T, ArrayRef<Constant *> V)
669   : Constant(T, ConstantStructVal,
670              OperandTraits<ConstantStruct>::op_end(this) - V.size(),
671              V.size()) {
672   assert(V.size() == T->getNumElements() &&
673          "Invalid initializer vector for constant structure");
674   for (unsigned i = 0, e = V.size(); i != e; ++i)
675     assert((T->isOpaque() || V[i]->getType() == T->getElementType(i)) &&
676            "Initializer for struct element doesn't match struct element type!");
677   std::copy(V.begin(), V.end(), op_begin());
678 }
679
680 // ConstantStruct accessors.
681 Constant *ConstantStruct::get(StructType *ST, ArrayRef<Constant*> V) {
682   // Create a ConstantAggregateZero value if all elements are zeros.
683   for (unsigned i = 0, e = V.size(); i != e; ++i)
684     if (!V[i]->isNullValue())
685       return ST->getContext().pImpl->StructConstants.getOrCreate(ST, V);
686
687   assert((ST->isOpaque() || ST->getNumElements() == V.size()) &&
688          "Incorrect # elements specified to ConstantStruct::get");
689   return ConstantAggregateZero::get(ST);
690 }
691
692 Constant *ConstantStruct::get(StructType *T, ...) {
693   va_list ap;
694   SmallVector<Constant*, 8> Values;
695   va_start(ap, T);
696   while (Constant *Val = va_arg(ap, llvm::Constant*))
697     Values.push_back(Val);
698   va_end(ap);
699   return get(T, Values);
700 }
701
702 ConstantVector::ConstantVector(VectorType *T, ArrayRef<Constant *> V)
703   : Constant(T, ConstantVectorVal,
704              OperandTraits<ConstantVector>::op_end(this) - V.size(),
705              V.size()) {
706   for (size_t i = 0, e = V.size(); i != e; i++)
707     assert(V[i]->getType() == T->getElementType() &&
708            "Initializer for vector element doesn't match vector element type!");
709   std::copy(V.begin(), V.end(), op_begin());
710 }
711
712 // ConstantVector accessors.
713 Constant *ConstantVector::get(ArrayRef<Constant*> V) {
714   assert(!V.empty() && "Vectors can't be empty");
715   VectorType *T = VectorType::get(V.front()->getType(), V.size());
716   LLVMContextImpl *pImpl = T->getContext().pImpl;
717
718   // If this is an all-undef or all-zero vector, return a
719   // ConstantAggregateZero or UndefValue.
720   Constant *C = V[0];
721   bool isZero = C->isNullValue();
722   bool isUndef = isa<UndefValue>(C);
723
724   if (isZero || isUndef) {
725     for (unsigned i = 1, e = V.size(); i != e; ++i)
726       if (V[i] != C) {
727         isZero = isUndef = false;
728         break;
729       }
730   }
731   
732   if (isZero)
733     return ConstantAggregateZero::get(T);
734   if (isUndef)
735     return UndefValue::get(T);
736     
737   return pImpl->VectorConstants.getOrCreate(T, V);
738 }
739
740 // Utility function for determining if a ConstantExpr is a CastOp or not. This
741 // can't be inline because we don't want to #include Instruction.h into
742 // Constant.h
743 bool ConstantExpr::isCast() const {
744   return Instruction::isCast(getOpcode());
745 }
746
747 bool ConstantExpr::isCompare() const {
748   return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
749 }
750
751 bool ConstantExpr::isGEPWithNoNotionalOverIndexing() const {
752   if (getOpcode() != Instruction::GetElementPtr) return false;
753
754   gep_type_iterator GEPI = gep_type_begin(this), E = gep_type_end(this);
755   User::const_op_iterator OI = llvm::next(this->op_begin());
756
757   // Skip the first index, as it has no static limit.
758   ++GEPI;
759   ++OI;
760
761   // The remaining indices must be compile-time known integers within the
762   // bounds of the corresponding notional static array types.
763   for (; GEPI != E; ++GEPI, ++OI) {
764     ConstantInt *CI = dyn_cast<ConstantInt>(*OI);
765     if (!CI) return false;
766     if (ArrayType *ATy = dyn_cast<ArrayType>(*GEPI))
767       if (CI->getValue().getActiveBits() > 64 ||
768           CI->getZExtValue() >= ATy->getNumElements())
769         return false;
770   }
771
772   // All the indices checked out.
773   return true;
774 }
775
776 bool ConstantExpr::hasIndices() const {
777   return getOpcode() == Instruction::ExtractValue ||
778          getOpcode() == Instruction::InsertValue;
779 }
780
781 ArrayRef<unsigned> ConstantExpr::getIndices() const {
782   if (const ExtractValueConstantExpr *EVCE =
783         dyn_cast<ExtractValueConstantExpr>(this))
784     return EVCE->Indices;
785
786   return cast<InsertValueConstantExpr>(this)->Indices;
787 }
788
789 unsigned ConstantExpr::getPredicate() const {
790   assert(isCompare());
791   return ((const CompareConstantExpr*)this)->predicate;
792 }
793
794 /// getWithOperandReplaced - Return a constant expression identical to this
795 /// one, but with the specified operand set to the specified value.
796 Constant *
797 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
798   assert(OpNo < getNumOperands() && "Operand num is out of range!");
799   assert(Op->getType() == getOperand(OpNo)->getType() &&
800          "Replacing operand with value of different type!");
801   if (getOperand(OpNo) == Op)
802     return const_cast<ConstantExpr*>(this);
803   
804   Constant *Op0, *Op1, *Op2;
805   switch (getOpcode()) {
806   case Instruction::Trunc:
807   case Instruction::ZExt:
808   case Instruction::SExt:
809   case Instruction::FPTrunc:
810   case Instruction::FPExt:
811   case Instruction::UIToFP:
812   case Instruction::SIToFP:
813   case Instruction::FPToUI:
814   case Instruction::FPToSI:
815   case Instruction::PtrToInt:
816   case Instruction::IntToPtr:
817   case Instruction::BitCast:
818     return ConstantExpr::getCast(getOpcode(), Op, getType());
819   case Instruction::Select:
820     Op0 = (OpNo == 0) ? Op : getOperand(0);
821     Op1 = (OpNo == 1) ? Op : getOperand(1);
822     Op2 = (OpNo == 2) ? Op : getOperand(2);
823     return ConstantExpr::getSelect(Op0, Op1, Op2);
824   case Instruction::InsertElement:
825     Op0 = (OpNo == 0) ? Op : getOperand(0);
826     Op1 = (OpNo == 1) ? Op : getOperand(1);
827     Op2 = (OpNo == 2) ? Op : getOperand(2);
828     return ConstantExpr::getInsertElement(Op0, Op1, Op2);
829   case Instruction::ExtractElement:
830     Op0 = (OpNo == 0) ? Op : getOperand(0);
831     Op1 = (OpNo == 1) ? Op : getOperand(1);
832     return ConstantExpr::getExtractElement(Op0, Op1);
833   case Instruction::ShuffleVector:
834     Op0 = (OpNo == 0) ? Op : getOperand(0);
835     Op1 = (OpNo == 1) ? Op : getOperand(1);
836     Op2 = (OpNo == 2) ? Op : getOperand(2);
837     return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
838   case Instruction::GetElementPtr: {
839     SmallVector<Constant*, 8> Ops;
840     Ops.resize(getNumOperands()-1);
841     for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
842       Ops[i-1] = getOperand(i);
843     if (OpNo == 0)
844       return
845         ConstantExpr::getGetElementPtr(Op, Ops,
846                                        cast<GEPOperator>(this)->isInBounds());
847     Ops[OpNo-1] = Op;
848     return
849       ConstantExpr::getGetElementPtr(getOperand(0), Ops,
850                                      cast<GEPOperator>(this)->isInBounds());
851   }
852   default:
853     assert(getNumOperands() == 2 && "Must be binary operator?");
854     Op0 = (OpNo == 0) ? Op : getOperand(0);
855     Op1 = (OpNo == 1) ? Op : getOperand(1);
856     return ConstantExpr::get(getOpcode(), Op0, Op1, SubclassOptionalData);
857   }
858 }
859
860 /// getWithOperands - This returns the current constant expression with the
861 /// operands replaced with the specified values.  The specified array must
862 /// have the same number of operands as our current one.
863 Constant *ConstantExpr::
864 getWithOperands(ArrayRef<Constant*> Ops, Type *Ty) const {
865   assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
866   bool AnyChange = Ty != getType();
867   for (unsigned i = 0; i != Ops.size(); ++i)
868     AnyChange |= Ops[i] != getOperand(i);
869   
870   if (!AnyChange)  // No operands changed, return self.
871     return const_cast<ConstantExpr*>(this);
872
873   switch (getOpcode()) {
874   case Instruction::Trunc:
875   case Instruction::ZExt:
876   case Instruction::SExt:
877   case Instruction::FPTrunc:
878   case Instruction::FPExt:
879   case Instruction::UIToFP:
880   case Instruction::SIToFP:
881   case Instruction::FPToUI:
882   case Instruction::FPToSI:
883   case Instruction::PtrToInt:
884   case Instruction::IntToPtr:
885   case Instruction::BitCast:
886     return ConstantExpr::getCast(getOpcode(), Ops[0], Ty);
887   case Instruction::Select:
888     return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
889   case Instruction::InsertElement:
890     return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
891   case Instruction::ExtractElement:
892     return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
893   case Instruction::ShuffleVector:
894     return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
895   case Instruction::GetElementPtr:
896     return
897       ConstantExpr::getGetElementPtr(Ops[0], Ops.slice(1),
898                                      cast<GEPOperator>(this)->isInBounds());
899   case Instruction::ICmp:
900   case Instruction::FCmp:
901     return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
902   default:
903     assert(getNumOperands() == 2 && "Must be binary operator?");
904     return ConstantExpr::get(getOpcode(), Ops[0], Ops[1], SubclassOptionalData);
905   }
906 }
907
908
909 //===----------------------------------------------------------------------===//
910 //                      isValueValidForType implementations
911
912 bool ConstantInt::isValueValidForType(Type *Ty, uint64_t Val) {
913   unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
914   if (Ty == Type::getInt1Ty(Ty->getContext()))
915     return Val == 0 || Val == 1;
916   if (NumBits >= 64)
917     return true; // always true, has to fit in largest type
918   uint64_t Max = (1ll << NumBits) - 1;
919   return Val <= Max;
920 }
921
922 bool ConstantInt::isValueValidForType(Type *Ty, int64_t Val) {
923   unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
924   if (Ty == Type::getInt1Ty(Ty->getContext()))
925     return Val == 0 || Val == 1 || Val == -1;
926   if (NumBits >= 64)
927     return true; // always true, has to fit in largest type
928   int64_t Min = -(1ll << (NumBits-1));
929   int64_t Max = (1ll << (NumBits-1)) - 1;
930   return (Val >= Min && Val <= Max);
931 }
932
933 bool ConstantFP::isValueValidForType(Type *Ty, const APFloat& Val) {
934   // convert modifies in place, so make a copy.
935   APFloat Val2 = APFloat(Val);
936   bool losesInfo;
937   switch (Ty->getTypeID()) {
938   default:
939     return false;         // These can't be represented as floating point!
940
941   // FIXME rounding mode needs to be more flexible
942   case Type::FloatTyID: {
943     if (&Val2.getSemantics() == &APFloat::IEEEsingle)
944       return true;
945     Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &losesInfo);
946     return !losesInfo;
947   }
948   case Type::DoubleTyID: {
949     if (&Val2.getSemantics() == &APFloat::IEEEsingle ||
950         &Val2.getSemantics() == &APFloat::IEEEdouble)
951       return true;
952     Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &losesInfo);
953     return !losesInfo;
954   }
955   case Type::X86_FP80TyID:
956     return &Val2.getSemantics() == &APFloat::IEEEsingle || 
957            &Val2.getSemantics() == &APFloat::IEEEdouble ||
958            &Val2.getSemantics() == &APFloat::x87DoubleExtended;
959   case Type::FP128TyID:
960     return &Val2.getSemantics() == &APFloat::IEEEsingle || 
961            &Val2.getSemantics() == &APFloat::IEEEdouble ||
962            &Val2.getSemantics() == &APFloat::IEEEquad;
963   case Type::PPC_FP128TyID:
964     return &Val2.getSemantics() == &APFloat::IEEEsingle || 
965            &Val2.getSemantics() == &APFloat::IEEEdouble ||
966            &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
967   }
968 }
969
970 //===----------------------------------------------------------------------===//
971 //                      Factory Function Implementation
972
973 ConstantAggregateZero* ConstantAggregateZero::get(Type* Ty) {
974   assert((Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()) &&
975          "Cannot create an aggregate zero of non-aggregate type!");
976   
977   LLVMContextImpl *pImpl = Ty->getContext().pImpl;
978   return pImpl->AggZeroConstants.getOrCreate(Ty, 0);
979 }
980
981 /// destroyConstant - Remove the constant from the constant table...
982 ///
983 void ConstantAggregateZero::destroyConstant() {
984   getType()->getContext().pImpl->AggZeroConstants.remove(this);
985   destroyConstantImpl();
986 }
987
988 /// destroyConstant - Remove the constant from the constant table...
989 ///
990 void ConstantArray::destroyConstant() {
991   getType()->getContext().pImpl->ArrayConstants.remove(this);
992   destroyConstantImpl();
993 }
994
995 /// isString - This method returns true if the array is an array of i8, and 
996 /// if the elements of the array are all ConstantInt's.
997 bool ConstantArray::isString() const {
998   // Check the element type for i8...
999   if (!getType()->getElementType()->isIntegerTy(8))
1000     return false;
1001   // Check the elements to make sure they are all integers, not constant
1002   // expressions.
1003   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1004     if (!isa<ConstantInt>(getOperand(i)))
1005       return false;
1006   return true;
1007 }
1008
1009 /// isCString - This method returns true if the array is a string (see
1010 /// isString) and it ends in a null byte \\0 and does not contains any other
1011 /// null bytes except its terminator.
1012 bool ConstantArray::isCString() const {
1013   // Check the element type for i8...
1014   if (!getType()->getElementType()->isIntegerTy(8))
1015     return false;
1016
1017   // Last element must be a null.
1018   if (!getOperand(getNumOperands()-1)->isNullValue())
1019     return false;
1020   // Other elements must be non-null integers.
1021   for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
1022     if (!isa<ConstantInt>(getOperand(i)))
1023       return false;
1024     if (getOperand(i)->isNullValue())
1025       return false;
1026   }
1027   return true;
1028 }
1029
1030
1031 /// convertToString - Helper function for getAsString() and getAsCString().
1032 static std::string convertToString(const User *U, unsigned len) {
1033   std::string Result;
1034   Result.reserve(len);
1035   for (unsigned i = 0; i != len; ++i)
1036     Result.push_back((char)cast<ConstantInt>(U->getOperand(i))->getZExtValue());
1037   return Result;
1038 }
1039
1040 /// getAsString - If this array is isString(), then this method converts the
1041 /// array to an std::string and returns it.  Otherwise, it asserts out.
1042 ///
1043 std::string ConstantArray::getAsString() const {
1044   assert(isString() && "Not a string!");
1045   return convertToString(this, getNumOperands());
1046 }
1047
1048
1049 /// getAsCString - If this array is isCString(), then this method converts the
1050 /// array (without the trailing null byte) to an std::string and returns it.
1051 /// Otherwise, it asserts out.
1052 ///
1053 std::string ConstantArray::getAsCString() const {
1054   assert(isCString() && "Not a string!");
1055   return convertToString(this, getNumOperands() - 1);
1056 }
1057
1058
1059 //---- ConstantStruct::get() implementation...
1060 //
1061
1062 // destroyConstant - Remove the constant from the constant table...
1063 //
1064 void ConstantStruct::destroyConstant() {
1065   getType()->getContext().pImpl->StructConstants.remove(this);
1066   destroyConstantImpl();
1067 }
1068
1069 // destroyConstant - Remove the constant from the constant table...
1070 //
1071 void ConstantVector::destroyConstant() {
1072   getType()->getContext().pImpl->VectorConstants.remove(this);
1073   destroyConstantImpl();
1074 }
1075
1076 /// getSplatValue - If this is a splat constant, where all of the
1077 /// elements have the same value, return that value. Otherwise return null.
1078 Constant *ConstantVector::getSplatValue() const {
1079   // Check out first element.
1080   Constant *Elt = getOperand(0);
1081   // Then make sure all remaining elements point to the same value.
1082   for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
1083     if (getOperand(I) != Elt)
1084       return 0;
1085   return Elt;
1086 }
1087
1088 //---- ConstantPointerNull::get() implementation.
1089 //
1090
1091 ConstantPointerNull *ConstantPointerNull::get(PointerType *Ty) {
1092   return Ty->getContext().pImpl->NullPtrConstants.getOrCreate(Ty, 0);
1093 }
1094
1095 // destroyConstant - Remove the constant from the constant table...
1096 //
1097 void ConstantPointerNull::destroyConstant() {
1098   getType()->getContext().pImpl->NullPtrConstants.remove(this);
1099   destroyConstantImpl();
1100 }
1101
1102
1103 //---- UndefValue::get() implementation.
1104 //
1105
1106 UndefValue *UndefValue::get(Type *Ty) {
1107   return Ty->getContext().pImpl->UndefValueConstants.getOrCreate(Ty, 0);
1108 }
1109
1110 // destroyConstant - Remove the constant from the constant table.
1111 //
1112 void UndefValue::destroyConstant() {
1113   getType()->getContext().pImpl->UndefValueConstants.remove(this);
1114   destroyConstantImpl();
1115 }
1116
1117 //---- BlockAddress::get() implementation.
1118 //
1119
1120 BlockAddress *BlockAddress::get(BasicBlock *BB) {
1121   assert(BB->getParent() != 0 && "Block must have a parent");
1122   return get(BB->getParent(), BB);
1123 }
1124
1125 BlockAddress *BlockAddress::get(Function *F, BasicBlock *BB) {
1126   BlockAddress *&BA =
1127     F->getContext().pImpl->BlockAddresses[std::make_pair(F, BB)];
1128   if (BA == 0)
1129     BA = new BlockAddress(F, BB);
1130   
1131   assert(BA->getFunction() == F && "Basic block moved between functions");
1132   return BA;
1133 }
1134
1135 BlockAddress::BlockAddress(Function *F, BasicBlock *BB)
1136 : Constant(Type::getInt8PtrTy(F->getContext()), Value::BlockAddressVal,
1137            &Op<0>(), 2) {
1138   setOperand(0, F);
1139   setOperand(1, BB);
1140   BB->AdjustBlockAddressRefCount(1);
1141 }
1142
1143
1144 // destroyConstant - Remove the constant from the constant table.
1145 //
1146 void BlockAddress::destroyConstant() {
1147   getFunction()->getType()->getContext().pImpl
1148     ->BlockAddresses.erase(std::make_pair(getFunction(), getBasicBlock()));
1149   getBasicBlock()->AdjustBlockAddressRefCount(-1);
1150   destroyConstantImpl();
1151 }
1152
1153 void BlockAddress::replaceUsesOfWithOnConstant(Value *From, Value *To, Use *U) {
1154   // This could be replacing either the Basic Block or the Function.  In either
1155   // case, we have to remove the map entry.
1156   Function *NewF = getFunction();
1157   BasicBlock *NewBB = getBasicBlock();
1158   
1159   if (U == &Op<0>())
1160     NewF = cast<Function>(To);
1161   else
1162     NewBB = cast<BasicBlock>(To);
1163   
1164   // See if the 'new' entry already exists, if not, just update this in place
1165   // and return early.
1166   BlockAddress *&NewBA =
1167     getContext().pImpl->BlockAddresses[std::make_pair(NewF, NewBB)];
1168   if (NewBA == 0) {
1169     getBasicBlock()->AdjustBlockAddressRefCount(-1);
1170     
1171     // Remove the old entry, this can't cause the map to rehash (just a
1172     // tombstone will get added).
1173     getContext().pImpl->BlockAddresses.erase(std::make_pair(getFunction(),
1174                                                             getBasicBlock()));
1175     NewBA = this;
1176     setOperand(0, NewF);
1177     setOperand(1, NewBB);
1178     getBasicBlock()->AdjustBlockAddressRefCount(1);
1179     return;
1180   }
1181
1182   // Otherwise, I do need to replace this with an existing value.
1183   assert(NewBA != this && "I didn't contain From!");
1184   
1185   // Everyone using this now uses the replacement.
1186   replaceAllUsesWith(NewBA);
1187   
1188   destroyConstant();
1189 }
1190
1191 //---- ConstantExpr::get() implementations.
1192 //
1193
1194 /// This is a utility function to handle folding of casts and lookup of the
1195 /// cast in the ExprConstants map. It is used by the various get* methods below.
1196 static inline Constant *getFoldedCast(
1197   Instruction::CastOps opc, Constant *C, Type *Ty) {
1198   assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1199   // Fold a few common cases
1200   if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
1201     return FC;
1202
1203   LLVMContextImpl *pImpl = Ty->getContext().pImpl;
1204
1205   // Look up the constant in the table first to ensure uniqueness
1206   std::vector<Constant*> argVec(1, C);
1207   ExprMapKeyType Key(opc, argVec);
1208   
1209   return pImpl->ExprConstants.getOrCreate(Ty, Key);
1210 }
1211  
1212 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, Type *Ty) {
1213   Instruction::CastOps opc = Instruction::CastOps(oc);
1214   assert(Instruction::isCast(opc) && "opcode out of range");
1215   assert(C && Ty && "Null arguments to getCast");
1216   assert(CastInst::castIsValid(opc, C, Ty) && "Invalid constantexpr cast!");
1217
1218   switch (opc) {
1219   default:
1220     llvm_unreachable("Invalid cast opcode");
1221     break;
1222   case Instruction::Trunc:    return getTrunc(C, Ty);
1223   case Instruction::ZExt:     return getZExt(C, Ty);
1224   case Instruction::SExt:     return getSExt(C, Ty);
1225   case Instruction::FPTrunc:  return getFPTrunc(C, Ty);
1226   case Instruction::FPExt:    return getFPExtend(C, Ty);
1227   case Instruction::UIToFP:   return getUIToFP(C, Ty);
1228   case Instruction::SIToFP:   return getSIToFP(C, Ty);
1229   case Instruction::FPToUI:   return getFPToUI(C, Ty);
1230   case Instruction::FPToSI:   return getFPToSI(C, Ty);
1231   case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1232   case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1233   case Instruction::BitCast:  return getBitCast(C, Ty);
1234   }
1235   return 0;
1236
1237
1238 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, Type *Ty) {
1239   if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1240     return getBitCast(C, Ty);
1241   return getZExt(C, Ty);
1242 }
1243
1244 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, Type *Ty) {
1245   if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1246     return getBitCast(C, Ty);
1247   return getSExt(C, Ty);
1248 }
1249
1250 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, Type *Ty) {
1251   if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1252     return getBitCast(C, Ty);
1253   return getTrunc(C, Ty);
1254 }
1255
1256 Constant *ConstantExpr::getPointerCast(Constant *S, Type *Ty) {
1257   assert(S->getType()->isPointerTy() && "Invalid cast");
1258   assert((Ty->isIntegerTy() || Ty->isPointerTy()) && "Invalid cast");
1259
1260   if (Ty->isIntegerTy())
1261     return getPtrToInt(S, Ty);
1262   return getBitCast(S, Ty);
1263 }
1264
1265 Constant *ConstantExpr::getIntegerCast(Constant *C, Type *Ty, 
1266                                        bool isSigned) {
1267   assert(C->getType()->isIntOrIntVectorTy() &&
1268          Ty->isIntOrIntVectorTy() && "Invalid cast");
1269   unsigned SrcBits = C->getType()->getScalarSizeInBits();
1270   unsigned DstBits = Ty->getScalarSizeInBits();
1271   Instruction::CastOps opcode =
1272     (SrcBits == DstBits ? Instruction::BitCast :
1273      (SrcBits > DstBits ? Instruction::Trunc :
1274       (isSigned ? Instruction::SExt : Instruction::ZExt)));
1275   return getCast(opcode, C, Ty);
1276 }
1277
1278 Constant *ConstantExpr::getFPCast(Constant *C, Type *Ty) {
1279   assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
1280          "Invalid cast");
1281   unsigned SrcBits = C->getType()->getScalarSizeInBits();
1282   unsigned DstBits = Ty->getScalarSizeInBits();
1283   if (SrcBits == DstBits)
1284     return C; // Avoid a useless cast
1285   Instruction::CastOps opcode =
1286     (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
1287   return getCast(opcode, C, Ty);
1288 }
1289
1290 Constant *ConstantExpr::getTrunc(Constant *C, Type *Ty) {
1291 #ifndef NDEBUG
1292   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1293   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1294 #endif
1295   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1296   assert(C->getType()->isIntOrIntVectorTy() && "Trunc operand must be integer");
1297   assert(Ty->isIntOrIntVectorTy() && "Trunc produces only integral");
1298   assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1299          "SrcTy must be larger than DestTy for Trunc!");
1300
1301   return getFoldedCast(Instruction::Trunc, C, Ty);
1302 }
1303
1304 Constant *ConstantExpr::getSExt(Constant *C, Type *Ty) {
1305 #ifndef NDEBUG
1306   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1307   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1308 #endif
1309   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1310   assert(C->getType()->isIntOrIntVectorTy() && "SExt operand must be integral");
1311   assert(Ty->isIntOrIntVectorTy() && "SExt produces only integer");
1312   assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1313          "SrcTy must be smaller than DestTy for SExt!");
1314
1315   return getFoldedCast(Instruction::SExt, C, Ty);
1316 }
1317
1318 Constant *ConstantExpr::getZExt(Constant *C, Type *Ty) {
1319 #ifndef NDEBUG
1320   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1321   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1322 #endif
1323   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1324   assert(C->getType()->isIntOrIntVectorTy() && "ZEXt operand must be integral");
1325   assert(Ty->isIntOrIntVectorTy() && "ZExt produces only integer");
1326   assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1327          "SrcTy must be smaller than DestTy for ZExt!");
1328
1329   return getFoldedCast(Instruction::ZExt, C, Ty);
1330 }
1331
1332 Constant *ConstantExpr::getFPTrunc(Constant *C, Type *Ty) {
1333 #ifndef NDEBUG
1334   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1335   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1336 #endif
1337   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1338   assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
1339          C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1340          "This is an illegal floating point truncation!");
1341   return getFoldedCast(Instruction::FPTrunc, C, Ty);
1342 }
1343
1344 Constant *ConstantExpr::getFPExtend(Constant *C, Type *Ty) {
1345 #ifndef NDEBUG
1346   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1347   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1348 #endif
1349   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1350   assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
1351          C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1352          "This is an illegal floating point extension!");
1353   return getFoldedCast(Instruction::FPExt, C, Ty);
1354 }
1355
1356 Constant *ConstantExpr::getUIToFP(Constant *C, Type *Ty) {
1357 #ifndef NDEBUG
1358   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1359   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1360 #endif
1361   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1362   assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
1363          "This is an illegal uint to floating point cast!");
1364   return getFoldedCast(Instruction::UIToFP, C, Ty);
1365 }
1366
1367 Constant *ConstantExpr::getSIToFP(Constant *C, Type *Ty) {
1368 #ifndef NDEBUG
1369   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1370   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1371 #endif
1372   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1373   assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
1374          "This is an illegal sint to floating point cast!");
1375   return getFoldedCast(Instruction::SIToFP, C, Ty);
1376 }
1377
1378 Constant *ConstantExpr::getFPToUI(Constant *C, Type *Ty) {
1379 #ifndef NDEBUG
1380   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1381   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1382 #endif
1383   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1384   assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
1385          "This is an illegal floating point to uint cast!");
1386   return getFoldedCast(Instruction::FPToUI, C, Ty);
1387 }
1388
1389 Constant *ConstantExpr::getFPToSI(Constant *C, Type *Ty) {
1390 #ifndef NDEBUG
1391   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1392   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1393 #endif
1394   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1395   assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
1396          "This is an illegal floating point to sint cast!");
1397   return getFoldedCast(Instruction::FPToSI, C, Ty);
1398 }
1399
1400 Constant *ConstantExpr::getPtrToInt(Constant *C, Type *DstTy) {
1401   assert(C->getType()->getScalarType()->isPointerTy() &&
1402          "PtrToInt source must be pointer or pointer vector");
1403   assert(DstTy->getScalarType()->isIntegerTy() && 
1404          "PtrToInt destination must be integer or integer vector");
1405   assert(C->getType()->getNumElements() == DstTy->getNumElements() &&
1406     "Invalid cast between a different number of vector elements");
1407   return getFoldedCast(Instruction::PtrToInt, C, DstTy);
1408 }
1409
1410 Constant *ConstantExpr::getIntToPtr(Constant *C, Type *DstTy) {
1411   assert(C->getType()->getScalarType()->isIntegerTy() &&
1412          "IntToPtr source must be integer or integer vector");
1413   assert(DstTy->getScalarType()->isPointerTy() &&
1414          "IntToPtr destination must be a pointer or pointer vector");
1415   assert(C->getType()->getNumElements() == DstTy->getNumElements() &&
1416     "Invalid cast between a different number of vector elements");
1417   return getFoldedCast(Instruction::IntToPtr, C, DstTy);
1418 }
1419
1420 Constant *ConstantExpr::getBitCast(Constant *C, Type *DstTy) {
1421   assert(CastInst::castIsValid(Instruction::BitCast, C, DstTy) &&
1422          "Invalid constantexpr bitcast!");
1423   
1424   // It is common to ask for a bitcast of a value to its own type, handle this
1425   // speedily.
1426   if (C->getType() == DstTy) return C;
1427   
1428   return getFoldedCast(Instruction::BitCast, C, DstTy);
1429 }
1430
1431 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2,
1432                             unsigned Flags) {
1433   // Check the operands for consistency first.
1434   assert(Opcode >= Instruction::BinaryOpsBegin &&
1435          Opcode <  Instruction::BinaryOpsEnd   &&
1436          "Invalid opcode in binary constant expression");
1437   assert(C1->getType() == C2->getType() &&
1438          "Operand types in binary constant expression should match");
1439   
1440 #ifndef NDEBUG
1441   switch (Opcode) {
1442   case Instruction::Add:
1443   case Instruction::Sub:
1444   case Instruction::Mul:
1445     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1446     assert(C1->getType()->isIntOrIntVectorTy() &&
1447            "Tried to create an integer operation on a non-integer type!");
1448     break;
1449   case Instruction::FAdd:
1450   case Instruction::FSub:
1451   case Instruction::FMul:
1452     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1453     assert(C1->getType()->isFPOrFPVectorTy() &&
1454            "Tried to create a floating-point operation on a "
1455            "non-floating-point type!");
1456     break;
1457   case Instruction::UDiv: 
1458   case Instruction::SDiv: 
1459     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1460     assert(C1->getType()->isIntOrIntVectorTy() &&
1461            "Tried to create an arithmetic operation on a non-arithmetic type!");
1462     break;
1463   case Instruction::FDiv:
1464     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1465     assert(C1->getType()->isFPOrFPVectorTy() &&
1466            "Tried to create an arithmetic operation on a non-arithmetic type!");
1467     break;
1468   case Instruction::URem: 
1469   case Instruction::SRem: 
1470     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1471     assert(C1->getType()->isIntOrIntVectorTy() &&
1472            "Tried to create an arithmetic operation on a non-arithmetic type!");
1473     break;
1474   case Instruction::FRem:
1475     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1476     assert(C1->getType()->isFPOrFPVectorTy() &&
1477            "Tried to create an arithmetic operation on a non-arithmetic type!");
1478     break;
1479   case Instruction::And:
1480   case Instruction::Or:
1481   case Instruction::Xor:
1482     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1483     assert(C1->getType()->isIntOrIntVectorTy() &&
1484            "Tried to create a logical operation on a non-integral type!");
1485     break;
1486   case Instruction::Shl:
1487   case Instruction::LShr:
1488   case Instruction::AShr:
1489     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1490     assert(C1->getType()->isIntOrIntVectorTy() &&
1491            "Tried to create a shift operation on a non-integer type!");
1492     break;
1493   default:
1494     break;
1495   }
1496 #endif
1497
1498   if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1499     return FC;          // Fold a few common cases.
1500   
1501   std::vector<Constant*> argVec(1, C1);
1502   argVec.push_back(C2);
1503   ExprMapKeyType Key(Opcode, argVec, 0, Flags);
1504   
1505   LLVMContextImpl *pImpl = C1->getContext().pImpl;
1506   return pImpl->ExprConstants.getOrCreate(C1->getType(), Key);
1507 }
1508
1509 Constant *ConstantExpr::getSizeOf(Type* Ty) {
1510   // sizeof is implemented as: (i64) gep (Ty*)null, 1
1511   // Note that a non-inbounds gep is used, as null isn't within any object.
1512   Constant *GEPIdx = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
1513   Constant *GEP = getGetElementPtr(
1514                  Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx);
1515   return getPtrToInt(GEP, 
1516                      Type::getInt64Ty(Ty->getContext()));
1517 }
1518
1519 Constant *ConstantExpr::getAlignOf(Type* Ty) {
1520   // alignof is implemented as: (i64) gep ({i1,Ty}*)null, 0, 1
1521   // Note that a non-inbounds gep is used, as null isn't within any object.
1522   Type *AligningTy = 
1523     StructType::get(Type::getInt1Ty(Ty->getContext()), Ty, NULL);
1524   Constant *NullPtr = Constant::getNullValue(AligningTy->getPointerTo());
1525   Constant *Zero = ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0);
1526   Constant *One = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
1527   Constant *Indices[2] = { Zero, One };
1528   Constant *GEP = getGetElementPtr(NullPtr, Indices);
1529   return getPtrToInt(GEP,
1530                      Type::getInt64Ty(Ty->getContext()));
1531 }
1532
1533 Constant *ConstantExpr::getOffsetOf(StructType* STy, unsigned FieldNo) {
1534   return getOffsetOf(STy, ConstantInt::get(Type::getInt32Ty(STy->getContext()),
1535                                            FieldNo));
1536 }
1537
1538 Constant *ConstantExpr::getOffsetOf(Type* Ty, Constant *FieldNo) {
1539   // offsetof is implemented as: (i64) gep (Ty*)null, 0, FieldNo
1540   // Note that a non-inbounds gep is used, as null isn't within any object.
1541   Constant *GEPIdx[] = {
1542     ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0),
1543     FieldNo
1544   };
1545   Constant *GEP = getGetElementPtr(
1546                 Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx);
1547   return getPtrToInt(GEP,
1548                      Type::getInt64Ty(Ty->getContext()));
1549 }
1550
1551 Constant *ConstantExpr::getCompare(unsigned short Predicate, 
1552                                    Constant *C1, Constant *C2) {
1553   assert(C1->getType() == C2->getType() && "Op types should be identical!");
1554   
1555   switch (Predicate) {
1556   default: llvm_unreachable("Invalid CmpInst predicate");
1557   case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
1558   case CmpInst::FCMP_OGE:   case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
1559   case CmpInst::FCMP_ONE:   case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
1560   case CmpInst::FCMP_UEQ:   case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
1561   case CmpInst::FCMP_ULT:   case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
1562   case CmpInst::FCMP_TRUE:
1563     return getFCmp(Predicate, C1, C2);
1564     
1565   case CmpInst::ICMP_EQ:  case CmpInst::ICMP_NE:  case CmpInst::ICMP_UGT:
1566   case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
1567   case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
1568   case CmpInst::ICMP_SLE:
1569     return getICmp(Predicate, C1, C2);
1570   }
1571 }
1572
1573 Constant *ConstantExpr::getSelect(Constant *C, Constant *V1, Constant *V2) {
1574   assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
1575
1576   if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1577     return SC;        // Fold common cases
1578
1579   std::vector<Constant*> argVec(3, C);
1580   argVec[1] = V1;
1581   argVec[2] = V2;
1582   ExprMapKeyType Key(Instruction::Select, argVec);
1583   
1584   LLVMContextImpl *pImpl = C->getContext().pImpl;
1585   return pImpl->ExprConstants.getOrCreate(V1->getType(), Key);
1586 }
1587
1588 Constant *ConstantExpr::getGetElementPtr(Constant *C, ArrayRef<Value *> Idxs,
1589                                          bool InBounds) {
1590   if (Constant *FC = ConstantFoldGetElementPtr(C, InBounds, Idxs))
1591     return FC;          // Fold a few common cases.
1592
1593   // Get the result type of the getelementptr!
1594   Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), Idxs);
1595   assert(Ty && "GEP indices invalid!");
1596   unsigned AS = cast<PointerType>(C->getType())->getAddressSpace();
1597   Type *ReqTy = Ty->getPointerTo(AS);
1598   
1599   assert(C->getType()->isPointerTy() &&
1600          "Non-pointer type for constant GetElementPtr expression");
1601   // Look up the constant in the table first to ensure uniqueness
1602   std::vector<Constant*> ArgVec;
1603   ArgVec.reserve(1 + Idxs.size());
1604   ArgVec.push_back(C);
1605   for (unsigned i = 0, e = Idxs.size(); i != e; ++i)
1606     ArgVec.push_back(cast<Constant>(Idxs[i]));
1607   const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec, 0,
1608                            InBounds ? GEPOperator::IsInBounds : 0);
1609   
1610   LLVMContextImpl *pImpl = C->getContext().pImpl;
1611   return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1612 }
1613
1614 Constant *
1615 ConstantExpr::getICmp(unsigned short pred, Constant *LHS, Constant *RHS) {
1616   assert(LHS->getType() == RHS->getType());
1617   assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE && 
1618          pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
1619
1620   if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
1621     return FC;          // Fold a few common cases...
1622
1623   // Look up the constant in the table first to ensure uniqueness
1624   std::vector<Constant*> ArgVec;
1625   ArgVec.push_back(LHS);
1626   ArgVec.push_back(RHS);
1627   // Get the key type with both the opcode and predicate
1628   const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
1629
1630   Type *ResultTy = Type::getInt1Ty(LHS->getContext());
1631   if (VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
1632     ResultTy = VectorType::get(ResultTy, VT->getNumElements());
1633
1634   LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
1635   return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
1636 }
1637
1638 Constant *
1639 ConstantExpr::getFCmp(unsigned short pred, Constant *LHS, Constant *RHS) {
1640   assert(LHS->getType() == RHS->getType());
1641   assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
1642
1643   if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
1644     return FC;          // Fold a few common cases...
1645
1646   // Look up the constant in the table first to ensure uniqueness
1647   std::vector<Constant*> ArgVec;
1648   ArgVec.push_back(LHS);
1649   ArgVec.push_back(RHS);
1650   // Get the key type with both the opcode and predicate
1651   const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
1652
1653   Type *ResultTy = Type::getInt1Ty(LHS->getContext());
1654   if (VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
1655     ResultTy = VectorType::get(ResultTy, VT->getNumElements());
1656
1657   LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
1658   return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
1659 }
1660
1661 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
1662   assert(Val->getType()->isVectorTy() &&
1663          "Tried to create extractelement operation on non-vector type!");
1664   assert(Idx->getType()->isIntegerTy(32) &&
1665          "Extractelement index must be i32 type!");
1666   
1667   if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
1668     return FC;          // Fold a few common cases.
1669   
1670   // Look up the constant in the table first to ensure uniqueness
1671   std::vector<Constant*> ArgVec(1, Val);
1672   ArgVec.push_back(Idx);
1673   const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
1674   
1675   LLVMContextImpl *pImpl = Val->getContext().pImpl;
1676   Type *ReqTy = cast<VectorType>(Val->getType())->getElementType();
1677   return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1678 }
1679
1680 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt, 
1681                                          Constant *Idx) {
1682   assert(Val->getType()->isVectorTy() &&
1683          "Tried to create insertelement operation on non-vector type!");
1684   assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType()
1685          && "Insertelement types must match!");
1686   assert(Idx->getType()->isIntegerTy(32) &&
1687          "Insertelement index must be i32 type!");
1688
1689   if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
1690     return FC;          // Fold a few common cases.
1691   // Look up the constant in the table first to ensure uniqueness
1692   std::vector<Constant*> ArgVec(1, Val);
1693   ArgVec.push_back(Elt);
1694   ArgVec.push_back(Idx);
1695   const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
1696   
1697   LLVMContextImpl *pImpl = Val->getContext().pImpl;
1698   return pImpl->ExprConstants.getOrCreate(Val->getType(), Key);
1699 }
1700
1701 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2, 
1702                                          Constant *Mask) {
1703   assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
1704          "Invalid shuffle vector constant expr operands!");
1705
1706   if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
1707     return FC;          // Fold a few common cases.
1708
1709   unsigned NElts = cast<VectorType>(Mask->getType())->getNumElements();
1710   Type *EltTy = cast<VectorType>(V1->getType())->getElementType();
1711   Type *ShufTy = VectorType::get(EltTy, NElts);
1712
1713   // Look up the constant in the table first to ensure uniqueness
1714   std::vector<Constant*> ArgVec(1, V1);
1715   ArgVec.push_back(V2);
1716   ArgVec.push_back(Mask);
1717   const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
1718   
1719   LLVMContextImpl *pImpl = ShufTy->getContext().pImpl;
1720   return pImpl->ExprConstants.getOrCreate(ShufTy, Key);
1721 }
1722
1723 Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
1724                                        ArrayRef<unsigned> Idxs) {
1725   assert(ExtractValueInst::getIndexedType(Agg->getType(),
1726                                           Idxs) == Val->getType() &&
1727          "insertvalue indices invalid!");
1728   assert(Agg->getType()->isFirstClassType() &&
1729          "Non-first-class type for constant insertvalue expression");
1730   Constant *FC = ConstantFoldInsertValueInstruction(Agg, Val, Idxs);
1731   assert(FC && "insertvalue constant expr couldn't be folded!");
1732   return FC;
1733 }
1734
1735 Constant *ConstantExpr::getExtractValue(Constant *Agg,
1736                                         ArrayRef<unsigned> Idxs) {
1737   assert(Agg->getType()->isFirstClassType() &&
1738          "Tried to create extractelement operation on non-first-class type!");
1739
1740   Type *ReqTy = ExtractValueInst::getIndexedType(Agg->getType(), Idxs);
1741   (void)ReqTy;
1742   assert(ReqTy && "extractvalue indices invalid!");
1743   
1744   assert(Agg->getType()->isFirstClassType() &&
1745          "Non-first-class type for constant extractvalue expression");
1746   Constant *FC = ConstantFoldExtractValueInstruction(Agg, Idxs);
1747   assert(FC && "ExtractValue constant expr couldn't be folded!");
1748   return FC;
1749 }
1750
1751 Constant *ConstantExpr::getNeg(Constant *C, bool HasNUW, bool HasNSW) {
1752   assert(C->getType()->isIntOrIntVectorTy() &&
1753          "Cannot NEG a nonintegral value!");
1754   return getSub(ConstantFP::getZeroValueForNegation(C->getType()),
1755                 C, HasNUW, HasNSW);
1756 }
1757
1758 Constant *ConstantExpr::getFNeg(Constant *C) {
1759   assert(C->getType()->isFPOrFPVectorTy() &&
1760          "Cannot FNEG a non-floating-point value!");
1761   return getFSub(ConstantFP::getZeroValueForNegation(C->getType()), C);
1762 }
1763
1764 Constant *ConstantExpr::getNot(Constant *C) {
1765   assert(C->getType()->isIntOrIntVectorTy() &&
1766          "Cannot NOT a nonintegral value!");
1767   return get(Instruction::Xor, C, Constant::getAllOnesValue(C->getType()));
1768 }
1769
1770 Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2,
1771                                bool HasNUW, bool HasNSW) {
1772   unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
1773                    (HasNSW ? OverflowingBinaryOperator::NoSignedWrap   : 0);
1774   return get(Instruction::Add, C1, C2, Flags);
1775 }
1776
1777 Constant *ConstantExpr::getFAdd(Constant *C1, Constant *C2) {
1778   return get(Instruction::FAdd, C1, C2);
1779 }
1780
1781 Constant *ConstantExpr::getSub(Constant *C1, Constant *C2,
1782                                bool HasNUW, bool HasNSW) {
1783   unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
1784                    (HasNSW ? OverflowingBinaryOperator::NoSignedWrap   : 0);
1785   return get(Instruction::Sub, C1, C2, Flags);
1786 }
1787
1788 Constant *ConstantExpr::getFSub(Constant *C1, Constant *C2) {
1789   return get(Instruction::FSub, C1, C2);
1790 }
1791
1792 Constant *ConstantExpr::getMul(Constant *C1, Constant *C2,
1793                                bool HasNUW, bool HasNSW) {
1794   unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
1795                    (HasNSW ? OverflowingBinaryOperator::NoSignedWrap   : 0);
1796   return get(Instruction::Mul, C1, C2, Flags);
1797 }
1798
1799 Constant *ConstantExpr::getFMul(Constant *C1, Constant *C2) {
1800   return get(Instruction::FMul, C1, C2);
1801 }
1802
1803 Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2, bool isExact) {
1804   return get(Instruction::UDiv, C1, C2,
1805              isExact ? PossiblyExactOperator::IsExact : 0);
1806 }
1807
1808 Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2, bool isExact) {
1809   return get(Instruction::SDiv, C1, C2,
1810              isExact ? PossiblyExactOperator::IsExact : 0);
1811 }
1812
1813 Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
1814   return get(Instruction::FDiv, C1, C2);
1815 }
1816
1817 Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
1818   return get(Instruction::URem, C1, C2);
1819 }
1820
1821 Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
1822   return get(Instruction::SRem, C1, C2);
1823 }
1824
1825 Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
1826   return get(Instruction::FRem, C1, C2);
1827 }
1828
1829 Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
1830   return get(Instruction::And, C1, C2);
1831 }
1832
1833 Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
1834   return get(Instruction::Or, C1, C2);
1835 }
1836
1837 Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
1838   return get(Instruction::Xor, C1, C2);
1839 }
1840
1841 Constant *ConstantExpr::getShl(Constant *C1, Constant *C2,
1842                                bool HasNUW, bool HasNSW) {
1843   unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
1844                    (HasNSW ? OverflowingBinaryOperator::NoSignedWrap   : 0);
1845   return get(Instruction::Shl, C1, C2, Flags);
1846 }
1847
1848 Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2, bool isExact) {
1849   return get(Instruction::LShr, C1, C2,
1850              isExact ? PossiblyExactOperator::IsExact : 0);
1851 }
1852
1853 Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2, bool isExact) {
1854   return get(Instruction::AShr, C1, C2,
1855              isExact ? PossiblyExactOperator::IsExact : 0);
1856 }
1857
1858 // destroyConstant - Remove the constant from the constant table...
1859 //
1860 void ConstantExpr::destroyConstant() {
1861   getType()->getContext().pImpl->ExprConstants.remove(this);
1862   destroyConstantImpl();
1863 }
1864
1865 const char *ConstantExpr::getOpcodeName() const {
1866   return Instruction::getOpcodeName(getOpcode());
1867 }
1868
1869
1870
1871 GetElementPtrConstantExpr::
1872 GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
1873                           Type *DestTy)
1874   : ConstantExpr(DestTy, Instruction::GetElementPtr,
1875                  OperandTraits<GetElementPtrConstantExpr>::op_end(this)
1876                  - (IdxList.size()+1), IdxList.size()+1) {
1877   OperandList[0] = C;
1878   for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
1879     OperandList[i+1] = IdxList[i];
1880 }
1881
1882
1883 //===----------------------------------------------------------------------===//
1884 //                replaceUsesOfWithOnConstant implementations
1885
1886 /// replaceUsesOfWithOnConstant - Update this constant array to change uses of
1887 /// 'From' to be uses of 'To'.  This must update the uniquing data structures
1888 /// etc.
1889 ///
1890 /// Note that we intentionally replace all uses of From with To here.  Consider
1891 /// a large array that uses 'From' 1000 times.  By handling this case all here,
1892 /// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
1893 /// single invocation handles all 1000 uses.  Handling them one at a time would
1894 /// work, but would be really slow because it would have to unique each updated
1895 /// array instance.
1896 ///
1897 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
1898                                                 Use *U) {
1899   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1900   Constant *ToC = cast<Constant>(To);
1901
1902   LLVMContextImpl *pImpl = getType()->getContext().pImpl;
1903
1904   std::pair<LLVMContextImpl::ArrayConstantsTy::MapKey, ConstantArray*> Lookup;
1905   Lookup.first.first = cast<ArrayType>(getType());
1906   Lookup.second = this;
1907
1908   std::vector<Constant*> &Values = Lookup.first.second;
1909   Values.reserve(getNumOperands());  // Build replacement array.
1910
1911   // Fill values with the modified operands of the constant array.  Also, 
1912   // compute whether this turns into an all-zeros array.
1913   bool isAllZeros = false;
1914   unsigned NumUpdated = 0;
1915   if (!ToC->isNullValue()) {
1916     for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1917       Constant *Val = cast<Constant>(O->get());
1918       if (Val == From) {
1919         Val = ToC;
1920         ++NumUpdated;
1921       }
1922       Values.push_back(Val);
1923     }
1924   } else {
1925     isAllZeros = true;
1926     for (Use *O = OperandList, *E = OperandList+getNumOperands();O != E; ++O) {
1927       Constant *Val = cast<Constant>(O->get());
1928       if (Val == From) {
1929         Val = ToC;
1930         ++NumUpdated;
1931       }
1932       Values.push_back(Val);
1933       if (isAllZeros) isAllZeros = Val->isNullValue();
1934     }
1935   }
1936   
1937   Constant *Replacement = 0;
1938   if (isAllZeros) {
1939     Replacement = ConstantAggregateZero::get(getType());
1940   } else {
1941     // Check to see if we have this array type already.
1942     bool Exists;
1943     LLVMContextImpl::ArrayConstantsTy::MapTy::iterator I =
1944       pImpl->ArrayConstants.InsertOrGetItem(Lookup, Exists);
1945     
1946     if (Exists) {
1947       Replacement = I->second;
1948     } else {
1949       // Okay, the new shape doesn't exist in the system yet.  Instead of
1950       // creating a new constant array, inserting it, replaceallusesof'ing the
1951       // old with the new, then deleting the old... just update the current one
1952       // in place!
1953       pImpl->ArrayConstants.MoveConstantToNewSlot(this, I);
1954       
1955       // Update to the new value.  Optimize for the case when we have a single
1956       // operand that we're changing, but handle bulk updates efficiently.
1957       if (NumUpdated == 1) {
1958         unsigned OperandToUpdate = U - OperandList;
1959         assert(getOperand(OperandToUpdate) == From &&
1960                "ReplaceAllUsesWith broken!");
1961         setOperand(OperandToUpdate, ToC);
1962       } else {
1963         for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1964           if (getOperand(i) == From)
1965             setOperand(i, ToC);
1966       }
1967       return;
1968     }
1969   }
1970  
1971   // Otherwise, I do need to replace this with an existing value.
1972   assert(Replacement != this && "I didn't contain From!");
1973   
1974   // Everyone using this now uses the replacement.
1975   replaceAllUsesWith(Replacement);
1976   
1977   // Delete the old constant!
1978   destroyConstant();
1979 }
1980
1981 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
1982                                                  Use *U) {
1983   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1984   Constant *ToC = cast<Constant>(To);
1985
1986   unsigned OperandToUpdate = U-OperandList;
1987   assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
1988
1989   std::pair<LLVMContextImpl::StructConstantsTy::MapKey, ConstantStruct*> Lookup;
1990   Lookup.first.first = cast<StructType>(getType());
1991   Lookup.second = this;
1992   std::vector<Constant*> &Values = Lookup.first.second;
1993   Values.reserve(getNumOperands());  // Build replacement struct.
1994   
1995   
1996   // Fill values with the modified operands of the constant struct.  Also, 
1997   // compute whether this turns into an all-zeros struct.
1998   bool isAllZeros = false;
1999   if (!ToC->isNullValue()) {
2000     for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O)
2001       Values.push_back(cast<Constant>(O->get()));
2002   } else {
2003     isAllZeros = true;
2004     for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2005       Constant *Val = cast<Constant>(O->get());
2006       Values.push_back(Val);
2007       if (isAllZeros) isAllZeros = Val->isNullValue();
2008     }
2009   }
2010   Values[OperandToUpdate] = ToC;
2011   
2012   LLVMContextImpl *pImpl = getContext().pImpl;
2013   
2014   Constant *Replacement = 0;
2015   if (isAllZeros) {
2016     Replacement = ConstantAggregateZero::get(getType());
2017   } else {
2018     // Check to see if we have this struct type already.
2019     bool Exists;
2020     LLVMContextImpl::StructConstantsTy::MapTy::iterator I =
2021       pImpl->StructConstants.InsertOrGetItem(Lookup, Exists);
2022     
2023     if (Exists) {
2024       Replacement = I->second;
2025     } else {
2026       // Okay, the new shape doesn't exist in the system yet.  Instead of
2027       // creating a new constant struct, inserting it, replaceallusesof'ing the
2028       // old with the new, then deleting the old... just update the current one
2029       // in place!
2030       pImpl->StructConstants.MoveConstantToNewSlot(this, I);
2031       
2032       // Update to the new value.
2033       setOperand(OperandToUpdate, ToC);
2034       return;
2035     }
2036   }
2037   
2038   assert(Replacement != this && "I didn't contain From!");
2039   
2040   // Everyone using this now uses the replacement.
2041   replaceAllUsesWith(Replacement);
2042   
2043   // Delete the old constant!
2044   destroyConstant();
2045 }
2046
2047 void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
2048                                                  Use *U) {
2049   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2050   
2051   std::vector<Constant*> Values;
2052   Values.reserve(getNumOperands());  // Build replacement array...
2053   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2054     Constant *Val = getOperand(i);
2055     if (Val == From) Val = cast<Constant>(To);
2056     Values.push_back(Val);
2057   }
2058   
2059   Constant *Replacement = get(Values);
2060   assert(Replacement != this && "I didn't contain From!");
2061   
2062   // Everyone using this now uses the replacement.
2063   replaceAllUsesWith(Replacement);
2064   
2065   // Delete the old constant!
2066   destroyConstant();
2067 }
2068
2069 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
2070                                                Use *U) {
2071   assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2072   Constant *To = cast<Constant>(ToV);
2073   
2074   Constant *Replacement = 0;
2075   if (getOpcode() == Instruction::GetElementPtr) {
2076     SmallVector<Constant*, 8> Indices;
2077     Constant *Pointer = getOperand(0);
2078     Indices.reserve(getNumOperands()-1);
2079     if (Pointer == From) Pointer = To;
2080     
2081     for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2082       Constant *Val = getOperand(i);
2083       if (Val == From) Val = To;
2084       Indices.push_back(Val);
2085     }
2086     Replacement = ConstantExpr::getGetElementPtr(Pointer, Indices,
2087                                          cast<GEPOperator>(this)->isInBounds());
2088   } else if (getOpcode() == Instruction::ExtractValue) {
2089     Constant *Agg = getOperand(0);
2090     if (Agg == From) Agg = To;
2091     
2092     ArrayRef<unsigned> Indices = getIndices();
2093     Replacement = ConstantExpr::getExtractValue(Agg, Indices);
2094   } else if (getOpcode() == Instruction::InsertValue) {
2095     Constant *Agg = getOperand(0);
2096     Constant *Val = getOperand(1);
2097     if (Agg == From) Agg = To;
2098     if (Val == From) Val = To;
2099     
2100     ArrayRef<unsigned> Indices = getIndices();
2101     Replacement = ConstantExpr::getInsertValue(Agg, Val, Indices);
2102   } else if (isCast()) {
2103     assert(getOperand(0) == From && "Cast only has one use!");
2104     Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
2105   } else if (getOpcode() == Instruction::Select) {
2106     Constant *C1 = getOperand(0);
2107     Constant *C2 = getOperand(1);
2108     Constant *C3 = getOperand(2);
2109     if (C1 == From) C1 = To;
2110     if (C2 == From) C2 = To;
2111     if (C3 == From) C3 = To;
2112     Replacement = ConstantExpr::getSelect(C1, C2, C3);
2113   } else if (getOpcode() == Instruction::ExtractElement) {
2114     Constant *C1 = getOperand(0);
2115     Constant *C2 = getOperand(1);
2116     if (C1 == From) C1 = To;
2117     if (C2 == From) C2 = To;
2118     Replacement = ConstantExpr::getExtractElement(C1, C2);
2119   } else if (getOpcode() == Instruction::InsertElement) {
2120     Constant *C1 = getOperand(0);
2121     Constant *C2 = getOperand(1);
2122     Constant *C3 = getOperand(1);
2123     if (C1 == From) C1 = To;
2124     if (C2 == From) C2 = To;
2125     if (C3 == From) C3 = To;
2126     Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2127   } else if (getOpcode() == Instruction::ShuffleVector) {
2128     Constant *C1 = getOperand(0);
2129     Constant *C2 = getOperand(1);
2130     Constant *C3 = getOperand(2);
2131     if (C1 == From) C1 = To;
2132     if (C2 == From) C2 = To;
2133     if (C3 == From) C3 = To;
2134     Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
2135   } else if (isCompare()) {
2136     Constant *C1 = getOperand(0);
2137     Constant *C2 = getOperand(1);
2138     if (C1 == From) C1 = To;
2139     if (C2 == From) C2 = To;
2140     if (getOpcode() == Instruction::ICmp)
2141       Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
2142     else {
2143       assert(getOpcode() == Instruction::FCmp);
2144       Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
2145     }
2146   } else if (getNumOperands() == 2) {
2147     Constant *C1 = getOperand(0);
2148     Constant *C2 = getOperand(1);
2149     if (C1 == From) C1 = To;
2150     if (C2 == From) C2 = To;
2151     Replacement = ConstantExpr::get(getOpcode(), C1, C2, SubclassOptionalData);
2152   } else {
2153     llvm_unreachable("Unknown ConstantExpr type!");
2154     return;
2155   }
2156   
2157   assert(Replacement != this && "I didn't contain From!");
2158   
2159   // Everyone using this now uses the replacement.
2160   replaceAllUsesWith(Replacement);
2161   
2162   // Delete the old constant!
2163   destroyConstant();
2164 }