35 #include "llvm/IR/IntrinsicsARM.h" 44 #define DEBUG_TYPE "type-promotion" 45 #define PASS_NAME "Type Promotion" 51 cl::desc(
"Disable type promotion pass"));
109 unsigned PromotedWidth = 0;
121 void PrepareWrappingAdds(
void);
122 void ExtendSources(
void);
123 void ConvertTruncs(
void);
124 void PromoteTree(
void);
125 void TruncateSinks(
void);
133 Ctx(C), OrigTy(Ty), PromotedWidth(Width), Visited(visited),
134 Sources(sources), Sinks(sinks), SafeWrap(wrap) {
137 &&
"Original type not smaller than extended type");
146 unsigned RegisterBitWidth = 0;
152 bool EqualTypeSize(
Value *V);
154 bool LessOrEqualTypeSize(
Value *V);
156 bool GreaterThanTypeSize(
Value *V);
158 bool LessThanTypeSize(
Value *V);
160 bool isSource(
Value *V);
162 bool isSink(
Value *V);
165 bool shouldPromote(
Value *V);
173 bool isSupportedValue(
Value *V);
177 bool TryToPromote(
Value *V,
unsigned PromotedWidth);
197 if (!isa<Instruction>(V))
200 unsigned Opc = cast<Instruction>(V)->
getOpcode();
201 return Opc == Instruction::AShr || Opc == Instruction::SDiv ||
202 Opc == Instruction::SRem || Opc == Instruction::SExt;
205 bool TypePromotion::EqualTypeSize(
Value *V) {
209 bool TypePromotion::LessOrEqualTypeSize(
Value *V) {
213 bool TypePromotion::GreaterThanTypeSize(
Value *V) {
217 bool TypePromotion::LessThanTypeSize(
Value *V) {
228 bool TypePromotion::isSource(
Value *V) {
229 if (!isa<IntegerType>(V->
getType()))
233 if (isa<Argument>(V))
235 else if (isa<LoadInst>(V))
237 else if (isa<BitCastInst>(V))
239 else if (
auto *Call = dyn_cast<CallInst>(V))
240 return Call->hasRetAttr(Attribute::AttrKind::ZExt);
241 else if (
auto *Trunc = dyn_cast<TruncInst>(V))
242 return EqualTypeSize(Trunc);
249 bool TypePromotion::isSink(
Value *V) {
260 if (
auto *
Store = dyn_cast<StoreInst>(V))
261 return LessOrEqualTypeSize(
Store->getValueOperand());
262 if (
auto *
Return = dyn_cast<ReturnInst>(V))
263 return LessOrEqualTypeSize(
Return->getReturnValue());
264 if (
auto *ZExt = dyn_cast<ZExtInst>(V))
265 return GreaterThanTypeSize(ZExt);
266 if (
auto *Switch = dyn_cast<SwitchInst>(V))
267 return LessThanTypeSize(Switch->getCondition());
268 if (
auto *ICmp = dyn_cast<ICmpInst>(V))
269 return ICmp->isSigned() || LessThanTypeSize(ICmp->getOperand(0));
271 return isa<CallInst>(V);
346 bool IsDecreasing = ((Opc == Instruction::Sub) && !NegImm) ||
353 if (CI->isSigned() || CI->isEquality())
357 if (
auto *Const = dyn_cast<ConstantInt>(CI->getOperand(0)))
359 else if (
auto *Const = dyn_cast<ConstantInt>(CI->getOperand(1)))
379 }
else if (Total.
ugt(Max))
388 bool TypePromotion::shouldPromote(
Value *V) {
389 if (!isa<IntegerType>(V->
getType()) || isSink(V))
399 if (isa<ICmpInst>(I))
411 if (!isa<Instruction>(V))
414 if (!isa<OverflowingBinaryOperator>(V))
423 bool ReplacedAll =
true;
425 LLVM_DEBUG(
dbgs() <<
"IR Promotion: Replacing " << *From <<
" with " << *To
429 auto *
User = cast<Instruction>(U.getUser());
430 if (InstTo &&
User->isIdenticalTo(InstTo)) {
437 for (
auto *U : Users)
438 U->replaceUsesOfWith(From, To);
441 if (
auto *I = dyn_cast<Instruction>(From))
445 void IRPromoter::PrepareWrappingAdds() {
453 for (
auto *I : SafeWrap) {
459 cast<ConstantInt>(I->
getOperand(1))->isNegative()) &&
460 "Wrapping should have a negative immediate as the second operand");
462 auto Const = cast<ConstantInt>(I->
getOperand(1));
464 Builder.SetInsertPoint(I);
466 if (
auto *NewInst = dyn_cast<Instruction>(NewVal)) {
467 NewInst->copyIRFlags(I);
472 LLVM_DEBUG(
dbgs() <<
"IR Promotion: New equivalent: " << *NewVal <<
"\n");
474 for (
auto *I : NewInsts)
478 void IRPromoter::ExtendSources() {
482 assert(V->
getType() != ExtTy &&
"zext already extends to i32");
483 LLVM_DEBUG(
dbgs() <<
"IR Promotion: Inserting ZExt for " << *V <<
"\n");
484 Builder.SetInsertPoint(InsertPt);
485 if (
auto *I = dyn_cast<Instruction>(V))
488 Value *ZExt = Builder.CreateZExt(V, ExtTy);
489 if (
auto *I = dyn_cast<Instruction>(ZExt)) {
490 if (isa<Argument>(V))
497 ReplaceAllUsersOfWith(V, ZExt);
502 for (
auto V : Sources) {
504 if (
auto *I = dyn_cast<Instruction>(V))
506 else if (
auto *
Arg = dyn_cast<Argument>(V)) {
516 void IRPromoter::PromoteTree() {
523 for (
auto *V : Visited) {
524 if (Sources.
count(V))
527 auto *I = cast<Instruction>(V);
536 if (
auto *Const = dyn_cast<ConstantInt>(Op)) {
539 }
else if (isa<UndefValue>(Op))
544 if (!isa<ICmpInst>(I)) {
551 void IRPromoter::TruncateSinks() {
557 if (!isa<Instruction>(V) || !isa<IntegerType>(V->
getType()))
563 LLVM_DEBUG(
dbgs() <<
"IR Promotion: Creating " << *TruncTy <<
" Trunc for " 565 Builder.SetInsertPoint(cast<Instruction>(V));
574 for (
auto I : Sinks) {
578 if (
auto *Call = dyn_cast<CallInst>(I)) {
579 for (
unsigned i = 0; i < Call->getNumArgOperands(); ++i) {
580 Value *
Arg = Call->getArgOperand(i);
581 Type *Ty = TruncTysMap[Call][i];
583 Trunc->moveBefore(Call);
584 Call->setArgOperand(i, Trunc);
591 if (
auto *Switch = dyn_cast<SwitchInst>(I)) {
592 Type *Ty = TruncTysMap[Switch][0];
593 if (
Instruction *Trunc = InsertTrunc(Switch->getCondition(), Ty)) {
594 Trunc->moveBefore(Switch);
595 Switch->setCondition(Trunc);
602 Type *Ty = TruncTysMap[
I][i];
604 Trunc->moveBefore(I);
615 for (
auto V : Visited) {
616 if (!isa<ZExtInst>(V))
619 auto ZExt = cast<ZExtInst>(V);
620 if (ZExt->getDestTy() != ExtTy)
623 Value *Src = ZExt->getOperand(0);
624 if (ZExt->getSrcTy() == ZExt->getDestTy()) {
625 LLVM_DEBUG(
dbgs() <<
"IR Promotion: Removing unnecessary cast: " << *ZExt
627 ReplaceAllUsersOfWith(ZExt, Src);
634 if (NewInsts.
count(Src) && isa<TruncInst>(Src) &&
636 auto *Trunc = cast<TruncInst>(Src);
637 assert(Trunc->getOperand(0)->getType() == ExtTy &&
638 "expected inserted trunc to be operating on i32");
639 ReplaceAllUsersOfWith(ZExt, Trunc->getOperand(0));
643 for (
auto *I : InstsToRemove) {
650 void IRPromoter::ConvertTruncs() {
654 for (
auto *V : Visited) {
655 if (!isa<TruncInst>(V) || Sources.
count(V))
658 auto *Trunc = cast<TruncInst>(V);
659 Builder.SetInsertPoint(Trunc);
660 IntegerType *SrcTy = cast<IntegerType>(Trunc->getOperand(0)->getType());
661 IntegerType *DestTy = cast<IntegerType>(TruncTysMap[Trunc][0]);
666 Value *Masked = Builder.CreateAnd(Trunc->getOperand(0),
Mask);
668 if (
auto *I = dyn_cast<Instruction>(Masked))
671 ReplaceAllUsersOfWith(Trunc, Masked);
675 void IRPromoter::Mutate() {
676 LLVM_DEBUG(
dbgs() <<
"IR Promotion: Promoting use-def chains from " 677 << OrigTy->
getBitWidth() <<
" to " << PromotedWidth <<
"-bits\n");
680 for (
auto *I : Sinks) {
681 if (
auto *Call = dyn_cast<CallInst>(I)) {
682 for (
unsigned i = 0; i < Call->getNumArgOperands(); ++i) {
683 Value *
Arg = Call->getArgOperand(i);
684 TruncTysMap[Call].push_back(Arg->
getType());
686 }
else if (
auto *Switch = dyn_cast<SwitchInst>(I))
687 TruncTysMap[I].push_back(Switch->getCondition()->getType());
693 for (
auto *V : Visited) {
694 if (!isa<TruncInst>(V) || Sources.
count(V))
696 auto *Trunc = cast<TruncInst>(V);
697 TruncTysMap[Trunc].push_back(Trunc->getDestTy());
702 PrepareWrappingAdds();
733 if (!isa<IntegerType>(Ty) ||
735 cast<IntegerType>(Ty)->
getBitWidth() > RegisterBitWidth)
738 return LessOrEqualTypeSize(V);
745 bool TypePromotion::isSupportedValue(
Value *V) {
746 if (
auto *I = dyn_cast<Instruction>(V)) {
751 case Instruction::GetElementPtr:
753 case Instruction::Br:
754 case Instruction::Switch:
756 case Instruction::PHI:
760 case Instruction::Trunc:
761 case Instruction::BitCast:
763 case Instruction::ZExt:
765 case Instruction::ICmp:
777 auto *Call = cast<CallInst>(
I);
779 Call->hasRetAttr(Attribute::AttrKind::ZExt);
782 }
else if (isa<Constant>(V) && !isa<ConstantExpr>(V)) {
784 }
else if (isa<Argument>(V))
787 return isa<BasicBlock>(V);
799 if (SafeToPromote.count(I))
803 SafeToPromote.insert(I);
809 bool TypePromotion::TryToPromote(
Value *V,
unsigned PromotedWidth) {
812 SafeToPromote.clear();
818 LLVM_DEBUG(
dbgs() <<
"IR Promotion: TryToPromote: " << *V <<
", from " 819 <<
TypeSize <<
" bits to " << PromotedWidth <<
"\n");
830 auto AddLegalInst = [&](
Value *V) {
831 if (CurrentVisited.
count(V))
836 if (isa<GetElementPtrInst>(V))
840 LLVM_DEBUG(
dbgs() <<
"IR Promotion: Can't handle: " << *V <<
"\n");
849 while (!WorkList.
empty()) {
851 if (CurrentVisited.
count(V))
855 if (!isa<Instruction>(V) && !isSource(V))
862 if (AllVisited.count(V))
866 AllVisited.insert(V);
870 Sinks.
insert(cast<Instruction>(V));
875 if (!isSink(V) && !isSource(V)) {
876 if (
auto *I = dyn_cast<Instruction>(V)) {
879 if (!AddLegalInst(U))
887 if (isSource(V) || shouldPromote(V)) {
889 if (!AddLegalInst(U.getUser()))
896 for (
auto *I : CurrentVisited)
900 unsigned ToPromote = 0;
901 unsigned NonFreeArgs = 0;
903 for (
auto *V : CurrentVisited) {
904 if (
auto *I = dyn_cast<Instruction>(V))
907 if (Sources.
count(V)) {
908 if (
auto *
Arg = dyn_cast<Argument>(V))
909 if (!
Arg->hasZExtAttr() && !
Arg->hasSExtAttr())
914 if (Sinks.
count(cast<Instruction>(V)))
921 if (ToPromote < 2 || (Blocks.
size() == 1 && (NonFreeArgs > SafeWrap.
size())))
927 IRPromoter Promoter(*Ctx, cast<IntegerType>(OrigTy), PromotedWidth,
928 CurrentVisited, Sources, Sinks, SafeWrap);
939 auto *TPC = getAnalysisIfAvailable<TargetPassConfig>();
944 SafeToPromote.clear();
946 bool MadeChange =
false;
952 getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
959 if (AllVisited.count(&I))
962 if (!isa<ICmpInst>(&I))
965 auto *ICmp = cast<ICmpInst>(&
I);
967 if (ICmp->isSigned() ||
968 !isa<IntegerType>(ICmp->getOperand(0)->getType()))
971 LLVM_DEBUG(
dbgs() <<
"IR Promotion: Searching from: " << *ICmp <<
"\n");
973 for (
auto &
Op : ICmp->operands()) {
974 if (
auto *I = dyn_cast<Instruction>(
Op)) {
985 LLVM_DEBUG(
dbgs() <<
"IR Promotion: Couldn't find target register " 986 <<
"for promoted type\n");
1004 SafeToPromote.clear();
1016 return new TypePromotion();
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
APInt abs() const
Get the absolute value;.
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
A parsed version of the target data layout string in and methods for querying it. ...
iterator_range< use_iterator > uses()
static APInt getAllOnesValue(unsigned numBits)
Get the all-ones value.
void dropAllReferences()
Drop all references to operands.
LLVM_NODISCARD T pop_back_val()
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
This class represents lattice values for constants.
void push_back(const T &Elt)
static void Cleanup(DenseMap< Instruction *, Instruction *> &NewPredicates, SetVector< Instruction *> &MaybeDead, Loop *L)
APInt zext(unsigned width) const
Zero extend to a new width.
MVT getSimpleVT() const
Return the SimpleValueType held in the specified simple EVT.
bool isLegalToPromote(CallSite CS, Function *Callee, const char **FailureReason=nullptr)
Return true if the given indirect call site can be made to call Callee.
iv Induction Variable Users
unsigned getBitWidth() const
Return the number of bits in the APInt.
void dump() const
Support for debugging, callable in GDB: V->dump()
AnalysisUsage & addRequired()
FunctionPass * createTypePromotionPass()
Create IR Type Promotion pass.
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
const HexagonInstrInfo * TII
LLVMContext & getContext() const
Get the global data context.
A Use represents the edge between a Value definition and its users.
static Optional< unsigned > getOpcode(ArrayRef< VPValue *> Values)
Returns the opcode of Values or ~0 if they do not all agree.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
This file contains the simple types necessary to represent the attributes associated with functions a...
This class defines information used to lower LLVM code to legal SelectionDAG operators that the targe...
Target-Independent Code Generator Pass Configuration Options.
static Constant * getZExt(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Type * getType() const
All values are typed, get the type of this value.
bool insert(const value_type &X)
Insert a new element into the SetVector.
const APInt & getValue() const
Return the constant as an APInt value reference.
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
unsigned getBitWidth() const
Get the number of bits in this IntegerType.
Value * getOperand(unsigned i) const
size_type count(const key_type &key) const
Count the number of elements of a given key in the SetVector.
bool isVoidTy() const
Return true if this is 'void'.
static bool runOnFunction(Function &F, bool PostInlining)
initializer< Ty > init(const Ty &Val)
const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
LLVM Basic Block Representation.
TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
The instances of the Type class are immutable: once they are created, they are never changed...
This is an important class for using LLVM in a threaded context.
This is an important base class in LLVM.
This file contains the declarations for the subclasses of Constant, which represent the different fla...
bool isPointerTy() const
True if this is an instance of PointerType.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Represent the analysis usage information of a pass.
FunctionPass class - This class is used to implement most global optimizations.
amdgpu Simplify well known AMD library false FunctionCallee Value * Arg
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
Class to represent integer types.
static bool hasNoUnsignedWrap(BinaryOperator &I)
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
TypeSize getSizeInBits() const
Return the size of the specified value type in bits.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
EVT getValueType(const DataLayout &DL, Type *Ty, bool AllowUnknown=false) const
Return the EVT corresponding to this LLVM type.
static IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
unsigned getNumOperands() const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
This is the shared class of boolean and integer constants.
BlockVerifier::State From
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
virtual const TargetSubtargetInfo * getSubtargetImpl(const Function &) const
Virtual method implemented by subclasses that returns a reference to that target's TargetSubtargetInf...
void setOperand(unsigned i, Value *Val)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
bool isTypeLegal(EVT VT) const
Return true if the target has native support for the specified value type.
Class for arbitrary precision integers.
static APInt getMaxValue(unsigned numBits)
Gets maximum unsigned value of APInt for specific bit width.
TargetSubtargetInfo - Generic base class for all target subtargets.
bool ugt(const APInt &RHS) const
Unsigned greater than comparison.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVMAttributeRef wrap(Attribute Attr)
StringRef getName() const
Return a constant reference to the value's name.
LegalizeTypeAction getTypeAction(LLVMContext &Context, EVT VT) const
Return how we should legalize values of this type, either it is already legal (return 'Legal') or we ...
bool empty() const
Determine if the SetVector is empty or not.
bool verifyFunction(const Function &F, raw_ostream *OS=nullptr)
Check a function for errors, useful for use when debugging a pass.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
static bool isSupportedType(const DataLayout &DL, const ARMTargetLowering &TLI, Type *T)
void mutateType(Type *Ty)
Mutate the type of this Value to be of the specified type.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
void moveAfter(Instruction *MovePos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
user_iterator user_begin()
Module * getParent()
Get the module that this global value is contained inside of...
LLVM Value Representation.
std::underlying_type< E >::type Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
void moveBefore(Instruction *MovePos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
Primary interface to the complete machine description for the target machine.
bool hasOneUse() const
Return true if there is exactly one user of this value.
StringRef - Represent a constant reference to a string, i.e.
bool isSimple() const
Test if the given EVT is simple (as opposed to being extended).
EVT getTypeToTransformTo(LLVMContext &Context, EVT VT) const
For types supported by the target, this is an identity function.
This file describes how to lower LLVM code to machine code.
const BasicBlock * getParent() const