61 #define DEBUG_TYPE "ctrloops"
67 STATISTIC(NumCTRLoops,
"Number of loops converted to CTR loops");
102 bool convertToCTRLoop(
Loop *
L);
157 "PowerPC CTR Loops Verify",
false,
false)
163 return new PPCCTRLoopsVerify();
167 bool PPCCTRLoops::runOnFunction(
Function &
F) {
171 auto *
TPC = getAnalysisIfAvailable<TargetPassConfig>();
176 STI =
TM->getSubtargetImpl(F);
177 TLI = STI->getTargetLowering();
179 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
180 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
181 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
183 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
184 LibInfo = TLIP ? &TLIP->getTLI() :
nullptr;
185 PreserveLCSSA = mustPreserveAnalysisID(
LCSSAID);
187 bool MadeChange =
false;
193 MadeChange |= convertToCTRLoop(L);
201 return ITy->getBitWidth() > (Is32Bit ? 32U : 64U);
212 if (
const auto *CV = dyn_cast<Constant>(MemAddr))
213 for (
const auto &CO : CV->operands())
220 if (!GV->isThreadLocal())
230 for (
unsigned i = 0, ie = CIV.size(); i < ie; ++i) {
233 for (
unsigned j = 0, je = C.
Codes.size(); j < je; ++j)
240 bool PPCCTRLoops::mightUseCTR(
BasicBlock *BB) {
243 if (
CallInst *CI = dyn_cast<CallInst>(J)) {
245 if (
InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue())) {
251 if (
Function *F = CI->getCalledFunction()) {
260 case Intrinsic::ppc_is_decremented_ctr_nonzero:
261 case Intrinsic::ppc_mtctr:
265 #if defined(_MSC_VER) && defined(setjmp) && \
266 !defined(setjmp_undefined_for_msvc)
267 # pragma push_macro("setjmp")
269 # define setjmp_undefined_for_msvc
272 case Intrinsic::setjmp:
274 #if defined(_MSC_VER) && defined(setjmp_undefined_for_msvc)
276 # pragma pop_macro("setjmp")
277 # undef setjmp_undefined_for_msvc
280 case Intrinsic::longjmp:
286 case Intrinsic::eh_sjlj_setjmp:
288 case Intrinsic::memcpy:
289 case Intrinsic::memmove:
290 case Intrinsic::memset:
291 case Intrinsic::powi:
293 case Intrinsic::log2:
294 case Intrinsic::log10:
296 case Intrinsic::exp2:
301 case Intrinsic::copysign:
302 if (CI->getArgOperand(0)->getType()->getScalarType()->
307 case Intrinsic::sqrt: Opcode =
ISD::FSQRT;
break;
308 case Intrinsic::floor: Opcode =
ISD::FFLOOR;
break;
309 case Intrinsic::ceil: Opcode =
ISD::FCEIL;
break;
310 case Intrinsic::trunc: Opcode =
ISD::FTRUNC;
break;
311 case Intrinsic::rint: Opcode =
ISD::FRINT;
break;
316 case Intrinsic::umul_with_overflow: Opcode =
ISD::UMULO;
break;
317 case Intrinsic::smul_with_overflow: Opcode =
ISD::SMULO;
break;
328 LibInfo->getLibFunc(F->
getName(), Func) &&
329 LibInfo->hasOptimizedCodeGen(Func)) {
331 if (!CI->onlyReadsMemory())
335 if (!CI->getArgOperand(0)->getType()->isFloatingPointTy())
339 default:
return true;
340 case LibFunc_copysign:
341 case LibFunc_copysignf:
343 case LibFunc_copysignl:
357 case LibFunc_nearbyint:
358 case LibFunc_nearbyintf:
359 case LibFunc_nearbyintl:
389 MVT VTy = TLI->getSimpleValueType(
390 *
DL, CI->getArgOperand(0)->getType(),
true);
394 if (TLI->isOperationLegalOrCustom(Opcode, VTy))
405 }
else if (isa<BinaryOperator>(J) &&
406 J->getType()->getScalarType()->isPPC_FP128Ty()) {
409 }
else if (isa<UIToFPInst>(J) || isa<SIToFPInst>(J) ||
410 isa<FPToUIInst>(J) || isa<FPToSIInst>(J)) {
418 J->getType()->getScalarType()) &&
419 (J->getOpcode() == Instruction::UDiv ||
420 J->getOpcode() == Instruction::SDiv ||
421 J->getOpcode() == Instruction::URem ||
422 J->getOpcode() == Instruction::SRem)) {
424 }
else if (!
TM->isPPC64() &&
426 (J->getOpcode() == Instruction::Shl ||
427 J->getOpcode() == Instruction::AShr ||
428 J->getOpcode() == Instruction::LShr)) {
432 }
else if (isa<IndirectBrInst>(J) || isa<InvokeInst>(J)) {
435 }
else if (
SwitchInst *SI = dyn_cast<SwitchInst>(J)) {
436 if (
SI->getNumCases() + 1 >= (
unsigned)TLI->getMinimumJumpTableEntries())
440 if (STI->useSoftFloat()) {
441 switch(J->getOpcode()) {
442 case Instruction::FAdd:
443 case Instruction::FSub:
444 case Instruction::FMul:
445 case Instruction::FDiv:
446 case Instruction::FRem:
447 case Instruction::FPTrunc:
448 case Instruction::FPExt:
449 case Instruction::FPToUI:
450 case Instruction::FPToSI:
451 case Instruction::UIToFP:
452 case Instruction::SIToFP:
453 case Instruction::FCmp:
458 for (
Value *Operand : J->operands())
466 bool PPCCTRLoops::convertToCTRLoop(
Loop *L) {
467 bool MadeChange =
false;
471 MadeChange |= convertToCTRLoop(*
I);
472 DEBUG(
dbgs() <<
"Nested loop converted\n");
500 const SCEV *ExitCount =
nullptr;
503 IE = ExitingBlocks.
end();
I !=
IE; ++
I) {
504 const SCEV *
EC = SE->getExitCount(L, *
I);
505 DEBUG(
dbgs() <<
"Exit Count for " << *L <<
" from block " <<
506 (*I)->
getName() <<
": " << *EC <<
"\n");
507 if (isa<SCEVCouldNotCompute>(EC))
509 if (
const SCEVConstant *ConstEC = dyn_cast<SCEVConstant>(EC)) {
510 if (ConstEC->getValue()->isZero())
512 }
else if (!SE->isLoopInvariant(EC, L))
515 if (SE->getTypeSizeInBits(EC->
getType()) > (
TM->isPPC64() ? 64 : 32))
525 bool NotAlways =
false;
531 if (!DT->dominates(*
I, *PI)) {
545 if (
BranchInst *BI = dyn_cast<BranchInst>(TI)) {
546 if (!BI->isConditional())
549 CountedExitBranch = BI;
555 CountedExitBlock = *
I;
560 if (!CountedExitBlock)
569 if (!Preheader || mightUseCTR(Preheader))
574 DEBUG(
dbgs() <<
"Preheader for exit count: " << Preheader->
getName() <<
"\n");
584 ExitCount->
getType() != CountType)
585 ExitCount = SE->getZeroExtendExpr(ExitCount, CountType);
586 ExitCount = SE->getAddExpr(ExitCount, SE->getOne(CountType));
588 SCEVE.expandCodeFor(ExitCount, CountType, Preheader->
getTerminator());
594 CountBuilder.CreateCall(MTCTRFunc, ECValue);
599 Value *NewCond = CondBuilder.CreateCall(DecFunc, {});
642 if (I == MBB->
begin()) {
655 unsigned Opc = I->getOpcode();
656 if (Opc == PPC::MTCTRloop || Opc == PPC::MTCTR8loop) {
664 " clobbers CTR, invalidating " <<
"BB#" <<
665 BI->getParent()->getNumber() <<
" (" <<
666 BI->getParent()->getFullName() <<
") instruction " <<
675 if (!CheckPreds && Preds.
empty())
681 DEBUG(
dbgs() <<
"Unable to find a MTCTR instruction for BB#" <<
682 BI->getParent()->getNumber() <<
" (" <<
683 BI->getParent()->getFullName() <<
") instruction " <<
689 PIE = MBB->
pred_end(); PI != PIE; ++PI)
695 if (!Visited.
count(MBB)) {
699 }
while (!Preds.
empty());
705 MDT = &getAnalysis<MachineDominatorTree>();
712 if (!MDT->isReachableFromEntry(MBB))
716 MIIE = MBB->
end(); MII != MIIE; ++MII) {
717 unsigned Opc = MII->getOpcode();
718 if (Opc == PPC::BDNZ8 || Opc ==
PPC::BDNZ ||
719 Opc == PPC::BDZ8 || Opc ==
PPC::BDZ)
void push_back(const T &Elt)
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
A parsed version of the target data layout string in and methods for querying it. ...
FMINNUM/FMAXNUM - Perform floating-point minimum or maximum on two values.
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
STATISTIC(NumFunctions,"Total number of functions")
void swapSuccessors()
Swap the successors of this branch instruction.
void initializePPCCTRLoopsVerifyPass(PassRegistry &)
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they're not in a MachineFuncti...
A Module instance is used to store all the information related to an LLVM module. ...
static bool memAddrUsesCTR(const PPCTargetMachine &TM, const Value *MemAddr)
iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
The main scalar evolution driver.
This class represents a function call, abstracting a target machine's calling convention.
StringRef getName() const
static uint64_t round(uint64_t Acc, uint64_t Input)
LLVM_NODISCARD bool equals_lower(StringRef RHS) const
equals_lower - Check for string equality, ignoring case.
BasicBlock * InsertPreheaderForLoop(Loop *L, DominatorTree *DT, LoopInfo *LI, bool PreserveLCSSA)
InsertPreheaderForLoop - Once we discover that a loop doesn't have a preheader, this method is called...
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
LoopT * getParentLoop() const
const Function * getParent() const
Return the enclosing method, or null if none.
static IntegerType * getInt64Ty(LLVMContext &C)
BlockT * getHeader() const
ConstraintCodeVector Codes
Code - The constraint code, either the register name (in braces) or the constraint letter/number...
StringRef getName() const
Return a constant reference to the value's name.
std::vector< LoopT * >::const_iterator iterator
iterator/begin/end - The interface to the top-level loops in the current function.
iterator begin()
Instruction iterator methods.
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
This is the base class for all instructions that perform data casts.
bool isReg() const
isReg - Tests if this is a MO_Register operand.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
FunctionPass * createPPCCTRLoops()
void getExitingBlocks(SmallVectorImpl< BlockT * > &ExitingBlocks) const
Return all blocks inside the loop that have successors outside of the loop.
MVT getScalarType() const
If this is a vector, return the element type, otherwise return this.
static cl::opt< int > CTRLoopLimit("ppc-max-ctrloop", cl::Hidden, cl::init(-1))
LLVM_NODISCARD bool empty() const
unsigned getNumOperands() const
Access to explicit operands of the instruction.
ppc ctr loops PowerPC CTR Loops Verify
CHAIN = BDNZ CHAIN, DESTBB - These are used to create counter-based loops.
BasicBlock * getSuccessor(unsigned i) const
bool DeleteDeadPHIs(BasicBlock *BB, const TargetLibraryInfo *TLI=nullptr)
Examine each PHI in the given block and delete it if it is dead.
FunctionPass * createPPCCTRLoopsVerify()
Function * getDeclaration(Module *M, ID id, ArrayRef< Type * > Tys=None)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
iterator getLastNonDebugInstr()
Returns an iterator to the last non-debug instruction in the basic block, or end().
ConstraintPrefix Type
Type - The basic type of the constraint: input/output/clobber.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
bool isPPC_FP128Ty() const
Return true if this is powerpc long double.
ppc ctr PowerPC CTR false
iterator_range< block_iterator > blocks() const
bool verify(const TargetRegisterInfo &TRI) const
Check that information hold by this instance make sense for the given TRI.
initializer< Ty > init(const Ty &Val)
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
LLVM Basic Block Representation.
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.
Type * getType() const
Return the LLVM type of this SCEV expression.
Conditional or Unconditional Branch instruction.
bool isVector() const
Return true if this is a vector value type.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
This file contains the declarations for the subclasses of Constant, which represent the different fla...
const MachineOperand & getOperand(unsigned i) const
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
Interval::pred_iterator pred_begin(Interval *I)
pred_begin/pred_end - define methods so that Intervals may be used just like BasicBlocks can with the...
Represent the analysis usage information of a pass.
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE,"Assign register bank of generic virtual registers", false, false) RegBankSelect
FunctionPass class - This class is used to implement most global optimizations.
Interval::pred_iterator pred_end(Interval *I)
Class to represent integer types.
std::pair< NoneType, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Type * getSrcTy() const
Return the source type, as a convenience.
Common code between 32-bit and 64-bit PowerPC targets.
std::vector< MachineBasicBlock * >::iterator pred_iterator
bool isPointerTy() const
True if this is an instance of PointerType.
bool RecursivelyDeleteTriviallyDeadInstructions(Value *V, const TargetLibraryInfo *TLI=nullptr)
If the specified value is a trivially dead instruction, delete it.
pred_iterator pred_begin()
INITIALIZE_PASS_BEGIN(PPCCTRLoops,"ppc-ctr-loops","PowerPC CTR Loops", false, false) INITIALIZE_PASS_END(PPCCTRLoops
LLVM_READONLY APFloat maxnum(const APFloat &A, const APFloat &B)
Implements IEEE maxNum semantics.
void initializePPCCTRLoopsPass(PassRegistry &)
std::vector< ConstraintInfo > ConstraintInfoVector
bool isRegMask() const
isRegMask - Tests if this is a MO_RegisterMask operand.
size_type count(const T &V) const
count - Return 1 if the element is in the set, 0 otherwise.
std::string getFullName() const
Return a formatted string to identify this block and its parent function.
Iterator for intrusive lists based on ilist_node.
MachineOperand class - Representation of each machine instruction operand.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Module.h This file contains the declarations for the Module class.
Provides information about what library functions are available for the current target.
Type * getDestTy() const
Return the destination type, as a convenience.
LLVM_NODISCARD T pop_back_val()
Intrinsic::ID getIntrinsicID() const LLVM_READONLY
getIntrinsicID - This method returns the ID number of the specified function, or Intrinsic::not_intri...
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
static bool clobbersPhysReg(const uint32_t *RegMask, unsigned PhysReg)
clobbersPhysReg - Returns true if this RegMask clobbers PhysReg.
typename SuperClass::iterator iterator
This class uses information about analyze scalars to rewrite expressions in canonical form...
std::vector< BlockT * >::const_iterator block_iterator
llvm_unreachable("Unknown RegBank!")
block_iterator block_end() const
Representation of each machine instruction.
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
Value * getCondition() const
static bool asmClobbersCTR(InlineAsm *IA)
This class represents an analyzed expression in the program.
Represents a single loop in the control flow graph.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
bool hasLocalLinkage() const
void setCondition(Value *V)
TLSModel::Model getTLSModel(const GlobalValue *GV) const
Returns the TLS model which should be used for the given global variable.
unsigned getReg() const
getReg - Returns the register number.
static bool clobbersCTR(const MachineInstr &MI)
static bool isLargeIntegerTy(bool Is32Bit, Type *Ty)
Module * getParent()
Get the module that this global value is contained inside of...
LLVM Value Representation.
block_iterator block_begin() const
The legacy pass manager's analysis pass to compute loop information.
StringRef - Represent a constant reference to a string, i.e.
PassRegistry - This class manages the registration and intitialization of the pass subsystem as appli...
Legacy analysis pass which computes a DominatorTree.
std::vector< LoopT * >::const_iterator iterator
const TerminatorInst * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
static bool verifyCTRBranch(MachineBasicBlock *MBB, MachineBasicBlock::iterator I)
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
LLVM_READONLY APFloat minnum(const APFloat &A, const APFloat &B)
Implements IEEE minNum semantics.
static ConstraintInfoVector ParseConstraints(StringRef ConstraintString)
ParseConstraints - Split up the constraint string into the specific constraints and their prefixes...
ppc ctr PowerPC CTR Loops
This class represents a constant integer value.