1 //===-- PPCCTRLoops.cpp - Identify and generate CTR loops -----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass identifies loops where we can generate the PPC branch instructions
11 // that decrement and test the count register (CTR) (bdnz and friends).
13 // The pattern that defines the induction variable can changed depending on
14 // prior optimizations. For example, the IndVarSimplify phase run by 'opt'
15 // normalizes induction variables, and the Loop Strength Reduction pass
16 // run by 'llc' may also make changes to the induction variable.
18 // Criteria for CTR loops:
19 // - Countable loops (w/ ind. var for a trip count)
20 // - Try inner-most loops first
21 // - No nested CTR loops.
22 // - No function calls in loops.
24 //===----------------------------------------------------------------------===//
26 #define DEBUG_TYPE "ctrloops"
28 #include "llvm/Transforms/Scalar.h"
29 #include "llvm/ADT/Statistic.h"
30 #include "llvm/ADT/STLExtras.h"
31 #include "llvm/Analysis/Dominators.h"
32 #include "llvm/Analysis/LoopInfo.h"
33 #include "llvm/Analysis/ScalarEvolutionExpander.h"
34 #include "llvm/IR/Constants.h"
35 #include "llvm/IR/DerivedTypes.h"
36 #include "llvm/IR/InlineAsm.h"
37 #include "llvm/IR/Instructions.h"
38 #include "llvm/IR/IntrinsicInst.h"
39 #include "llvm/IR/Module.h"
40 #include "llvm/PassSupport.h"
41 #include "llvm/Support/CommandLine.h"
42 #include "llvm/Support/Debug.h"
43 #include "llvm/Support/ValueHandle.h"
44 #include "llvm/Support/raw_ostream.h"
45 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
46 #include "llvm/Transforms/Utils/Local.h"
47 #include "llvm/Target/TargetLibraryInfo.h"
48 #include "PPCTargetMachine.h"
57 static cl::opt<int> CTRLoopLimit("ppc-max-ctrloop", cl::Hidden, cl::init(-1));
60 STATISTIC(NumCTRLoops, "Number of loops converted to CTR loops");
63 void initializePPCCTRLoopsPass(PassRegistry&);
67 struct PPCCTRLoops : public FunctionPass {
76 PPCCTRLoops() : FunctionPass(ID), TM(0) {
77 initializePPCCTRLoopsPass(*PassRegistry::getPassRegistry());
79 PPCCTRLoops(PPCTargetMachine &TM) : FunctionPass(ID), TM(&TM) {
80 initializePPCCTRLoopsPass(*PassRegistry::getPassRegistry());
83 virtual bool runOnFunction(Function &F);
85 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
86 AU.addRequired<LoopInfo>();
87 AU.addPreserved<LoopInfo>();
88 AU.addRequired<DominatorTree>();
89 AU.addPreserved<DominatorTree>();
90 AU.addRequired<ScalarEvolution>();
94 // FIXME: Copied from LoopSimplify.
95 BasicBlock *InsertPreheaderForLoop(Loop *L);
96 void PlaceSplitBlockCarefully(BasicBlock *NewBB,
97 SmallVectorImpl<BasicBlock*> &SplitPreds,
100 bool mightUseCTR(const Triple &TT, BasicBlock *BB);
101 bool convertToCTRLoop(Loop *L);
103 PPCTargetMachine *TM;
108 const TargetLibraryInfo *LibInfo;
111 char PPCCTRLoops::ID = 0;
113 int PPCCTRLoops::Counter = 0;
115 } // end anonymous namespace
117 INITIALIZE_PASS_BEGIN(PPCCTRLoops, "ppc-ctr-loops", "PowerPC CTR Loops",
119 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
120 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
121 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
122 INITIALIZE_PASS_END(PPCCTRLoops, "ppc-ctr-loops", "PowerPC CTR Loops",
125 FunctionPass *llvm::createPPCCTRLoops(PPCTargetMachine &TM) {
126 return new PPCCTRLoops(TM);
129 bool PPCCTRLoops::runOnFunction(Function &F) {
130 LI = &getAnalysis<LoopInfo>();
131 SE = &getAnalysis<ScalarEvolution>();
132 DT = &getAnalysis<DominatorTree>();
133 TD = getAnalysisIfAvailable<DataLayout>();
134 LibInfo = getAnalysisIfAvailable<TargetLibraryInfo>();
136 bool MadeChange = false;
138 for (LoopInfo::iterator I = LI->begin(), E = LI->end();
141 if (!L->getParentLoop())
142 MadeChange |= convertToCTRLoop(L);
148 bool PPCCTRLoops::mightUseCTR(const Triple &TT, BasicBlock *BB) {
149 for (BasicBlock::iterator J = BB->begin(), JE = BB->end();
151 if (CallInst *CI = dyn_cast<CallInst>(J)) {
152 if (InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue())) {
153 // Inline ASM is okay, unless it clobbers the ctr register.
154 InlineAsm::ConstraintInfoVector CIV = IA->ParseConstraints();
155 for (unsigned i = 0, ie = CIV.size(); i < ie; ++i) {
156 InlineAsm::ConstraintInfo &C = CIV[i];
157 if (C.Type != InlineAsm::isInput)
158 for (unsigned j = 0, je = C.Codes.size(); j < je; ++j)
159 if (StringRef(C.Codes[j]).equals_lower("{ctr}"))
168 const TargetLowering *TLI = TM->getTargetLowering();
170 if (Function *F = CI->getCalledFunction()) {
171 // Most intrinsics don't become function calls, but some might.
172 // sin, cos, exp and log are always calls.
174 if (F->getIntrinsicID() != Intrinsic::not_intrinsic) {
175 switch (F->getIntrinsicID()) {
178 // VisualStudio defines setjmp as _setjmp
179 #if defined(_MSC_VER) && defined(setjmp) && \
180 !defined(setjmp_undefined_for_msvc)
181 # pragma push_macro("setjmp")
183 # define setjmp_undefined_for_msvc
186 case Intrinsic::setjmp:
188 #if defined(_MSC_VER) && defined(setjmp_undefined_for_msvc)
189 // let's return it to _setjmp state
190 # pragma pop_macro("setjmp")
191 # undef setjmp_undefined_for_msvc
194 case Intrinsic::longjmp:
195 case Intrinsic::memcpy:
196 case Intrinsic::memmove:
197 case Intrinsic::memset:
198 case Intrinsic::powi:
200 case Intrinsic::log2:
201 case Intrinsic::log10:
203 case Intrinsic::exp2:
208 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break;
209 case Intrinsic::floor: Opcode = ISD::FFLOOR; break;
210 case Intrinsic::ceil: Opcode = ISD::FCEIL; break;
211 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break;
212 case Intrinsic::rint: Opcode = ISD::FRINT; break;
213 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
217 // PowerPC does not use [US]DIVREM or other library calls for
218 // operations on regular types which are not otherwise library calls
219 // (i.e. soft float or atomics). If adapting for targets that do,
220 // additional care is required here.
223 if (!F->hasLocalLinkage() && F->hasName() && LibInfo &&
224 LibInfo->getLibFunc(F->getName(), Func) &&
225 LibInfo->hasOptimizedCodeGen(Func)) {
226 // Non-read-only functions are never treated as intrinsics.
227 if (!CI->onlyReadsMemory())
230 // Conversion happens only for FP calls.
231 if (!CI->getArgOperand(0)->getType()->isFloatingPointTy())
235 default: return true;
236 case LibFunc::copysign:
237 case LibFunc::copysignf:
238 case LibFunc::copysignl:
239 continue; // ISD::FCOPYSIGN is never a library call.
243 continue; // ISD::FABS is never a library call.
247 Opcode = ISD::FSQRT; break;
249 case LibFunc::floorf:
250 case LibFunc::floorl:
251 Opcode = ISD::FFLOOR; break;
252 case LibFunc::nearbyint:
253 case LibFunc::nearbyintf:
254 case LibFunc::nearbyintl:
255 Opcode = ISD::FNEARBYINT; break;
259 Opcode = ISD::FCEIL; break;
263 Opcode = ISD::FRINT; break;
265 case LibFunc::truncf:
266 case LibFunc::truncl:
267 Opcode = ISD::FTRUNC; break;
271 TLI->getSimpleValueType(CI->getArgOperand(0)->getType(), true);
272 if (VTy == MVT::Other)
275 if (TLI->isOperationLegalOrCustom(Opcode, VTy))
277 else if (VTy.isVector() &&
278 TLI->isOperationLegalOrCustom(Opcode, VTy.getScalarType()))
286 } else if (isa<BinaryOperator>(J) &&
287 J->getType()->getScalarType()->isPPC_FP128Ty()) {
288 // Most operations on ppc_f128 values become calls.
290 } else if (isa<UIToFPInst>(J) || isa<SIToFPInst>(J) ||
291 isa<FPToUIInst>(J) || isa<FPToSIInst>(J)) {
292 CastInst *CI = cast<CastInst>(J);
293 if (CI->getSrcTy()->getScalarType()->isPPC_FP128Ty() ||
294 CI->getDestTy()->getScalarType()->isPPC_FP128Ty() ||
296 (CI->getSrcTy()->getScalarType()->isIntegerTy(64) ||
297 CI->getDestTy()->getScalarType()->isIntegerTy(64))
300 } else if (isa<IndirectBrInst>(J) || isa<InvokeInst>(J)) {
301 // On PowerPC, indirect jumps use the counter register.
303 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(J)) {
306 const TargetLowering *TLI = TM->getTargetLowering();
308 if (TLI->supportJumpTables() &&
309 SI->getNumCases()+1 >= (unsigned) TLI->getMinimumJumpTableEntries())
317 bool PPCCTRLoops::convertToCTRLoop(Loop *L) {
318 bool MadeChange = false;
320 Triple TT = Triple(L->getHeader()->getParent()->getParent()->
322 if (!TT.isArch32Bit() && !TT.isArch64Bit())
323 return MadeChange; // Unknown arch. type.
325 // Process nested loops first.
326 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I) {
327 MadeChange |= convertToCTRLoop(*I);
330 // If a nested loop has been converted, then we can't convert this loop.
335 // Stop trying after reaching the limit (if any).
336 int Limit = CTRLoopLimit;
338 if (Counter >= CTRLoopLimit)
344 // We don't want to spill/restore the counter register, and so we don't
345 // want to use the counter register if the loop contains calls.
346 for (Loop::block_iterator I = L->block_begin(), IE = L->block_end();
348 if (mightUseCTR(TT, *I))
351 SmallVector<BasicBlock*, 4> ExitingBlocks;
352 L->getExitingBlocks(ExitingBlocks);
354 BasicBlock *CountedExitBlock = 0;
355 const SCEV *ExitCount = 0;
356 BranchInst *CountedExitBranch = 0;
357 for (SmallVector<BasicBlock*, 4>::iterator I = ExitingBlocks.begin(),
358 IE = ExitingBlocks.end(); I != IE; ++I) {
359 const SCEV *EC = SE->getExitCount(L, *I);
360 DEBUG(dbgs() << "Exit Count for " << *L << " from block " <<
361 (*I)->getName() << ": " << *EC << "\n");
362 if (isa<SCEVCouldNotCompute>(EC))
364 if (const SCEVConstant *ConstEC = dyn_cast<SCEVConstant>(EC)) {
365 if (ConstEC->getValue()->isZero())
367 } else if (!SE->isLoopInvariant(EC, L))
370 // We now have a loop-invariant count of loop iterations (which is not the
371 // constant zero) for which we know that this loop will not exit via this
374 // We need to make sure that this block will run on every loop iteration.
375 // For this to be true, we must dominate all blocks with backedges. Such
376 // blocks are in-loop predecessors to the header block.
377 bool NotAlways = false;
378 for (pred_iterator PI = pred_begin(L->getHeader()),
379 PIE = pred_end(L->getHeader()); PI != PIE; ++PI) {
380 if (!L->contains(*PI))
383 if (!DT->dominates(*I, *PI)) {
392 // Make sure this blocks ends with a conditional branch.
393 Instruction *TI = (*I)->getTerminator();
397 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
398 if (!BI->isConditional())
401 CountedExitBranch = BI;
405 // Note that this block may not be the loop latch block, even if the loop
406 // has a latch block.
407 CountedExitBlock = *I;
412 if (!CountedExitBlock)
415 BasicBlock *Preheader = L->getLoopPreheader();
417 // If we don't have a preheader, then insert one. If we already have a
418 // preheader, then we can use it (except if the preheader contains a use of
419 // the CTR register because some such uses might be reordered by the
420 // selection DAG after the mtctr instruction).
421 if (!Preheader || mightUseCTR(TT, Preheader))
422 Preheader = InsertPreheaderForLoop(L);
426 DEBUG(dbgs() << "Preheader for exit count: " << Preheader->getName() << "\n");
428 // Insert the count into the preheader and replace the condition used by the
432 SCEVExpander SCEVE(*SE, "loopcnt");
433 LLVMContext &C = SE->getContext();
434 Type *CountType = TT.isArch64Bit() ? Type::getInt64Ty(C) :
436 if (!ExitCount->getType()->isPointerTy() &&
437 ExitCount->getType() != CountType)
438 ExitCount = SE->getZeroExtendExpr(ExitCount, CountType);
439 ExitCount = SE->getAddExpr(ExitCount,
440 SE->getConstant(CountType, 1));
441 Value *ECValue = SCEVE.expandCodeFor(ExitCount, CountType,
442 Preheader->getTerminator());
444 IRBuilder<> CountBuilder(Preheader->getTerminator());
445 Module *M = Preheader->getParent()->getParent();
446 Value *MTCTRFunc = Intrinsic::getDeclaration(M, Intrinsic::ppc_mtctr,
448 CountBuilder.CreateCall(MTCTRFunc, ECValue);
450 IRBuilder<> CondBuilder(CountedExitBranch);
452 Intrinsic::getDeclaration(M, Intrinsic::ppc_is_decremented_ctr_nonzero);
453 Value *NewCond = CondBuilder.CreateCall(DecFunc);
454 Value *OldCond = CountedExitBranch->getCondition();
455 CountedExitBranch->setCondition(NewCond);
457 // The false branch must exit the loop.
458 if (!L->contains(CountedExitBranch->getSuccessor(0)))
459 CountedExitBranch->swapSuccessors();
461 // The old condition may be dead now, and may have even created a dead PHI
462 // (the original induction variable).
463 RecursivelyDeleteTriviallyDeadInstructions(OldCond);
464 DeleteDeadPHIs(CountedExitBlock);
470 // FIXME: Copied from LoopSimplify.
471 BasicBlock *PPCCTRLoops::InsertPreheaderForLoop(Loop *L) {
472 BasicBlock *Header = L->getHeader();
474 // Compute the set of predecessors of the loop that are not in the loop.
475 SmallVector<BasicBlock*, 8> OutsideBlocks;
476 for (pred_iterator PI = pred_begin(Header), PE = pred_end(Header);
479 if (!L->contains(P)) { // Coming in from outside the loop?
480 // If the loop is branched to from an indirect branch, we won't
481 // be able to fully transform the loop, because it prohibits
483 if (isa<IndirectBrInst>(P->getTerminator())) return 0;
486 OutsideBlocks.push_back(P);
490 // Split out the loop pre-header.
491 BasicBlock *PreheaderBB;
492 if (!Header->isLandingPad()) {
493 PreheaderBB = SplitBlockPredecessors(Header, OutsideBlocks, ".preheader",
496 SmallVector<BasicBlock*, 2> NewBBs;
497 SplitLandingPadPredecessors(Header, OutsideBlocks, ".preheader",
498 ".split-lp", this, NewBBs);
499 PreheaderBB = NewBBs[0];
502 PreheaderBB->getTerminator()->setDebugLoc(
503 Header->getFirstNonPHI()->getDebugLoc());
504 DEBUG(dbgs() << "Creating pre-header "
505 << PreheaderBB->getName() << "\n");
507 // Make sure that NewBB is put someplace intelligent, which doesn't mess up
508 // code layout too horribly.
509 PlaceSplitBlockCarefully(PreheaderBB, OutsideBlocks, L);
514 void PPCCTRLoops::PlaceSplitBlockCarefully(BasicBlock *NewBB,
515 SmallVectorImpl<BasicBlock*> &SplitPreds,
517 // Check to see if NewBB is already well placed.
518 Function::iterator BBI = NewBB; --BBI;
519 for (unsigned i = 0, e = SplitPreds.size(); i != e; ++i) {
520 if (&*BBI == SplitPreds[i])
524 // If it isn't already after an outside block, move it after one. This is
525 // always good as it makes the uncond branch from the outside block into a
528 // Figure out *which* outside block to put this after. Prefer an outside
529 // block that neighbors a BB actually in the loop.
530 BasicBlock *FoundBB = 0;
531 for (unsigned i = 0, e = SplitPreds.size(); i != e; ++i) {
532 Function::iterator BBI = SplitPreds[i];
533 if (++BBI != NewBB->getParent()->end() &&
535 FoundBB = SplitPreds[i];
540 // If our heuristic for a *good* bb to place this after doesn't find
541 // anything, just pick something. It's likely better than leaving it within
544 FoundBB = SplitPreds[0];
545 NewBB->moveAfter(FoundBB);