forked from llvm-mirror/llvm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Constants.cpp
2840 lines (2412 loc) · 105 KB
/
Constants.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===-- Constants.cpp - Implement Constant nodes --------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the Constant* classes.
//
//===----------------------------------------------------------------------===//
#include "llvm/IR/Constants.h"
#include "ConstantFold.h"
#include "LLVMContextImpl.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/FoldingSet.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/GetElementPtrTypeIterator.h"
#include "llvm/IR/GlobalValue.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Operator.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/MathExtras.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
#include <cstdarg>
using namespace llvm;
//===----------------------------------------------------------------------===//
// Constant Class
//===----------------------------------------------------------------------===//
void Constant::anchor() { }
bool Constant::isNegativeZeroValue() const {
// Floating point values have an explicit -0.0 value.
if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
return CFP->isZero() && CFP->isNegative();
// Equivalent for a vector of -0.0's.
if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
if (ConstantFP *SplatCFP = dyn_cast_or_null<ConstantFP>(CV->getSplatValue()))
if (SplatCFP && SplatCFP->isZero() && SplatCFP->isNegative())
return true;
// We've already handled true FP case; any other FP vectors can't represent -0.0.
if (getType()->isFPOrFPVectorTy())
return false;
// Otherwise, just use +0.0.
return isNullValue();
}
// Return true iff this constant is positive zero (floating point), negative
// zero (floating point), or a null value.
bool Constant::isZeroValue() const {
// Floating point values have an explicit -0.0 value.
if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
return CFP->isZero();
// Otherwise, just use +0.0.
return isNullValue();
}
bool Constant::isNullValue() const {
// 0 is null.
if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
return CI->isZero();
// +0.0 is null.
if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
return CFP->isZero() && !CFP->isNegative();
// constant zero is zero for aggregates and cpnull is null for pointers.
return isa<ConstantAggregateZero>(this) || isa<ConstantPointerNull>(this);
}
bool Constant::isAllOnesValue() const {
// Check for -1 integers
if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
return CI->isMinusOne();
// Check for FP which are bitcasted from -1 integers
if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
return CFP->getValueAPF().bitcastToAPInt().isAllOnesValue();
// Check for constant vectors which are splats of -1 values.
if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
if (Constant *Splat = CV->getSplatValue())
return Splat->isAllOnesValue();
// Check for constant vectors which are splats of -1 values.
if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
if (Constant *Splat = CV->getSplatValue())
return Splat->isAllOnesValue();
return false;
}
// Constructor to create a '0' constant of arbitrary type...
Constant *Constant::getNullValue(Type *Ty) {
switch (Ty->getTypeID()) {
case Type::IntegerTyID:
return ConstantInt::get(Ty, 0);
case Type::HalfTyID:
return ConstantFP::get(Ty->getContext(),
APFloat::getZero(APFloat::IEEEhalf));
case Type::FloatTyID:
return ConstantFP::get(Ty->getContext(),
APFloat::getZero(APFloat::IEEEsingle));
case Type::DoubleTyID:
return ConstantFP::get(Ty->getContext(),
APFloat::getZero(APFloat::IEEEdouble));
case Type::X86_FP80TyID:
return ConstantFP::get(Ty->getContext(),
APFloat::getZero(APFloat::x87DoubleExtended));
case Type::FP128TyID:
return ConstantFP::get(Ty->getContext(),
APFloat::getZero(APFloat::IEEEquad));
case Type::PPC_FP128TyID:
return ConstantFP::get(Ty->getContext(),
APFloat(APFloat::PPCDoubleDouble,
APInt::getNullValue(128)));
case Type::PointerTyID:
return ConstantPointerNull::get(cast<PointerType>(Ty));
case Type::StructTyID:
case Type::ArrayTyID:
case Type::VectorTyID:
return ConstantAggregateZero::get(Ty);
default:
// Function, Label, or Opaque type?
llvm_unreachable("Cannot create a null constant of that type!");
}
}
Constant *Constant::getIntegerValue(Type *Ty, const APInt &V) {
Type *ScalarTy = Ty->getScalarType();
// Create the base integer constant.
Constant *C = ConstantInt::get(Ty->getContext(), V);
// Convert an integer to a pointer, if necessary.
if (PointerType *PTy = dyn_cast<PointerType>(ScalarTy))
C = ConstantExpr::getIntToPtr(C, PTy);
// Broadcast a scalar to a vector, if necessary.
if (VectorType *VTy = dyn_cast<VectorType>(Ty))
C = ConstantVector::getSplat(VTy->getNumElements(), C);
return C;
}
Constant *Constant::getAllOnesValue(Type *Ty) {
if (IntegerType *ITy = dyn_cast<IntegerType>(Ty))
return ConstantInt::get(Ty->getContext(),
APInt::getAllOnesValue(ITy->getBitWidth()));
if (Ty->isFloatingPointTy()) {
APFloat FL = APFloat::getAllOnesValue(Ty->getPrimitiveSizeInBits(),
!Ty->isPPC_FP128Ty());
return ConstantFP::get(Ty->getContext(), FL);
}
VectorType *VTy = cast<VectorType>(Ty);
return ConstantVector::getSplat(VTy->getNumElements(),
getAllOnesValue(VTy->getElementType()));
}
/// getAggregateElement - For aggregates (struct/array/vector) return the
/// constant that corresponds to the specified element if possible, or null if
/// not. This can return null if the element index is a ConstantExpr, or if
/// 'this' is a constant expr.
Constant *Constant::getAggregateElement(unsigned Elt) const {
if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(this))
return Elt < CS->getNumOperands() ? CS->getOperand(Elt) : nullptr;
if (const ConstantArray *CA = dyn_cast<ConstantArray>(this))
return Elt < CA->getNumOperands() ? CA->getOperand(Elt) : nullptr;
if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
return Elt < CV->getNumOperands() ? CV->getOperand(Elt) : nullptr;
if (const ConstantAggregateZero *CAZ =dyn_cast<ConstantAggregateZero>(this))
return CAZ->getElementValue(Elt);
if (const UndefValue *UV = dyn_cast<UndefValue>(this))
return UV->getElementValue(Elt);
if (const ConstantDataSequential *CDS =dyn_cast<ConstantDataSequential>(this))
return Elt < CDS->getNumElements() ? CDS->getElementAsConstant(Elt)
: nullptr;
return nullptr;
}
Constant *Constant::getAggregateElement(Constant *Elt) const {
assert(isa<IntegerType>(Elt->getType()) && "Index must be an integer");
if (ConstantInt *CI = dyn_cast<ConstantInt>(Elt))
return getAggregateElement(CI->getZExtValue());
return nullptr;
}
void Constant::destroyConstantImpl() {
// When a Constant is destroyed, there may be lingering
// references to the constant by other constants in the constant pool. These
// constants are implicitly dependent on the module that is being deleted,
// but they don't know that. Because we only find out when the CPV is
// deleted, we must now notify all of our users (that should only be
// Constants) that they are, in fact, invalid now and should be deleted.
//
while (!use_empty()) {
Value *V = user_back();
#ifndef NDEBUG // Only in -g mode...
if (!isa<Constant>(V)) {
dbgs() << "While deleting: " << *this
<< "\n\nUse still stuck around after Def is destroyed: "
<< *V << "\n\n";
}
#endif
assert(isa<Constant>(V) && "References remain to Constant being destroyed");
cast<Constant>(V)->destroyConstant();
// The constant should remove itself from our use list...
assert((use_empty() || user_back() != V) && "Constant not removed!");
}
// Value has no outstanding references it is safe to delete it now...
delete this;
}
static bool canTrapImpl(const Constant *C,
SmallPtrSet<const ConstantExpr *, 4> &NonTrappingOps) {
assert(C->getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
// The only thing that could possibly trap are constant exprs.
const ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
if (!CE)
return false;
// ConstantExpr traps if any operands can trap.
for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) {
if (ConstantExpr *Op = dyn_cast<ConstantExpr>(CE->getOperand(i))) {
if (NonTrappingOps.insert(Op) && canTrapImpl(Op, NonTrappingOps))
return true;
}
}
// Otherwise, only specific operations can trap.
switch (CE->getOpcode()) {
default:
return false;
case Instruction::UDiv:
case Instruction::SDiv:
case Instruction::FDiv:
case Instruction::URem:
case Instruction::SRem:
case Instruction::FRem:
// Div and rem can trap if the RHS is not known to be non-zero.
if (!isa<ConstantInt>(CE->getOperand(1)) ||CE->getOperand(1)->isNullValue())
return true;
return false;
}
}
/// canTrap - Return true if evaluation of this constant could trap. This is
/// true for things like constant expressions that could divide by zero.
bool Constant::canTrap() const {
SmallPtrSet<const ConstantExpr *, 4> NonTrappingOps;
return canTrapImpl(this, NonTrappingOps);
}
/// isThreadDependent - Return true if the value can vary between threads.
bool Constant::isThreadDependent() const {
SmallPtrSet<const Constant*, 64> Visited;
SmallVector<const Constant*, 64> WorkList;
WorkList.push_back(this);
Visited.insert(this);
while (!WorkList.empty()) {
const Constant *C = WorkList.pop_back_val();
if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
if (GV->isThreadLocal())
return true;
}
for (unsigned I = 0, E = C->getNumOperands(); I != E; ++I) {
const Constant *D = dyn_cast<Constant>(C->getOperand(I));
if (!D)
continue;
if (Visited.insert(D))
WorkList.push_back(D);
}
}
return false;
}
/// isConstantUsed - Return true if the constant has users other than constant
/// exprs and other dangling things.
bool Constant::isConstantUsed() const {
for (const User *U : users()) {
const Constant *UC = dyn_cast<Constant>(U);
if (!UC || isa<GlobalValue>(UC))
return true;
if (UC->isConstantUsed())
return true;
}
return false;
}
/// getRelocationInfo - This method classifies the entry according to
/// whether or not it may generate a relocation entry. This must be
/// conservative, so if it might codegen to a relocatable entry, it should say
/// so. The return values are:
///
/// NoRelocation: This constant pool entry is guaranteed to never have a
/// relocation applied to it (because it holds a simple constant like
/// '4').
/// LocalRelocation: This entry has relocations, but the entries are
/// guaranteed to be resolvable by the static linker, so the dynamic
/// linker will never see them.
/// GlobalRelocations: This entry may have arbitrary relocations.
///
/// FIXME: This really should not be in IR.
Constant::PossibleRelocationsTy Constant::getRelocationInfo() const {
if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
if (GV->hasLocalLinkage() || GV->hasHiddenVisibility())
return LocalRelocation; // Local to this file/library.
return GlobalRelocations; // Global reference.
}
if (const BlockAddress *BA = dyn_cast<BlockAddress>(this))
return BA->getFunction()->getRelocationInfo();
// While raw uses of blockaddress need to be relocated, differences between
// two of them don't when they are for labels in the same function. This is a
// common idiom when creating a table for the indirect goto extension, so we
// handle it efficiently here.
if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(this))
if (CE->getOpcode() == Instruction::Sub) {
ConstantExpr *LHS = dyn_cast<ConstantExpr>(CE->getOperand(0));
ConstantExpr *RHS = dyn_cast<ConstantExpr>(CE->getOperand(1));
if (LHS && RHS &&
LHS->getOpcode() == Instruction::PtrToInt &&
RHS->getOpcode() == Instruction::PtrToInt &&
isa<BlockAddress>(LHS->getOperand(0)) &&
isa<BlockAddress>(RHS->getOperand(0)) &&
cast<BlockAddress>(LHS->getOperand(0))->getFunction() ==
cast<BlockAddress>(RHS->getOperand(0))->getFunction())
return NoRelocation;
}
PossibleRelocationsTy Result = NoRelocation;
for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
Result = std::max(Result,
cast<Constant>(getOperand(i))->getRelocationInfo());
return Result;
}
/// removeDeadUsersOfConstant - If the specified constantexpr is dead, remove
/// it. This involves recursively eliminating any dead users of the
/// constantexpr.
static bool removeDeadUsersOfConstant(const Constant *C) {
if (isa<GlobalValue>(C)) return false; // Cannot remove this
while (!C->use_empty()) {
const Constant *User = dyn_cast<Constant>(C->user_back());
if (!User) return false; // Non-constant usage;
if (!removeDeadUsersOfConstant(User))
return false; // Constant wasn't dead
}
const_cast<Constant*>(C)->destroyConstant();
return true;
}
/// removeDeadConstantUsers - If there are any dead constant users dangling
/// off of this constant, remove them. This method is useful for clients
/// that want to check to see if a global is unused, but don't want to deal
/// with potentially dead constants hanging off of the globals.
void Constant::removeDeadConstantUsers() const {
Value::const_user_iterator I = user_begin(), E = user_end();
Value::const_user_iterator LastNonDeadUser = E;
while (I != E) {
const Constant *User = dyn_cast<Constant>(*I);
if (!User) {
LastNonDeadUser = I;
++I;
continue;
}
if (!removeDeadUsersOfConstant(User)) {
// If the constant wasn't dead, remember that this was the last live use
// and move on to the next constant.
LastNonDeadUser = I;
++I;
continue;
}
// If the constant was dead, then the iterator is invalidated.
if (LastNonDeadUser == E) {
I = user_begin();
if (I == E) break;
} else {
I = LastNonDeadUser;
++I;
}
}
}
//===----------------------------------------------------------------------===//
// ConstantInt
//===----------------------------------------------------------------------===//
void ConstantInt::anchor() { }
ConstantInt::ConstantInt(IntegerType *Ty, const APInt& V)
: Constant(Ty, ConstantIntVal, nullptr, 0), Val(V) {
assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
}
ConstantInt *ConstantInt::getTrue(LLVMContext &Context) {
LLVMContextImpl *pImpl = Context.pImpl;
if (!pImpl->TheTrueVal)
pImpl->TheTrueVal = ConstantInt::get(Type::getInt1Ty(Context), 1);
return pImpl->TheTrueVal;
}
ConstantInt *ConstantInt::getFalse(LLVMContext &Context) {
LLVMContextImpl *pImpl = Context.pImpl;
if (!pImpl->TheFalseVal)
pImpl->TheFalseVal = ConstantInt::get(Type::getInt1Ty(Context), 0);
return pImpl->TheFalseVal;
}
Constant *ConstantInt::getTrue(Type *Ty) {
VectorType *VTy = dyn_cast<VectorType>(Ty);
if (!VTy) {
assert(Ty->isIntegerTy(1) && "True must be i1 or vector of i1.");
return ConstantInt::getTrue(Ty->getContext());
}
assert(VTy->getElementType()->isIntegerTy(1) &&
"True must be vector of i1 or i1.");
return ConstantVector::getSplat(VTy->getNumElements(),
ConstantInt::getTrue(Ty->getContext()));
}
Constant *ConstantInt::getFalse(Type *Ty) {
VectorType *VTy = dyn_cast<VectorType>(Ty);
if (!VTy) {
assert(Ty->isIntegerTy(1) && "False must be i1 or vector of i1.");
return ConstantInt::getFalse(Ty->getContext());
}
assert(VTy->getElementType()->isIntegerTy(1) &&
"False must be vector of i1 or i1.");
return ConstantVector::getSplat(VTy->getNumElements(),
ConstantInt::getFalse(Ty->getContext()));
}
// Get a ConstantInt from an APInt. Note that the value stored in the DenseMap
// as the key, is a DenseMapAPIntKeyInfo::KeyTy which has provided the
// operator== and operator!= to ensure that the DenseMap doesn't attempt to
// compare APInt's of different widths, which would violate an APInt class
// invariant which generates an assertion.
ConstantInt *ConstantInt::get(LLVMContext &Context, const APInt &V) {
// Get the corresponding integer type for the bit width of the value.
IntegerType *ITy = IntegerType::get(Context, V.getBitWidth());
// get an existing value or the insertion position
LLVMContextImpl *pImpl = Context.pImpl;
ConstantInt *&Slot = pImpl->IntConstants[DenseMapAPIntKeyInfo::KeyTy(V, ITy)];
if (!Slot) Slot = new ConstantInt(ITy, V);
return Slot;
}
Constant *ConstantInt::get(Type *Ty, uint64_t V, bool isSigned) {
Constant *C = get(cast<IntegerType>(Ty->getScalarType()), V, isSigned);
// For vectors, broadcast the value.
if (VectorType *VTy = dyn_cast<VectorType>(Ty))
return ConstantVector::getSplat(VTy->getNumElements(), C);
return C;
}
ConstantInt *ConstantInt::get(IntegerType *Ty, uint64_t V,
bool isSigned) {
return get(Ty->getContext(), APInt(Ty->getBitWidth(), V, isSigned));
}
ConstantInt *ConstantInt::getSigned(IntegerType *Ty, int64_t V) {
return get(Ty, V, true);
}
Constant *ConstantInt::getSigned(Type *Ty, int64_t V) {
return get(Ty, V, true);
}
Constant *ConstantInt::get(Type *Ty, const APInt& V) {
ConstantInt *C = get(Ty->getContext(), V);
assert(C->getType() == Ty->getScalarType() &&
"ConstantInt type doesn't match the type implied by its value!");
// For vectors, broadcast the value.
if (VectorType *VTy = dyn_cast<VectorType>(Ty))
return ConstantVector::getSplat(VTy->getNumElements(), C);
return C;
}
ConstantInt *ConstantInt::get(IntegerType* Ty, StringRef Str,
uint8_t radix) {
return get(Ty->getContext(), APInt(Ty->getBitWidth(), Str, radix));
}
//===----------------------------------------------------------------------===//
// ConstantFP
//===----------------------------------------------------------------------===//
static const fltSemantics *TypeToFloatSemantics(Type *Ty) {
if (Ty->isHalfTy())
return &APFloat::IEEEhalf;
if (Ty->isFloatTy())
return &APFloat::IEEEsingle;
if (Ty->isDoubleTy())
return &APFloat::IEEEdouble;
if (Ty->isX86_FP80Ty())
return &APFloat::x87DoubleExtended;
else if (Ty->isFP128Ty())
return &APFloat::IEEEquad;
assert(Ty->isPPC_FP128Ty() && "Unknown FP format");
return &APFloat::PPCDoubleDouble;
}
void ConstantFP::anchor() { }
/// get() - This returns a constant fp for the specified value in the
/// specified type. This should only be used for simple constant values like
/// 2.0/1.0 etc, that are known-valid both as double and as the target format.
Constant *ConstantFP::get(Type *Ty, double V) {
LLVMContext &Context = Ty->getContext();
APFloat FV(V);
bool ignored;
FV.convert(*TypeToFloatSemantics(Ty->getScalarType()),
APFloat::rmNearestTiesToEven, &ignored);
Constant *C = get(Context, FV);
// For vectors, broadcast the value.
if (VectorType *VTy = dyn_cast<VectorType>(Ty))
return ConstantVector::getSplat(VTy->getNumElements(), C);
return C;
}
Constant *ConstantFP::get(Type *Ty, StringRef Str) {
LLVMContext &Context = Ty->getContext();
APFloat FV(*TypeToFloatSemantics(Ty->getScalarType()), Str);
Constant *C = get(Context, FV);
// For vectors, broadcast the value.
if (VectorType *VTy = dyn_cast<VectorType>(Ty))
return ConstantVector::getSplat(VTy->getNumElements(), C);
return C;
}
Constant *ConstantFP::getNegativeZero(Type *Ty) {
const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
APFloat NegZero = APFloat::getZero(Semantics, /*Negative=*/true);
Constant *C = get(Ty->getContext(), NegZero);
if (VectorType *VTy = dyn_cast<VectorType>(Ty))
return ConstantVector::getSplat(VTy->getNumElements(), C);
return C;
}
Constant *ConstantFP::getZeroValueForNegation(Type *Ty) {
if (Ty->isFPOrFPVectorTy())
return getNegativeZero(Ty);
return Constant::getNullValue(Ty);
}
// ConstantFP accessors.
ConstantFP* ConstantFP::get(LLVMContext &Context, const APFloat& V) {
LLVMContextImpl* pImpl = Context.pImpl;
ConstantFP *&Slot = pImpl->FPConstants[DenseMapAPFloatKeyInfo::KeyTy(V)];
if (!Slot) {
Type *Ty;
if (&V.getSemantics() == &APFloat::IEEEhalf)
Ty = Type::getHalfTy(Context);
else if (&V.getSemantics() == &APFloat::IEEEsingle)
Ty = Type::getFloatTy(Context);
else if (&V.getSemantics() == &APFloat::IEEEdouble)
Ty = Type::getDoubleTy(Context);
else if (&V.getSemantics() == &APFloat::x87DoubleExtended)
Ty = Type::getX86_FP80Ty(Context);
else if (&V.getSemantics() == &APFloat::IEEEquad)
Ty = Type::getFP128Ty(Context);
else {
assert(&V.getSemantics() == &APFloat::PPCDoubleDouble &&
"Unknown FP format");
Ty = Type::getPPC_FP128Ty(Context);
}
Slot = new ConstantFP(Ty, V);
}
return Slot;
}
Constant *ConstantFP::getInfinity(Type *Ty, bool Negative) {
const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
Constant *C = get(Ty->getContext(), APFloat::getInf(Semantics, Negative));
if (VectorType *VTy = dyn_cast<VectorType>(Ty))
return ConstantVector::getSplat(VTy->getNumElements(), C);
return C;
}
ConstantFP::ConstantFP(Type *Ty, const APFloat& V)
: Constant(Ty, ConstantFPVal, nullptr, 0), Val(V) {
assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
"FP type Mismatch");
}
bool ConstantFP::isExactlyValue(const APFloat &V) const {
return Val.bitwiseIsEqual(V);
}
//===----------------------------------------------------------------------===//
// ConstantAggregateZero Implementation
//===----------------------------------------------------------------------===//
/// getSequentialElement - If this CAZ has array or vector type, return a zero
/// with the right element type.
Constant *ConstantAggregateZero::getSequentialElement() const {
return Constant::getNullValue(getType()->getSequentialElementType());
}
/// getStructElement - If this CAZ has struct type, return a zero with the
/// right element type for the specified element.
Constant *ConstantAggregateZero::getStructElement(unsigned Elt) const {
return Constant::getNullValue(getType()->getStructElementType(Elt));
}
/// getElementValue - Return a zero of the right value for the specified GEP
/// index if we can, otherwise return null (e.g. if C is a ConstantExpr).
Constant *ConstantAggregateZero::getElementValue(Constant *C) const {
if (isa<SequentialType>(getType()))
return getSequentialElement();
return getStructElement(cast<ConstantInt>(C)->getZExtValue());
}
/// getElementValue - Return a zero of the right value for the specified GEP
/// index.
Constant *ConstantAggregateZero::getElementValue(unsigned Idx) const {
if (isa<SequentialType>(getType()))
return getSequentialElement();
return getStructElement(Idx);
}
//===----------------------------------------------------------------------===//
// UndefValue Implementation
//===----------------------------------------------------------------------===//
/// getSequentialElement - If this undef has array or vector type, return an
/// undef with the right element type.
UndefValue *UndefValue::getSequentialElement() const {
return UndefValue::get(getType()->getSequentialElementType());
}
/// getStructElement - If this undef has struct type, return a zero with the
/// right element type for the specified element.
UndefValue *UndefValue::getStructElement(unsigned Elt) const {
return UndefValue::get(getType()->getStructElementType(Elt));
}
/// getElementValue - Return an undef of the right value for the specified GEP
/// index if we can, otherwise return null (e.g. if C is a ConstantExpr).
UndefValue *UndefValue::getElementValue(Constant *C) const {
if (isa<SequentialType>(getType()))
return getSequentialElement();
return getStructElement(cast<ConstantInt>(C)->getZExtValue());
}
/// getElementValue - Return an undef of the right value for the specified GEP
/// index.
UndefValue *UndefValue::getElementValue(unsigned Idx) const {
if (isa<SequentialType>(getType()))
return getSequentialElement();
return getStructElement(Idx);
}
//===----------------------------------------------------------------------===//
// ConstantXXX Classes
//===----------------------------------------------------------------------===//
template <typename ItTy, typename EltTy>
static bool rangeOnlyContains(ItTy Start, ItTy End, EltTy Elt) {
for (; Start != End; ++Start)
if (*Start != Elt)
return false;
return true;
}
ConstantArray::ConstantArray(ArrayType *T, ArrayRef<Constant *> V)
: Constant(T, ConstantArrayVal,
OperandTraits<ConstantArray>::op_end(this) - V.size(),
V.size()) {
assert(V.size() == T->getNumElements() &&
"Invalid initializer vector for constant array");
for (unsigned i = 0, e = V.size(); i != e; ++i)
assert(V[i]->getType() == T->getElementType() &&
"Initializer for array element doesn't match array element type!");
std::copy(V.begin(), V.end(), op_begin());
}
Constant *ConstantArray::get(ArrayType *Ty, ArrayRef<Constant*> V) {
// Empty arrays are canonicalized to ConstantAggregateZero.
if (V.empty())
return ConstantAggregateZero::get(Ty);
for (unsigned i = 0, e = V.size(); i != e; ++i) {
assert(V[i]->getType() == Ty->getElementType() &&
"Wrong type in array element initializer");
}
LLVMContextImpl *pImpl = Ty->getContext().pImpl;
// If this is an all-zero array, return a ConstantAggregateZero object. If
// all undef, return an UndefValue, if "all simple", then return a
// ConstantDataArray.
Constant *C = V[0];
if (isa<UndefValue>(C) && rangeOnlyContains(V.begin(), V.end(), C))
return UndefValue::get(Ty);
if (C->isNullValue() && rangeOnlyContains(V.begin(), V.end(), C))
return ConstantAggregateZero::get(Ty);
// Check to see if all of the elements are ConstantFP or ConstantInt and if
// the element type is compatible with ConstantDataVector. If so, use it.
if (ConstantDataSequential::isElementTypeCompatible(C->getType())) {
// We speculatively build the elements here even if it turns out that there
// is a constantexpr or something else weird in the array, since it is so
// uncommon for that to happen.
if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
if (CI->getType()->isIntegerTy(8)) {
SmallVector<uint8_t, 16> Elts;
for (unsigned i = 0, e = V.size(); i != e; ++i)
if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
Elts.push_back(CI->getZExtValue());
else
break;
if (Elts.size() == V.size())
return ConstantDataArray::get(C->getContext(), Elts);
} else if (CI->getType()->isIntegerTy(16)) {
SmallVector<uint16_t, 16> Elts;
for (unsigned i = 0, e = V.size(); i != e; ++i)
if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
Elts.push_back(CI->getZExtValue());
else
break;
if (Elts.size() == V.size())
return ConstantDataArray::get(C->getContext(), Elts);
} else if (CI->getType()->isIntegerTy(32)) {
SmallVector<uint32_t, 16> Elts;
for (unsigned i = 0, e = V.size(); i != e; ++i)
if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
Elts.push_back(CI->getZExtValue());
else
break;
if (Elts.size() == V.size())
return ConstantDataArray::get(C->getContext(), Elts);
} else if (CI->getType()->isIntegerTy(64)) {
SmallVector<uint64_t, 16> Elts;
for (unsigned i = 0, e = V.size(); i != e; ++i)
if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
Elts.push_back(CI->getZExtValue());
else
break;
if (Elts.size() == V.size())
return ConstantDataArray::get(C->getContext(), Elts);
}
}
if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
if (CFP->getType()->isFloatTy()) {
SmallVector<float, 16> Elts;
for (unsigned i = 0, e = V.size(); i != e; ++i)
if (ConstantFP *CFP = dyn_cast<ConstantFP>(V[i]))
Elts.push_back(CFP->getValueAPF().convertToFloat());
else
break;
if (Elts.size() == V.size())
return ConstantDataArray::get(C->getContext(), Elts);
} else if (CFP->getType()->isDoubleTy()) {
SmallVector<double, 16> Elts;
for (unsigned i = 0, e = V.size(); i != e; ++i)
if (ConstantFP *CFP = dyn_cast<ConstantFP>(V[i]))
Elts.push_back(CFP->getValueAPF().convertToDouble());
else
break;
if (Elts.size() == V.size())
return ConstantDataArray::get(C->getContext(), Elts);
}
}
}
// Otherwise, we really do want to create a ConstantArray.
return pImpl->ArrayConstants.getOrCreate(Ty, V);
}
/// getTypeForElements - Return an anonymous struct type to use for a constant
/// with the specified set of elements. The list must not be empty.
StructType *ConstantStruct::getTypeForElements(LLVMContext &Context,
ArrayRef<Constant*> V,
bool Packed) {
unsigned VecSize = V.size();
SmallVector<Type*, 16> EltTypes(VecSize);
for (unsigned i = 0; i != VecSize; ++i)
EltTypes[i] = V[i]->getType();
return StructType::get(Context, EltTypes, Packed);
}
StructType *ConstantStruct::getTypeForElements(ArrayRef<Constant*> V,
bool Packed) {
assert(!V.empty() &&
"ConstantStruct::getTypeForElements cannot be called on empty list");
return getTypeForElements(V[0]->getContext(), V, Packed);
}
ConstantStruct::ConstantStruct(StructType *T, ArrayRef<Constant *> V)
: Constant(T, ConstantStructVal,
OperandTraits<ConstantStruct>::op_end(this) - V.size(),
V.size()) {
assert(V.size() == T->getNumElements() &&
"Invalid initializer vector for constant structure");
for (unsigned i = 0, e = V.size(); i != e; ++i)
assert((T->isOpaque() || V[i]->getType() == T->getElementType(i)) &&
"Initializer for struct element doesn't match struct element type!");
std::copy(V.begin(), V.end(), op_begin());
}
// ConstantStruct accessors.
Constant *ConstantStruct::get(StructType *ST, ArrayRef<Constant*> V) {
assert((ST->isOpaque() || ST->getNumElements() == V.size()) &&
"Incorrect # elements specified to ConstantStruct::get");
// Create a ConstantAggregateZero value if all elements are zeros.
bool isZero = true;
bool isUndef = false;
if (!V.empty()) {
isUndef = isa<UndefValue>(V[0]);
isZero = V[0]->isNullValue();
if (isUndef || isZero) {
for (unsigned i = 0, e = V.size(); i != e; ++i) {
if (!V[i]->isNullValue())
isZero = false;
if (!isa<UndefValue>(V[i]))
isUndef = false;
}
}
}
if (isZero)
return ConstantAggregateZero::get(ST);
if (isUndef)
return UndefValue::get(ST);
return ST->getContext().pImpl->StructConstants.getOrCreate(ST, V);
}
Constant *ConstantStruct::get(StructType *T, ...) {
va_list ap;
SmallVector<Constant*, 8> Values;
va_start(ap, T);
while (Constant *Val = va_arg(ap, llvm::Constant*))
Values.push_back(Val);
va_end(ap);
return get(T, Values);
}
ConstantVector::ConstantVector(VectorType *T, ArrayRef<Constant *> V)
: Constant(T, ConstantVectorVal,
OperandTraits<ConstantVector>::op_end(this) - V.size(),
V.size()) {
for (size_t i = 0, e = V.size(); i != e; i++)
assert(V[i]->getType() == T->getElementType() &&
"Initializer for vector element doesn't match vector element type!");
std::copy(V.begin(), V.end(), op_begin());
}
// ConstantVector accessors.
Constant *ConstantVector::get(ArrayRef<Constant*> V) {
assert(!V.empty() && "Vectors can't be empty");
VectorType *T = VectorType::get(V.front()->getType(), V.size());
LLVMContextImpl *pImpl = T->getContext().pImpl;
// If this is an all-undef or all-zero vector, return a
// ConstantAggregateZero or UndefValue.
Constant *C = V[0];
bool isZero = C->isNullValue();
bool isUndef = isa<UndefValue>(C);
if (isZero || isUndef) {
for (unsigned i = 1, e = V.size(); i != e; ++i)
if (V[i] != C) {
isZero = isUndef = false;
break;
}
}
if (isZero)
return ConstantAggregateZero::get(T);
if (isUndef)
return UndefValue::get(T);
// Check to see if all of the elements are ConstantFP or ConstantInt and if
// the element type is compatible with ConstantDataVector. If so, use it.
if (ConstantDataSequential::isElementTypeCompatible(C->getType())) {
// We speculatively build the elements here even if it turns out that there
// is a constantexpr or something else weird in the array, since it is so
// uncommon for that to happen.
if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
if (CI->getType()->isIntegerTy(8)) {
SmallVector<uint8_t, 16> Elts;
for (unsigned i = 0, e = V.size(); i != e; ++i)
if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
Elts.push_back(CI->getZExtValue());
else
break;
if (Elts.size() == V.size())
return ConstantDataVector::get(C->getContext(), Elts);
} else if (CI->getType()->isIntegerTy(16)) {
SmallVector<uint16_t, 16> Elts;
for (unsigned i = 0, e = V.size(); i != e; ++i)
if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
Elts.push_back(CI->getZExtValue());
else
break;
if (Elts.size() == V.size())
return ConstantDataVector::get(C->getContext(), Elts);
} else if (CI->getType()->isIntegerTy(32)) {
SmallVector<uint32_t, 16> Elts;
for (unsigned i = 0, e = V.size(); i != e; ++i)
if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
Elts.push_back(CI->getZExtValue());
else
break;
if (Elts.size() == V.size())
return ConstantDataVector::get(C->getContext(), Elts);
} else if (CI->getType()->isIntegerTy(64)) {
SmallVector<uint64_t, 16> Elts;
for (unsigned i = 0, e = V.size(); i != e; ++i)
if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
Elts.push_back(CI->getZExtValue());
else
break;
if (Elts.size() == V.size())
return ConstantDataVector::get(C->getContext(), Elts);
}
}
if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
if (CFP->getType()->isFloatTy()) {
SmallVector<float, 16> Elts;
for (unsigned i = 0, e = V.size(); i != e; ++i)
if (ConstantFP *CFP = dyn_cast<ConstantFP>(V[i]))