blob: 0cb38f70c51dda747e994f26972d1e4e145a15c5 [file] [log] [blame]
Chris Lattner2b383d2e2003-05-13 21:37:02 +00001//===-- Constants.cpp - Implement Constant nodes --------------------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner2f7c9632001-06-06 20:29:01 +00009//
Chris Lattnere17322b2011-02-07 20:03:14 +000010// This file implements the Constant* classes.
Chris Lattner2f7c9632001-06-06 20:29:01 +000011//
12//===----------------------------------------------------------------------===//
13
Chris Lattnerca142372002-04-28 19:55:58 +000014#include "llvm/Constants.h"
Chris Lattner78683a72009-08-23 04:02:03 +000015#include "LLVMContextImpl.h"
Chris Lattner33e93b82007-02-27 03:05:06 +000016#include "ConstantFold.h"
Chris Lattner2f7c9632001-06-06 20:29:01 +000017#include "llvm/DerivedTypes.h"
Reid Spencer1ebe1ab2004-07-17 23:48:33 +000018#include "llvm/GlobalValue.h"
Misha Brukman63b38bd2004-07-29 17:30:56 +000019#include "llvm/Instructions.h"
Chris Lattnerd7a73302001-10-13 06:57:33 +000020#include "llvm/Module.h"
Dan Gohman7d82e132009-07-18 01:49:22 +000021#include "llvm/Operator.h"
Nick Lewycky49f89192009-04-04 07:22:01 +000022#include "llvm/ADT/FoldingSet.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000023#include "llvm/ADT/StringExtras.h"
Nick Lewycky49f89192009-04-04 07:22:01 +000024#include "llvm/ADT/StringMap.h"
Chris Lattner3d27be12006-08-27 12:54:02 +000025#include "llvm/Support/Compiler.h"
Bill Wendling6a462f12006-11-17 08:03:48 +000026#include "llvm/Support/Debug.h"
Torok Edwinccb29cd2009-07-11 13:10:19 +000027#include "llvm/Support/ErrorHandling.h"
Chris Lattner69edc982006-09-28 00:35:06 +000028#include "llvm/Support/ManagedStatic.h"
Bill Wendling6a462f12006-11-17 08:03:48 +000029#include "llvm/Support/MathExtras.h"
Chris Lattner78683a72009-08-23 04:02:03 +000030#include "llvm/Support/raw_ostream.h"
Dan Gohman7190d482009-09-10 23:37:55 +000031#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattnera80bf0b2007-02-20 06:39:57 +000032#include "llvm/ADT/DenseMap.h"
Chris Lattnerb5d70302007-02-19 20:01:23 +000033#include "llvm/ADT/SmallVector.h"
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000034#include "llvm/ADT/STLExtras.h"
Chris Lattner2f7c9632001-06-06 20:29:01 +000035#include <algorithm>
Talin3a0a30d2011-02-28 23:53:27 +000036#include <cstdarg>
Chris Lattner189d19f2003-11-21 20:23:48 +000037using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000038
Chris Lattner2f7c9632001-06-06 20:29:01 +000039//===----------------------------------------------------------------------===//
Chris Lattner3462ae32001-12-03 22:26:30 +000040// Constant Class
Chris Lattner2f7c9632001-06-06 20:29:01 +000041//===----------------------------------------------------------------------===//
42
David Blaikiea379b1812011-12-20 02:50:00 +000043void Constant::anchor() { }
44
Chris Lattnerac5fb562011-07-15 05:58:04 +000045bool Constant::isNegativeZeroValue() const {
46 // Floating point values have an explicit -0.0 value.
47 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
48 return CFP->isZero() && CFP->isNegative();
49
50 // Otherwise, just use +0.0.
51 return isNullValue();
52}
53
Chris Lattnerbe6610c2011-07-15 06:14:08 +000054bool Constant::isNullValue() const {
55 // 0 is null.
56 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
57 return CI->isZero();
58
59 // +0.0 is null.
60 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
61 return CFP->isZero() && !CFP->isNegative();
62
63 // constant zero is zero for aggregates and cpnull is null for pointers.
64 return isa<ConstantAggregateZero>(this) || isa<ConstantPointerNull>(this);
65}
66
Nadav Rotem365af6f2011-08-24 20:18:38 +000067bool Constant::isAllOnesValue() const {
68 // Check for -1 integers
69 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
70 return CI->isMinusOne();
71
72 // Check for FP which are bitcasted from -1 integers
73 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
74 return CFP->getValueAPF().bitcastToAPInt().isAllOnesValue();
75
Benjamin Kramer42d098e2011-11-14 19:12:20 +000076 // Check for constant vectors which are splats of -1 values.
Nadav Rotem365af6f2011-08-24 20:18:38 +000077 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
Benjamin Kramer42d098e2011-11-14 19:12:20 +000078 if (Constant *Splat = CV->getSplatValue())
79 return Splat->isAllOnesValue();
Nadav Rotem365af6f2011-08-24 20:18:38 +000080
81 return false;
82}
Benjamin Kramer42d098e2011-11-14 19:12:20 +000083
Owen Anderson5a1acd92009-07-31 20:28:14 +000084// Constructor to create a '0' constant of arbitrary type...
Chris Lattner229907c2011-07-18 04:54:35 +000085Constant *Constant::getNullValue(Type *Ty) {
Owen Anderson5a1acd92009-07-31 20:28:14 +000086 switch (Ty->getTypeID()) {
87 case Type::IntegerTyID:
88 return ConstantInt::get(Ty, 0);
Dan Gohman518cda42011-12-17 00:04:22 +000089 case Type::HalfTyID:
90 return ConstantFP::get(Ty->getContext(),
91 APFloat::getZero(APFloat::IEEEhalf));
Owen Anderson5a1acd92009-07-31 20:28:14 +000092 case Type::FloatTyID:
Benjamin Kramer8ceebfa2010-12-04 14:22:24 +000093 return ConstantFP::get(Ty->getContext(),
94 APFloat::getZero(APFloat::IEEEsingle));
Owen Anderson5a1acd92009-07-31 20:28:14 +000095 case Type::DoubleTyID:
Benjamin Kramer8ceebfa2010-12-04 14:22:24 +000096 return ConstantFP::get(Ty->getContext(),
97 APFloat::getZero(APFloat::IEEEdouble));
Owen Anderson5a1acd92009-07-31 20:28:14 +000098 case Type::X86_FP80TyID:
Benjamin Kramer8ceebfa2010-12-04 14:22:24 +000099 return ConstantFP::get(Ty->getContext(),
100 APFloat::getZero(APFloat::x87DoubleExtended));
Owen Anderson5a1acd92009-07-31 20:28:14 +0000101 case Type::FP128TyID:
102 return ConstantFP::get(Ty->getContext(),
Benjamin Kramer8ceebfa2010-12-04 14:22:24 +0000103 APFloat::getZero(APFloat::IEEEquad));
Owen Anderson5a1acd92009-07-31 20:28:14 +0000104 case Type::PPC_FP128TyID:
Benjamin Kramer8ceebfa2010-12-04 14:22:24 +0000105 return ConstantFP::get(Ty->getContext(),
Benjamin Kramer6f88fcb2010-12-04 14:43:08 +0000106 APFloat(APInt::getNullValue(128)));
Owen Anderson5a1acd92009-07-31 20:28:14 +0000107 case Type::PointerTyID:
108 return ConstantPointerNull::get(cast<PointerType>(Ty));
109 case Type::StructTyID:
110 case Type::ArrayTyID:
111 case Type::VectorTyID:
112 return ConstantAggregateZero::get(Ty);
113 default:
114 // Function, Label, or Opaque type?
Richard Trieua318b8d2011-09-21 03:09:09 +0000115 assert(0 && "Cannot create a null constant of that type!");
Owen Anderson5a1acd92009-07-31 20:28:14 +0000116 return 0;
117 }
118}
119
Chris Lattner229907c2011-07-18 04:54:35 +0000120Constant *Constant::getIntegerValue(Type *Ty, const APInt &V) {
121 Type *ScalarTy = Ty->getScalarType();
Dan Gohmanf011f5a2009-08-03 22:07:33 +0000122
123 // Create the base integer constant.
124 Constant *C = ConstantInt::get(Ty->getContext(), V);
125
126 // Convert an integer to a pointer, if necessary.
Chris Lattner229907c2011-07-18 04:54:35 +0000127 if (PointerType *PTy = dyn_cast<PointerType>(ScalarTy))
Dan Gohmanf011f5a2009-08-03 22:07:33 +0000128 C = ConstantExpr::getIntToPtr(C, PTy);
129
130 // Broadcast a scalar to a vector, if necessary.
Chris Lattner229907c2011-07-18 04:54:35 +0000131 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
Chris Lattner9fe7dd82012-01-25 01:53:58 +0000132 C = ConstantVector::getSplat(VTy->getNumElements(), C);
Dan Gohmanf011f5a2009-08-03 22:07:33 +0000133
134 return C;
135}
136
Chris Lattner229907c2011-07-18 04:54:35 +0000137Constant *Constant::getAllOnesValue(Type *Ty) {
138 if (IntegerType *ITy = dyn_cast<IntegerType>(Ty))
Owen Anderson5a1acd92009-07-31 20:28:14 +0000139 return ConstantInt::get(Ty->getContext(),
140 APInt::getAllOnesValue(ITy->getBitWidth()));
Nadav Rotem7cc6d122011-02-17 21:22:27 +0000141
142 if (Ty->isFloatingPointTy()) {
143 APFloat FL = APFloat::getAllOnesValue(Ty->getPrimitiveSizeInBits(),
144 !Ty->isPPC_FP128Ty());
145 return ConstantFP::get(Ty->getContext(), FL);
146 }
147
Chris Lattner229907c2011-07-18 04:54:35 +0000148 VectorType *VTy = cast<VectorType>(Ty);
Chris Lattner9fe7dd82012-01-25 01:53:58 +0000149 return ConstantVector::getSplat(VTy->getNumElements(),
150 getAllOnesValue(VTy->getElementType()));
Owen Anderson5a1acd92009-07-31 20:28:14 +0000151}
152
Chris Lattner3462ae32001-12-03 22:26:30 +0000153void Constant::destroyConstantImpl() {
154 // When a Constant is destroyed, there may be lingering
Chris Lattnerd7a73302001-10-13 06:57:33 +0000155 // references to the constant by other constants in the constant pool. These
Misha Brukmanbe372b92003-08-21 22:14:26 +0000156 // constants are implicitly dependent on the module that is being deleted,
Chris Lattnerd7a73302001-10-13 06:57:33 +0000157 // but they don't know that. Because we only find out when the CPV is
158 // deleted, we must now notify all of our users (that should only be
Chris Lattner3462ae32001-12-03 22:26:30 +0000159 // Constants) that they are, in fact, invalid now and should be deleted.
Chris Lattnerd7a73302001-10-13 06:57:33 +0000160 //
161 while (!use_empty()) {
162 Value *V = use_back();
163#ifndef NDEBUG // Only in -g mode...
Chris Lattner78683a72009-08-23 04:02:03 +0000164 if (!isa<Constant>(V)) {
David Greene1e27a132010-01-05 01:29:19 +0000165 dbgs() << "While deleting: " << *this
Chris Lattner78683a72009-08-23 04:02:03 +0000166 << "\n\nUse still stuck around after Def is destroyed: "
167 << *V << "\n\n";
168 }
Chris Lattnerd7a73302001-10-13 06:57:33 +0000169#endif
Vikram S. Adve4e537b22002-07-14 23:13:17 +0000170 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
Reid Spencer1ebe1ab2004-07-17 23:48:33 +0000171 Constant *CV = cast<Constant>(V);
172 CV->destroyConstant();
Chris Lattnerd7a73302001-10-13 06:57:33 +0000173
174 // The constant should remove itself from our use list...
Vikram S. Adve4e537b22002-07-14 23:13:17 +0000175 assert((use_empty() || use_back() != V) && "Constant not removed!");
Chris Lattnerd7a73302001-10-13 06:57:33 +0000176 }
177
178 // Value has no outstanding references it is safe to delete it now...
179 delete this;
Chris Lattner38569342001-10-01 20:11:19 +0000180}
Chris Lattner2f7c9632001-06-06 20:29:01 +0000181
Chris Lattner23dd1f62006-10-20 00:27:06 +0000182/// canTrap - Return true if evaluation of this constant could trap. This is
183/// true for things like constant expressions that could divide by zero.
184bool Constant::canTrap() const {
185 assert(getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
186 // The only thing that could possibly trap are constant exprs.
187 const ConstantExpr *CE = dyn_cast<ConstantExpr>(this);
188 if (!CE) return false;
189
190 // ConstantExpr traps if any operands can trap.
191 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
Chris Lattnera91a5632009-10-28 05:14:34 +0000192 if (CE->getOperand(i)->canTrap())
Chris Lattner23dd1f62006-10-20 00:27:06 +0000193 return true;
194
195 // Otherwise, only specific operations can trap.
196 switch (CE->getOpcode()) {
197 default:
198 return false;
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000199 case Instruction::UDiv:
200 case Instruction::SDiv:
201 case Instruction::FDiv:
Reid Spencer7eb55b32006-11-02 01:53:59 +0000202 case Instruction::URem:
203 case Instruction::SRem:
204 case Instruction::FRem:
Chris Lattner23dd1f62006-10-20 00:27:06 +0000205 // Div and rem can trap if the RHS is not known to be non-zero.
Chris Lattnera91a5632009-10-28 05:14:34 +0000206 if (!isa<ConstantInt>(CE->getOperand(1)) ||CE->getOperand(1)->isNullValue())
Chris Lattner23dd1f62006-10-20 00:27:06 +0000207 return true;
208 return false;
209 }
210}
211
Chris Lattner253bc772009-11-01 18:11:50 +0000212/// isConstantUsed - Return true if the constant has users other than constant
213/// exprs and other dangling things.
214bool Constant::isConstantUsed() const {
Gabor Greifc78d7202010-03-25 23:06:16 +0000215 for (const_use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
Chris Lattner253bc772009-11-01 18:11:50 +0000216 const Constant *UC = dyn_cast<Constant>(*UI);
217 if (UC == 0 || isa<GlobalValue>(UC))
218 return true;
219
220 if (UC->isConstantUsed())
221 return true;
222 }
223 return false;
224}
225
226
Chris Lattner4565ef52009-07-22 00:05:44 +0000227
228/// getRelocationInfo - This method classifies the entry according to
229/// whether or not it may generate a relocation entry. This must be
230/// conservative, so if it might codegen to a relocatable entry, it should say
231/// so. The return values are:
232///
Chris Lattner5cd4dd32009-07-24 03:27:21 +0000233/// NoRelocation: This constant pool entry is guaranteed to never have a
234/// relocation applied to it (because it holds a simple constant like
235/// '4').
236/// LocalRelocation: This entry has relocations, but the entries are
237/// guaranteed to be resolvable by the static linker, so the dynamic
238/// linker will never see them.
239/// GlobalRelocations: This entry may have arbitrary relocations.
Chris Lattner4565ef52009-07-22 00:05:44 +0000240///
241/// FIXME: This really should not be in VMCore.
Chris Lattner5cd4dd32009-07-24 03:27:21 +0000242Constant::PossibleRelocationsTy Constant::getRelocationInfo() const {
243 if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
Chris Lattner4565ef52009-07-22 00:05:44 +0000244 if (GV->hasLocalLinkage() || GV->hasHiddenVisibility())
Chris Lattner5cd4dd32009-07-24 03:27:21 +0000245 return LocalRelocation; // Local to this file/library.
246 return GlobalRelocations; // Global reference.
Anton Korobeynikov7437b592009-03-29 17:13:18 +0000247 }
Chris Lattner4565ef52009-07-22 00:05:44 +0000248
Chris Lattner2cb85b42009-10-28 04:12:16 +0000249 if (const BlockAddress *BA = dyn_cast<BlockAddress>(this))
250 return BA->getFunction()->getRelocationInfo();
251
Chris Lattnera7cfc432010-01-03 18:09:40 +0000252 // While raw uses of blockaddress need to be relocated, differences between
253 // two of them don't when they are for labels in the same function. This is a
254 // common idiom when creating a table for the indirect goto extension, so we
255 // handle it efficiently here.
256 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(this))
257 if (CE->getOpcode() == Instruction::Sub) {
258 ConstantExpr *LHS = dyn_cast<ConstantExpr>(CE->getOperand(0));
259 ConstantExpr *RHS = dyn_cast<ConstantExpr>(CE->getOperand(1));
260 if (LHS && RHS &&
261 LHS->getOpcode() == Instruction::PtrToInt &&
262 RHS->getOpcode() == Instruction::PtrToInt &&
263 isa<BlockAddress>(LHS->getOperand(0)) &&
264 isa<BlockAddress>(RHS->getOperand(0)) &&
265 cast<BlockAddress>(LHS->getOperand(0))->getFunction() ==
266 cast<BlockAddress>(RHS->getOperand(0))->getFunction())
267 return NoRelocation;
268 }
269
Chris Lattner5cd4dd32009-07-24 03:27:21 +0000270 PossibleRelocationsTy Result = NoRelocation;
Evan Chengf9e003b2007-03-08 00:59:12 +0000271 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
Chris Lattnera91a5632009-10-28 05:14:34 +0000272 Result = std::max(Result,
273 cast<Constant>(getOperand(i))->getRelocationInfo());
Chris Lattner4565ef52009-07-22 00:05:44 +0000274
275 return Result;
Evan Chengf9e003b2007-03-08 00:59:12 +0000276}
277
Chris Lattner4565ef52009-07-22 00:05:44 +0000278
Chris Lattner2105d662008-07-10 00:28:11 +0000279/// getVectorElements - This method, which is only valid on constant of vector
280/// type, returns the elements of the vector in the specified smallvector.
Chris Lattnerc5098a22008-07-14 05:10:41 +0000281/// This handles breaking down a vector undef into undef elements, etc. For
282/// constant exprs and other cases we can't handle, we return an empty vector.
Chris Lattnerf5edeeb2010-02-01 20:48:08 +0000283void Constant::getVectorElements(SmallVectorImpl<Constant*> &Elts) const {
Duncan Sands19d0b472010-02-16 11:11:14 +0000284 assert(getType()->isVectorTy() && "Not a vector constant!");
Chris Lattner2105d662008-07-10 00:28:11 +0000285
286 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this)) {
287 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i)
288 Elts.push_back(CV->getOperand(i));
289 return;
290 }
291
Chris Lattner229907c2011-07-18 04:54:35 +0000292 VectorType *VT = cast<VectorType>(getType());
Chris Lattner2105d662008-07-10 00:28:11 +0000293 if (isa<ConstantAggregateZero>(this)) {
294 Elts.assign(VT->getNumElements(),
Owen Anderson5a1acd92009-07-31 20:28:14 +0000295 Constant::getNullValue(VT->getElementType()));
Chris Lattner2105d662008-07-10 00:28:11 +0000296 return;
297 }
298
Chris Lattnerc5098a22008-07-14 05:10:41 +0000299 if (isa<UndefValue>(this)) {
Owen Andersonb292b8c2009-07-30 23:03:37 +0000300 Elts.assign(VT->getNumElements(), UndefValue::get(VT->getElementType()));
Chris Lattnerc5098a22008-07-14 05:10:41 +0000301 return;
302 }
303
304 // Unknown type, must be constant expr etc.
Chris Lattner2105d662008-07-10 00:28:11 +0000305}
306
307
Chris Lattner84886402011-02-18 04:41:42 +0000308/// removeDeadUsersOfConstant - If the specified constantexpr is dead, remove
309/// it. This involves recursively eliminating any dead users of the
310/// constantexpr.
311static bool removeDeadUsersOfConstant(const Constant *C) {
312 if (isa<GlobalValue>(C)) return false; // Cannot remove this
313
314 while (!C->use_empty()) {
315 const Constant *User = dyn_cast<Constant>(C->use_back());
316 if (!User) return false; // Non-constant usage;
317 if (!removeDeadUsersOfConstant(User))
318 return false; // Constant wasn't dead
319 }
320
321 const_cast<Constant*>(C)->destroyConstant();
322 return true;
323}
324
325
326/// removeDeadConstantUsers - If there are any dead constant users dangling
327/// off of this constant, remove them. This method is useful for clients
328/// that want to check to see if a global is unused, but don't want to deal
329/// with potentially dead constants hanging off of the globals.
330void Constant::removeDeadConstantUsers() const {
331 Value::const_use_iterator I = use_begin(), E = use_end();
332 Value::const_use_iterator LastNonDeadUser = E;
333 while (I != E) {
334 const Constant *User = dyn_cast<Constant>(*I);
335 if (User == 0) {
336 LastNonDeadUser = I;
337 ++I;
338 continue;
339 }
340
341 if (!removeDeadUsersOfConstant(User)) {
342 // If the constant wasn't dead, remember that this was the last live use
343 // and move on to the next constant.
344 LastNonDeadUser = I;
345 ++I;
346 continue;
347 }
348
349 // If the constant was dead, then the iterator is invalidated.
350 if (LastNonDeadUser == E) {
351 I = use_begin();
352 if (I == E) break;
353 } else {
354 I = LastNonDeadUser;
355 ++I;
356 }
357 }
358}
359
360
Chris Lattner2105d662008-07-10 00:28:11 +0000361
Chris Lattner2f7c9632001-06-06 20:29:01 +0000362//===----------------------------------------------------------------------===//
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000363// ConstantInt
Chris Lattner2f7c9632001-06-06 20:29:01 +0000364//===----------------------------------------------------------------------===//
365
David Blaikiea379b1812011-12-20 02:50:00 +0000366void ConstantInt::anchor() { }
367
Chris Lattner229907c2011-07-18 04:54:35 +0000368ConstantInt::ConstantInt(IntegerType *Ty, const APInt& V)
Chris Lattner5db2f472007-02-20 05:55:46 +0000369 : Constant(Ty, ConstantIntVal, 0, 0), Val(V) {
Reid Spencerb31bffe2007-02-26 23:54:03 +0000370 assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
Chris Lattner2f7c9632001-06-06 20:29:01 +0000371}
372
Nick Lewycky92db8e82011-03-06 03:36:19 +0000373ConstantInt *ConstantInt::getTrue(LLVMContext &Context) {
Owen Anderson23a204d2009-07-31 17:39:07 +0000374 LLVMContextImpl *pImpl = Context.pImpl;
Benjamin Kramerddd1b7b2010-11-20 18:43:35 +0000375 if (!pImpl->TheTrueVal)
376 pImpl->TheTrueVal = ConstantInt::get(Type::getInt1Ty(Context), 1);
377 return pImpl->TheTrueVal;
Owen Anderson23a204d2009-07-31 17:39:07 +0000378}
379
Nick Lewycky92db8e82011-03-06 03:36:19 +0000380ConstantInt *ConstantInt::getFalse(LLVMContext &Context) {
Owen Anderson23a204d2009-07-31 17:39:07 +0000381 LLVMContextImpl *pImpl = Context.pImpl;
Benjamin Kramerddd1b7b2010-11-20 18:43:35 +0000382 if (!pImpl->TheFalseVal)
383 pImpl->TheFalseVal = ConstantInt::get(Type::getInt1Ty(Context), 0);
384 return pImpl->TheFalseVal;
Owen Anderson23a204d2009-07-31 17:39:07 +0000385}
386
Chris Lattner229907c2011-07-18 04:54:35 +0000387Constant *ConstantInt::getTrue(Type *Ty) {
388 VectorType *VTy = dyn_cast<VectorType>(Ty);
Nick Lewycky92db8e82011-03-06 03:36:19 +0000389 if (!VTy) {
390 assert(Ty->isIntegerTy(1) && "True must be i1 or vector of i1.");
391 return ConstantInt::getTrue(Ty->getContext());
392 }
393 assert(VTy->getElementType()->isIntegerTy(1) &&
394 "True must be vector of i1 or i1.");
Chris Lattner9fe7dd82012-01-25 01:53:58 +0000395 return ConstantVector::getSplat(VTy->getNumElements(),
396 ConstantInt::getTrue(Ty->getContext()));
Nick Lewycky92db8e82011-03-06 03:36:19 +0000397}
398
Chris Lattner229907c2011-07-18 04:54:35 +0000399Constant *ConstantInt::getFalse(Type *Ty) {
400 VectorType *VTy = dyn_cast<VectorType>(Ty);
Nick Lewycky92db8e82011-03-06 03:36:19 +0000401 if (!VTy) {
402 assert(Ty->isIntegerTy(1) && "False must be i1 or vector of i1.");
403 return ConstantInt::getFalse(Ty->getContext());
404 }
405 assert(VTy->getElementType()->isIntegerTy(1) &&
406 "False must be vector of i1 or i1.");
Chris Lattner9fe7dd82012-01-25 01:53:58 +0000407 return ConstantVector::getSplat(VTy->getNumElements(),
408 ConstantInt::getFalse(Ty->getContext()));
Nick Lewycky92db8e82011-03-06 03:36:19 +0000409}
410
Owen Anderson23a204d2009-07-31 17:39:07 +0000411
Owen Andersonedb4a702009-07-24 23:12:02 +0000412// Get a ConstantInt from an APInt. Note that the value stored in the DenseMap
413// as the key, is a DenseMapAPIntKeyInfo::KeyTy which has provided the
414// operator== and operator!= to ensure that the DenseMap doesn't attempt to
415// compare APInt's of different widths, which would violate an APInt class
416// invariant which generates an assertion.
Nick Lewycky92db8e82011-03-06 03:36:19 +0000417ConstantInt *ConstantInt::get(LLVMContext &Context, const APInt &V) {
Owen Andersonedb4a702009-07-24 23:12:02 +0000418 // Get the corresponding integer type for the bit width of the value.
Chris Lattner229907c2011-07-18 04:54:35 +0000419 IntegerType *ITy = IntegerType::get(Context, V.getBitWidth());
Owen Andersonedb4a702009-07-24 23:12:02 +0000420 // get an existing value or the insertion position
421 DenseMapAPIntKeyInfo::KeyTy Key(V, ITy);
Owen Andersonedb4a702009-07-24 23:12:02 +0000422 ConstantInt *&Slot = Context.pImpl->IntConstants[Key];
Owen Anderson5dab84c2009-10-19 20:11:52 +0000423 if (!Slot) Slot = new ConstantInt(ITy, V);
424 return Slot;
Owen Andersonedb4a702009-07-24 23:12:02 +0000425}
426
Chris Lattner229907c2011-07-18 04:54:35 +0000427Constant *ConstantInt::get(Type *Ty, uint64_t V, bool isSigned) {
Nick Lewycky92db8e82011-03-06 03:36:19 +0000428 Constant *C = get(cast<IntegerType>(Ty->getScalarType()), V, isSigned);
Owen Andersonedb4a702009-07-24 23:12:02 +0000429
430 // For vectors, broadcast the value.
Chris Lattner229907c2011-07-18 04:54:35 +0000431 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
Chris Lattner9fe7dd82012-01-25 01:53:58 +0000432 return ConstantVector::getSplat(VTy->getNumElements(), C);
Owen Andersonedb4a702009-07-24 23:12:02 +0000433
434 return C;
435}
436
Chris Lattner229907c2011-07-18 04:54:35 +0000437ConstantInt* ConstantInt::get(IntegerType* Ty, uint64_t V,
Owen Andersonedb4a702009-07-24 23:12:02 +0000438 bool isSigned) {
439 return get(Ty->getContext(), APInt(Ty->getBitWidth(), V, isSigned));
440}
441
Chris Lattner229907c2011-07-18 04:54:35 +0000442ConstantInt* ConstantInt::getSigned(IntegerType* Ty, int64_t V) {
Owen Andersonedb4a702009-07-24 23:12:02 +0000443 return get(Ty, V, true);
444}
445
Chris Lattner229907c2011-07-18 04:54:35 +0000446Constant *ConstantInt::getSigned(Type *Ty, int64_t V) {
Owen Andersonedb4a702009-07-24 23:12:02 +0000447 return get(Ty, V, true);
448}
449
Chris Lattner229907c2011-07-18 04:54:35 +0000450Constant *ConstantInt::get(Type* Ty, const APInt& V) {
Owen Andersonedb4a702009-07-24 23:12:02 +0000451 ConstantInt *C = get(Ty->getContext(), V);
452 assert(C->getType() == Ty->getScalarType() &&
453 "ConstantInt type doesn't match the type implied by its value!");
454
455 // For vectors, broadcast the value.
Chris Lattner229907c2011-07-18 04:54:35 +0000456 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
Chris Lattner9fe7dd82012-01-25 01:53:58 +0000457 return ConstantVector::getSplat(VTy->getNumElements(), C);
Owen Andersonedb4a702009-07-24 23:12:02 +0000458
459 return C;
460}
461
Chris Lattner229907c2011-07-18 04:54:35 +0000462ConstantInt* ConstantInt::get(IntegerType* Ty, StringRef Str,
Erick Tryzelaarfc2280d2009-08-16 23:36:33 +0000463 uint8_t radix) {
464 return get(Ty->getContext(), APInt(Ty->getBitWidth(), Str, radix));
465}
466
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000467//===----------------------------------------------------------------------===//
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000468// ConstantFP
Chris Lattnera80bf0b2007-02-20 06:39:57 +0000469//===----------------------------------------------------------------------===//
470
Chris Lattner229907c2011-07-18 04:54:35 +0000471static const fltSemantics *TypeToFloatSemantics(Type *Ty) {
Dan Gohman518cda42011-12-17 00:04:22 +0000472 if (Ty->isHalfTy())
473 return &APFloat::IEEEhalf;
Chris Lattnerfdd87902009-10-05 05:54:46 +0000474 if (Ty->isFloatTy())
Rafael Espindolaf5d53d42009-07-15 17:40:42 +0000475 return &APFloat::IEEEsingle;
Chris Lattnerfdd87902009-10-05 05:54:46 +0000476 if (Ty->isDoubleTy())
Rafael Espindolaf5d53d42009-07-15 17:40:42 +0000477 return &APFloat::IEEEdouble;
Chris Lattnerfdd87902009-10-05 05:54:46 +0000478 if (Ty->isX86_FP80Ty())
Rafael Espindolaf5d53d42009-07-15 17:40:42 +0000479 return &APFloat::x87DoubleExtended;
Chris Lattnerfdd87902009-10-05 05:54:46 +0000480 else if (Ty->isFP128Ty())
Rafael Espindolaf5d53d42009-07-15 17:40:42 +0000481 return &APFloat::IEEEquad;
482
Chris Lattnerfdd87902009-10-05 05:54:46 +0000483 assert(Ty->isPPC_FP128Ty() && "Unknown FP format");
Rafael Espindolaf5d53d42009-07-15 17:40:42 +0000484 return &APFloat::PPCDoubleDouble;
485}
486
David Blaikiea379b1812011-12-20 02:50:00 +0000487void ConstantFP::anchor() { }
488
Owen Anderson69c464d2009-07-27 20:59:43 +0000489/// get() - This returns a constant fp for the specified value in the
490/// specified type. This should only be used for simple constant values like
491/// 2.0/1.0 etc, that are known-valid both as double and as the target format.
Chris Lattner229907c2011-07-18 04:54:35 +0000492Constant *ConstantFP::get(Type* Ty, double V) {
Owen Anderson69c464d2009-07-27 20:59:43 +0000493 LLVMContext &Context = Ty->getContext();
494
495 APFloat FV(V);
496 bool ignored;
497 FV.convert(*TypeToFloatSemantics(Ty->getScalarType()),
498 APFloat::rmNearestTiesToEven, &ignored);
499 Constant *C = get(Context, FV);
500
501 // For vectors, broadcast the value.
Chris Lattner229907c2011-07-18 04:54:35 +0000502 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
Chris Lattner9fe7dd82012-01-25 01:53:58 +0000503 return ConstantVector::getSplat(VTy->getNumElements(), C);
Owen Anderson69c464d2009-07-27 20:59:43 +0000504
505 return C;
506}
507
Erick Tryzelaarfc2280d2009-08-16 23:36:33 +0000508
Chris Lattner229907c2011-07-18 04:54:35 +0000509Constant *ConstantFP::get(Type* Ty, StringRef Str) {
Erick Tryzelaarfc2280d2009-08-16 23:36:33 +0000510 LLVMContext &Context = Ty->getContext();
511
512 APFloat FV(*TypeToFloatSemantics(Ty->getScalarType()), Str);
513 Constant *C = get(Context, FV);
514
515 // For vectors, broadcast the value.
Chris Lattner229907c2011-07-18 04:54:35 +0000516 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
Chris Lattner9fe7dd82012-01-25 01:53:58 +0000517 return ConstantVector::getSplat(VTy->getNumElements(), C);
Erick Tryzelaarfc2280d2009-08-16 23:36:33 +0000518
519 return C;
520}
521
522
Chris Lattner229907c2011-07-18 04:54:35 +0000523ConstantFP* ConstantFP::getNegativeZero(Type* Ty) {
Owen Anderson69c464d2009-07-27 20:59:43 +0000524 LLVMContext &Context = Ty->getContext();
Owen Anderson5a1acd92009-07-31 20:28:14 +0000525 APFloat apf = cast <ConstantFP>(Constant::getNullValue(Ty))->getValueAPF();
Owen Anderson69c464d2009-07-27 20:59:43 +0000526 apf.changeSign();
527 return get(Context, apf);
528}
529
530
Chris Lattner229907c2011-07-18 04:54:35 +0000531Constant *ConstantFP::getZeroValueForNegation(Type* Ty) {
Chris Lattner9fe7dd82012-01-25 01:53:58 +0000532 if (Ty->getScalarType()->isFloatingPointTy()) {
533 Constant *C = getNegativeZero(Ty);
534 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
535 return ConstantVector::getSplat(VTy->getNumElements(), C);
536 return C;
537 }
Owen Anderson69c464d2009-07-27 20:59:43 +0000538
Owen Anderson5a1acd92009-07-31 20:28:14 +0000539 return Constant::getNullValue(Ty);
Owen Anderson69c464d2009-07-27 20:59:43 +0000540}
541
542
543// ConstantFP accessors.
544ConstantFP* ConstantFP::get(LLVMContext &Context, const APFloat& V) {
545 DenseMapAPFloatKeyInfo::KeyTy Key(V);
546
547 LLVMContextImpl* pImpl = Context.pImpl;
548
Owen Anderson69c464d2009-07-27 20:59:43 +0000549 ConstantFP *&Slot = pImpl->FPConstants[Key];
Owen Anderson69c464d2009-07-27 20:59:43 +0000550
551 if (!Slot) {
Chris Lattner229907c2011-07-18 04:54:35 +0000552 Type *Ty;
Dan Gohman518cda42011-12-17 00:04:22 +0000553 if (&V.getSemantics() == &APFloat::IEEEhalf)
554 Ty = Type::getHalfTy(Context);
555 else if (&V.getSemantics() == &APFloat::IEEEsingle)
Owen Anderson5dab84c2009-10-19 20:11:52 +0000556 Ty = Type::getFloatTy(Context);
557 else if (&V.getSemantics() == &APFloat::IEEEdouble)
558 Ty = Type::getDoubleTy(Context);
559 else if (&V.getSemantics() == &APFloat::x87DoubleExtended)
560 Ty = Type::getX86_FP80Ty(Context);
561 else if (&V.getSemantics() == &APFloat::IEEEquad)
562 Ty = Type::getFP128Ty(Context);
563 else {
564 assert(&V.getSemantics() == &APFloat::PPCDoubleDouble &&
565 "Unknown FP format");
566 Ty = Type::getPPC_FP128Ty(Context);
Owen Anderson69c464d2009-07-27 20:59:43 +0000567 }
Owen Anderson5dab84c2009-10-19 20:11:52 +0000568 Slot = new ConstantFP(Ty, V);
Owen Anderson69c464d2009-07-27 20:59:43 +0000569 }
570
571 return Slot;
572}
573
Chris Lattner229907c2011-07-18 04:54:35 +0000574ConstantFP *ConstantFP::getInfinity(Type *Ty, bool Negative) {
Dan Gohmanfeb50212009-09-25 23:00:48 +0000575 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty);
576 return ConstantFP::get(Ty->getContext(),
577 APFloat::getInf(Semantics, Negative));
578}
579
Chris Lattner229907c2011-07-18 04:54:35 +0000580ConstantFP::ConstantFP(Type *Ty, const APFloat& V)
Dale Johannesend246b2c2007-08-30 00:23:21 +0000581 : Constant(Ty, ConstantFPVal, 0, 0), Val(V) {
Chris Lattner98bd9392008-04-09 06:38:30 +0000582 assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
583 "FP type Mismatch");
Chris Lattner2f7c9632001-06-06 20:29:01 +0000584}
585
Chris Lattnerbe6610c2011-07-15 06:14:08 +0000586bool ConstantFP::isExactlyValue(const APFloat &V) const {
Dale Johannesend246b2c2007-08-30 00:23:21 +0000587 return Val.bitwiseIsEqual(V);
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000588}
589
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000590//===----------------------------------------------------------------------===//
Chris Lattner030af792012-01-24 05:42:11 +0000591// ConstantAggregateZero Implementation
592//===----------------------------------------------------------------------===//
593
594/// getSequentialElement - If this CAZ has array or vector type, return a zero
595/// with the right element type.
596Constant *ConstantAggregateZero::getSequentialElement() {
597 return Constant::getNullValue(
598 cast<SequentialType>(getType())->getElementType());
599}
600
601/// getStructElement - If this CAZ has struct type, return a zero with the
602/// right element type for the specified element.
603Constant *ConstantAggregateZero::getStructElement(unsigned Elt) {
604 return Constant::getNullValue(
605 cast<StructType>(getType())->getElementType(Elt));
606}
607
608/// getElementValue - Return a zero of the right value for the specified GEP
609/// index if we can, otherwise return null (e.g. if C is a ConstantExpr).
610Constant *ConstantAggregateZero::getElementValue(Constant *C) {
611 if (isa<SequentialType>(getType()))
612 return getSequentialElement();
613 return getStructElement(cast<ConstantInt>(C)->getZExtValue());
614}
615
Chris Lattnerf7eb5432012-01-24 07:54:10 +0000616/// getElementValue - Return a zero of the right value for the specified GEP
617/// index.
618Constant *ConstantAggregateZero::getElementValue(unsigned Idx) {
619 if (isa<SequentialType>(getType()))
620 return getSequentialElement();
621 return getStructElement(Idx);
622}
623
624
Chris Lattner030af792012-01-24 05:42:11 +0000625//===----------------------------------------------------------------------===//
626// UndefValue Implementation
627//===----------------------------------------------------------------------===//
628
629/// getSequentialElement - If this undef has array or vector type, return an
630/// undef with the right element type.
631UndefValue *UndefValue::getSequentialElement() {
632 return UndefValue::get(cast<SequentialType>(getType())->getElementType());
633}
634
635/// getStructElement - If this undef has struct type, return a zero with the
636/// right element type for the specified element.
637UndefValue *UndefValue::getStructElement(unsigned Elt) {
638 return UndefValue::get(cast<StructType>(getType())->getElementType(Elt));
639}
640
641/// getElementValue - Return an undef of the right value for the specified GEP
642/// index if we can, otherwise return null (e.g. if C is a ConstantExpr).
643UndefValue *UndefValue::getElementValue(Constant *C) {
644 if (isa<SequentialType>(getType()))
645 return getSequentialElement();
646 return getStructElement(cast<ConstantInt>(C)->getZExtValue());
647}
648
Chris Lattnerf7eb5432012-01-24 07:54:10 +0000649/// getElementValue - Return an undef of the right value for the specified GEP
650/// index.
651UndefValue *UndefValue::getElementValue(unsigned Idx) {
652 if (isa<SequentialType>(getType()))
653 return getSequentialElement();
654 return getStructElement(Idx);
655}
656
657
Chris Lattner030af792012-01-24 05:42:11 +0000658
659//===----------------------------------------------------------------------===//
Chris Lattnerc6ee77d2007-02-20 07:17:17 +0000660// ConstantXXX Classes
661//===----------------------------------------------------------------------===//
662
663
Jay Foad89d9b812011-07-25 10:14:44 +0000664ConstantArray::ConstantArray(ArrayType *T, ArrayRef<Constant *> V)
Gabor Greiff6caff662008-05-10 08:32:32 +0000665 : Constant(T, ConstantArrayVal,
666 OperandTraits<ConstantArray>::op_end(this) - V.size(),
667 V.size()) {
Alkis Evlogimenos0507ffe2004-09-15 02:32:15 +0000668 assert(V.size() == T->getNumElements() &&
669 "Invalid initializer vector for constant array");
Jay Foad89d9b812011-07-25 10:14:44 +0000670 for (unsigned i = 0, e = V.size(); i != e; ++i)
671 assert(V[i]->getType() == T->getElementType() &&
Alkis Evlogimenoscb031d92004-09-10 04:16:59 +0000672 "Initializer for array element doesn't match array element type!");
Jay Foad89d9b812011-07-25 10:14:44 +0000673 std::copy(V.begin(), V.end(), op_begin());
Chris Lattner2f7c9632001-06-06 20:29:01 +0000674}
675
Chris Lattner229907c2011-07-18 04:54:35 +0000676Constant *ConstantArray::get(ArrayType *Ty, ArrayRef<Constant*> V) {
Jeffrey Yasskin8ce67f82009-09-30 21:08:08 +0000677 for (unsigned i = 0, e = V.size(); i != e; ++i) {
678 assert(V[i]->getType() == Ty->getElementType() &&
679 "Wrong type in array element initializer");
680 }
Owen Andersonc2c79322009-07-28 18:32:17 +0000681 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
682 // If this is an all-zero array, return a ConstantAggregateZero object
683 if (!V.empty()) {
684 Constant *C = V[0];
Chris Lattner09660c92009-12-30 20:25:09 +0000685 if (!C->isNullValue())
Owen Andersonc2c79322009-07-28 18:32:17 +0000686 return pImpl->ArrayConstants.getOrCreate(Ty, V);
Chris Lattner09660c92009-12-30 20:25:09 +0000687
Owen Andersonc2c79322009-07-28 18:32:17 +0000688 for (unsigned i = 1, e = V.size(); i != e; ++i)
Chris Lattner09660c92009-12-30 20:25:09 +0000689 if (V[i] != C)
Owen Andersonc2c79322009-07-28 18:32:17 +0000690 return pImpl->ArrayConstants.getOrCreate(Ty, V);
Owen Andersonc2c79322009-07-28 18:32:17 +0000691 }
692
Owen Andersonb292b8c2009-07-30 23:03:37 +0000693 return ConstantAggregateZero::get(Ty);
Owen Andersonc2c79322009-07-28 18:32:17 +0000694}
695
Owen Andersonc2c79322009-07-28 18:32:17 +0000696/// ConstantArray::get(const string&) - Return an array that is initialized to
697/// contain the specified string. If length is zero then a null terminator is
698/// added to the specified string so that it may be used in a natural way.
699/// Otherwise, the length parameter specifies how much of the string to use
700/// and it won't be null terminated.
701///
Chris Lattnera676c0f2011-02-07 16:40:21 +0000702Constant *ConstantArray::get(LLVMContext &Context, StringRef Str,
Owen Anderson55f1c092009-08-13 21:58:54 +0000703 bool AddNull) {
Owen Andersonc2c79322009-07-28 18:32:17 +0000704 std::vector<Constant*> ElementVals;
Benjamin Kramer3d4af4e2010-08-01 11:43:26 +0000705 ElementVals.reserve(Str.size() + size_t(AddNull));
Owen Andersonc2c79322009-07-28 18:32:17 +0000706 for (unsigned i = 0; i < Str.size(); ++i)
Owen Anderson55f1c092009-08-13 21:58:54 +0000707 ElementVals.push_back(ConstantInt::get(Type::getInt8Ty(Context), Str[i]));
Owen Andersonc2c79322009-07-28 18:32:17 +0000708
709 // Add a null terminator to the string...
Chris Lattner20683932012-01-24 14:04:40 +0000710 if (AddNull)
Owen Anderson55f1c092009-08-13 21:58:54 +0000711 ElementVals.push_back(ConstantInt::get(Type::getInt8Ty(Context), 0));
Owen Andersonc2c79322009-07-28 18:32:17 +0000712
Owen Anderson55f1c092009-08-13 21:58:54 +0000713 ArrayType *ATy = ArrayType::get(Type::getInt8Ty(Context), ElementVals.size());
Owen Andersonc2c79322009-07-28 18:32:17 +0000714 return get(ATy, ElementVals);
715}
716
Chris Lattnercc19efa2011-06-20 04:01:31 +0000717/// getTypeForElements - Return an anonymous struct type to use for a constant
718/// with the specified set of elements. The list must not be empty.
719StructType *ConstantStruct::getTypeForElements(LLVMContext &Context,
720 ArrayRef<Constant*> V,
721 bool Packed) {
Jay Foadb804a2b2011-07-12 14:06:48 +0000722 SmallVector<Type*, 16> EltTypes;
Chris Lattnercc19efa2011-06-20 04:01:31 +0000723 for (unsigned i = 0, e = V.size(); i != e; ++i)
724 EltTypes.push_back(V[i]->getType());
725
726 return StructType::get(Context, EltTypes, Packed);
727}
728
729
730StructType *ConstantStruct::getTypeForElements(ArrayRef<Constant*> V,
731 bool Packed) {
732 assert(!V.empty() &&
733 "ConstantStruct::getTypeForElements cannot be called on empty list");
734 return getTypeForElements(V[0]->getContext(), V, Packed);
735}
736
737
Jay Foad89d9b812011-07-25 10:14:44 +0000738ConstantStruct::ConstantStruct(StructType *T, ArrayRef<Constant *> V)
Gabor Greiff6caff662008-05-10 08:32:32 +0000739 : Constant(T, ConstantStructVal,
740 OperandTraits<ConstantStruct>::op_end(this) - V.size(),
741 V.size()) {
Chris Lattnerc3e74cd2011-08-07 04:18:48 +0000742 assert(V.size() == T->getNumElements() &&
Vikram S. Adve4e537b22002-07-14 23:13:17 +0000743 "Invalid initializer vector for constant structure");
Jay Foad89d9b812011-07-25 10:14:44 +0000744 for (unsigned i = 0, e = V.size(); i != e; ++i)
745 assert((T->isOpaque() || V[i]->getType() == T->getElementType(i)) &&
Chris Lattner93c8f142003-06-02 17:42:47 +0000746 "Initializer for struct element doesn't match struct element type!");
Jay Foad89d9b812011-07-25 10:14:44 +0000747 std::copy(V.begin(), V.end(), op_begin());
Chris Lattner2f7c9632001-06-06 20:29:01 +0000748}
749
Owen Anderson45308b52009-07-27 22:29:26 +0000750// ConstantStruct accessors.
Chris Lattner229907c2011-07-18 04:54:35 +0000751Constant *ConstantStruct::get(StructType *ST, ArrayRef<Constant*> V) {
Chris Lattnercc19efa2011-06-20 04:01:31 +0000752 // Create a ConstantAggregateZero value if all elements are zeros.
Owen Anderson45308b52009-07-27 22:29:26 +0000753 for (unsigned i = 0, e = V.size(); i != e; ++i)
Jay Foad687bd0a2011-06-22 08:55:11 +0000754 if (!V[i]->isNullValue())
755 return ST->getContext().pImpl->StructConstants.getOrCreate(ST, V);
Owen Anderson45308b52009-07-27 22:29:26 +0000756
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000757 assert((ST->isOpaque() || ST->getNumElements() == V.size()) &&
758 "Incorrect # elements specified to ConstantStruct::get");
Chris Lattnercc19efa2011-06-20 04:01:31 +0000759 return ConstantAggregateZero::get(ST);
Owen Anderson45308b52009-07-27 22:29:26 +0000760}
761
Chris Lattnerc3e74cd2011-08-07 04:18:48 +0000762Constant *ConstantStruct::get(StructType *T, ...) {
Talin3a0a30d2011-02-28 23:53:27 +0000763 va_list ap;
Chris Lattnercc19efa2011-06-20 04:01:31 +0000764 SmallVector<Constant*, 8> Values;
765 va_start(ap, T);
766 while (Constant *Val = va_arg(ap, llvm::Constant*))
Talin3a0a30d2011-02-28 23:53:27 +0000767 Values.push_back(Val);
Talinde422be2011-03-01 18:00:49 +0000768 va_end(ap);
Chris Lattnercc19efa2011-06-20 04:01:31 +0000769 return get(T, Values);
Talin3a0a30d2011-02-28 23:53:27 +0000770}
771
Jay Foad89d9b812011-07-25 10:14:44 +0000772ConstantVector::ConstantVector(VectorType *T, ArrayRef<Constant *> V)
Gabor Greiff6caff662008-05-10 08:32:32 +0000773 : Constant(T, ConstantVectorVal,
774 OperandTraits<ConstantVector>::op_end(this) - V.size(),
775 V.size()) {
Jay Foad89d9b812011-07-25 10:14:44 +0000776 for (size_t i = 0, e = V.size(); i != e; i++)
777 assert(V[i]->getType() == T->getElementType() &&
Dan Gohman30978072007-05-24 14:36:04 +0000778 "Initializer for vector element doesn't match vector element type!");
Jay Foad89d9b812011-07-25 10:14:44 +0000779 std::copy(V.begin(), V.end(), op_begin());
Brian Gaeke02209042004-08-20 06:00:58 +0000780}
781
Owen Anderson4aa32952009-07-28 21:19:26 +0000782// ConstantVector accessors.
Jay Foadb8a8bed32011-06-22 09:10:19 +0000783Constant *ConstantVector::get(ArrayRef<Constant*> V) {
Jay Foad9f32cfd2011-01-27 14:44:55 +0000784 assert(!V.empty() && "Vectors can't be empty");
Chris Lattner229907c2011-07-18 04:54:35 +0000785 VectorType *T = VectorType::get(V.front()->getType(), V.size());
Chris Lattner69229312011-02-15 00:14:00 +0000786 LLVMContextImpl *pImpl = T->getContext().pImpl;
Jay Foad9f32cfd2011-01-27 14:44:55 +0000787
Chris Lattner69229312011-02-15 00:14:00 +0000788 // If this is an all-undef or all-zero vector, return a
Owen Anderson4aa32952009-07-28 21:19:26 +0000789 // ConstantAggregateZero or UndefValue.
790 Constant *C = V[0];
791 bool isZero = C->isNullValue();
792 bool isUndef = isa<UndefValue>(C);
793
794 if (isZero || isUndef) {
795 for (unsigned i = 1, e = V.size(); i != e; ++i)
796 if (V[i] != C) {
797 isZero = isUndef = false;
798 break;
799 }
800 }
801
802 if (isZero)
Owen Andersonb292b8c2009-07-30 23:03:37 +0000803 return ConstantAggregateZero::get(T);
Owen Anderson4aa32952009-07-28 21:19:26 +0000804 if (isUndef)
Owen Andersonb292b8c2009-07-30 23:03:37 +0000805 return UndefValue::get(T);
Owen Anderson4aa32952009-07-28 21:19:26 +0000806
Owen Anderson4aa32952009-07-28 21:19:26 +0000807 return pImpl->VectorConstants.getOrCreate(T, V);
808}
809
Chris Lattner9fe7dd82012-01-25 01:53:58 +0000810Constant *ConstantVector::getSplat(unsigned NumElts, Constant *V) {
811 SmallVector<Constant*, 32> Elts(NumElts, V);
812 return get(Elts);
813}
814
815
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000816// Utility function for determining if a ConstantExpr is a CastOp or not. This
817// can't be inline because we don't want to #include Instruction.h into
818// Constant.h
819bool ConstantExpr::isCast() const {
820 return Instruction::isCast(getOpcode());
821}
822
Reid Spenceree3c9912006-12-04 05:19:50 +0000823bool ConstantExpr::isCompare() const {
Nick Lewyckya21d3da2009-07-08 03:04:38 +0000824 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
Reid Spenceree3c9912006-12-04 05:19:50 +0000825}
826
Dan Gohman7190d482009-09-10 23:37:55 +0000827bool ConstantExpr::isGEPWithNoNotionalOverIndexing() const {
828 if (getOpcode() != Instruction::GetElementPtr) return false;
829
830 gep_type_iterator GEPI = gep_type_begin(this), E = gep_type_end(this);
Oscar Fuentes40b31ad2010-08-02 06:00:15 +0000831 User::const_op_iterator OI = llvm::next(this->op_begin());
Dan Gohman7190d482009-09-10 23:37:55 +0000832
833 // Skip the first index, as it has no static limit.
834 ++GEPI;
835 ++OI;
836
837 // The remaining indices must be compile-time known integers within the
838 // bounds of the corresponding notional static array types.
839 for (; GEPI != E; ++GEPI, ++OI) {
840 ConstantInt *CI = dyn_cast<ConstantInt>(*OI);
841 if (!CI) return false;
Chris Lattner229907c2011-07-18 04:54:35 +0000842 if (ArrayType *ATy = dyn_cast<ArrayType>(*GEPI))
Dan Gohman7190d482009-09-10 23:37:55 +0000843 if (CI->getValue().getActiveBits() > 64 ||
844 CI->getZExtValue() >= ATy->getNumElements())
845 return false;
846 }
847
848 // All the indices checked out.
849 return true;
850}
851
Dan Gohman1ecaf452008-05-31 00:58:22 +0000852bool ConstantExpr::hasIndices() const {
853 return getOpcode() == Instruction::ExtractValue ||
854 getOpcode() == Instruction::InsertValue;
855}
856
Jay Foad0091fe82011-04-13 15:22:40 +0000857ArrayRef<unsigned> ConstantExpr::getIndices() const {
Dan Gohman1ecaf452008-05-31 00:58:22 +0000858 if (const ExtractValueConstantExpr *EVCE =
859 dyn_cast<ExtractValueConstantExpr>(this))
860 return EVCE->Indices;
Dan Gohmana469bdb2008-06-23 16:39:44 +0000861
862 return cast<InsertValueConstantExpr>(this)->Indices;
Dan Gohman1ecaf452008-05-31 00:58:22 +0000863}
864
Reid Spencer10fbf0e2006-12-03 05:48:19 +0000865unsigned ConstantExpr::getPredicate() const {
Chris Lattnerd04e32d2011-07-17 06:01:30 +0000866 assert(isCompare());
Chris Lattneref650092007-10-18 16:26:24 +0000867 return ((const CompareConstantExpr*)this)->predicate;
Reid Spencer10fbf0e2006-12-03 05:48:19 +0000868}
Chris Lattner60e0dd72001-10-03 06:12:09 +0000869
Chris Lattner7c1018a2006-07-14 19:37:40 +0000870/// getWithOperandReplaced - Return a constant expression identical to this
871/// one, but with the specified operand set to the specified value.
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000872Constant *
873ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
Chris Lattner7c1018a2006-07-14 19:37:40 +0000874 assert(OpNo < getNumOperands() && "Operand num is out of range!");
875 assert(Op->getType() == getOperand(OpNo)->getType() &&
876 "Replacing operand with value of different type!");
Chris Lattner227816342006-07-14 22:20:01 +0000877 if (getOperand(OpNo) == Op)
878 return const_cast<ConstantExpr*>(this);
Chris Lattner7c1018a2006-07-14 19:37:40 +0000879
Chris Lattner227816342006-07-14 22:20:01 +0000880 Constant *Op0, *Op1, *Op2;
Chris Lattner7c1018a2006-07-14 19:37:40 +0000881 switch (getOpcode()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000882 case Instruction::Trunc:
883 case Instruction::ZExt:
884 case Instruction::SExt:
885 case Instruction::FPTrunc:
886 case Instruction::FPExt:
887 case Instruction::UIToFP:
888 case Instruction::SIToFP:
889 case Instruction::FPToUI:
890 case Instruction::FPToSI:
891 case Instruction::PtrToInt:
892 case Instruction::IntToPtr:
893 case Instruction::BitCast:
894 return ConstantExpr::getCast(getOpcode(), Op, getType());
Chris Lattner227816342006-07-14 22:20:01 +0000895 case Instruction::Select:
896 Op0 = (OpNo == 0) ? Op : getOperand(0);
897 Op1 = (OpNo == 1) ? Op : getOperand(1);
898 Op2 = (OpNo == 2) ? Op : getOperand(2);
899 return ConstantExpr::getSelect(Op0, Op1, Op2);
900 case Instruction::InsertElement:
901 Op0 = (OpNo == 0) ? Op : getOperand(0);
902 Op1 = (OpNo == 1) ? Op : getOperand(1);
903 Op2 = (OpNo == 2) ? Op : getOperand(2);
904 return ConstantExpr::getInsertElement(Op0, Op1, Op2);
905 case Instruction::ExtractElement:
906 Op0 = (OpNo == 0) ? Op : getOperand(0);
907 Op1 = (OpNo == 1) ? Op : getOperand(1);
908 return ConstantExpr::getExtractElement(Op0, Op1);
909 case Instruction::ShuffleVector:
910 Op0 = (OpNo == 0) ? Op : getOperand(0);
911 Op1 = (OpNo == 1) ? Op : getOperand(1);
912 Op2 = (OpNo == 2) ? Op : getOperand(2);
913 return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Chris Lattner7c1018a2006-07-14 19:37:40 +0000914 case Instruction::GetElementPtr: {
Chris Lattnerb5d70302007-02-19 20:01:23 +0000915 SmallVector<Constant*, 8> Ops;
Dan Gohman12fce772008-05-15 19:50:34 +0000916 Ops.resize(getNumOperands()-1);
Chris Lattner7c1018a2006-07-14 19:37:40 +0000917 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
Dan Gohman12fce772008-05-15 19:50:34 +0000918 Ops[i-1] = getOperand(i);
Chris Lattner7c1018a2006-07-14 19:37:40 +0000919 if (OpNo == 0)
Jay Foad2f5fc8c2011-07-21 15:15:37 +0000920 return
921 ConstantExpr::getGetElementPtr(Op, Ops,
922 cast<GEPOperator>(this)->isInBounds());
Chris Lattner7c1018a2006-07-14 19:37:40 +0000923 Ops[OpNo-1] = Op;
Jay Foad2f5fc8c2011-07-21 15:15:37 +0000924 return
925 ConstantExpr::getGetElementPtr(getOperand(0), Ops,
926 cast<GEPOperator>(this)->isInBounds());
Chris Lattner7c1018a2006-07-14 19:37:40 +0000927 }
Chris Lattner7c1018a2006-07-14 19:37:40 +0000928 default:
929 assert(getNumOperands() == 2 && "Must be binary operator?");
Chris Lattner227816342006-07-14 22:20:01 +0000930 Op0 = (OpNo == 0) ? Op : getOperand(0);
931 Op1 = (OpNo == 1) ? Op : getOperand(1);
Chris Lattnerb9c86512009-12-29 02:14:09 +0000932 return ConstantExpr::get(getOpcode(), Op0, Op1, SubclassOptionalData);
Chris Lattner227816342006-07-14 22:20:01 +0000933 }
934}
935
936/// getWithOperands - This returns the current constant expression with the
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000937/// operands replaced with the specified values. The specified array must
938/// have the same number of operands as our current one.
Chris Lattner227816342006-07-14 22:20:01 +0000939Constant *ConstantExpr::
Chris Lattner229907c2011-07-18 04:54:35 +0000940getWithOperands(ArrayRef<Constant*> Ops, Type *Ty) const {
Jay Foad5c984e562011-04-13 13:46:01 +0000941 assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000942 bool AnyChange = Ty != getType();
943 for (unsigned i = 0; i != Ops.size(); ++i)
Chris Lattner227816342006-07-14 22:20:01 +0000944 AnyChange |= Ops[i] != getOperand(i);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000945
Chris Lattner227816342006-07-14 22:20:01 +0000946 if (!AnyChange) // No operands changed, return self.
947 return const_cast<ConstantExpr*>(this);
948
949 switch (getOpcode()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000950 case Instruction::Trunc:
951 case Instruction::ZExt:
952 case Instruction::SExt:
953 case Instruction::FPTrunc:
954 case Instruction::FPExt:
955 case Instruction::UIToFP:
956 case Instruction::SIToFP:
957 case Instruction::FPToUI:
958 case Instruction::FPToSI:
959 case Instruction::PtrToInt:
960 case Instruction::IntToPtr:
961 case Instruction::BitCast:
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000962 return ConstantExpr::getCast(getOpcode(), Ops[0], Ty);
Chris Lattner227816342006-07-14 22:20:01 +0000963 case Instruction::Select:
964 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
965 case Instruction::InsertElement:
966 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
967 case Instruction::ExtractElement:
968 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
969 case Instruction::ShuffleVector:
970 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
Chris Lattnerb5d70302007-02-19 20:01:23 +0000971 case Instruction::GetElementPtr:
Jay Foad2f5fc8c2011-07-21 15:15:37 +0000972 return
973 ConstantExpr::getGetElementPtr(Ops[0], Ops.slice(1),
974 cast<GEPOperator>(this)->isInBounds());
Reid Spencer266e42b2006-12-23 06:05:41 +0000975 case Instruction::ICmp:
976 case Instruction::FCmp:
977 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
Chris Lattner227816342006-07-14 22:20:01 +0000978 default:
979 assert(getNumOperands() == 2 && "Must be binary operator?");
Chris Lattnerb9c86512009-12-29 02:14:09 +0000980 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1], SubclassOptionalData);
Chris Lattner7c1018a2006-07-14 19:37:40 +0000981 }
982}
983
Chris Lattner2f7c9632001-06-06 20:29:01 +0000984
985//===----------------------------------------------------------------------===//
Chris Lattner2f7c9632001-06-06 20:29:01 +0000986// isValueValidForType implementations
987
Chris Lattner229907c2011-07-18 04:54:35 +0000988bool ConstantInt::isValueValidForType(Type *Ty, uint64_t Val) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000989 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
Owen Anderson55f1c092009-08-13 21:58:54 +0000990 if (Ty == Type::getInt1Ty(Ty->getContext()))
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000991 return Val == 0 || Val == 1;
Reid Spencerd7a00d72007-02-05 23:47:56 +0000992 if (NumBits >= 64)
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000993 return true; // always true, has to fit in largest type
994 uint64_t Max = (1ll << NumBits) - 1;
995 return Val <= Max;
Reid Spencere7334722006-12-19 01:28:19 +0000996}
997
Chris Lattner229907c2011-07-18 04:54:35 +0000998bool ConstantInt::isValueValidForType(Type *Ty, int64_t Val) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000999 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
Owen Anderson55f1c092009-08-13 21:58:54 +00001000 if (Ty == Type::getInt1Ty(Ty->getContext()))
Reid Spencera94d3942007-01-19 21:13:56 +00001001 return Val == 0 || Val == 1 || Val == -1;
Reid Spencerd7a00d72007-02-05 23:47:56 +00001002 if (NumBits >= 64)
Reid Spencer7a9c62b2007-01-12 07:05:14 +00001003 return true; // always true, has to fit in largest type
1004 int64_t Min = -(1ll << (NumBits-1));
1005 int64_t Max = (1ll << (NumBits-1)) - 1;
1006 return (Val >= Min && Val <= Max);
Chris Lattner2f7c9632001-06-06 20:29:01 +00001007}
1008
Chris Lattner229907c2011-07-18 04:54:35 +00001009bool ConstantFP::isValueValidForType(Type *Ty, const APFloat& Val) {
Dale Johannesend246b2c2007-08-30 00:23:21 +00001010 // convert modifies in place, so make a copy.
1011 APFloat Val2 = APFloat(Val);
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001012 bool losesInfo;
Chris Lattner6b727592004-06-17 18:19:28 +00001013 switch (Ty->getTypeID()) {
Chris Lattner2f7c9632001-06-06 20:29:01 +00001014 default:
1015 return false; // These can't be represented as floating point!
1016
Dale Johannesend246b2c2007-08-30 00:23:21 +00001017 // FIXME rounding mode needs to be more flexible
Dan Gohman518cda42011-12-17 00:04:22 +00001018 case Type::HalfTyID: {
1019 if (&Val2.getSemantics() == &APFloat::IEEEhalf)
1020 return true;
1021 Val2.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven, &losesInfo);
1022 return !losesInfo;
1023 }
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001024 case Type::FloatTyID: {
1025 if (&Val2.getSemantics() == &APFloat::IEEEsingle)
1026 return true;
1027 Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &losesInfo);
1028 return !losesInfo;
1029 }
1030 case Type::DoubleTyID: {
Dan Gohman518cda42011-12-17 00:04:22 +00001031 if (&Val2.getSemantics() == &APFloat::IEEEhalf ||
1032 &Val2.getSemantics() == &APFloat::IEEEsingle ||
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001033 &Val2.getSemantics() == &APFloat::IEEEdouble)
1034 return true;
1035 Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &losesInfo);
1036 return !losesInfo;
1037 }
Dale Johannesenbdad8092007-08-09 22:51:36 +00001038 case Type::X86_FP80TyID:
Dan Gohman518cda42011-12-17 00:04:22 +00001039 return &Val2.getSemantics() == &APFloat::IEEEhalf ||
1040 &Val2.getSemantics() == &APFloat::IEEEsingle ||
Dale Johannesen028084e2007-09-12 03:30:33 +00001041 &Val2.getSemantics() == &APFloat::IEEEdouble ||
1042 &Val2.getSemantics() == &APFloat::x87DoubleExtended;
Dale Johannesenbdad8092007-08-09 22:51:36 +00001043 case Type::FP128TyID:
Dan Gohman518cda42011-12-17 00:04:22 +00001044 return &Val2.getSemantics() == &APFloat::IEEEhalf ||
1045 &Val2.getSemantics() == &APFloat::IEEEsingle ||
Dale Johannesen028084e2007-09-12 03:30:33 +00001046 &Val2.getSemantics() == &APFloat::IEEEdouble ||
1047 &Val2.getSemantics() == &APFloat::IEEEquad;
Dale Johannesen007aa372007-10-11 18:07:22 +00001048 case Type::PPC_FP128TyID:
Dan Gohman518cda42011-12-17 00:04:22 +00001049 return &Val2.getSemantics() == &APFloat::IEEEhalf ||
1050 &Val2.getSemantics() == &APFloat::IEEEsingle ||
Dale Johannesen007aa372007-10-11 18:07:22 +00001051 &Val2.getSemantics() == &APFloat::IEEEdouble ||
1052 &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
Chris Lattner2f7c9632001-06-06 20:29:01 +00001053 }
Chris Lattneraa2372562006-05-24 17:04:05 +00001054}
Chris Lattner9655e542001-07-20 19:16:02 +00001055
Chris Lattner030af792012-01-24 05:42:11 +00001056
Chris Lattner49d855c2001-09-07 16:46:31 +00001057//===----------------------------------------------------------------------===//
Chris Lattner49d855c2001-09-07 16:46:31 +00001058// Factory Function Implementation
1059
Chris Lattnerc7f9fd42012-01-23 15:20:12 +00001060ConstantAggregateZero *ConstantAggregateZero::get(Type *Ty) {
Chris Lattner13ee7952010-08-28 04:09:24 +00001061 assert((Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()) &&
Owen Andersonb292b8c2009-07-30 23:03:37 +00001062 "Cannot create an aggregate zero of non-aggregate type!");
1063
Chris Lattnerc7f9fd42012-01-23 15:20:12 +00001064 ConstantAggregateZero *&Entry = Ty->getContext().pImpl->CAZConstants[Ty];
1065 if (Entry == 0)
1066 Entry = new ConstantAggregateZero(Ty);
1067
1068 return Entry;
Owen Andersonb292b8c2009-07-30 23:03:37 +00001069}
1070
Chris Lattner030af792012-01-24 05:42:11 +00001071/// destroyConstant - Remove the constant from the constant table.
Dan Gohman92b551b2009-03-03 02:55:14 +00001072///
Owen Anderson0d2de8c2009-06-20 00:24:58 +00001073void ConstantAggregateZero::destroyConstant() {
Chris Lattnerc7f9fd42012-01-23 15:20:12 +00001074 getContext().pImpl->CAZConstants.erase(getType());
Chris Lattner9fba3da2004-02-15 05:53:04 +00001075 destroyConstantImpl();
1076}
1077
Dan Gohman92b551b2009-03-03 02:55:14 +00001078/// destroyConstant - Remove the constant from the constant table...
1079///
Owen Anderson0d2de8c2009-06-20 00:24:58 +00001080void ConstantArray::destroyConstant() {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001081 getType()->getContext().pImpl->ArrayConstants.remove(this);
Chris Lattner98fa07b2003-05-23 20:03:32 +00001082 destroyConstantImpl();
1083}
1084
Reid Spencer2546b762007-01-26 07:37:34 +00001085/// isString - This method returns true if the array is an array of i8, and
1086/// if the elements of the array are all ConstantInt's.
Chris Lattnere8dfcca2004-01-14 17:06:38 +00001087bool ConstantArray::isString() const {
Reid Spencer2546b762007-01-26 07:37:34 +00001088 // Check the element type for i8...
Duncan Sands9dff9be2010-02-15 16:12:20 +00001089 if (!getType()->getElementType()->isIntegerTy(8))
Chris Lattnere8dfcca2004-01-14 17:06:38 +00001090 return false;
1091 // Check the elements to make sure they are all integers, not constant
1092 // expressions.
1093 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1094 if (!isa<ConstantInt>(getOperand(i)))
1095 return false;
1096 return true;
1097}
1098
Evan Cheng3763c5b2006-10-26 19:15:05 +00001099/// isCString - This method returns true if the array is a string (see
Dan Gohman92b551b2009-03-03 02:55:14 +00001100/// isString) and it ends in a null byte \\0 and does not contains any other
Evan Cheng3763c5b2006-10-26 19:15:05 +00001101/// null bytes except its terminator.
Owen Andersone4dcecd2009-07-13 21:27:19 +00001102bool ConstantArray::isCString() const {
Reid Spencer2546b762007-01-26 07:37:34 +00001103 // Check the element type for i8...
Duncan Sands9dff9be2010-02-15 16:12:20 +00001104 if (!getType()->getElementType()->isIntegerTy(8))
Evan Chenge974da62006-10-26 21:48:03 +00001105 return false;
Owen Andersone4dcecd2009-07-13 21:27:19 +00001106
Evan Chenge974da62006-10-26 21:48:03 +00001107 // Last element must be a null.
Owen Andersone4dcecd2009-07-13 21:27:19 +00001108 if (!getOperand(getNumOperands()-1)->isNullValue())
Evan Chenge974da62006-10-26 21:48:03 +00001109 return false;
1110 // Other elements must be non-null integers.
1111 for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
1112 if (!isa<ConstantInt>(getOperand(i)))
Evan Cheng3763c5b2006-10-26 19:15:05 +00001113 return false;
Owen Andersone4dcecd2009-07-13 21:27:19 +00001114 if (getOperand(i)->isNullValue())
Evan Chenge974da62006-10-26 21:48:03 +00001115 return false;
1116 }
Evan Cheng3763c5b2006-10-26 19:15:05 +00001117 return true;
1118}
1119
1120
Jay Foad2a31eb42011-06-28 08:24:19 +00001121/// convertToString - Helper function for getAsString() and getAsCString().
Chris Lattnerd04e32d2011-07-17 06:01:30 +00001122static std::string convertToString(const User *U, unsigned len) {
Jay Foad2a31eb42011-06-28 08:24:19 +00001123 std::string Result;
1124 Result.reserve(len);
1125 for (unsigned i = 0; i != len; ++i)
1126 Result.push_back((char)cast<ConstantInt>(U->getOperand(i))->getZExtValue());
1127 return Result;
1128}
1129
1130/// getAsString - If this array is isString(), then this method converts the
1131/// array to an std::string and returns it. Otherwise, it asserts out.
Dan Gohman92b551b2009-03-03 02:55:14 +00001132///
Chris Lattner81fabb02002-08-26 17:53:56 +00001133std::string ConstantArray::getAsString() const {
Chris Lattnere8dfcca2004-01-14 17:06:38 +00001134 assert(isString() && "Not a string!");
Jay Foad2a31eb42011-06-28 08:24:19 +00001135 return convertToString(this, getNumOperands());
1136}
1137
1138
1139/// getAsCString - If this array is isCString(), then this method converts the
1140/// array (without the trailing null byte) to an std::string and returns it.
1141/// Otherwise, it asserts out.
1142///
1143std::string ConstantArray::getAsCString() const {
1144 assert(isCString() && "Not a string!");
1145 return convertToString(this, getNumOperands() - 1);
Chris Lattner81fabb02002-08-26 17:53:56 +00001146}
1147
1148
Chris Lattner3462ae32001-12-03 22:26:30 +00001149//---- ConstantStruct::get() implementation...
Chris Lattner49d855c2001-09-07 16:46:31 +00001150//
Chris Lattnerb50d1352003-10-05 00:17:43 +00001151
Chris Lattnerd7a73302001-10-13 06:57:33 +00001152// destroyConstant - Remove the constant from the constant table...
Chris Lattner883ad0b2001-10-03 15:39:36 +00001153//
Owen Anderson0d2de8c2009-06-20 00:24:58 +00001154void ConstantStruct::destroyConstant() {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001155 getType()->getContext().pImpl->StructConstants.remove(this);
Chris Lattnerd7a73302001-10-13 06:57:33 +00001156 destroyConstantImpl();
1157}
Chris Lattner883ad0b2001-10-03 15:39:36 +00001158
Brian Gaeke02209042004-08-20 06:00:58 +00001159// destroyConstant - Remove the constant from the constant table...
1160//
Owen Anderson0d2de8c2009-06-20 00:24:58 +00001161void ConstantVector::destroyConstant() {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001162 getType()->getContext().pImpl->VectorConstants.remove(this);
Brian Gaeke02209042004-08-20 06:00:58 +00001163 destroyConstantImpl();
1164}
1165
Dan Gohman07159202007-10-17 17:51:30 +00001166/// getSplatValue - If this is a splat constant, where all of the
1167/// elements have the same value, return that value. Otherwise return null.
Duncan Sandscf0ff032011-02-01 08:39:12 +00001168Constant *ConstantVector::getSplatValue() const {
Dan Gohman07159202007-10-17 17:51:30 +00001169 // Check out first element.
1170 Constant *Elt = getOperand(0);
1171 // Then make sure all remaining elements point to the same value.
1172 for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
Chris Lattnerd04e32d2011-07-17 06:01:30 +00001173 if (getOperand(I) != Elt)
1174 return 0;
Dan Gohman07159202007-10-17 17:51:30 +00001175 return Elt;
1176}
1177
Chris Lattner31b132c2009-10-28 00:01:44 +00001178//---- ConstantPointerNull::get() implementation.
Chris Lattnerd7a73302001-10-13 06:57:33 +00001179//
Chris Lattner98fa07b2003-05-23 20:03:32 +00001180
Chris Lattner229907c2011-07-18 04:54:35 +00001181ConstantPointerNull *ConstantPointerNull::get(PointerType *Ty) {
Chris Lattnerc7f9fd42012-01-23 15:20:12 +00001182 ConstantPointerNull *&Entry = Ty->getContext().pImpl->CPNConstants[Ty];
1183 if (Entry == 0)
1184 Entry = new ConstantPointerNull(Ty);
1185
1186 return Entry;
Chris Lattner883ad0b2001-10-03 15:39:36 +00001187}
1188
Chris Lattner0c6e0b92002-08-18 00:40:04 +00001189// destroyConstant - Remove the constant from the constant table...
1190//
Owen Anderson0d2de8c2009-06-20 00:24:58 +00001191void ConstantPointerNull::destroyConstant() {
Chris Lattnerc7f9fd42012-01-23 15:20:12 +00001192 getContext().pImpl->CPNConstants.erase(getType());
1193 // Free the constant and any dangling references to it.
Chris Lattner0c6e0b92002-08-18 00:40:04 +00001194 destroyConstantImpl();
1195}
1196
1197
Chris Lattner31b132c2009-10-28 00:01:44 +00001198//---- UndefValue::get() implementation.
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001199//
1200
Chris Lattner229907c2011-07-18 04:54:35 +00001201UndefValue *UndefValue::get(Type *Ty) {
Chris Lattnerc7f9fd42012-01-23 15:20:12 +00001202 UndefValue *&Entry = Ty->getContext().pImpl->UVConstants[Ty];
1203 if (Entry == 0)
1204 Entry = new UndefValue(Ty);
1205
1206 return Entry;
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001207}
1208
1209// destroyConstant - Remove the constant from the constant table.
1210//
Owen Anderson0d2de8c2009-06-20 00:24:58 +00001211void UndefValue::destroyConstant() {
Chris Lattnerc7f9fd42012-01-23 15:20:12 +00001212 // Free the constant and any dangling references to it.
1213 getContext().pImpl->UVConstants.erase(getType());
Chris Lattnerd5f67d82004-10-16 18:07:16 +00001214 destroyConstantImpl();
1215}
1216
Chris Lattner31b132c2009-10-28 00:01:44 +00001217//---- BlockAddress::get() implementation.
1218//
1219
1220BlockAddress *BlockAddress::get(BasicBlock *BB) {
1221 assert(BB->getParent() != 0 && "Block must have a parent");
1222 return get(BB->getParent(), BB);
1223}
1224
1225BlockAddress *BlockAddress::get(Function *F, BasicBlock *BB) {
1226 BlockAddress *&BA =
1227 F->getContext().pImpl->BlockAddresses[std::make_pair(F, BB)];
1228 if (BA == 0)
1229 BA = new BlockAddress(F, BB);
1230
1231 assert(BA->getFunction() == F && "Basic block moved between functions");
1232 return BA;
1233}
1234
1235BlockAddress::BlockAddress(Function *F, BasicBlock *BB)
1236: Constant(Type::getInt8PtrTy(F->getContext()), Value::BlockAddressVal,
1237 &Op<0>(), 2) {
Chris Lattnerc559a9f2009-11-01 03:03:03 +00001238 setOperand(0, F);
1239 setOperand(1, BB);
Chris Lattneraa99c942009-11-01 01:27:45 +00001240 BB->AdjustBlockAddressRefCount(1);
Chris Lattner31b132c2009-10-28 00:01:44 +00001241}
1242
1243
1244// destroyConstant - Remove the constant from the constant table.
1245//
1246void BlockAddress::destroyConstant() {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001247 getFunction()->getType()->getContext().pImpl
Chris Lattner31b132c2009-10-28 00:01:44 +00001248 ->BlockAddresses.erase(std::make_pair(getFunction(), getBasicBlock()));
Chris Lattneraa99c942009-11-01 01:27:45 +00001249 getBasicBlock()->AdjustBlockAddressRefCount(-1);
Chris Lattner31b132c2009-10-28 00:01:44 +00001250 destroyConstantImpl();
1251}
1252
1253void BlockAddress::replaceUsesOfWithOnConstant(Value *From, Value *To, Use *U) {
1254 // This could be replacing either the Basic Block or the Function. In either
1255 // case, we have to remove the map entry.
1256 Function *NewF = getFunction();
1257 BasicBlock *NewBB = getBasicBlock();
1258
1259 if (U == &Op<0>())
1260 NewF = cast<Function>(To);
1261 else
1262 NewBB = cast<BasicBlock>(To);
1263
1264 // See if the 'new' entry already exists, if not, just update this in place
1265 // and return early.
1266 BlockAddress *&NewBA =
1267 getContext().pImpl->BlockAddresses[std::make_pair(NewF, NewBB)];
1268 if (NewBA == 0) {
Chris Lattnerc559a9f2009-11-01 03:03:03 +00001269 getBasicBlock()->AdjustBlockAddressRefCount(-1);
1270
Chris Lattner31b132c2009-10-28 00:01:44 +00001271 // Remove the old entry, this can't cause the map to rehash (just a
1272 // tombstone will get added).
1273 getContext().pImpl->BlockAddresses.erase(std::make_pair(getFunction(),
1274 getBasicBlock()));
1275 NewBA = this;
Chris Lattnerc559a9f2009-11-01 03:03:03 +00001276 setOperand(0, NewF);
1277 setOperand(1, NewBB);
1278 getBasicBlock()->AdjustBlockAddressRefCount(1);
Chris Lattner31b132c2009-10-28 00:01:44 +00001279 return;
1280 }
1281
1282 // Otherwise, I do need to replace this with an existing value.
1283 assert(NewBA != this && "I didn't contain From!");
1284
1285 // Everyone using this now uses the replacement.
Chris Lattneraf1783f2011-07-15 06:18:52 +00001286 replaceAllUsesWith(NewBA);
Chris Lattner31b132c2009-10-28 00:01:44 +00001287
1288 destroyConstant();
1289}
1290
1291//---- ConstantExpr::get() implementations.
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001292//
Reid Spencer8d9336d2006-12-31 05:26:44 +00001293
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001294/// This is a utility function to handle folding of casts and lookup of the
Duncan Sands7d6c8ae2008-03-30 19:38:55 +00001295/// cast in the ExprConstants map. It is used by the various get* methods below.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001296static inline Constant *getFoldedCast(
Chris Lattner229907c2011-07-18 04:54:35 +00001297 Instruction::CastOps opc, Constant *C, Type *Ty) {
Chris Lattner815ae2b2003-10-07 22:19:19 +00001298 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001299 // Fold a few common cases
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00001300 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001301 return FC;
Chris Lattneracdbe712003-04-17 19:24:48 +00001302
Owen Anderson1584a292009-08-04 20:25:11 +00001303 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
1304
Vikram S. Adve4c485332002-07-15 18:19:33 +00001305 // Look up the constant in the table first to ensure uniqueness
Chris Lattner2b383d2e2003-05-13 21:37:02 +00001306 std::vector<Constant*> argVec(1, C);
Reid Spenceree3c9912006-12-04 05:19:50 +00001307 ExprMapKeyType Key(opc, argVec);
Owen Anderson2d7231d2009-06-17 18:40:29 +00001308
Owen Anderson1584a292009-08-04 20:25:11 +00001309 return pImpl->ExprConstants.getOrCreate(Ty, Key);
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001310}
Reid Spencerf37dc652006-12-05 19:14:13 +00001311
Chris Lattner229907c2011-07-18 04:54:35 +00001312Constant *ConstantExpr::getCast(unsigned oc, Constant *C, Type *Ty) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001313 Instruction::CastOps opc = Instruction::CastOps(oc);
1314 assert(Instruction::isCast(opc) && "opcode out of range");
1315 assert(C && Ty && "Null arguments to getCast");
Chris Lattner37bc78a2010-01-26 21:51:43 +00001316 assert(CastInst::castIsValid(opc, C, Ty) && "Invalid constantexpr cast!");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001317
1318 switch (opc) {
Chris Lattner37bc78a2010-01-26 21:51:43 +00001319 default:
1320 llvm_unreachable("Invalid cast opcode");
Chris Lattner37bc78a2010-01-26 21:51:43 +00001321 case Instruction::Trunc: return getTrunc(C, Ty);
1322 case Instruction::ZExt: return getZExt(C, Ty);
1323 case Instruction::SExt: return getSExt(C, Ty);
1324 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
1325 case Instruction::FPExt: return getFPExtend(C, Ty);
1326 case Instruction::UIToFP: return getUIToFP(C, Ty);
1327 case Instruction::SIToFP: return getSIToFP(C, Ty);
1328 case Instruction::FPToUI: return getFPToUI(C, Ty);
1329 case Instruction::FPToSI: return getFPToSI(C, Ty);
1330 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1331 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1332 case Instruction::BitCast: return getBitCast(C, Ty);
Chris Lattner1ece6f82005-01-01 15:59:57 +00001333 }
Reid Spencerf37dc652006-12-05 19:14:13 +00001334}
1335
Chris Lattner229907c2011-07-18 04:54:35 +00001336Constant *ConstantExpr::getZExtOrBitCast(Constant *C, Type *Ty) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001337 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
Dan Gohman3cdcc3f2010-04-12 22:12:29 +00001338 return getBitCast(C, Ty);
1339 return getZExt(C, Ty);
Reid Spencer5c140882006-12-04 20:17:56 +00001340}
1341
Chris Lattner229907c2011-07-18 04:54:35 +00001342Constant *ConstantExpr::getSExtOrBitCast(Constant *C, Type *Ty) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001343 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
Dan Gohman3cdcc3f2010-04-12 22:12:29 +00001344 return getBitCast(C, Ty);
1345 return getSExt(C, Ty);
Reid Spencer5c140882006-12-04 20:17:56 +00001346}
1347
Chris Lattner229907c2011-07-18 04:54:35 +00001348Constant *ConstantExpr::getTruncOrBitCast(Constant *C, Type *Ty) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001349 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
Dan Gohman3cdcc3f2010-04-12 22:12:29 +00001350 return getBitCast(C, Ty);
1351 return getTrunc(C, Ty);
Reid Spencer5c140882006-12-04 20:17:56 +00001352}
1353
Chris Lattner229907c2011-07-18 04:54:35 +00001354Constant *ConstantExpr::getPointerCast(Constant *S, Type *Ty) {
Duncan Sands19d0b472010-02-16 11:11:14 +00001355 assert(S->getType()->isPointerTy() && "Invalid cast");
1356 assert((Ty->isIntegerTy() || Ty->isPointerTy()) && "Invalid cast");
Reid Spencerbc245a02006-12-05 03:25:26 +00001357
Duncan Sands9dff9be2010-02-15 16:12:20 +00001358 if (Ty->isIntegerTy())
Dan Gohman3cdcc3f2010-04-12 22:12:29 +00001359 return getPtrToInt(S, Ty);
1360 return getBitCast(S, Ty);
Reid Spencerbc245a02006-12-05 03:25:26 +00001361}
1362
Chris Lattner229907c2011-07-18 04:54:35 +00001363Constant *ConstantExpr::getIntegerCast(Constant *C, Type *Ty,
Reid Spencer56521c42006-12-12 00:51:07 +00001364 bool isSigned) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00001365 assert(C->getType()->isIntOrIntVectorTy() &&
1366 Ty->isIntOrIntVectorTy() && "Invalid cast");
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001367 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1368 unsigned DstBits = Ty->getScalarSizeInBits();
Reid Spencer56521c42006-12-12 00:51:07 +00001369 Instruction::CastOps opcode =
1370 (SrcBits == DstBits ? Instruction::BitCast :
1371 (SrcBits > DstBits ? Instruction::Trunc :
1372 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1373 return getCast(opcode, C, Ty);
1374}
1375
Chris Lattner229907c2011-07-18 04:54:35 +00001376Constant *ConstantExpr::getFPCast(Constant *C, Type *Ty) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00001377 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
Reid Spencer56521c42006-12-12 00:51:07 +00001378 "Invalid cast");
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001379 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1380 unsigned DstBits = Ty->getScalarSizeInBits();
Reid Spencerca104e82006-12-12 05:38:50 +00001381 if (SrcBits == DstBits)
1382 return C; // Avoid a useless cast
Reid Spencer56521c42006-12-12 00:51:07 +00001383 Instruction::CastOps opcode =
Jay Foad9f32cfd2011-01-27 14:44:55 +00001384 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
Reid Spencer56521c42006-12-12 00:51:07 +00001385 return getCast(opcode, C, Ty);
1386}
1387
Chris Lattner229907c2011-07-18 04:54:35 +00001388Constant *ConstantExpr::getTrunc(Constant *C, Type *Ty) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001389#ifndef NDEBUG
1390 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1391 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1392#endif
1393 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001394 assert(C->getType()->isIntOrIntVectorTy() && "Trunc operand must be integer");
1395 assert(Ty->isIntOrIntVectorTy() && "Trunc produces only integral");
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001396 assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001397 "SrcTy must be larger than DestTy for Trunc!");
1398
Owen Anderson0d2de8c2009-06-20 00:24:58 +00001399 return getFoldedCast(Instruction::Trunc, C, Ty);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001400}
1401
Chris Lattner229907c2011-07-18 04:54:35 +00001402Constant *ConstantExpr::getSExt(Constant *C, Type *Ty) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001403#ifndef NDEBUG
1404 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1405 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1406#endif
1407 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001408 assert(C->getType()->isIntOrIntVectorTy() && "SExt operand must be integral");
1409 assert(Ty->isIntOrIntVectorTy() && "SExt produces only integer");
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001410 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001411 "SrcTy must be smaller than DestTy for SExt!");
1412
Owen Anderson0d2de8c2009-06-20 00:24:58 +00001413 return getFoldedCast(Instruction::SExt, C, Ty);
Chris Lattnerdd284742004-04-04 23:20:30 +00001414}
1415
Chris Lattner229907c2011-07-18 04:54:35 +00001416Constant *ConstantExpr::getZExt(Constant *C, Type *Ty) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001417#ifndef NDEBUG
1418 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1419 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1420#endif
1421 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001422 assert(C->getType()->isIntOrIntVectorTy() && "ZEXt operand must be integral");
1423 assert(Ty->isIntOrIntVectorTy() && "ZExt produces only integer");
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001424 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001425 "SrcTy must be smaller than DestTy for ZExt!");
1426
Owen Anderson0d2de8c2009-06-20 00:24:58 +00001427 return getFoldedCast(Instruction::ZExt, C, Ty);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001428}
1429
Chris Lattner229907c2011-07-18 04:54:35 +00001430Constant *ConstantExpr::getFPTrunc(Constant *C, Type *Ty) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001431#ifndef NDEBUG
1432 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1433 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1434#endif
1435 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001436 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001437 C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001438 "This is an illegal floating point truncation!");
Owen Anderson0d2de8c2009-06-20 00:24:58 +00001439 return getFoldedCast(Instruction::FPTrunc, C, Ty);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001440}
1441
Chris Lattner229907c2011-07-18 04:54:35 +00001442Constant *ConstantExpr::getFPExtend(Constant *C, Type *Ty) {
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001443#ifndef NDEBUG
1444 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1445 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1446#endif
1447 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001448 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001449 C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001450 "This is an illegal floating point extension!");
Owen Anderson0d2de8c2009-06-20 00:24:58 +00001451 return getFoldedCast(Instruction::FPExt, C, Ty);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001452}
1453
Chris Lattner229907c2011-07-18 04:54:35 +00001454Constant *ConstantExpr::getUIToFP(Constant *C, Type *Ty) {
Devang Pateld26344d2008-11-03 23:20:04 +00001455#ifndef NDEBUG
Nate Begemand4d45c22007-11-17 03:58:34 +00001456 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1457 bool toVec = Ty->getTypeID() == Type::VectorTyID;
Devang Pateld26344d2008-11-03 23:20:04 +00001458#endif
Nate Begemand4d45c22007-11-17 03:58:34 +00001459 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001460 assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
Nate Begemand4d45c22007-11-17 03:58:34 +00001461 "This is an illegal uint to floating point cast!");
Owen Anderson0d2de8c2009-06-20 00:24:58 +00001462 return getFoldedCast(Instruction::UIToFP, C, Ty);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001463}
1464
Chris Lattner229907c2011-07-18 04:54:35 +00001465Constant *ConstantExpr::getSIToFP(Constant *C, Type *Ty) {
Devang Pateld26344d2008-11-03 23:20:04 +00001466#ifndef NDEBUG
Nate Begemand4d45c22007-11-17 03:58:34 +00001467 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1468 bool toVec = Ty->getTypeID() == Type::VectorTyID;
Devang Pateld26344d2008-11-03 23:20:04 +00001469#endif
Nate Begemand4d45c22007-11-17 03:58:34 +00001470 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001471 assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001472 "This is an illegal sint to floating point cast!");
Owen Anderson0d2de8c2009-06-20 00:24:58 +00001473 return getFoldedCast(Instruction::SIToFP, C, Ty);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001474}
1475
Chris Lattner229907c2011-07-18 04:54:35 +00001476Constant *ConstantExpr::getFPToUI(Constant *C, Type *Ty) {
Devang Pateld26344d2008-11-03 23:20:04 +00001477#ifndef NDEBUG
Nate Begemand4d45c22007-11-17 03:58:34 +00001478 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1479 bool toVec = Ty->getTypeID() == Type::VectorTyID;
Devang Pateld26344d2008-11-03 23:20:04 +00001480#endif
Nate Begemand4d45c22007-11-17 03:58:34 +00001481 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001482 assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
Nate Begemand4d45c22007-11-17 03:58:34 +00001483 "This is an illegal floating point to uint cast!");
Owen Anderson0d2de8c2009-06-20 00:24:58 +00001484 return getFoldedCast(Instruction::FPToUI, C, Ty);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001485}
1486
Chris Lattner229907c2011-07-18 04:54:35 +00001487Constant *ConstantExpr::getFPToSI(Constant *C, Type *Ty) {
Devang Pateld26344d2008-11-03 23:20:04 +00001488#ifndef NDEBUG
Nate Begemand4d45c22007-11-17 03:58:34 +00001489 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1490 bool toVec = Ty->getTypeID() == Type::VectorTyID;
Devang Pateld26344d2008-11-03 23:20:04 +00001491#endif
Nate Begemand4d45c22007-11-17 03:58:34 +00001492 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001493 assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
Nate Begemand4d45c22007-11-17 03:58:34 +00001494 "This is an illegal floating point to sint cast!");
Owen Anderson0d2de8c2009-06-20 00:24:58 +00001495 return getFoldedCast(Instruction::FPToSI, C, Ty);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001496}
1497
Chris Lattner229907c2011-07-18 04:54:35 +00001498Constant *ConstantExpr::getPtrToInt(Constant *C, Type *DstTy) {
Nadav Rotem3924cb02011-12-05 06:29:09 +00001499 assert(C->getType()->getScalarType()->isPointerTy() &&
1500 "PtrToInt source must be pointer or pointer vector");
1501 assert(DstTy->getScalarType()->isIntegerTy() &&
1502 "PtrToInt destination must be integer or integer vector");
Chris Lattner8a3df542012-01-25 01:32:59 +00001503 assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
1504 if (VectorType *VT = dyn_cast<VectorType>(C->getType()))
1505 assert(VT->getNumElements() == cast<VectorType>(DstTy)->getNumElements() &&
1506 "Invalid cast between a different number of vector elements");
Owen Anderson0d2de8c2009-06-20 00:24:58 +00001507 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001508}
1509
Chris Lattner229907c2011-07-18 04:54:35 +00001510Constant *ConstantExpr::getIntToPtr(Constant *C, Type *DstTy) {
Nadav Rotem3924cb02011-12-05 06:29:09 +00001511 assert(C->getType()->getScalarType()->isIntegerTy() &&
1512 "IntToPtr source must be integer or integer vector");
1513 assert(DstTy->getScalarType()->isPointerTy() &&
1514 "IntToPtr destination must be a pointer or pointer vector");
Chris Lattner8a3df542012-01-25 01:32:59 +00001515 assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
1516 if (VectorType *VT = dyn_cast<VectorType>(C->getType()))
1517 assert(VT->getNumElements() == cast<VectorType>(DstTy)->getNumElements() &&
1518 "Invalid cast between a different number of vector elements");
Owen Anderson0d2de8c2009-06-20 00:24:58 +00001519 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001520}
1521
Chris Lattner229907c2011-07-18 04:54:35 +00001522Constant *ConstantExpr::getBitCast(Constant *C, Type *DstTy) {
Chris Lattner37bc78a2010-01-26 21:51:43 +00001523 assert(CastInst::castIsValid(Instruction::BitCast, C, DstTy) &&
1524 "Invalid constantexpr bitcast!");
Chris Lattnercbeda872009-03-21 06:55:54 +00001525
1526 // It is common to ask for a bitcast of a value to its own type, handle this
1527 // speedily.
1528 if (C->getType() == DstTy) return C;
1529
Owen Anderson0d2de8c2009-06-20 00:24:58 +00001530 return getFoldedCast(Instruction::BitCast, C, DstTy);
Chris Lattnerdd284742004-04-04 23:20:30 +00001531}
1532
Chris Lattner887ecac2011-07-09 18:23:52 +00001533Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2,
1534 unsigned Flags) {
1535 // Check the operands for consistency first.
Reid Spencer7eb55b32006-11-02 01:53:59 +00001536 assert(Opcode >= Instruction::BinaryOpsBegin &&
1537 Opcode < Instruction::BinaryOpsEnd &&
Chris Lattner38a9bcd2003-05-21 17:49:25 +00001538 "Invalid opcode in binary constant expression");
1539 assert(C1->getType() == C2->getType() &&
1540 "Operand types in binary constant expression should match");
Owen Anderson61794042009-06-17 20:10:08 +00001541
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001542#ifndef NDEBUG
1543 switch (Opcode) {
Dan Gohmana5b96452009-06-04 22:49:04 +00001544 case Instruction::Add:
Reid Spencer7eb55b32006-11-02 01:53:59 +00001545 case Instruction::Sub:
Dan Gohmana5b96452009-06-04 22:49:04 +00001546 case Instruction::Mul:
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001547 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001548 assert(C1->getType()->isIntOrIntVectorTy() &&
Dan Gohmana5b96452009-06-04 22:49:04 +00001549 "Tried to create an integer operation on a non-integer type!");
1550 break;
1551 case Instruction::FAdd:
1552 case Instruction::FSub:
1553 case Instruction::FMul:
1554 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001555 assert(C1->getType()->isFPOrFPVectorTy() &&
Dan Gohmana5b96452009-06-04 22:49:04 +00001556 "Tried to create a floating-point operation on a "
1557 "non-floating-point type!");
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001558 break;
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001559 case Instruction::UDiv:
1560 case Instruction::SDiv:
1561 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001562 assert(C1->getType()->isIntOrIntVectorTy() &&
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001563 "Tried to create an arithmetic operation on a non-arithmetic type!");
1564 break;
1565 case Instruction::FDiv:
1566 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001567 assert(C1->getType()->isFPOrFPVectorTy() &&
Dan Gohman7889f2b2009-06-15 22:25:12 +00001568 "Tried to create an arithmetic operation on a non-arithmetic type!");
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001569 break;
Reid Spencer7eb55b32006-11-02 01:53:59 +00001570 case Instruction::URem:
1571 case Instruction::SRem:
1572 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001573 assert(C1->getType()->isIntOrIntVectorTy() &&
Reid Spencer7eb55b32006-11-02 01:53:59 +00001574 "Tried to create an arithmetic operation on a non-arithmetic type!");
1575 break;
1576 case Instruction::FRem:
1577 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001578 assert(C1->getType()->isFPOrFPVectorTy() &&
Dan Gohman7889f2b2009-06-15 22:25:12 +00001579 "Tried to create an arithmetic operation on a non-arithmetic type!");
Reid Spencer7eb55b32006-11-02 01:53:59 +00001580 break;
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001581 case Instruction::And:
1582 case Instruction::Or:
1583 case Instruction::Xor:
1584 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001585 assert(C1->getType()->isIntOrIntVectorTy() &&
Misha Brukman3852f652005-01-27 06:46:38 +00001586 "Tried to create a logical operation on a non-integral type!");
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001587 break;
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001588 case Instruction::Shl:
Reid Spencerfdff9382006-11-08 06:47:33 +00001589 case Instruction::LShr:
1590 case Instruction::AShr:
Reid Spencer2341c222007-02-02 02:16:23 +00001591 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001592 assert(C1->getType()->isIntOrIntVectorTy() &&
Chris Lattnercaf3f3e2004-08-17 17:28:46 +00001593 "Tried to create a shift operation on a non-integer type!");
1594 break;
1595 default:
1596 break;
1597 }
1598#endif
1599
Chris Lattner887ecac2011-07-09 18:23:52 +00001600 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1601 return FC; // Fold a few common cases.
1602
1603 std::vector<Constant*> argVec(1, C1);
1604 argVec.push_back(C2);
1605 ExprMapKeyType Key(Opcode, argVec, 0, Flags);
1606
1607 LLVMContextImpl *pImpl = C1->getContext().pImpl;
1608 return pImpl->ExprConstants.getOrCreate(C1->getType(), Key);
Reid Spencera009d0d2006-12-04 21:35:24 +00001609}
1610
Chris Lattner229907c2011-07-18 04:54:35 +00001611Constant *ConstantExpr::getSizeOf(Type* Ty) {
Owen Anderson487375e2009-07-29 18:55:55 +00001612 // sizeof is implemented as: (i64) gep (Ty*)null, 1
1613 // Note that a non-inbounds gep is used, as null isn't within any object.
Owen Anderson55f1c092009-08-13 21:58:54 +00001614 Constant *GEPIdx = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
Owen Anderson487375e2009-07-29 18:55:55 +00001615 Constant *GEP = getGetElementPtr(
Jay Foaded8db7d2011-07-21 14:31:17 +00001616 Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx);
Dan Gohman3cdcc3f2010-04-12 22:12:29 +00001617 return getPtrToInt(GEP,
1618 Type::getInt64Ty(Ty->getContext()));
Owen Anderson487375e2009-07-29 18:55:55 +00001619}
1620
Chris Lattner229907c2011-07-18 04:54:35 +00001621Constant *ConstantExpr::getAlignOf(Type* Ty) {
Dan Gohmancf913832010-01-28 02:15:55 +00001622 // alignof is implemented as: (i64) gep ({i1,Ty}*)null, 0, 1
Dan Gohman50c09d02009-08-11 17:57:01 +00001623 // Note that a non-inbounds gep is used, as null isn't within any object.
Chris Lattner229907c2011-07-18 04:54:35 +00001624 Type *AligningTy =
Chris Lattnerf3f545e2011-06-18 22:48:56 +00001625 StructType::get(Type::getInt1Ty(Ty->getContext()), Ty, NULL);
Owen Anderson5a1acd92009-07-31 20:28:14 +00001626 Constant *NullPtr = Constant::getNullValue(AligningTy->getPointerTo());
Dan Gohmana9be7392010-01-28 02:43:22 +00001627 Constant *Zero = ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0);
Owen Anderson55f1c092009-08-13 21:58:54 +00001628 Constant *One = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
Owen Anderson487375e2009-07-29 18:55:55 +00001629 Constant *Indices[2] = { Zero, One };
Jay Foaded8db7d2011-07-21 14:31:17 +00001630 Constant *GEP = getGetElementPtr(NullPtr, Indices);
Dan Gohman3cdcc3f2010-04-12 22:12:29 +00001631 return getPtrToInt(GEP,
1632 Type::getInt64Ty(Ty->getContext()));
Owen Anderson487375e2009-07-29 18:55:55 +00001633}
1634
Chris Lattner229907c2011-07-18 04:54:35 +00001635Constant *ConstantExpr::getOffsetOf(StructType* STy, unsigned FieldNo) {
Dan Gohmanede94e62010-02-01 16:37:38 +00001636 return getOffsetOf(STy, ConstantInt::get(Type::getInt32Ty(STy->getContext()),
1637 FieldNo));
1638}
1639
Chris Lattner229907c2011-07-18 04:54:35 +00001640Constant *ConstantExpr::getOffsetOf(Type* Ty, Constant *FieldNo) {
Dan Gohmanff3af7252009-08-16 21:26:11 +00001641 // offsetof is implemented as: (i64) gep (Ty*)null, 0, FieldNo
1642 // Note that a non-inbounds gep is used, as null isn't within any object.
1643 Constant *GEPIdx[] = {
Dan Gohmanede94e62010-02-01 16:37:38 +00001644 ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0),
1645 FieldNo
Dan Gohmanff3af7252009-08-16 21:26:11 +00001646 };
1647 Constant *GEP = getGetElementPtr(
Jay Foaded8db7d2011-07-21 14:31:17 +00001648 Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx);
Dan Gohman3cdcc3f2010-04-12 22:12:29 +00001649 return getPtrToInt(GEP,
1650 Type::getInt64Ty(Ty->getContext()));
Dan Gohmanff3af7252009-08-16 21:26:11 +00001651}
Owen Anderson487375e2009-07-29 18:55:55 +00001652
Chris Lattner887ecac2011-07-09 18:23:52 +00001653Constant *ConstantExpr::getCompare(unsigned short Predicate,
1654 Constant *C1, Constant *C2) {
Reid Spencera009d0d2006-12-04 21:35:24 +00001655 assert(C1->getType() == C2->getType() && "Op types should be identical!");
Chris Lattner887ecac2011-07-09 18:23:52 +00001656
1657 switch (Predicate) {
1658 default: llvm_unreachable("Invalid CmpInst predicate");
1659 case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
1660 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
1661 case CmpInst::FCMP_ONE: case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
1662 case CmpInst::FCMP_UEQ: case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
1663 case CmpInst::FCMP_ULT: case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
1664 case CmpInst::FCMP_TRUE:
1665 return getFCmp(Predicate, C1, C2);
1666
1667 case CmpInst::ICMP_EQ: case CmpInst::ICMP_NE: case CmpInst::ICMP_UGT:
1668 case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
1669 case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
1670 case CmpInst::ICMP_SLE:
1671 return getICmp(Predicate, C1, C2);
1672 }
Chris Lattner29ca2c62004-08-04 18:50:09 +00001673}
1674
Chris Lattner887ecac2011-07-09 18:23:52 +00001675Constant *ConstantExpr::getSelect(Constant *C, Constant *V1, Constant *V2) {
Chris Lattner41632132008-12-29 00:16:12 +00001676 assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
Chris Lattner6e415c02004-03-12 05:54:04 +00001677
Chris Lattner887ecac2011-07-09 18:23:52 +00001678 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1679 return SC; // Fold common cases
Chris Lattner6e415c02004-03-12 05:54:04 +00001680
1681 std::vector<Constant*> argVec(3, C);
1682 argVec[1] = V1;
1683 argVec[2] = V2;
Reid Spenceree3c9912006-12-04 05:19:50 +00001684 ExprMapKeyType Key(Instruction::Select, argVec);
Owen Anderson61794042009-06-17 20:10:08 +00001685
Chris Lattner887ecac2011-07-09 18:23:52 +00001686 LLVMContextImpl *pImpl = C->getContext().pImpl;
1687 return pImpl->ExprConstants.getOrCreate(V1->getType(), Key);
Chris Lattner6e415c02004-03-12 05:54:04 +00001688}
1689
Jay Foaded8db7d2011-07-21 14:31:17 +00001690Constant *ConstantExpr::getGetElementPtr(Constant *C, ArrayRef<Value *> Idxs,
1691 bool InBounds) {
1692 if (Constant *FC = ConstantFoldGetElementPtr(C, InBounds, Idxs))
Chris Lattner94c8d292011-02-11 05:34:33 +00001693 return FC; // Fold a few common cases.
Dan Gohman1b849082009-09-07 23:54:19 +00001694
Chris Lattner887ecac2011-07-09 18:23:52 +00001695 // Get the result type of the getelementptr!
Jay Foadd1b78492011-07-25 09:48:08 +00001696 Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), Idxs);
Chris Lattner887ecac2011-07-09 18:23:52 +00001697 assert(Ty && "GEP indices invalid!");
1698 unsigned AS = cast<PointerType>(C->getType())->getAddressSpace();
1699 Type *ReqTy = Ty->getPointerTo(AS);
1700
Duncan Sands19d0b472010-02-16 11:11:14 +00001701 assert(C->getType()->isPointerTy() &&
Dan Gohman1b849082009-09-07 23:54:19 +00001702 "Non-pointer type for constant GetElementPtr expression");
1703 // Look up the constant in the table first to ensure uniqueness
1704 std::vector<Constant*> ArgVec;
Jay Foaded8db7d2011-07-21 14:31:17 +00001705 ArgVec.reserve(1 + Idxs.size());
Dan Gohman1b849082009-09-07 23:54:19 +00001706 ArgVec.push_back(C);
Jay Foaded8db7d2011-07-21 14:31:17 +00001707 for (unsigned i = 0, e = Idxs.size(); i != e; ++i)
Dan Gohman1b849082009-09-07 23:54:19 +00001708 ArgVec.push_back(cast<Constant>(Idxs[i]));
1709 const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec, 0,
Chris Lattner94c8d292011-02-11 05:34:33 +00001710 InBounds ? GEPOperator::IsInBounds : 0);
Chris Lattner887ecac2011-07-09 18:23:52 +00001711
1712 LLVMContextImpl *pImpl = C->getContext().pImpl;
Dan Gohman1b849082009-09-07 23:54:19 +00001713 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1714}
1715
Reid Spenceree3c9912006-12-04 05:19:50 +00001716Constant *
Nick Lewycky9e26c1c2010-01-21 07:03:21 +00001717ConstantExpr::getICmp(unsigned short pred, Constant *LHS, Constant *RHS) {
Reid Spenceree3c9912006-12-04 05:19:50 +00001718 assert(LHS->getType() == RHS->getType());
1719 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
1720 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
1721
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00001722 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
Reid Spenceree3c9912006-12-04 05:19:50 +00001723 return FC; // Fold a few common cases...
1724
1725 // Look up the constant in the table first to ensure uniqueness
1726 std::vector<Constant*> ArgVec;
1727 ArgVec.push_back(LHS);
1728 ArgVec.push_back(RHS);
Reid Spencerb1537492006-12-24 18:42:29 +00001729 // Get the key type with both the opcode and predicate
Reid Spenceree3c9912006-12-04 05:19:50 +00001730 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
Owen Anderson61794042009-06-17 20:10:08 +00001731
Chris Lattner229907c2011-07-18 04:54:35 +00001732 Type *ResultTy = Type::getInt1Ty(LHS->getContext());
1733 if (VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
Nick Lewycky9e26c1c2010-01-21 07:03:21 +00001734 ResultTy = VectorType::get(ResultTy, VT->getNumElements());
1735
Owen Anderson1584a292009-08-04 20:25:11 +00001736 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
Nick Lewycky9e26c1c2010-01-21 07:03:21 +00001737 return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
Reid Spenceree3c9912006-12-04 05:19:50 +00001738}
1739
1740Constant *
Nick Lewycky9e26c1c2010-01-21 07:03:21 +00001741ConstantExpr::getFCmp(unsigned short pred, Constant *LHS, Constant *RHS) {
Reid Spenceree3c9912006-12-04 05:19:50 +00001742 assert(LHS->getType() == RHS->getType());
1743 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
1744
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00001745 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
Reid Spenceree3c9912006-12-04 05:19:50 +00001746 return FC; // Fold a few common cases...
1747
1748 // Look up the constant in the table first to ensure uniqueness
1749 std::vector<Constant*> ArgVec;
1750 ArgVec.push_back(LHS);
1751 ArgVec.push_back(RHS);
Reid Spencerb1537492006-12-24 18:42:29 +00001752 // Get the key type with both the opcode and predicate
Reid Spenceree3c9912006-12-04 05:19:50 +00001753 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
Nick Lewycky9e26c1c2010-01-21 07:03:21 +00001754
Chris Lattner229907c2011-07-18 04:54:35 +00001755 Type *ResultTy = Type::getInt1Ty(LHS->getContext());
1756 if (VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
Nick Lewycky9e26c1c2010-01-21 07:03:21 +00001757 ResultTy = VectorType::get(ResultTy, VT->getNumElements());
1758
Owen Anderson1584a292009-08-04 20:25:11 +00001759 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
Nick Lewycky9e26c1c2010-01-21 07:03:21 +00001760 return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
Reid Spenceree3c9912006-12-04 05:19:50 +00001761}
1762
Robert Bocchino23004482006-01-10 19:05:34 +00001763Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
Duncan Sands19d0b472010-02-16 11:11:14 +00001764 assert(Val->getType()->isVectorTy() &&
Reid Spencer09575ba2007-02-15 03:39:18 +00001765 "Tried to create extractelement operation on non-vector type!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001766 assert(Idx->getType()->isIntegerTy(32) &&
Reid Spencer2546b762007-01-26 07:37:34 +00001767 "Extractelement index must be i32 type!");
Chris Lattner887ecac2011-07-09 18:23:52 +00001768
1769 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
Chris Lattner09660c92009-12-30 20:25:09 +00001770 return FC; // Fold a few common cases.
Chris Lattner887ecac2011-07-09 18:23:52 +00001771
Robert Bocchinoca27f032006-01-17 20:07:22 +00001772 // Look up the constant in the table first to ensure uniqueness
1773 std::vector<Constant*> ArgVec(1, Val);
Robert Bocchinoca27f032006-01-17 20:07:22 +00001774 ArgVec.push_back(Idx);
Chris Lattner887ecac2011-07-09 18:23:52 +00001775 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
Owen Anderson61794042009-06-17 20:10:08 +00001776
Chris Lattner887ecac2011-07-09 18:23:52 +00001777 LLVMContextImpl *pImpl = Val->getContext().pImpl;
1778 Type *ReqTy = cast<VectorType>(Val->getType())->getElementType();
Owen Anderson1584a292009-08-04 20:25:11 +00001779 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
Robert Bocchinoca27f032006-01-17 20:07:22 +00001780}
1781
1782Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
1783 Constant *Idx) {
Duncan Sands19d0b472010-02-16 11:11:14 +00001784 assert(Val->getType()->isVectorTy() &&
Reid Spencer09575ba2007-02-15 03:39:18 +00001785 "Tried to create insertelement operation on non-vector type!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00001786 assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType()
Robert Bocchinoca27f032006-01-17 20:07:22 +00001787 && "Insertelement types must match!");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001788 assert(Idx->getType()->isIntegerTy(32) &&
Reid Spencer2546b762007-01-26 07:37:34 +00001789 "Insertelement index must be i32 type!");
Robert Bocchinoca27f032006-01-17 20:07:22 +00001790
Chris Lattner887ecac2011-07-09 18:23:52 +00001791 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
1792 return FC; // Fold a few common cases.
Chris Lattnerbbe0a422006-04-08 01:18:18 +00001793 // Look up the constant in the table first to ensure uniqueness
Chris Lattner887ecac2011-07-09 18:23:52 +00001794 std::vector<Constant*> ArgVec(1, Val);
1795 ArgVec.push_back(Elt);
1796 ArgVec.push_back(Idx);
1797 const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
Owen Anderson61794042009-06-17 20:10:08 +00001798
Chris Lattner887ecac2011-07-09 18:23:52 +00001799 LLVMContextImpl *pImpl = Val->getContext().pImpl;
1800 return pImpl->ExprConstants.getOrCreate(Val->getType(), Key);
Chris Lattnerbbe0a422006-04-08 01:18:18 +00001801}
1802
1803Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
1804 Constant *Mask) {
1805 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
1806 "Invalid shuffle vector constant expr operands!");
Nate Begeman94aa38d2009-02-12 21:28:33 +00001807
Chris Lattner887ecac2011-07-09 18:23:52 +00001808 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
1809 return FC; // Fold a few common cases.
1810
Nate Begeman94aa38d2009-02-12 21:28:33 +00001811 unsigned NElts = cast<VectorType>(Mask->getType())->getNumElements();
Chris Lattner229907c2011-07-18 04:54:35 +00001812 Type *EltTy = cast<VectorType>(V1->getType())->getElementType();
1813 Type *ShufTy = VectorType::get(EltTy, NElts);
Chris Lattner887ecac2011-07-09 18:23:52 +00001814
1815 // Look up the constant in the table first to ensure uniqueness
1816 std::vector<Constant*> ArgVec(1, V1);
1817 ArgVec.push_back(V2);
1818 ArgVec.push_back(Mask);
1819 const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
1820
1821 LLVMContextImpl *pImpl = ShufTy->getContext().pImpl;
1822 return pImpl->ExprConstants.getOrCreate(ShufTy, Key);
Chris Lattnerbbe0a422006-04-08 01:18:18 +00001823}
1824
Chris Lattner887ecac2011-07-09 18:23:52 +00001825Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
Jay Foad57aa6362011-07-13 10:26:04 +00001826 ArrayRef<unsigned> Idxs) {
1827 assert(ExtractValueInst::getIndexedType(Agg->getType(),
1828 Idxs) == Val->getType() &&
Dan Gohman12fce772008-05-15 19:50:34 +00001829 "insertvalue indices invalid!");
Dan Gohman0752bff2008-05-23 00:36:11 +00001830 assert(Agg->getType()->isFirstClassType() &&
Chris Lattner6ebfbf52011-07-12 05:26:21 +00001831 "Non-first-class type for constant insertvalue expression");
Jay Foad57aa6362011-07-13 10:26:04 +00001832 Constant *FC = ConstantFoldInsertValueInstruction(Agg, Val, Idxs);
Chris Lattner6ebfbf52011-07-12 05:26:21 +00001833 assert(FC && "insertvalue constant expr couldn't be folded!");
Dan Gohmand5d24f62008-07-21 23:30:30 +00001834 return FC;
Dan Gohman12fce772008-05-15 19:50:34 +00001835}
1836
Chris Lattner887ecac2011-07-09 18:23:52 +00001837Constant *ConstantExpr::getExtractValue(Constant *Agg,
Jay Foad57aa6362011-07-13 10:26:04 +00001838 ArrayRef<unsigned> Idxs) {
Dan Gohman0752bff2008-05-23 00:36:11 +00001839 assert(Agg->getType()->isFirstClassType() &&
Chris Lattner887ecac2011-07-09 18:23:52 +00001840 "Tried to create extractelement operation on non-first-class type!");
Dan Gohman12fce772008-05-15 19:50:34 +00001841
Chris Lattner229907c2011-07-18 04:54:35 +00001842 Type *ReqTy = ExtractValueInst::getIndexedType(Agg->getType(), Idxs);
Chandler Carruth9db56b82011-07-10 09:45:35 +00001843 (void)ReqTy;
Chris Lattner887ecac2011-07-09 18:23:52 +00001844 assert(ReqTy && "extractvalue indices invalid!");
1845
Dan Gohman0752bff2008-05-23 00:36:11 +00001846 assert(Agg->getType()->isFirstClassType() &&
1847 "Non-first-class type for constant extractvalue expression");
Jay Foad57aa6362011-07-13 10:26:04 +00001848 Constant *FC = ConstantFoldExtractValueInstruction(Agg, Idxs);
Dan Gohmand5d24f62008-07-21 23:30:30 +00001849 assert(FC && "ExtractValue constant expr couldn't be folded!");
1850 return FC;
Dan Gohman12fce772008-05-15 19:50:34 +00001851}
1852
Chris Lattnere9b4ad72011-02-10 07:01:55 +00001853Constant *ConstantExpr::getNeg(Constant *C, bool HasNUW, bool HasNSW) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00001854 assert(C->getType()->isIntOrIntVectorTy() &&
Owen Anderson487375e2009-07-29 18:55:55 +00001855 "Cannot NEG a nonintegral value!");
Chris Lattnere9b4ad72011-02-10 07:01:55 +00001856 return getSub(ConstantFP::getZeroValueForNegation(C->getType()),
1857 C, HasNUW, HasNSW);
Owen Anderson487375e2009-07-29 18:55:55 +00001858}
1859
Chris Lattnera676c0f2011-02-07 16:40:21 +00001860Constant *ConstantExpr::getFNeg(Constant *C) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00001861 assert(C->getType()->isFPOrFPVectorTy() &&
Owen Anderson487375e2009-07-29 18:55:55 +00001862 "Cannot FNEG a non-floating-point value!");
Chris Lattnere9b4ad72011-02-10 07:01:55 +00001863 return getFSub(ConstantFP::getZeroValueForNegation(C->getType()), C);
Owen Anderson487375e2009-07-29 18:55:55 +00001864}
1865
Chris Lattnera676c0f2011-02-07 16:40:21 +00001866Constant *ConstantExpr::getNot(Constant *C) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00001867 assert(C->getType()->isIntOrIntVectorTy() &&
Owen Anderson487375e2009-07-29 18:55:55 +00001868 "Cannot NOT a nonintegral value!");
Owen Anderson5a1acd92009-07-31 20:28:14 +00001869 return get(Instruction::Xor, C, Constant::getAllOnesValue(C->getType()));
Owen Anderson487375e2009-07-29 18:55:55 +00001870}
1871
Chris Lattnere9b4ad72011-02-10 07:01:55 +00001872Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2,
1873 bool HasNUW, bool HasNSW) {
1874 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
1875 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
1876 return get(Instruction::Add, C1, C2, Flags);
Owen Anderson487375e2009-07-29 18:55:55 +00001877}
1878
Chris Lattnera676c0f2011-02-07 16:40:21 +00001879Constant *ConstantExpr::getFAdd(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00001880 return get(Instruction::FAdd, C1, C2);
1881}
1882
Chris Lattnere9b4ad72011-02-10 07:01:55 +00001883Constant *ConstantExpr::getSub(Constant *C1, Constant *C2,
1884 bool HasNUW, bool HasNSW) {
1885 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
1886 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
1887 return get(Instruction::Sub, C1, C2, Flags);
Owen Anderson487375e2009-07-29 18:55:55 +00001888}
1889
Chris Lattnera676c0f2011-02-07 16:40:21 +00001890Constant *ConstantExpr::getFSub(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00001891 return get(Instruction::FSub, C1, C2);
1892}
1893
Chris Lattnere9b4ad72011-02-10 07:01:55 +00001894Constant *ConstantExpr::getMul(Constant *C1, Constant *C2,
1895 bool HasNUW, bool HasNSW) {
1896 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
1897 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
1898 return get(Instruction::Mul, C1, C2, Flags);
Owen Anderson487375e2009-07-29 18:55:55 +00001899}
1900
Chris Lattnera676c0f2011-02-07 16:40:21 +00001901Constant *ConstantExpr::getFMul(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00001902 return get(Instruction::FMul, C1, C2);
1903}
1904
Chris Lattner0d75eac2011-02-09 16:43:07 +00001905Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2, bool isExact) {
1906 return get(Instruction::UDiv, C1, C2,
1907 isExact ? PossiblyExactOperator::IsExact : 0);
Owen Anderson487375e2009-07-29 18:55:55 +00001908}
1909
Chris Lattner0d75eac2011-02-09 16:43:07 +00001910Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2, bool isExact) {
1911 return get(Instruction::SDiv, C1, C2,
1912 isExact ? PossiblyExactOperator::IsExact : 0);
Owen Anderson487375e2009-07-29 18:55:55 +00001913}
1914
Chris Lattnera676c0f2011-02-07 16:40:21 +00001915Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00001916 return get(Instruction::FDiv, C1, C2);
1917}
1918
Chris Lattnera676c0f2011-02-07 16:40:21 +00001919Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00001920 return get(Instruction::URem, C1, C2);
1921}
1922
Chris Lattnera676c0f2011-02-07 16:40:21 +00001923Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00001924 return get(Instruction::SRem, C1, C2);
1925}
1926
Chris Lattnera676c0f2011-02-07 16:40:21 +00001927Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00001928 return get(Instruction::FRem, C1, C2);
1929}
1930
Chris Lattnera676c0f2011-02-07 16:40:21 +00001931Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00001932 return get(Instruction::And, C1, C2);
1933}
1934
Chris Lattnera676c0f2011-02-07 16:40:21 +00001935Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00001936 return get(Instruction::Or, C1, C2);
1937}
1938
Chris Lattnera676c0f2011-02-07 16:40:21 +00001939Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
Owen Anderson487375e2009-07-29 18:55:55 +00001940 return get(Instruction::Xor, C1, C2);
1941}
1942
Chris Lattnere9b4ad72011-02-10 07:01:55 +00001943Constant *ConstantExpr::getShl(Constant *C1, Constant *C2,
1944 bool HasNUW, bool HasNSW) {
1945 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
1946 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
1947 return get(Instruction::Shl, C1, C2, Flags);
Owen Anderson487375e2009-07-29 18:55:55 +00001948}
1949
Chris Lattner0d75eac2011-02-09 16:43:07 +00001950Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2, bool isExact) {
1951 return get(Instruction::LShr, C1, C2,
1952 isExact ? PossiblyExactOperator::IsExact : 0);
Owen Anderson487375e2009-07-29 18:55:55 +00001953}
1954
Chris Lattner0d75eac2011-02-09 16:43:07 +00001955Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2, bool isExact) {
1956 return get(Instruction::AShr, C1, C2,
1957 isExact ? PossiblyExactOperator::IsExact : 0);
Owen Anderson487375e2009-07-29 18:55:55 +00001958}
1959
Vikram S. Adve4c485332002-07-15 18:19:33 +00001960// destroyConstant - Remove the constant from the constant table...
1961//
Owen Anderson0d2de8c2009-06-20 00:24:58 +00001962void ConstantExpr::destroyConstant() {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001963 getType()->getContext().pImpl->ExprConstants.remove(this);
Vikram S. Adve4c485332002-07-15 18:19:33 +00001964 destroyConstantImpl();
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001965}
1966
Chris Lattner3cd8c562002-07-30 18:54:25 +00001967const char *ConstantExpr::getOpcodeName() const {
1968 return Instruction::getOpcodeName(getOpcode());
Vikram S. Adve4e537b22002-07-14 23:13:17 +00001969}
Reid Spencer1ebe1ab2004-07-17 23:48:33 +00001970
Chris Lattnera3b94ba2010-03-30 20:48:48 +00001971
1972
1973GetElementPtrConstantExpr::
1974GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
Chris Lattner229907c2011-07-18 04:54:35 +00001975 Type *DestTy)
Chris Lattnera3b94ba2010-03-30 20:48:48 +00001976 : ConstantExpr(DestTy, Instruction::GetElementPtr,
1977 OperandTraits<GetElementPtrConstantExpr>::op_end(this)
1978 - (IdxList.size()+1), IdxList.size()+1) {
1979 OperandList[0] = C;
1980 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
1981 OperandList[i+1] = IdxList[i];
1982}
1983
Chris Lattner3756b912012-01-23 22:57:10 +00001984//===----------------------------------------------------------------------===//
1985// ConstantData* implementations
1986
1987void ConstantDataArray::anchor() {}
1988void ConstantDataVector::anchor() {}
1989
Chris Lattnere4f3f102012-01-24 04:43:41 +00001990/// getElementType - Return the element type of the array/vector.
1991Type *ConstantDataSequential::getElementType() const {
1992 return getType()->getElementType();
1993}
1994
Chris Lattner5d4497b2012-01-24 09:31:43 +00001995StringRef ConstantDataSequential::getRawDataValues() const {
Chris Lattner00245f42012-01-24 13:41:11 +00001996 return StringRef(DataElements, getNumElements()*getElementByteSize());
Chris Lattner5d4497b2012-01-24 09:31:43 +00001997}
1998
Chris Lattner030af792012-01-24 05:42:11 +00001999/// isElementTypeCompatible - Return true if a ConstantDataSequential can be
2000/// formed with a vector or array of the specified element type.
2001/// ConstantDataArray only works with normal float and int types that are
2002/// stored densely in memory, not with things like i42 or x86_f80.
2003bool ConstantDataSequential::isElementTypeCompatible(const Type *Ty) {
Chris Lattnere4f3f102012-01-24 04:43:41 +00002004 if (Ty->isFloatTy() || Ty->isDoubleTy()) return true;
2005 if (const IntegerType *IT = dyn_cast<IntegerType>(Ty)) {
2006 switch (IT->getBitWidth()) {
2007 case 8:
2008 case 16:
2009 case 32:
2010 case 64:
2011 return true;
2012 default: break;
2013 }
2014 }
2015 return false;
2016}
2017
Chris Lattner00245f42012-01-24 13:41:11 +00002018/// getNumElements - Return the number of elements in the array or vector.
2019unsigned ConstantDataSequential::getNumElements() const {
Chris Lattner8a3df542012-01-25 01:32:59 +00002020 if (ArrayType *AT = dyn_cast<ArrayType>(getType()))
2021 return AT->getNumElements();
2022 return cast<VectorType>(getType())->getNumElements();
Chris Lattner00245f42012-01-24 13:41:11 +00002023}
2024
2025
Chris Lattnere4f3f102012-01-24 04:43:41 +00002026/// getElementByteSize - Return the size in bytes of the elements in the data.
2027uint64_t ConstantDataSequential::getElementByteSize() const {
2028 return getElementType()->getPrimitiveSizeInBits()/8;
2029}
2030
2031/// getElementPointer - Return the start of the specified element.
2032const char *ConstantDataSequential::getElementPointer(unsigned Elt) const {
Chris Lattner00245f42012-01-24 13:41:11 +00002033 assert(Elt < getNumElements() && "Invalid Elt");
Chris Lattnere4f3f102012-01-24 04:43:41 +00002034 return DataElements+Elt*getElementByteSize();
2035}
2036
2037
Chris Lattner3756b912012-01-23 22:57:10 +00002038/// isAllZeros - return true if the array is empty or all zeros.
2039static bool isAllZeros(StringRef Arr) {
2040 for (StringRef::iterator I = Arr.begin(), E = Arr.end(); I != E; ++I)
2041 if (*I != 0)
2042 return false;
2043 return true;
2044}
Chris Lattner030af792012-01-24 05:42:11 +00002045
Chris Lattner3756b912012-01-23 22:57:10 +00002046/// getImpl - This is the underlying implementation of all of the
2047/// ConstantDataSequential::get methods. They all thunk down to here, providing
2048/// the correct element type. We take the bytes in as an StringRef because
2049/// we *want* an underlying "char*" to avoid TBAA type punning violations.
2050Constant *ConstantDataSequential::getImpl(StringRef Elements, Type *Ty) {
Chris Lattner030af792012-01-24 05:42:11 +00002051 assert(isElementTypeCompatible(cast<SequentialType>(Ty)->getElementType()));
Chris Lattner139822f2012-01-24 14:17:05 +00002052 // If the elements are all zero or there are no elements, return a CAZ, which
2053 // is more dense and canonical.
Chris Lattner3756b912012-01-23 22:57:10 +00002054 if (isAllZeros(Elements))
2055 return ConstantAggregateZero::get(Ty);
2056
2057 // Do a lookup to see if we have already formed one of these.
2058 StringMap<ConstantDataSequential*>::MapEntryTy &Slot =
2059 Ty->getContext().pImpl->CDSConstants.GetOrCreateValue(Elements);
2060
2061 // The bucket can point to a linked list of different CDS's that have the same
2062 // body but different types. For example, 0,0,0,1 could be a 4 element array
2063 // of i8, or a 1-element array of i32. They'll both end up in the same
2064 /// StringMap bucket, linked up by their Next pointers. Walk the list.
2065 ConstantDataSequential **Entry = &Slot.getValue();
2066 for (ConstantDataSequential *Node = *Entry; Node != 0;
2067 Entry = &Node->Next, Node = *Entry)
2068 if (Node->getType() == Ty)
2069 return Node;
2070
2071 // Okay, we didn't get a hit. Create a node of the right class, link it in,
2072 // and return it.
2073 if (isa<ArrayType>(Ty))
2074 return *Entry = new ConstantDataArray(Ty, Slot.getKeyData());
2075
2076 assert(isa<VectorType>(Ty));
2077 return *Entry = new ConstantDataVector(Ty, Slot.getKeyData());
2078}
2079
2080void ConstantDataSequential::destroyConstant() {
Chris Lattner3756b912012-01-23 22:57:10 +00002081 // Remove the constant from the StringMap.
2082 StringMap<ConstantDataSequential*> &CDSConstants =
2083 getType()->getContext().pImpl->CDSConstants;
2084
2085 StringMap<ConstantDataSequential*>::iterator Slot =
Chris Lattner5d4497b2012-01-24 09:31:43 +00002086 CDSConstants.find(getRawDataValues());
Chris Lattner3756b912012-01-23 22:57:10 +00002087
2088 assert(Slot != CDSConstants.end() && "CDS not found in uniquing table");
2089
2090 ConstantDataSequential **Entry = &Slot->getValue();
2091
2092 // Remove the entry from the hash table.
2093 if ((*Entry)->Next == 0) {
2094 // If there is only one value in the bucket (common case) it must be this
2095 // entry, and removing the entry should remove the bucket completely.
2096 assert((*Entry) == this && "Hash mismatch in ConstantDataSequential");
2097 getContext().pImpl->CDSConstants.erase(Slot);
2098 } else {
2099 // Otherwise, there are multiple entries linked off the bucket, unlink the
2100 // node we care about but keep the bucket around.
2101 for (ConstantDataSequential *Node = *Entry; ;
2102 Entry = &Node->Next, Node = *Entry) {
2103 assert(Node && "Didn't find entry in its uniquing hash table!");
2104 // If we found our entry, unlink it from the list and we're done.
2105 if (Node == this) {
2106 *Entry = Node->Next;
2107 break;
2108 }
2109 }
2110 }
2111
2112 // If we were part of a list, make sure that we don't delete the list that is
2113 // still owned by the uniquing map.
2114 Next = 0;
2115
2116 // Finally, actually delete it.
2117 destroyConstantImpl();
2118}
2119
2120/// get() constructors - Return a constant with array type with an element
2121/// count and element type matching the ArrayRef passed in. Note that this
2122/// can return a ConstantAggregateZero object.
Chris Lattner20683932012-01-24 14:04:40 +00002123Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint8_t> Elts) {
Chris Lattner3756b912012-01-23 22:57:10 +00002124 Type *Ty = ArrayType::get(Type::getInt8Ty(Context), Elts.size());
2125 return getImpl(StringRef((char*)Elts.data(), Elts.size()*1), Ty);
2126}
Chris Lattner20683932012-01-24 14:04:40 +00002127Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint16_t> Elts){
Chris Lattner3756b912012-01-23 22:57:10 +00002128 Type *Ty = ArrayType::get(Type::getInt16Ty(Context), Elts.size());
2129 return getImpl(StringRef((char*)Elts.data(), Elts.size()*2), Ty);
2130}
Chris Lattner20683932012-01-24 14:04:40 +00002131Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint32_t> Elts){
Chris Lattner3756b912012-01-23 22:57:10 +00002132 Type *Ty = ArrayType::get(Type::getInt32Ty(Context), Elts.size());
2133 return getImpl(StringRef((char*)Elts.data(), Elts.size()*4), Ty);
2134}
Chris Lattner20683932012-01-24 14:04:40 +00002135Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint64_t> Elts){
Chris Lattner3756b912012-01-23 22:57:10 +00002136 Type *Ty = ArrayType::get(Type::getInt64Ty(Context), Elts.size());
2137 return getImpl(StringRef((char*)Elts.data(), Elts.size()*8), Ty);
2138}
Chris Lattner20683932012-01-24 14:04:40 +00002139Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<float> Elts) {
Chris Lattner3756b912012-01-23 22:57:10 +00002140 Type *Ty = ArrayType::get(Type::getFloatTy(Context), Elts.size());
2141 return getImpl(StringRef((char*)Elts.data(), Elts.size()*4), Ty);
2142}
Chris Lattner20683932012-01-24 14:04:40 +00002143Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<double> Elts) {
Chris Lattner3756b912012-01-23 22:57:10 +00002144 Type *Ty = ArrayType::get(Type::getDoubleTy(Context), Elts.size());
2145 return getImpl(StringRef((char*)Elts.data(), Elts.size()*8), Ty);
2146}
2147
Chris Lattner20683932012-01-24 14:04:40 +00002148/// getString - This method constructs a CDS and initializes it with a text
2149/// string. The default behavior (AddNull==true) causes a null terminator to
2150/// be placed at the end of the array (increasing the length of the string by
2151/// one more than the StringRef would normally indicate. Pass AddNull=false
2152/// to disable this behavior.
2153Constant *ConstantDataArray::getString(LLVMContext &Context,
2154 StringRef Str, bool AddNull) {
2155 if (!AddNull)
2156 return get(Context, ArrayRef<uint8_t>((uint8_t*)Str.data(), Str.size()));
2157
2158 SmallVector<uint8_t, 64> ElementVals;
2159 ElementVals.append(Str.begin(), Str.end());
2160 ElementVals.push_back(0);
2161 return get(Context, ElementVals);
2162}
Chris Lattner3756b912012-01-23 22:57:10 +00002163
2164/// get() constructors - Return a constant with vector type with an element
2165/// count and element type matching the ArrayRef passed in. Note that this
2166/// can return a ConstantAggregateZero object.
Chris Lattner20683932012-01-24 14:04:40 +00002167Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint8_t> Elts){
Chris Lattner3756b912012-01-23 22:57:10 +00002168 Type *Ty = VectorType::get(Type::getInt8Ty(Context), Elts.size());
2169 return getImpl(StringRef((char*)Elts.data(), Elts.size()*1), Ty);
2170}
Chris Lattner20683932012-01-24 14:04:40 +00002171Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint16_t> Elts){
Chris Lattner3756b912012-01-23 22:57:10 +00002172 Type *Ty = VectorType::get(Type::getInt16Ty(Context), Elts.size());
2173 return getImpl(StringRef((char*)Elts.data(), Elts.size()*2), Ty);
2174}
Chris Lattner20683932012-01-24 14:04:40 +00002175Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint32_t> Elts){
Chris Lattner3756b912012-01-23 22:57:10 +00002176 Type *Ty = VectorType::get(Type::getInt32Ty(Context), Elts.size());
2177 return getImpl(StringRef((char*)Elts.data(), Elts.size()*4), Ty);
2178}
Chris Lattner20683932012-01-24 14:04:40 +00002179Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint64_t> Elts){
Chris Lattner3756b912012-01-23 22:57:10 +00002180 Type *Ty = VectorType::get(Type::getInt64Ty(Context), Elts.size());
2181 return getImpl(StringRef((char*)Elts.data(), Elts.size()*8), Ty);
2182}
Chris Lattner20683932012-01-24 14:04:40 +00002183Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<float> Elts) {
Chris Lattner3756b912012-01-23 22:57:10 +00002184 Type *Ty = VectorType::get(Type::getFloatTy(Context), Elts.size());
2185 return getImpl(StringRef((char*)Elts.data(), Elts.size()*4), Ty);
2186}
Chris Lattner20683932012-01-24 14:04:40 +00002187Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<double> Elts) {
Chris Lattner3756b912012-01-23 22:57:10 +00002188 Type *Ty = VectorType::get(Type::getDoubleTy(Context), Elts.size());
2189 return getImpl(StringRef((char*)Elts.data(), Elts.size()*8), Ty);
2190}
2191
Chris Lattner9fe7dd82012-01-25 01:53:58 +00002192Constant *ConstantDataVector::getSplat(unsigned NumElts, Constant *V) {
2193 assert(isElementTypeCompatible(V->getType()) &&
2194 "Element type not compatible with ConstantData");
2195 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
2196 if (CI->getType()->isIntegerTy(8)) {
2197 SmallVector<uint8_t, 16> Elts(NumElts, CI->getZExtValue());
2198 return get(V->getContext(), Elts);
2199 }
2200 if (CI->getType()->isIntegerTy(16)) {
2201 SmallVector<uint16_t, 16> Elts(NumElts, CI->getZExtValue());
2202 return get(V->getContext(), Elts);
2203 }
2204 if (CI->getType()->isIntegerTy(32)) {
2205 SmallVector<uint32_t, 16> Elts(NumElts, CI->getZExtValue());
2206 return get(V->getContext(), Elts);
2207 }
2208 assert(CI->getType()->isIntegerTy(64) && "Unsupported ConstantData type");
2209 SmallVector<uint64_t, 16> Elts(NumElts, CI->getZExtValue());
2210 return get(V->getContext(), Elts);
2211 }
2212
2213 ConstantFP *CFP = cast<ConstantFP>(V);
2214 if (CFP->getType()->isFloatTy()) {
2215 SmallVector<float, 16> Elts(NumElts, CFP->getValueAPF().convertToFloat());
2216 return get(V->getContext(), Elts);
2217 }
2218 assert(CFP->getType()->isDoubleTy() && "Unsupported ConstantData type");
2219 SmallVector<double, 16> Elts(NumElts, CFP->getValueAPF().convertToDouble());
2220 return get(V->getContext(), Elts);
2221}
2222
2223
Chris Lattnere4f3f102012-01-24 04:43:41 +00002224/// getElementAsInteger - If this is a sequential container of integers (of
2225/// any size), return the specified element in the low bits of a uint64_t.
2226uint64_t ConstantDataSequential::getElementAsInteger(unsigned Elt) const {
2227 assert(isa<IntegerType>(getElementType()) &&
2228 "Accessor can only be used when element is an integer");
2229 const char *EltPtr = getElementPointer(Elt);
2230
2231 // The data is stored in host byte order, make sure to cast back to the right
2232 // type to load with the right endianness.
2233 switch (cast<IntegerType>(getElementType())->getBitWidth()) {
2234 default: assert(0 && "Invalid bitwidth for CDS");
2235 case 8: return *(uint8_t*)EltPtr;
2236 case 16: return *(uint16_t*)EltPtr;
2237 case 32: return *(uint32_t*)EltPtr;
2238 case 64: return *(uint64_t*)EltPtr;
2239 }
2240}
2241
2242/// getElementAsAPFloat - If this is a sequential container of floating point
2243/// type, return the specified element as an APFloat.
2244APFloat ConstantDataSequential::getElementAsAPFloat(unsigned Elt) const {
2245 const char *EltPtr = getElementPointer(Elt);
2246
2247 switch (getElementType()->getTypeID()) {
2248 default: assert("Accessor can only be used when element is float/double!");
2249 case Type::FloatTyID: return APFloat(*(float*)EltPtr);
2250 case Type::DoubleTyID: return APFloat(*(double*)EltPtr);
2251 }
2252}
2253
2254/// getElementAsFloat - If this is an sequential container of floats, return
2255/// the specified element as a float.
2256float ConstantDataSequential::getElementAsFloat(unsigned Elt) const {
2257 assert(getElementType()->isFloatTy() &&
2258 "Accessor can only be used when element is a 'float'");
2259 return *(float*)getElementPointer(Elt);
2260}
2261
2262/// getElementAsDouble - If this is an sequential container of doubles, return
2263/// the specified element as a float.
2264double ConstantDataSequential::getElementAsDouble(unsigned Elt) const {
2265 assert(getElementType()->isDoubleTy() &&
2266 "Accessor can only be used when element is a 'float'");
2267 return *(double*)getElementPointer(Elt);
2268}
2269
2270/// getElementAsConstant - Return a Constant for a specified index's element.
2271/// Note that this has to compute a new constant to return, so it isn't as
2272/// efficient as getElementAsInteger/Float/Double.
2273Constant *ConstantDataSequential::getElementAsConstant(unsigned Elt) const {
2274 if (getElementType()->isFloatTy() || getElementType()->isDoubleTy())
2275 return ConstantFP::get(getContext(), getElementAsAPFloat(Elt));
2276
2277 return ConstantInt::get(getElementType(), getElementAsInteger(Elt));
2278}
2279
Chris Lattner5dd4d872012-01-24 09:01:07 +00002280/// isString - This method returns true if this is an array of i8.
2281bool ConstantDataSequential::isString() const {
2282 return isa<ArrayType>(getType()) && getElementType()->isIntegerTy(8);
2283}
Chris Lattner3756b912012-01-23 22:57:10 +00002284
Chris Lattner5dd4d872012-01-24 09:01:07 +00002285/// isCString - This method returns true if the array "isString", ends with a
2286/// nul byte, and does not contains any other nul bytes.
2287bool ConstantDataSequential::isCString() const {
2288 if (!isString())
2289 return false;
2290
2291 StringRef Str = getAsString();
2292
2293 // The last value must be nul.
2294 if (Str.back() != 0) return false;
2295
2296 // Other elements must be non-nul.
2297 return Str.drop_back().find(0) == StringRef::npos;
2298}
Chris Lattner3756b912012-01-23 22:57:10 +00002299
Chris Lattnera3b94ba2010-03-30 20:48:48 +00002300
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002301//===----------------------------------------------------------------------===//
2302// replaceUsesOfWithOnConstant implementations
2303
Chris Lattner913849b2007-08-21 00:55:23 +00002304/// replaceUsesOfWithOnConstant - Update this constant array to change uses of
2305/// 'From' to be uses of 'To'. This must update the uniquing data structures
2306/// etc.
2307///
2308/// Note that we intentionally replace all uses of From with To here. Consider
2309/// a large array that uses 'From' 1000 times. By handling this case all here,
2310/// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
2311/// single invocation handles all 1000 uses. Handling them one at a time would
2312/// work, but would be really slow because it would have to unique each updated
2313/// array instance.
Chris Lattner31b132c2009-10-28 00:01:44 +00002314///
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002315void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
Chris Lattner7a1450d2005-10-04 18:13:04 +00002316 Use *U) {
Owen Andersonc2c79322009-07-28 18:32:17 +00002317 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2318 Constant *ToC = cast<Constant>(To);
2319
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002320 LLVMContextImpl *pImpl = getType()->getContext().pImpl;
Owen Andersonc2c79322009-07-28 18:32:17 +00002321
Dan Gohmane4532f32009-09-15 15:58:07 +00002322 std::pair<LLVMContextImpl::ArrayConstantsTy::MapKey, ConstantArray*> Lookup;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002323 Lookup.first.first = cast<ArrayType>(getType());
Owen Andersonc2c79322009-07-28 18:32:17 +00002324 Lookup.second = this;
2325
2326 std::vector<Constant*> &Values = Lookup.first.second;
2327 Values.reserve(getNumOperands()); // Build replacement array.
2328
2329 // Fill values with the modified operands of the constant array. Also,
2330 // compute whether this turns into an all-zeros array.
2331 bool isAllZeros = false;
2332 unsigned NumUpdated = 0;
2333 if (!ToC->isNullValue()) {
2334 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2335 Constant *Val = cast<Constant>(O->get());
2336 if (Val == From) {
2337 Val = ToC;
2338 ++NumUpdated;
2339 }
2340 Values.push_back(Val);
2341 }
2342 } else {
2343 isAllZeros = true;
2344 for (Use *O = OperandList, *E = OperandList+getNumOperands();O != E; ++O) {
2345 Constant *Val = cast<Constant>(O->get());
2346 if (Val == From) {
2347 Val = ToC;
2348 ++NumUpdated;
2349 }
2350 Values.push_back(Val);
2351 if (isAllZeros) isAllZeros = Val->isNullValue();
2352 }
2353 }
2354
2355 Constant *Replacement = 0;
2356 if (isAllZeros) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002357 Replacement = ConstantAggregateZero::get(getType());
Owen Andersonc2c79322009-07-28 18:32:17 +00002358 } else {
2359 // Check to see if we have this array type already.
Owen Andersonc2c79322009-07-28 18:32:17 +00002360 bool Exists;
2361 LLVMContextImpl::ArrayConstantsTy::MapTy::iterator I =
2362 pImpl->ArrayConstants.InsertOrGetItem(Lookup, Exists);
2363
2364 if (Exists) {
Devang Patelf7188322009-09-03 01:39:20 +00002365 Replacement = I->second;
Owen Andersonc2c79322009-07-28 18:32:17 +00002366 } else {
2367 // Okay, the new shape doesn't exist in the system yet. Instead of
2368 // creating a new constant array, inserting it, replaceallusesof'ing the
2369 // old with the new, then deleting the old... just update the current one
2370 // in place!
2371 pImpl->ArrayConstants.MoveConstantToNewSlot(this, I);
2372
2373 // Update to the new value. Optimize for the case when we have a single
2374 // operand that we're changing, but handle bulk updates efficiently.
2375 if (NumUpdated == 1) {
2376 unsigned OperandToUpdate = U - OperandList;
2377 assert(getOperand(OperandToUpdate) == From &&
2378 "ReplaceAllUsesWith broken!");
2379 setOperand(OperandToUpdate, ToC);
2380 } else {
2381 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2382 if (getOperand(i) == From)
2383 setOperand(i, ToC);
2384 }
2385 return;
2386 }
2387 }
Chris Lattnerb64419a2005-10-03 22:51:37 +00002388
2389 // Otherwise, I do need to replace this with an existing value.
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002390 assert(Replacement != this && "I didn't contain From!");
2391
Chris Lattner7a1450d2005-10-04 18:13:04 +00002392 // Everyone using this now uses the replacement.
Chris Lattneraf1783f2011-07-15 06:18:52 +00002393 replaceAllUsesWith(Replacement);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002394
2395 // Delete the old constant!
2396 destroyConstant();
2397}
2398
2399void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
Chris Lattner7a1450d2005-10-04 18:13:04 +00002400 Use *U) {
Owen Anderson45308b52009-07-27 22:29:26 +00002401 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2402 Constant *ToC = cast<Constant>(To);
2403
2404 unsigned OperandToUpdate = U-OperandList;
2405 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
2406
Dan Gohmane4532f32009-09-15 15:58:07 +00002407 std::pair<LLVMContextImpl::StructConstantsTy::MapKey, ConstantStruct*> Lookup;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002408 Lookup.first.first = cast<StructType>(getType());
Owen Anderson45308b52009-07-27 22:29:26 +00002409 Lookup.second = this;
2410 std::vector<Constant*> &Values = Lookup.first.second;
2411 Values.reserve(getNumOperands()); // Build replacement struct.
2412
2413
2414 // Fill values with the modified operands of the constant struct. Also,
2415 // compute whether this turns into an all-zeros struct.
2416 bool isAllZeros = false;
2417 if (!ToC->isNullValue()) {
2418 for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O)
2419 Values.push_back(cast<Constant>(O->get()));
2420 } else {
2421 isAllZeros = true;
2422 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2423 Constant *Val = cast<Constant>(O->get());
2424 Values.push_back(Val);
2425 if (isAllZeros) isAllZeros = Val->isNullValue();
2426 }
2427 }
2428 Values[OperandToUpdate] = ToC;
2429
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002430 LLVMContextImpl *pImpl = getContext().pImpl;
Owen Anderson45308b52009-07-27 22:29:26 +00002431
2432 Constant *Replacement = 0;
2433 if (isAllZeros) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002434 Replacement = ConstantAggregateZero::get(getType());
Owen Anderson45308b52009-07-27 22:29:26 +00002435 } else {
Chris Lattner718da702010-07-17 06:13:52 +00002436 // Check to see if we have this struct type already.
Owen Anderson45308b52009-07-27 22:29:26 +00002437 bool Exists;
2438 LLVMContextImpl::StructConstantsTy::MapTy::iterator I =
2439 pImpl->StructConstants.InsertOrGetItem(Lookup, Exists);
2440
2441 if (Exists) {
Devang Patelf7188322009-09-03 01:39:20 +00002442 Replacement = I->second;
Owen Anderson45308b52009-07-27 22:29:26 +00002443 } else {
2444 // Okay, the new shape doesn't exist in the system yet. Instead of
2445 // creating a new constant struct, inserting it, replaceallusesof'ing the
2446 // old with the new, then deleting the old... just update the current one
2447 // in place!
2448 pImpl->StructConstants.MoveConstantToNewSlot(this, I);
2449
2450 // Update to the new value.
2451 setOperand(OperandToUpdate, ToC);
2452 return;
2453 }
2454 }
2455
2456 assert(Replacement != this && "I didn't contain From!");
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002457
Chris Lattner7a1450d2005-10-04 18:13:04 +00002458 // Everyone using this now uses the replacement.
Chris Lattneraf1783f2011-07-15 06:18:52 +00002459 replaceAllUsesWith(Replacement);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002460
2461 // Delete the old constant!
2462 destroyConstant();
2463}
2464
Reid Spencerd84d35b2007-02-15 02:26:10 +00002465void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
Chris Lattner7a1450d2005-10-04 18:13:04 +00002466 Use *U) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002467 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2468
2469 std::vector<Constant*> Values;
2470 Values.reserve(getNumOperands()); // Build replacement array...
2471 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2472 Constant *Val = getOperand(i);
2473 if (Val == From) Val = cast<Constant>(To);
2474 Values.push_back(Val);
2475 }
2476
Jay Foadb8a8bed32011-06-22 09:10:19 +00002477 Constant *Replacement = get(Values);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002478 assert(Replacement != this && "I didn't contain From!");
2479
Chris Lattner7a1450d2005-10-04 18:13:04 +00002480 // Everyone using this now uses the replacement.
Chris Lattneraf1783f2011-07-15 06:18:52 +00002481 replaceAllUsesWith(Replacement);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002482
2483 // Delete the old constant!
2484 destroyConstant();
2485}
2486
2487void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
Chris Lattner7a1450d2005-10-04 18:13:04 +00002488 Use *U) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002489 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2490 Constant *To = cast<Constant>(ToV);
2491
2492 Constant *Replacement = 0;
2493 if (getOpcode() == Instruction::GetElementPtr) {
Chris Lattnerb5d70302007-02-19 20:01:23 +00002494 SmallVector<Constant*, 8> Indices;
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002495 Constant *Pointer = getOperand(0);
2496 Indices.reserve(getNumOperands()-1);
2497 if (Pointer == From) Pointer = To;
2498
2499 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2500 Constant *Val = getOperand(i);
2501 if (Val == From) Val = To;
2502 Indices.push_back(Val);
2503 }
Jay Foaded8db7d2011-07-21 14:31:17 +00002504 Replacement = ConstantExpr::getGetElementPtr(Pointer, Indices,
Chris Lattner603af182011-02-11 05:37:21 +00002505 cast<GEPOperator>(this)->isInBounds());
Dan Gohman12fce772008-05-15 19:50:34 +00002506 } else if (getOpcode() == Instruction::ExtractValue) {
Dan Gohman12fce772008-05-15 19:50:34 +00002507 Constant *Agg = getOperand(0);
Dan Gohman12fce772008-05-15 19:50:34 +00002508 if (Agg == From) Agg = To;
2509
Jay Foad0091fe82011-04-13 15:22:40 +00002510 ArrayRef<unsigned> Indices = getIndices();
Jay Foad57aa6362011-07-13 10:26:04 +00002511 Replacement = ConstantExpr::getExtractValue(Agg, Indices);
Dan Gohman12fce772008-05-15 19:50:34 +00002512 } else if (getOpcode() == Instruction::InsertValue) {
Dan Gohman12fce772008-05-15 19:50:34 +00002513 Constant *Agg = getOperand(0);
2514 Constant *Val = getOperand(1);
Dan Gohman12fce772008-05-15 19:50:34 +00002515 if (Agg == From) Agg = To;
2516 if (Val == From) Val = To;
2517
Jay Foad0091fe82011-04-13 15:22:40 +00002518 ArrayRef<unsigned> Indices = getIndices();
Jay Foad57aa6362011-07-13 10:26:04 +00002519 Replacement = ConstantExpr::getInsertValue(Agg, Val, Indices);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002520 } else if (isCast()) {
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002521 assert(getOperand(0) == From && "Cast only has one use!");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002522 Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002523 } else if (getOpcode() == Instruction::Select) {
2524 Constant *C1 = getOperand(0);
2525 Constant *C2 = getOperand(1);
2526 Constant *C3 = getOperand(2);
2527 if (C1 == From) C1 = To;
2528 if (C2 == From) C2 = To;
2529 if (C3 == From) C3 = To;
2530 Replacement = ConstantExpr::getSelect(C1, C2, C3);
Robert Bocchino23004482006-01-10 19:05:34 +00002531 } else if (getOpcode() == Instruction::ExtractElement) {
2532 Constant *C1 = getOperand(0);
2533 Constant *C2 = getOperand(1);
2534 if (C1 == From) C1 = To;
2535 if (C2 == From) C2 = To;
2536 Replacement = ConstantExpr::getExtractElement(C1, C2);
Chris Lattnera93b4b52006-04-08 05:09:48 +00002537 } else if (getOpcode() == Instruction::InsertElement) {
2538 Constant *C1 = getOperand(0);
2539 Constant *C2 = getOperand(1);
2540 Constant *C3 = getOperand(1);
2541 if (C1 == From) C1 = To;
2542 if (C2 == From) C2 = To;
2543 if (C3 == From) C3 = To;
2544 Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2545 } else if (getOpcode() == Instruction::ShuffleVector) {
2546 Constant *C1 = getOperand(0);
2547 Constant *C2 = getOperand(1);
2548 Constant *C3 = getOperand(2);
2549 if (C1 == From) C1 = To;
2550 if (C2 == From) C2 = To;
2551 if (C3 == From) C3 = To;
2552 Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
Reid Spenceree3c9912006-12-04 05:19:50 +00002553 } else if (isCompare()) {
2554 Constant *C1 = getOperand(0);
2555 Constant *C2 = getOperand(1);
2556 if (C1 == From) C1 = To;
2557 if (C2 == From) C2 = To;
2558 if (getOpcode() == Instruction::ICmp)
2559 Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
Chris Lattnereab49262008-07-14 05:17:31 +00002560 else {
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002561 assert(getOpcode() == Instruction::FCmp);
2562 Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
Chris Lattnereab49262008-07-14 05:17:31 +00002563 }
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002564 } else if (getNumOperands() == 2) {
2565 Constant *C1 = getOperand(0);
2566 Constant *C2 = getOperand(1);
2567 if (C1 == From) C1 = To;
2568 if (C2 == From) C2 = To;
Chris Lattnerb9c86512009-12-29 02:14:09 +00002569 Replacement = ConstantExpr::get(getOpcode(), C1, C2, SubclassOptionalData);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002570 } else {
Torok Edwinfbcc6632009-07-14 16:55:14 +00002571 llvm_unreachable("Unknown ConstantExpr type!");
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002572 }
2573
2574 assert(Replacement != this && "I didn't contain From!");
2575
Chris Lattner7a1450d2005-10-04 18:13:04 +00002576 // Everyone using this now uses the replacement.
Chris Lattneraf1783f2011-07-15 06:18:52 +00002577 replaceAllUsesWith(Replacement);
Chris Lattnerc4062ba2005-10-03 21:58:36 +00002578
2579 // Delete the old constant!
2580 destroyConstant();
Matthijs Kooijmanba5d7ef2008-07-03 07:46:41 +00002581}