1 //===- ConstantFolding.cpp - LLVM constant folder -------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements folding of constants for LLVM. This implements the
11 // (internal) ConstantFolding.h interface, which is used by the
12 // ConstantExpr::get* methods to automatically fold constants when possible.
14 // The current constant folding implementation is implemented in two pieces: the
15 // template-based folder for simple primitive constants like ConstantInt, and
16 // the special case hackery that we use to symbolically evaluate expressions
17 // that use ConstantExprs.
19 //===----------------------------------------------------------------------===//
21 #include "ConstantFolding.h"
22 #include "llvm/Constants.h"
23 #include "llvm/Instructions.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/Function.h"
26 #include "llvm/Support/GetElementPtrTypeIterator.h"
34 // Binary Operators...
35 virtual Constant *add(const Constant *V1, const Constant *V2) const = 0;
36 virtual Constant *sub(const Constant *V1, const Constant *V2) const = 0;
37 virtual Constant *mul(const Constant *V1, const Constant *V2) const = 0;
38 virtual Constant *div(const Constant *V1, const Constant *V2) const = 0;
39 virtual Constant *rem(const Constant *V1, const Constant *V2) const = 0;
40 virtual Constant *op_and(const Constant *V1, const Constant *V2) const = 0;
41 virtual Constant *op_or (const Constant *V1, const Constant *V2) const = 0;
42 virtual Constant *op_xor(const Constant *V1, const Constant *V2) const = 0;
43 virtual Constant *shl(const Constant *V1, const Constant *V2) const = 0;
44 virtual Constant *shr(const Constant *V1, const Constant *V2) const = 0;
45 virtual Constant *lessthan(const Constant *V1, const Constant *V2) const =0;
46 virtual Constant *equalto(const Constant *V1, const Constant *V2) const = 0;
49 virtual Constant *castToBool (const Constant *V) const = 0;
50 virtual Constant *castToSByte (const Constant *V) const = 0;
51 virtual Constant *castToUByte (const Constant *V) const = 0;
52 virtual Constant *castToShort (const Constant *V) const = 0;
53 virtual Constant *castToUShort(const Constant *V) const = 0;
54 virtual Constant *castToInt (const Constant *V) const = 0;
55 virtual Constant *castToUInt (const Constant *V) const = 0;
56 virtual Constant *castToLong (const Constant *V) const = 0;
57 virtual Constant *castToULong (const Constant *V) const = 0;
58 virtual Constant *castToFloat (const Constant *V) const = 0;
59 virtual Constant *castToDouble(const Constant *V) const = 0;
60 virtual Constant *castToPointer(const Constant *V,
61 const PointerType *Ty) const = 0;
63 // ConstRules::get - Return an instance of ConstRules for the specified
66 static ConstRules &get(const Constant *V1, const Constant *V2);
68 ConstRules(const ConstRules &); // Do not implement
69 ConstRules &operator=(const ConstRules &); // Do not implement
74 //===----------------------------------------------------------------------===//
75 // TemplateRules Class
76 //===----------------------------------------------------------------------===//
78 // TemplateRules - Implement a subclass of ConstRules that provides all
79 // operations as noops. All other rules classes inherit from this class so
80 // that if functionality is needed in the future, it can simply be added here
81 // and to ConstRules without changing anything else...
83 // This class also provides subclasses with typesafe implementations of methods
84 // so that don't have to do type casting.
86 template<class ArgType, class SubClassName>
87 class TemplateRules : public ConstRules {
89 //===--------------------------------------------------------------------===//
90 // Redirecting functions that cast to the appropriate types
91 //===--------------------------------------------------------------------===//
93 virtual Constant *add(const Constant *V1, const Constant *V2) const {
94 return SubClassName::Add((const ArgType *)V1, (const ArgType *)V2);
96 virtual Constant *sub(const Constant *V1, const Constant *V2) const {
97 return SubClassName::Sub((const ArgType *)V1, (const ArgType *)V2);
99 virtual Constant *mul(const Constant *V1, const Constant *V2) const {
100 return SubClassName::Mul((const ArgType *)V1, (const ArgType *)V2);
102 virtual Constant *div(const Constant *V1, const Constant *V2) const {
103 return SubClassName::Div((const ArgType *)V1, (const ArgType *)V2);
105 virtual Constant *rem(const Constant *V1, const Constant *V2) const {
106 return SubClassName::Rem((const ArgType *)V1, (const ArgType *)V2);
108 virtual Constant *op_and(const Constant *V1, const Constant *V2) const {
109 return SubClassName::And((const ArgType *)V1, (const ArgType *)V2);
111 virtual Constant *op_or(const Constant *V1, const Constant *V2) const {
112 return SubClassName::Or((const ArgType *)V1, (const ArgType *)V2);
114 virtual Constant *op_xor(const Constant *V1, const Constant *V2) const {
115 return SubClassName::Xor((const ArgType *)V1, (const ArgType *)V2);
117 virtual Constant *shl(const Constant *V1, const Constant *V2) const {
118 return SubClassName::Shl((const ArgType *)V1, (const ArgType *)V2);
120 virtual Constant *shr(const Constant *V1, const Constant *V2) const {
121 return SubClassName::Shr((const ArgType *)V1, (const ArgType *)V2);
124 virtual Constant *lessthan(const Constant *V1, const Constant *V2) const {
125 return SubClassName::LessThan((const ArgType *)V1, (const ArgType *)V2);
127 virtual Constant *equalto(const Constant *V1, const Constant *V2) const {
128 return SubClassName::EqualTo((const ArgType *)V1, (const ArgType *)V2);
131 // Casting operators. ick
132 virtual Constant *castToBool(const Constant *V) const {
133 return SubClassName::CastToBool((const ArgType*)V);
135 virtual Constant *castToSByte(const Constant *V) const {
136 return SubClassName::CastToSByte((const ArgType*)V);
138 virtual Constant *castToUByte(const Constant *V) const {
139 return SubClassName::CastToUByte((const ArgType*)V);
141 virtual Constant *castToShort(const Constant *V) const {
142 return SubClassName::CastToShort((const ArgType*)V);
144 virtual Constant *castToUShort(const Constant *V) const {
145 return SubClassName::CastToUShort((const ArgType*)V);
147 virtual Constant *castToInt(const Constant *V) const {
148 return SubClassName::CastToInt((const ArgType*)V);
150 virtual Constant *castToUInt(const Constant *V) const {
151 return SubClassName::CastToUInt((const ArgType*)V);
153 virtual Constant *castToLong(const Constant *V) const {
154 return SubClassName::CastToLong((const ArgType*)V);
156 virtual Constant *castToULong(const Constant *V) const {
157 return SubClassName::CastToULong((const ArgType*)V);
159 virtual Constant *castToFloat(const Constant *V) const {
160 return SubClassName::CastToFloat((const ArgType*)V);
162 virtual Constant *castToDouble(const Constant *V) const {
163 return SubClassName::CastToDouble((const ArgType*)V);
165 virtual Constant *castToPointer(const Constant *V,
166 const PointerType *Ty) const {
167 return SubClassName::CastToPointer((const ArgType*)V, Ty);
170 //===--------------------------------------------------------------------===//
171 // Default "noop" implementations
172 //===--------------------------------------------------------------------===//
174 static Constant *Add(const ArgType *V1, const ArgType *V2) { return 0; }
175 static Constant *Sub(const ArgType *V1, const ArgType *V2) { return 0; }
176 static Constant *Mul(const ArgType *V1, const ArgType *V2) { return 0; }
177 static Constant *Div(const ArgType *V1, const ArgType *V2) { return 0; }
178 static Constant *Rem(const ArgType *V1, const ArgType *V2) { return 0; }
179 static Constant *And(const ArgType *V1, const ArgType *V2) { return 0; }
180 static Constant *Or (const ArgType *V1, const ArgType *V2) { return 0; }
181 static Constant *Xor(const ArgType *V1, const ArgType *V2) { return 0; }
182 static Constant *Shl(const ArgType *V1, const ArgType *V2) { return 0; }
183 static Constant *Shr(const ArgType *V1, const ArgType *V2) { return 0; }
184 static Constant *LessThan(const ArgType *V1, const ArgType *V2) {
187 static Constant *EqualTo(const ArgType *V1, const ArgType *V2) {
191 // Casting operators. ick
192 static Constant *CastToBool (const Constant *V) { return 0; }
193 static Constant *CastToSByte (const Constant *V) { return 0; }
194 static Constant *CastToUByte (const Constant *V) { return 0; }
195 static Constant *CastToShort (const Constant *V) { return 0; }
196 static Constant *CastToUShort(const Constant *V) { return 0; }
197 static Constant *CastToInt (const Constant *V) { return 0; }
198 static Constant *CastToUInt (const Constant *V) { return 0; }
199 static Constant *CastToLong (const Constant *V) { return 0; }
200 static Constant *CastToULong (const Constant *V) { return 0; }
201 static Constant *CastToFloat (const Constant *V) { return 0; }
202 static Constant *CastToDouble(const Constant *V) { return 0; }
203 static Constant *CastToPointer(const Constant *,
204 const PointerType *) {return 0;}
209 //===----------------------------------------------------------------------===//
211 //===----------------------------------------------------------------------===//
213 // EmptyRules provides a concrete base class of ConstRules that does nothing
215 struct EmptyRules : public TemplateRules<Constant, EmptyRules> {
216 static Constant *EqualTo(const Constant *V1, const Constant *V2) {
217 if (V1 == V2) return ConstantBool::True;
224 //===----------------------------------------------------------------------===//
226 //===----------------------------------------------------------------------===//
228 // BoolRules provides a concrete base class of ConstRules for the 'bool' type.
230 struct BoolRules : public TemplateRules<ConstantBool, BoolRules> {
232 static Constant *LessThan(const ConstantBool *V1, const ConstantBool *V2){
233 return ConstantBool::get(V1->getValue() < V2->getValue());
236 static Constant *EqualTo(const Constant *V1, const Constant *V2) {
237 return ConstantBool::get(V1 == V2);
240 static Constant *And(const ConstantBool *V1, const ConstantBool *V2) {
241 return ConstantBool::get(V1->getValue() & V2->getValue());
244 static Constant *Or(const ConstantBool *V1, const ConstantBool *V2) {
245 return ConstantBool::get(V1->getValue() | V2->getValue());
248 static Constant *Xor(const ConstantBool *V1, const ConstantBool *V2) {
249 return ConstantBool::get(V1->getValue() ^ V2->getValue());
252 // Casting operators. ick
253 #define DEF_CAST(TYPE, CLASS, CTYPE) \
254 static Constant *CastTo##TYPE (const ConstantBool *V) { \
255 return CLASS::get(Type::TYPE##Ty, (CTYPE)(bool)V->getValue()); \
258 DEF_CAST(Bool , ConstantBool, bool)
259 DEF_CAST(SByte , ConstantSInt, signed char)
260 DEF_CAST(UByte , ConstantUInt, unsigned char)
261 DEF_CAST(Short , ConstantSInt, signed short)
262 DEF_CAST(UShort, ConstantUInt, unsigned short)
263 DEF_CAST(Int , ConstantSInt, signed int)
264 DEF_CAST(UInt , ConstantUInt, unsigned int)
265 DEF_CAST(Long , ConstantSInt, int64_t)
266 DEF_CAST(ULong , ConstantUInt, uint64_t)
267 DEF_CAST(Float , ConstantFP , float)
268 DEF_CAST(Double, ConstantFP , double)
273 //===----------------------------------------------------------------------===//
274 // NullPointerRules Class
275 //===----------------------------------------------------------------------===//
277 // NullPointerRules provides a concrete base class of ConstRules for null
280 struct NullPointerRules : public TemplateRules<ConstantPointerNull,
282 static Constant *EqualTo(const Constant *V1, const Constant *V2) {
283 return ConstantBool::True; // Null pointers are always equal
285 static Constant *CastToBool(const Constant *V) {
286 return ConstantBool::False;
288 static Constant *CastToSByte (const Constant *V) {
289 return ConstantSInt::get(Type::SByteTy, 0);
291 static Constant *CastToUByte (const Constant *V) {
292 return ConstantUInt::get(Type::UByteTy, 0);
294 static Constant *CastToShort (const Constant *V) {
295 return ConstantSInt::get(Type::ShortTy, 0);
297 static Constant *CastToUShort(const Constant *V) {
298 return ConstantUInt::get(Type::UShortTy, 0);
300 static Constant *CastToInt (const Constant *V) {
301 return ConstantSInt::get(Type::IntTy, 0);
303 static Constant *CastToUInt (const Constant *V) {
304 return ConstantUInt::get(Type::UIntTy, 0);
306 static Constant *CastToLong (const Constant *V) {
307 return ConstantSInt::get(Type::LongTy, 0);
309 static Constant *CastToULong (const Constant *V) {
310 return ConstantUInt::get(Type::ULongTy, 0);
312 static Constant *CastToFloat (const Constant *V) {
313 return ConstantFP::get(Type::FloatTy, 0);
315 static Constant *CastToDouble(const Constant *V) {
316 return ConstantFP::get(Type::DoubleTy, 0);
319 static Constant *CastToPointer(const ConstantPointerNull *V,
320 const PointerType *PTy) {
321 return ConstantPointerNull::get(PTy);
326 //===----------------------------------------------------------------------===//
328 //===----------------------------------------------------------------------===//
330 // DirectRules provides a concrete base classes of ConstRules for a variety of
331 // different types. This allows the C++ compiler to automatically generate our
332 // constant handling operations in a typesafe and accurate manner.
334 template<class ConstantClass, class BuiltinType, Type **Ty, class SuperClass>
335 struct DirectRules : public TemplateRules<ConstantClass, SuperClass> {
336 static Constant *Add(const ConstantClass *V1, const ConstantClass *V2) {
337 BuiltinType R = (BuiltinType)V1->getValue() + (BuiltinType)V2->getValue();
338 return ConstantClass::get(*Ty, R);
341 static Constant *Sub(const ConstantClass *V1, const ConstantClass *V2) {
342 BuiltinType R = (BuiltinType)V1->getValue() - (BuiltinType)V2->getValue();
343 return ConstantClass::get(*Ty, R);
346 static Constant *Mul(const ConstantClass *V1, const ConstantClass *V2) {
347 BuiltinType R = (BuiltinType)V1->getValue() * (BuiltinType)V2->getValue();
348 return ConstantClass::get(*Ty, R);
351 static Constant *Div(const ConstantClass *V1, const ConstantClass *V2) {
352 if (V2->isNullValue()) return 0;
353 BuiltinType R = (BuiltinType)V1->getValue() / (BuiltinType)V2->getValue();
354 return ConstantClass::get(*Ty, R);
357 static Constant *LessThan(const ConstantClass *V1, const ConstantClass *V2) {
358 bool R = (BuiltinType)V1->getValue() < (BuiltinType)V2->getValue();
359 return ConstantBool::get(R);
362 static Constant *EqualTo(const ConstantClass *V1, const ConstantClass *V2) {
363 bool R = (BuiltinType)V1->getValue() == (BuiltinType)V2->getValue();
364 return ConstantBool::get(R);
367 static Constant *CastToPointer(const ConstantClass *V,
368 const PointerType *PTy) {
369 if (V->isNullValue()) // Is it a FP or Integral null value?
370 return ConstantPointerNull::get(PTy);
371 return 0; // Can't const prop other types of pointers
374 // Casting operators. ick
375 #define DEF_CAST(TYPE, CLASS, CTYPE) \
376 static Constant *CastTo##TYPE (const ConstantClass *V) { \
377 return CLASS::get(Type::TYPE##Ty, (CTYPE)(BuiltinType)V->getValue()); \
380 DEF_CAST(Bool , ConstantBool, bool)
381 DEF_CAST(SByte , ConstantSInt, signed char)
382 DEF_CAST(UByte , ConstantUInt, unsigned char)
383 DEF_CAST(Short , ConstantSInt, signed short)
384 DEF_CAST(UShort, ConstantUInt, unsigned short)
385 DEF_CAST(Int , ConstantSInt, signed int)
386 DEF_CAST(UInt , ConstantUInt, unsigned int)
387 DEF_CAST(Long , ConstantSInt, int64_t)
388 DEF_CAST(ULong , ConstantUInt, uint64_t)
389 DEF_CAST(Float , ConstantFP , float)
390 DEF_CAST(Double, ConstantFP , double)
395 //===----------------------------------------------------------------------===//
396 // DirectIntRules Class
397 //===----------------------------------------------------------------------===//
399 // DirectIntRules provides implementations of functions that are valid on
400 // integer types, but not all types in general.
402 template <class ConstantClass, class BuiltinType, Type **Ty>
403 struct DirectIntRules
404 : public DirectRules<ConstantClass, BuiltinType, Ty,
405 DirectIntRules<ConstantClass, BuiltinType, Ty> > {
407 static Constant *Div(const ConstantClass *V1, const ConstantClass *V2) {
408 if (V2->isNullValue()) return 0;
409 if (V2->isAllOnesValue() && // MIN_INT / -1
410 (BuiltinType)V1->getValue() == -(BuiltinType)V1->getValue())
412 BuiltinType R = (BuiltinType)V1->getValue() / (BuiltinType)V2->getValue();
413 return ConstantClass::get(*Ty, R);
416 static Constant *Rem(const ConstantClass *V1,
417 const ConstantClass *V2) {
418 if (V2->isNullValue()) return 0; // X / 0
419 if (V2->isAllOnesValue() && // MIN_INT / -1
420 (BuiltinType)V1->getValue() == -(BuiltinType)V1->getValue())
422 BuiltinType R = (BuiltinType)V1->getValue() % (BuiltinType)V2->getValue();
423 return ConstantClass::get(*Ty, R);
426 static Constant *And(const ConstantClass *V1, const ConstantClass *V2) {
427 BuiltinType R = (BuiltinType)V1->getValue() & (BuiltinType)V2->getValue();
428 return ConstantClass::get(*Ty, R);
430 static Constant *Or(const ConstantClass *V1, const ConstantClass *V2) {
431 BuiltinType R = (BuiltinType)V1->getValue() | (BuiltinType)V2->getValue();
432 return ConstantClass::get(*Ty, R);
434 static Constant *Xor(const ConstantClass *V1, const ConstantClass *V2) {
435 BuiltinType R = (BuiltinType)V1->getValue() ^ (BuiltinType)V2->getValue();
436 return ConstantClass::get(*Ty, R);
439 static Constant *Shl(const ConstantClass *V1, const ConstantClass *V2) {
440 BuiltinType R = (BuiltinType)V1->getValue() << (BuiltinType)V2->getValue();
441 return ConstantClass::get(*Ty, R);
444 static Constant *Shr(const ConstantClass *V1, const ConstantClass *V2) {
445 BuiltinType R = (BuiltinType)V1->getValue() >> (BuiltinType)V2->getValue();
446 return ConstantClass::get(*Ty, R);
451 //===----------------------------------------------------------------------===//
452 // DirectFPRules Class
453 //===----------------------------------------------------------------------===//
455 /// DirectFPRules provides implementations of functions that are valid on
456 /// floating point types, but not all types in general.
458 template <class ConstantClass, class BuiltinType, Type **Ty>
460 : public DirectRules<ConstantClass, BuiltinType, Ty,
461 DirectFPRules<ConstantClass, BuiltinType, Ty> > {
462 static Constant *Rem(const ConstantClass *V1, const ConstantClass *V2) {
463 if (V2->isNullValue()) return 0;
464 BuiltinType Result = std::fmod((BuiltinType)V1->getValue(),
465 (BuiltinType)V2->getValue());
466 return ConstantClass::get(*Ty, Result);
471 /// ConstRules::get - This method returns the constant rules implementation that
472 /// implements the semantics of the two specified constants.
473 ConstRules &ConstRules::get(const Constant *V1, const Constant *V2) {
474 static EmptyRules EmptyR;
475 static BoolRules BoolR;
476 static NullPointerRules NullPointerR;
477 static DirectIntRules<ConstantSInt, signed char , &Type::SByteTy> SByteR;
478 static DirectIntRules<ConstantUInt, unsigned char , &Type::UByteTy> UByteR;
479 static DirectIntRules<ConstantSInt, signed short, &Type::ShortTy> ShortR;
480 static DirectIntRules<ConstantUInt, unsigned short, &Type::UShortTy> UShortR;
481 static DirectIntRules<ConstantSInt, signed int , &Type::IntTy> IntR;
482 static DirectIntRules<ConstantUInt, unsigned int , &Type::UIntTy> UIntR;
483 static DirectIntRules<ConstantSInt, int64_t , &Type::LongTy> LongR;
484 static DirectIntRules<ConstantUInt, uint64_t , &Type::ULongTy> ULongR;
485 static DirectFPRules <ConstantFP , float , &Type::FloatTy> FloatR;
486 static DirectFPRules <ConstantFP , double , &Type::DoubleTy> DoubleR;
488 if (isa<ConstantExpr>(V1) || isa<ConstantExpr>(V2) ||
489 isa<GlobalValue>(V1) || isa<GlobalValue>(V2))
492 switch (V1->getType()->getTypeID()) {
493 default: assert(0 && "Unknown value type for constant folding!");
494 case Type::BoolTyID: return BoolR;
495 case Type::PointerTyID: return NullPointerR;
496 case Type::SByteTyID: return SByteR;
497 case Type::UByteTyID: return UByteR;
498 case Type::ShortTyID: return ShortR;
499 case Type::UShortTyID: return UShortR;
500 case Type::IntTyID: return IntR;
501 case Type::UIntTyID: return UIntR;
502 case Type::LongTyID: return LongR;
503 case Type::ULongTyID: return ULongR;
504 case Type::FloatTyID: return FloatR;
505 case Type::DoubleTyID: return DoubleR;
510 //===----------------------------------------------------------------------===//
511 // ConstantFold*Instruction Implementations
512 //===----------------------------------------------------------------------===//
514 // These methods contain the special case hackery required to symbolically
515 // evaluate some constant expression cases, and use the ConstantRules class to
516 // evaluate normal constants.
518 static unsigned getSize(const Type *Ty) {
519 unsigned S = Ty->getPrimitiveSize();
520 return S ? S : 8; // Treat pointers at 8 bytes
523 Constant *llvm::ConstantFoldCastInstruction(const Constant *V,
524 const Type *DestTy) {
525 if (V->getType() == DestTy) return (Constant*)V;
527 // Cast of a global address to boolean is always true.
528 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
529 if (DestTy == Type::BoolTy)
530 // FIXME: When we support 'external weak' references, we have to prevent
531 // this transformation from happening. In the meantime we avoid folding
532 // any cast of an external symbol.
533 if (!GV->isExternal())
534 return ConstantBool::True;
536 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
537 if (CE->getOpcode() == Instruction::Cast) {
538 Constant *Op = const_cast<Constant*>(CE->getOperand(0));
539 // Try to not produce a cast of a cast, which is almost always redundant.
540 if (!Op->getType()->isFloatingPoint() &&
541 !CE->getType()->isFloatingPoint() &&
542 !DestTy->isFloatingPoint()) {
543 unsigned S1 = getSize(Op->getType()), S2 = getSize(CE->getType());
544 unsigned S3 = getSize(DestTy);
545 if (Op->getType() == DestTy && S3 >= S2)
547 if (S1 >= S2 && S2 >= S3)
548 return ConstantExpr::getCast(Op, DestTy);
549 if (S1 <= S2 && S2 >= S3 && S1 <= S3)
550 return ConstantExpr::getCast(Op, DestTy);
552 } else if (CE->getOpcode() == Instruction::GetElementPtr) {
553 // If all of the indexes in the GEP are null values, there is no pointer
554 // adjustment going on. We might as well cast the source pointer.
555 bool isAllNull = true;
556 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
557 if (!CE->getOperand(i)->isNullValue()) {
562 return ConstantExpr::getCast(CE->getOperand(0), DestTy);
565 ConstRules &Rules = ConstRules::get(V, V);
567 switch (DestTy->getTypeID()) {
568 case Type::BoolTyID: return Rules.castToBool(V);
569 case Type::UByteTyID: return Rules.castToUByte(V);
570 case Type::SByteTyID: return Rules.castToSByte(V);
571 case Type::UShortTyID: return Rules.castToUShort(V);
572 case Type::ShortTyID: return Rules.castToShort(V);
573 case Type::UIntTyID: return Rules.castToUInt(V);
574 case Type::IntTyID: return Rules.castToInt(V);
575 case Type::ULongTyID: return Rules.castToULong(V);
576 case Type::LongTyID: return Rules.castToLong(V);
577 case Type::FloatTyID: return Rules.castToFloat(V);
578 case Type::DoubleTyID: return Rules.castToDouble(V);
579 case Type::PointerTyID:
580 return Rules.castToPointer(V, cast<PointerType>(DestTy));
585 Constant *llvm::ConstantFoldSelectInstruction(const Constant *Cond,
587 const Constant *V2) {
588 if (Cond == ConstantBool::True)
589 return const_cast<Constant*>(V1);
590 else if (Cond == ConstantBool::False)
591 return const_cast<Constant*>(V2);
596 /// IdxCompare - Compare the two constants as though they were getelementptr
597 /// indices. This allows coersion of the types to be the same thing.
599 /// If the two constants are the "same" (after coersion), return 0. If the
600 /// first is less than the second, return -1, if the second is less than the
601 /// first, return 1. If the constants are not integral, return -2.
603 static int IdxCompare(Constant *C1, Constant *C2) {
604 if (C1 == C2) return 0;
606 // Ok, we found a different index. Are either of the operands
607 // ConstantExprs? If so, we can't do anything with them.
608 if (!isa<ConstantInt>(C1) || !isa<ConstantInt>(C2))
609 return -2; // don't know!
611 // Ok, we have two differing integer indices. Sign extend them to be the same
612 // type. Long is always big enough, so we use it.
613 C1 = ConstantExpr::getSignExtend(C1, Type::LongTy);
614 C2 = ConstantExpr::getSignExtend(C2, Type::LongTy);
615 if (C1 == C2) return 0; // Are they just differing types?
617 // If they are really different, now that they are the same type, then we
618 // found a difference!
619 if (cast<ConstantSInt>(C1)->getValue() < cast<ConstantSInt>(C2)->getValue())
625 /// evaluateRelation - This function determines if there is anything we can
626 /// decide about the two constants provided. This doesn't need to handle simple
627 /// things like integer comparisons, but should instead handle ConstantExprs
628 /// and GlobalValuess. If we can determine that the two constants have a
629 /// particular relation to each other, we should return the corresponding SetCC
630 /// code, otherwise return Instruction::BinaryOpsEnd.
632 /// To simplify this code we canonicalize the relation so that the first
633 /// operand is always the most "complex" of the two. We consider simple
634 /// constants (like ConstantInt) to be the simplest, followed by
635 /// GlobalValues, followed by ConstantExpr's (the most complex).
637 static Instruction::BinaryOps evaluateRelation(const Constant *V1,
638 const Constant *V2) {
639 assert(V1->getType() == V2->getType() &&
640 "Cannot compare different types of values!");
641 if (V1 == V2) return Instruction::SetEQ;
643 if (!isa<ConstantExpr>(V1) && !isa<GlobalValue>(V1)) {
644 // If the first operand is simple, swap operands.
645 assert((isa<GlobalValue>(V2) || isa<ConstantExpr>(V2)) &&
646 "Simple cases should have been handled by caller!");
647 Instruction::BinaryOps SwappedRelation = evaluateRelation(V2, V1);
648 if (SwappedRelation != Instruction::BinaryOpsEnd)
649 return SetCondInst::getSwappedCondition(SwappedRelation);
651 } else if (const GlobalValue *CPR1 = dyn_cast<GlobalValue>(V1)){
652 if (isa<ConstantExpr>(V2)) { // Swap as necessary.
653 Instruction::BinaryOps SwappedRelation = evaluateRelation(V2, V1);
654 if (SwappedRelation != Instruction::BinaryOpsEnd)
655 return SetCondInst::getSwappedCondition(SwappedRelation);
657 return Instruction::BinaryOpsEnd;
660 // Now we know that the RHS is a GlobalValue or simple constant,
661 // which (since the types must match) means that it's a ConstantPointerNull.
662 if (const GlobalValue *CPR2 = dyn_cast<GlobalValue>(V2)) {
663 assert(CPR1 != CPR2 &&
664 "GVs for the same value exist at different addresses??");
665 // FIXME: If both globals are external weak, they might both be null!
666 return Instruction::SetNE;
668 assert(isa<ConstantPointerNull>(V2) && "Canonicalization guarantee!");
669 // Global can never be null. FIXME: if we implement external weak
670 // linkage, this is not necessarily true!
671 return Instruction::SetNE;
675 // Ok, the LHS is known to be a constantexpr. The RHS can be any of a
676 // constantexpr, a CPR, or a simple constant.
677 const ConstantExpr *CE1 = cast<ConstantExpr>(V1);
678 Constant *CE1Op0 = CE1->getOperand(0);
680 switch (CE1->getOpcode()) {
681 case Instruction::Cast:
682 // If the cast is not actually changing bits, and the second operand is a
683 // null pointer, do the comparison with the pre-casted value.
684 if (V2->isNullValue() &&
685 CE1->getType()->isLosslesslyConvertibleTo(CE1Op0->getType()))
686 return evaluateRelation(CE1Op0,
687 Constant::getNullValue(CE1Op0->getType()));
690 case Instruction::GetElementPtr:
691 // Ok, since this is a getelementptr, we know that the constant has a
692 // pointer type. Check the various cases.
693 if (isa<ConstantPointerNull>(V2)) {
694 // If we are comparing a GEP to a null pointer, check to see if the base
695 // of the GEP equals the null pointer.
696 if (isa<GlobalValue>(CE1Op0)) {
697 // FIXME: this is not true when we have external weak references!
698 // No offset can go from a global to a null pointer.
699 return Instruction::SetGT;
700 } else if (isa<ConstantPointerNull>(CE1Op0)) {
701 // If we are indexing from a null pointer, check to see if we have any
703 for (unsigned i = 1, e = CE1->getNumOperands(); i != e; ++i)
704 if (!CE1->getOperand(i)->isNullValue())
705 // Offsetting from null, must not be equal.
706 return Instruction::SetGT;
707 // Only zero indexes from null, must still be zero.
708 return Instruction::SetEQ;
710 // Otherwise, we can't really say if the first operand is null or not.
711 } else if (const GlobalValue *CPR2 = dyn_cast<GlobalValue>(V2)) {
712 if (isa<ConstantPointerNull>(CE1Op0)) {
713 // FIXME: This is not true with external weak references.
714 return Instruction::SetLT;
715 } else if (const GlobalValue *CPR1 = dyn_cast<GlobalValue>(CE1Op0)) {
717 // If this is a getelementptr of the same global, then it must be
718 // different. Because the types must match, the getelementptr could
719 // only have at most one index, and because we fold getelementptr's
720 // with a single zero index, it must be nonzero.
721 assert(CE1->getNumOperands() == 2 &&
722 !CE1->getOperand(1)->isNullValue() &&
723 "Suprising getelementptr!");
724 return Instruction::SetGT;
726 // If they are different globals, we don't know what the value is,
727 // but they can't be equal.
728 return Instruction::SetNE;
732 const ConstantExpr *CE2 = cast<ConstantExpr>(V2);
733 const Constant *CE2Op0 = CE2->getOperand(0);
735 // There are MANY other foldings that we could perform here. They will
736 // probably be added on demand, as they seem needed.
737 switch (CE2->getOpcode()) {
739 case Instruction::GetElementPtr:
740 // By far the most common case to handle is when the base pointers are
741 // obviously to the same or different globals.
742 if (isa<GlobalValue>(CE1Op0) && isa<GlobalValue>(CE2Op0)) {
743 if (CE1Op0 != CE2Op0) // Don't know relative ordering, but not equal
744 return Instruction::SetNE;
745 // Ok, we know that both getelementptr instructions are based on the
746 // same global. From this, we can precisely determine the relative
747 // ordering of the resultant pointers.
750 // Compare all of the operands the GEP's have in common.
751 for (;i != CE1->getNumOperands() && i != CE2->getNumOperands(); ++i)
752 switch (IdxCompare(CE1->getOperand(i), CE2->getOperand(i))) {
753 case -1: return Instruction::SetLT;
754 case 1: return Instruction::SetGT;
755 case -2: return Instruction::BinaryOpsEnd;
758 // Ok, we ran out of things they have in common. If any leftovers
759 // are non-zero then we have a difference, otherwise we are equal.
760 for (; i < CE1->getNumOperands(); ++i)
761 if (!CE1->getOperand(i)->isNullValue())
762 return Instruction::SetGT;
763 for (; i < CE2->getNumOperands(); ++i)
764 if (!CE2->getOperand(i)->isNullValue())
765 return Instruction::SetLT;
766 return Instruction::SetEQ;
776 return Instruction::BinaryOpsEnd;
779 Constant *llvm::ConstantFoldBinaryInstruction(unsigned Opcode,
781 const Constant *V2) {
785 case Instruction::Add: C = ConstRules::get(V1, V2).add(V1, V2); break;
786 case Instruction::Sub: C = ConstRules::get(V1, V2).sub(V1, V2); break;
787 case Instruction::Mul: C = ConstRules::get(V1, V2).mul(V1, V2); break;
788 case Instruction::Div: C = ConstRules::get(V1, V2).div(V1, V2); break;
789 case Instruction::Rem: C = ConstRules::get(V1, V2).rem(V1, V2); break;
790 case Instruction::And: C = ConstRules::get(V1, V2).op_and(V1, V2); break;
791 case Instruction::Or: C = ConstRules::get(V1, V2).op_or (V1, V2); break;
792 case Instruction::Xor: C = ConstRules::get(V1, V2).op_xor(V1, V2); break;
793 case Instruction::Shl: C = ConstRules::get(V1, V2).shl(V1, V2); break;
794 case Instruction::Shr: C = ConstRules::get(V1, V2).shr(V1, V2); break;
795 case Instruction::SetEQ: C = ConstRules::get(V1, V2).equalto(V1, V2); break;
796 case Instruction::SetLT: C = ConstRules::get(V1, V2).lessthan(V1, V2);break;
797 case Instruction::SetGT: C = ConstRules::get(V1, V2).lessthan(V2, V1);break;
798 case Instruction::SetNE: // V1 != V2 === !(V1 == V2)
799 C = ConstRules::get(V1, V2).equalto(V1, V2);
800 if (C) return ConstantExpr::get(Instruction::Xor, C, ConstantBool::True);
802 case Instruction::SetLE: // V1 <= V2 === !(V2 < V1)
803 C = ConstRules::get(V1, V2).lessthan(V2, V1);
804 if (C) return ConstantExpr::get(Instruction::Xor, C, ConstantBool::True);
806 case Instruction::SetGE: // V1 >= V2 === !(V1 < V2)
807 C = ConstRules::get(V1, V2).lessthan(V1, V2);
808 if (C) return ConstantExpr::get(Instruction::Xor, C, ConstantBool::True);
812 // If we successfully folded the expression, return it now.
815 if (SetCondInst::isRelational(Opcode))
816 switch (evaluateRelation(V1, V2)) {
817 default: assert(0 && "Unknown relational!");
818 case Instruction::BinaryOpsEnd:
819 break; // Couldn't determine anything about these constants.
820 case Instruction::SetEQ: // We know the constants are equal!
821 // If we know the constants are equal, we can decide the result of this
822 // computation precisely.
823 return ConstantBool::get(Opcode == Instruction::SetEQ ||
824 Opcode == Instruction::SetLE ||
825 Opcode == Instruction::SetGE);
826 case Instruction::SetLT:
827 // If we know that V1 < V2, we can decide the result of this computation
829 return ConstantBool::get(Opcode == Instruction::SetLT ||
830 Opcode == Instruction::SetNE ||
831 Opcode == Instruction::SetLE);
832 case Instruction::SetGT:
833 // If we know that V1 > V2, we can decide the result of this computation
835 return ConstantBool::get(Opcode == Instruction::SetGT ||
836 Opcode == Instruction::SetNE ||
837 Opcode == Instruction::SetGE);
838 case Instruction::SetLE:
839 // If we know that V1 <= V2, we can only partially decide this relation.
840 if (Opcode == Instruction::SetGT) return ConstantBool::False;
841 if (Opcode == Instruction::SetLT) return ConstantBool::True;
844 case Instruction::SetGE:
845 // If we know that V1 >= V2, we can only partially decide this relation.
846 if (Opcode == Instruction::SetLT) return ConstantBool::False;
847 if (Opcode == Instruction::SetGT) return ConstantBool::True;
850 case Instruction::SetNE:
851 // If we know that V1 != V2, we can only partially decide this relation.
852 if (Opcode == Instruction::SetEQ) return ConstantBool::False;
853 if (Opcode == Instruction::SetNE) return ConstantBool::True;
857 if (const ConstantExpr *CE1 = dyn_cast<ConstantExpr>(V1)) {
858 if (const ConstantExpr *CE2 = dyn_cast<ConstantExpr>(V2)) {
859 // There are many possible foldings we could do here. We should probably
860 // at least fold add of a pointer with an integer into the appropriate
861 // getelementptr. This will improve alias analysis a bit.
867 // Just implement a couple of simple identities.
869 case Instruction::Add:
870 if (V2->isNullValue()) return const_cast<Constant*>(V1); // X + 0 == X
872 case Instruction::Sub:
873 if (V2->isNullValue()) return const_cast<Constant*>(V1); // X - 0 == X
875 case Instruction::Mul:
876 if (V2->isNullValue()) return const_cast<Constant*>(V2); // X * 0 == 0
877 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V2))
878 if (CI->getRawValue() == 1)
879 return const_cast<Constant*>(V1); // X * 1 == X
881 case Instruction::Div:
882 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V2))
883 if (CI->getRawValue() == 1)
884 return const_cast<Constant*>(V1); // X / 1 == X
886 case Instruction::Rem:
887 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V2))
888 if (CI->getRawValue() == 1)
889 return Constant::getNullValue(CI->getType()); // X % 1 == 0
891 case Instruction::And:
892 if (cast<ConstantIntegral>(V2)->isAllOnesValue())
893 return const_cast<Constant*>(V1); // X & -1 == X
894 if (V2->isNullValue()) return const_cast<Constant*>(V2); // X & 0 == 0
895 if (CE1->getOpcode() == Instruction::Cast &&
896 isa<GlobalValue>(CE1->getOperand(0))) {
897 GlobalValue *CPR =cast<GlobalValue>(CE1->getOperand(0));
899 // Functions are at least 4-byte aligned. If and'ing the address of a
900 // function with a constant < 4, fold it to zero.
901 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V2))
902 if (CI->getRawValue() < 4 && isa<Function>(CPR))
903 return Constant::getNullValue(CI->getType());
906 case Instruction::Or:
907 if (V2->isNullValue()) return const_cast<Constant*>(V1); // X | 0 == X
908 if (cast<ConstantIntegral>(V2)->isAllOnesValue())
909 return const_cast<Constant*>(V2); // X | -1 == -1
911 case Instruction::Xor:
912 if (V2->isNullValue()) return const_cast<Constant*>(V1); // X ^ 0 == X
917 } else if (const ConstantExpr *CE2 = dyn_cast<ConstantExpr>(V2)) {
918 // If V2 is a constant expr and V1 isn't, flop them around and fold the
919 // other way if possible.
921 case Instruction::Add:
922 case Instruction::Mul:
923 case Instruction::And:
924 case Instruction::Or:
925 case Instruction::Xor:
926 case Instruction::SetEQ:
927 case Instruction::SetNE:
928 // No change of opcode required.
929 return ConstantFoldBinaryInstruction(Opcode, V2, V1);
931 case Instruction::SetLT:
932 case Instruction::SetGT:
933 case Instruction::SetLE:
934 case Instruction::SetGE:
935 // Change the opcode as necessary to swap the operands.
936 Opcode = SetCondInst::getSwappedCondition((Instruction::BinaryOps)Opcode);
937 return ConstantFoldBinaryInstruction(Opcode, V2, V1);
939 case Instruction::Shl:
940 case Instruction::Shr:
941 case Instruction::Sub:
942 case Instruction::Div:
943 case Instruction::Rem:
944 default: // These instructions cannot be flopped around.
951 Constant *llvm::ConstantFoldGetElementPtr(const Constant *C,
952 const std::vector<Constant*> &IdxList) {
953 if (IdxList.size() == 0 ||
954 (IdxList.size() == 1 && IdxList[0]->isNullValue()))
955 return const_cast<Constant*>(C);
957 if (C->isNullValue()) {
959 for (unsigned i = 0, e = IdxList.size(); i != e; ++i)
960 if (!IdxList[i]->isNullValue()) {
965 std::vector<Value*> VIdxList(IdxList.begin(), IdxList.end());
966 const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), VIdxList,
968 assert(Ty != 0 && "Invalid indices for GEP!");
969 return ConstantPointerNull::get(PointerType::get(Ty));
972 if (IdxList.size() == 1) {
973 const Type *ElTy = cast<PointerType>(C->getType())->getElementType();
974 if (unsigned ElSize = ElTy->getPrimitiveSize()) {
975 // gep null, C is equal to C*sizeof(nullty). If nullty is a known llvm
976 // type, we can statically fold this.
977 Constant *R = ConstantUInt::get(Type::UIntTy, ElSize);
978 R = ConstantExpr::getCast(R, IdxList[0]->getType());
979 R = ConstantExpr::getMul(R, IdxList[0]);
980 return ConstantExpr::getCast(R, C->getType());
985 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(const_cast<Constant*>(C))) {
986 // Combine Indices - If the source pointer to this getelementptr instruction
987 // is a getelementptr instruction, combine the indices of the two
988 // getelementptr instructions into a single instruction.
990 if (CE->getOpcode() == Instruction::GetElementPtr) {
991 const Type *LastTy = 0;
992 for (gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
996 if ((LastTy && isa<ArrayType>(LastTy)) || IdxList[0]->isNullValue()) {
997 std::vector<Constant*> NewIndices;
998 NewIndices.reserve(IdxList.size() + CE->getNumOperands());
999 for (unsigned i = 1, e = CE->getNumOperands()-1; i != e; ++i)
1000 NewIndices.push_back(cast<Constant>(CE->getOperand(i)));
1002 // Add the last index of the source with the first index of the new GEP.
1003 // Make sure to handle the case when they are actually different types.
1004 Constant *Combined = CE->getOperand(CE->getNumOperands()-1);
1005 if (!IdxList[0]->isNullValue()) { // Otherwise it must be an array
1006 const Type *IdxTy = Combined->getType();
1007 if (IdxTy != IdxList[0]->getType()) IdxTy = Type::LongTy;
1009 ConstantExpr::get(Instruction::Add,
1010 ConstantExpr::getCast(IdxList[0], IdxTy),
1011 ConstantExpr::getCast(Combined, IdxTy));
1014 NewIndices.push_back(Combined);
1015 NewIndices.insert(NewIndices.end(), IdxList.begin()+1, IdxList.end());
1016 return ConstantExpr::getGetElementPtr(CE->getOperand(0), NewIndices);
1020 // Implement folding of:
1021 // int* getelementptr ([2 x int]* cast ([3 x int]* %X to [2 x int]*),
1023 // To: int* getelementptr ([3 x int]* %X, long 0, long 0)
1025 if (CE->getOpcode() == Instruction::Cast && IdxList.size() > 1 &&
1026 IdxList[0]->isNullValue())
1027 if (const PointerType *SPT =
1028 dyn_cast<PointerType>(CE->getOperand(0)->getType()))
1029 if (const ArrayType *SAT = dyn_cast<ArrayType>(SPT->getElementType()))
1030 if (const ArrayType *CAT =
1031 dyn_cast<ArrayType>(cast<PointerType>(C->getType())->getElementType()))
1032 if (CAT->getElementType() == SAT->getElementType())
1033 return ConstantExpr::getGetElementPtr(
1034 (Constant*)CE->getOperand(0), IdxList);