blob: d36fec0a0a51179256e281d19564da6f99ea5ff8 [file] [log] [blame]
Hal Finkel99f823f2012-06-08 15:38:21 +00001//===-- PPCCTRLoops.cpp - Identify and generate CTR loops -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
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).
Hal Finkel99f823f2012-06-08 15:38:21 +000012//
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.
Hal Finkel99f823f2012-06-08 15:38:21 +000017//
18// Criteria for CTR loops:
19// - Countable loops (w/ ind. var for a trip count)
Hal Finkel99f823f2012-06-08 15:38:21 +000020// - Try inner-most loops first
21// - No nested CTR loops.
22// - No function calls in loops.
23//
Hal Finkel99f823f2012-06-08 15:38:21 +000024//===----------------------------------------------------------------------===//
25
26#define DEBUG_TYPE "ctrloops"
Hal Finkelb1fd3cd2013-05-15 21:37:41 +000027
28#include "llvm/Transforms/Scalar.h"
Hal Finkel99f823f2012-06-08 15:38:21 +000029#include "llvm/ADT/Statistic.h"
Hal Finkelb1fd3cd2013-05-15 21:37:41 +000030#include "llvm/ADT/STLExtras.h"
31#include "llvm/Analysis/Dominators.h"
32#include "llvm/Analysis/LoopInfo.h"
33#include "llvm/Analysis/ScalarEvolutionExpander.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000034#include "llvm/IR/Constants.h"
Hal Finkelb1fd3cd2013-05-15 21:37:41 +000035#include "llvm/IR/DerivedTypes.h"
Hal Finkelbf0bc3b2013-05-18 09:20:39 +000036#include "llvm/IR/InlineAsm.h"
Hal Finkelb1fd3cd2013-05-15 21:37:41 +000037#include "llvm/IR/Instructions.h"
38#include "llvm/IR/IntrinsicInst.h"
39#include "llvm/IR/Module.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000040#include "llvm/PassSupport.h"
Hal Finkelb1fd3cd2013-05-15 21:37:41 +000041#include "llvm/Support/CommandLine.h"
Hal Finkel99f823f2012-06-08 15:38:21 +000042#include "llvm/Support/Debug.h"
Hal Finkelb1fd3cd2013-05-15 21:37:41 +000043#include "llvm/Support/ValueHandle.h"
Hal Finkel99f823f2012-06-08 15:38:21 +000044#include "llvm/Support/raw_ostream.h"
Hal Finkelb1fd3cd2013-05-15 21:37:41 +000045#include "llvm/Transforms/Utils/BasicBlockUtils.h"
46#include "llvm/Transforms/Utils/Local.h"
47#include "llvm/Target/TargetLibraryInfo.h"
48#include "PPCTargetMachine.h"
49#include "PPC.h"
50
Hal Finkele50c8c12013-05-20 16:08:17 +000051#ifndef NDEBUG
52#include "llvm/CodeGen/MachineDominators.h"
53#include "llvm/CodeGen/MachineFunction.h"
54#include "llvm/CodeGen/MachineFunctionPass.h"
55#include "llvm/CodeGen/MachineRegisterInfo.h"
56#endif
57
Hal Finkel99f823f2012-06-08 15:38:21 +000058#include <algorithm>
Hal Finkelb1fd3cd2013-05-15 21:37:41 +000059#include <vector>
Hal Finkel99f823f2012-06-08 15:38:21 +000060
61using namespace llvm;
62
Hal Finkelb1fd3cd2013-05-15 21:37:41 +000063#ifndef NDEBUG
64static cl::opt<int> CTRLoopLimit("ppc-max-ctrloop", cl::Hidden, cl::init(-1));
65#endif
66
Hal Finkel99f823f2012-06-08 15:38:21 +000067STATISTIC(NumCTRLoops, "Number of loops converted to CTR loops");
68
Krzysztof Parzyszek96848df2013-02-13 17:40:07 +000069namespace llvm {
70 void initializePPCCTRLoopsPass(PassRegistry&);
Hal Finkele50c8c12013-05-20 16:08:17 +000071#ifndef NDEBUG
72 void initializePPCCTRLoopsVerifyPass(PassRegistry&);
73#endif
Krzysztof Parzyszek96848df2013-02-13 17:40:07 +000074}
75
Hal Finkel99f823f2012-06-08 15:38:21 +000076namespace {
Hal Finkelb1fd3cd2013-05-15 21:37:41 +000077 struct PPCCTRLoops : public FunctionPass {
78
79#ifndef NDEBUG
80 static int Counter;
81#endif
Hal Finkel99f823f2012-06-08 15:38:21 +000082
83 public:
Hal Finkelb1fd3cd2013-05-15 21:37:41 +000084 static char ID;
Hal Finkel99f823f2012-06-08 15:38:21 +000085
Hal Finkelb1fd3cd2013-05-15 21:37:41 +000086 PPCCTRLoops() : FunctionPass(ID), TM(0) {
87 initializePPCCTRLoopsPass(*PassRegistry::getPassRegistry());
88 }
89 PPCCTRLoops(PPCTargetMachine &TM) : FunctionPass(ID), TM(&TM) {
Krzysztof Parzyszek96848df2013-02-13 17:40:07 +000090 initializePPCCTRLoopsPass(*PassRegistry::getPassRegistry());
91 }
Hal Finkel99f823f2012-06-08 15:38:21 +000092
Hal Finkelb1fd3cd2013-05-15 21:37:41 +000093 virtual bool runOnFunction(Function &F);
Hal Finkel99f823f2012-06-08 15:38:21 +000094
95 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Hal Finkelb1fd3cd2013-05-15 21:37:41 +000096 AU.addRequired<LoopInfo>();
97 AU.addPreserved<LoopInfo>();
98 AU.addRequired<DominatorTree>();
99 AU.addPreserved<DominatorTree>();
100 AU.addRequired<ScalarEvolution>();
Hal Finkel99f823f2012-06-08 15:38:21 +0000101 }
102
103 private:
Hal Finkelb1fd3cd2013-05-15 21:37:41 +0000104 // FIXME: Copied from LoopSimplify.
105 BasicBlock *InsertPreheaderForLoop(Loop *L);
106 void PlaceSplitBlockCarefully(BasicBlock *NewBB,
107 SmallVectorImpl<BasicBlock*> &SplitPreds,
108 Loop *L);
Hal Finkel99f823f2012-06-08 15:38:21 +0000109
Hal Finkelc4824542013-05-16 19:58:38 +0000110 bool mightUseCTR(const Triple &TT, BasicBlock *BB);
Hal Finkelb1fd3cd2013-05-15 21:37:41 +0000111 bool convertToCTRLoop(Loop *L);
112 private:
113 PPCTargetMachine *TM;
114 LoopInfo *LI;
115 ScalarEvolution *SE;
116 DataLayout *TD;
117 DominatorTree *DT;
118 const TargetLibraryInfo *LibInfo;
Hal Finkel99f823f2012-06-08 15:38:21 +0000119 };
120
121 char PPCCTRLoops::ID = 0;
Hal Finkelb1fd3cd2013-05-15 21:37:41 +0000122#ifndef NDEBUG
123 int PPCCTRLoops::Counter = 0;
124#endif
Hal Finkele50c8c12013-05-20 16:08:17 +0000125
126#ifndef NDEBUG
127 struct PPCCTRLoopsVerify : public MachineFunctionPass {
128 public:
129 static char ID;
130
131 PPCCTRLoopsVerify() : MachineFunctionPass(ID) {
132 initializePPCCTRLoopsVerifyPass(*PassRegistry::getPassRegistry());
133 }
134
135 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
136 AU.addRequired<MachineDominatorTree>();
137 MachineFunctionPass::getAnalysisUsage(AU);
138 }
139
140 virtual bool runOnMachineFunction(MachineFunction &MF);
141
142 private:
143 MachineDominatorTree *MDT;
144 };
145
146 char PPCCTRLoopsVerify::ID = 0;
147#endif // NDEBUG
Hal Finkel99f823f2012-06-08 15:38:21 +0000148} // end anonymous namespace
149
Krzysztof Parzyszek96848df2013-02-13 17:40:07 +0000150INITIALIZE_PASS_BEGIN(PPCCTRLoops, "ppc-ctr-loops", "PowerPC CTR Loops",
151 false, false)
Hal Finkelb1fd3cd2013-05-15 21:37:41 +0000152INITIALIZE_PASS_DEPENDENCY(DominatorTree)
153INITIALIZE_PASS_DEPENDENCY(LoopInfo)
154INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
Krzysztof Parzyszek96848df2013-02-13 17:40:07 +0000155INITIALIZE_PASS_END(PPCCTRLoops, "ppc-ctr-loops", "PowerPC CTR Loops",
156 false, false)
Hal Finkel99f823f2012-06-08 15:38:21 +0000157
Hal Finkelb1fd3cd2013-05-15 21:37:41 +0000158FunctionPass *llvm::createPPCCTRLoops(PPCTargetMachine &TM) {
159 return new PPCCTRLoops(TM);
Hal Finkel99f823f2012-06-08 15:38:21 +0000160}
161
Hal Finkele50c8c12013-05-20 16:08:17 +0000162#ifndef NDEBUG
163INITIALIZE_PASS_BEGIN(PPCCTRLoopsVerify, "ppc-ctr-loops-verify",
164 "PowerPC CTR Loops Verify", false, false)
165INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
166INITIALIZE_PASS_END(PPCCTRLoopsVerify, "ppc-ctr-loops-verify",
167 "PowerPC CTR Loops Verify", false, false)
168
169FunctionPass *llvm::createPPCCTRLoopsVerify() {
170 return new PPCCTRLoopsVerify();
171}
172#endif // NDEBUG
173
Hal Finkelb1fd3cd2013-05-15 21:37:41 +0000174bool PPCCTRLoops::runOnFunction(Function &F) {
175 LI = &getAnalysis<LoopInfo>();
176 SE = &getAnalysis<ScalarEvolution>();
177 DT = &getAnalysis<DominatorTree>();
178 TD = getAnalysisIfAvailable<DataLayout>();
179 LibInfo = getAnalysisIfAvailable<TargetLibraryInfo>();
Hal Finkel99f823f2012-06-08 15:38:21 +0000180
Hal Finkelb1fd3cd2013-05-15 21:37:41 +0000181 bool MadeChange = false;
Hal Finkel99f823f2012-06-08 15:38:21 +0000182
Hal Finkelb1fd3cd2013-05-15 21:37:41 +0000183 for (LoopInfo::iterator I = LI->begin(), E = LI->end();
Hal Finkel99f823f2012-06-08 15:38:21 +0000184 I != E; ++I) {
Hal Finkelb1fd3cd2013-05-15 21:37:41 +0000185 Loop *L = *I;
186 if (!L->getParentLoop())
187 MadeChange |= convertToCTRLoop(L);
Hal Finkel99f823f2012-06-08 15:38:21 +0000188 }
189
Hal Finkelb1fd3cd2013-05-15 21:37:41 +0000190 return MadeChange;
Hal Finkel99f823f2012-06-08 15:38:21 +0000191}
192
Hal Finkelc4824542013-05-16 19:58:38 +0000193bool PPCCTRLoops::mightUseCTR(const Triple &TT, BasicBlock *BB) {
194 for (BasicBlock::iterator J = BB->begin(), JE = BB->end();
195 J != JE; ++J) {
196 if (CallInst *CI = dyn_cast<CallInst>(J)) {
Hal Finkelbf0bc3b2013-05-18 09:20:39 +0000197 if (InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue())) {
198 // Inline ASM is okay, unless it clobbers the ctr register.
199 InlineAsm::ConstraintInfoVector CIV = IA->ParseConstraints();
200 for (unsigned i = 0, ie = CIV.size(); i < ie; ++i) {
201 InlineAsm::ConstraintInfo &C = CIV[i];
202 if (C.Type != InlineAsm::isInput)
203 for (unsigned j = 0, je = C.Codes.size(); j < je; ++j)
204 if (StringRef(C.Codes[j]).equals_lower("{ctr}"))
205 return true;
206 }
207
208 continue;
209 }
210
Hal Finkelc4824542013-05-16 19:58:38 +0000211 if (!TM)
212 return true;
213 const TargetLowering *TLI = TM->getTargetLowering();
214
215 if (Function *F = CI->getCalledFunction()) {
216 // Most intrinsics don't become function calls, but some might.
217 // sin, cos, exp and log are always calls.
218 unsigned Opcode;
219 if (F->getIntrinsicID() != Intrinsic::not_intrinsic) {
220 switch (F->getIntrinsicID()) {
221 default: continue;
222
223// VisualStudio defines setjmp as _setjmp
224#if defined(_MSC_VER) && defined(setjmp) && \
225 !defined(setjmp_undefined_for_msvc)
226# pragma push_macro("setjmp")
227# undef setjmp
228# define setjmp_undefined_for_msvc
229#endif
230
231 case Intrinsic::setjmp:
232
233#if defined(_MSC_VER) && defined(setjmp_undefined_for_msvc)
234 // let's return it to _setjmp state
235# pragma pop_macro("setjmp")
236# undef setjmp_undefined_for_msvc
237#endif
238
239 case Intrinsic::longjmp:
240 case Intrinsic::memcpy:
241 case Intrinsic::memmove:
242 case Intrinsic::memset:
243 case Intrinsic::powi:
244 case Intrinsic::log:
245 case Intrinsic::log2:
246 case Intrinsic::log10:
247 case Intrinsic::exp:
248 case Intrinsic::exp2:
249 case Intrinsic::pow:
250 case Intrinsic::sin:
251 case Intrinsic::cos:
252 return true;
253 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break;
254 case Intrinsic::floor: Opcode = ISD::FFLOOR; break;
255 case Intrinsic::ceil: Opcode = ISD::FCEIL; break;
256 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break;
257 case Intrinsic::rint: Opcode = ISD::FRINT; break;
258 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
259 }
260 }
261
262 // PowerPC does not use [US]DIVREM or other library calls for
263 // operations on regular types which are not otherwise library calls
264 // (i.e. soft float or atomics). If adapting for targets that do,
265 // additional care is required here.
266
267 LibFunc::Func Func;
268 if (!F->hasLocalLinkage() && F->hasName() && LibInfo &&
269 LibInfo->getLibFunc(F->getName(), Func) &&
270 LibInfo->hasOptimizedCodeGen(Func)) {
271 // Non-read-only functions are never treated as intrinsics.
272 if (!CI->onlyReadsMemory())
273 return true;
274
275 // Conversion happens only for FP calls.
276 if (!CI->getArgOperand(0)->getType()->isFloatingPointTy())
277 return true;
278
279 switch (Func) {
280 default: return true;
281 case LibFunc::copysign:
282 case LibFunc::copysignf:
283 case LibFunc::copysignl:
284 continue; // ISD::FCOPYSIGN is never a library call.
285 case LibFunc::fabs:
286 case LibFunc::fabsf:
287 case LibFunc::fabsl:
288 continue; // ISD::FABS is never a library call.
289 case LibFunc::sqrt:
290 case LibFunc::sqrtf:
291 case LibFunc::sqrtl:
292 Opcode = ISD::FSQRT; break;
293 case LibFunc::floor:
294 case LibFunc::floorf:
295 case LibFunc::floorl:
296 Opcode = ISD::FFLOOR; break;
297 case LibFunc::nearbyint:
298 case LibFunc::nearbyintf:
299 case LibFunc::nearbyintl:
300 Opcode = ISD::FNEARBYINT; break;
301 case LibFunc::ceil:
302 case LibFunc::ceilf:
303 case LibFunc::ceill:
304 Opcode = ISD::FCEIL; break;
305 case LibFunc::rint:
306 case LibFunc::rintf:
307 case LibFunc::rintl:
308 Opcode = ISD::FRINT; break;
309 case LibFunc::trunc:
310 case LibFunc::truncf:
311 case LibFunc::truncl:
312 Opcode = ISD::FTRUNC; break;
313 }
314
315 MVT VTy =
316 TLI->getSimpleValueType(CI->getArgOperand(0)->getType(), true);
317 if (VTy == MVT::Other)
318 return true;
319
320 if (TLI->isOperationLegalOrCustom(Opcode, VTy))
321 continue;
322 else if (VTy.isVector() &&
323 TLI->isOperationLegalOrCustom(Opcode, VTy.getScalarType()))
324 continue;
325
326 return true;
327 }
328 }
329
330 return true;
331 } else if (isa<BinaryOperator>(J) &&
332 J->getType()->getScalarType()->isPPC_FP128Ty()) {
333 // Most operations on ppc_f128 values become calls.
334 return true;
335 } else if (isa<UIToFPInst>(J) || isa<SIToFPInst>(J) ||
336 isa<FPToUIInst>(J) || isa<FPToSIInst>(J)) {
337 CastInst *CI = cast<CastInst>(J);
338 if (CI->getSrcTy()->getScalarType()->isPPC_FP128Ty() ||
339 CI->getDestTy()->getScalarType()->isPPC_FP128Ty() ||
340 (TT.isArch32Bit() &&
341 (CI->getSrcTy()->getScalarType()->isIntegerTy(64) ||
342 CI->getDestTy()->getScalarType()->isIntegerTy(64))
343 ))
344 return true;
345 } else if (isa<IndirectBrInst>(J) || isa<InvokeInst>(J)) {
346 // On PowerPC, indirect jumps use the counter register.
347 return true;
348 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(J)) {
349 if (!TM)
350 return true;
351 const TargetLowering *TLI = TM->getTargetLowering();
352
353 if (TLI->supportJumpTables() &&
354 SI->getNumCases()+1 >= (unsigned) TLI->getMinimumJumpTableEntries())
355 return true;
356 }
357 }
358
359 return false;
360}
361
Hal Finkelb1fd3cd2013-05-15 21:37:41 +0000362bool PPCCTRLoops::convertToCTRLoop(Loop *L) {
363 bool MadeChange = false;
Hal Finkel99f823f2012-06-08 15:38:21 +0000364
Hal Finkelb1fd3cd2013-05-15 21:37:41 +0000365 Triple TT = Triple(L->getHeader()->getParent()->getParent()->
366 getTargetTriple());
367 if (!TT.isArch32Bit() && !TT.isArch64Bit())
368 return MadeChange; // Unknown arch. type.
Hal Finkel99f823f2012-06-08 15:38:21 +0000369
Hal Finkel99f823f2012-06-08 15:38:21 +0000370 // Process nested loops first.
Hal Finkelb1fd3cd2013-05-15 21:37:41 +0000371 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I) {
372 MadeChange |= convertToCTRLoop(*I);
Hal Finkel99f823f2012-06-08 15:38:21 +0000373 }
Hal Finkelb1fd3cd2013-05-15 21:37:41 +0000374
Hal Finkel99f823f2012-06-08 15:38:21 +0000375 // If a nested loop has been converted, then we can't convert this loop.
Hal Finkelb1fd3cd2013-05-15 21:37:41 +0000376 if (MadeChange)
377 return MadeChange;
Hal Finkel99f823f2012-06-08 15:38:21 +0000378
Hal Finkelb1fd3cd2013-05-15 21:37:41 +0000379#ifndef NDEBUG
380 // Stop trying after reaching the limit (if any).
381 int Limit = CTRLoopLimit;
382 if (Limit >= 0) {
383 if (Counter >= CTRLoopLimit)
Hal Finkel9887ec32013-03-18 17:40:44 +0000384 return false;
Hal Finkelb1fd3cd2013-05-15 21:37:41 +0000385 Counter++;
Hal Finkel9887ec32013-03-18 17:40:44 +0000386 }
Hal Finkelb1fd3cd2013-05-15 21:37:41 +0000387#endif
Hal Finkel9887ec32013-03-18 17:40:44 +0000388
Hal Finkelb1fd3cd2013-05-15 21:37:41 +0000389 // We don't want to spill/restore the counter register, and so we don't
390 // want to use the counter register if the loop contains calls.
391 for (Loop::block_iterator I = L->block_begin(), IE = L->block_end();
Hal Finkelc4824542013-05-16 19:58:38 +0000392 I != IE; ++I)
393 if (mightUseCTR(TT, *I))
394 return MadeChange;
Hal Finkel99f823f2012-06-08 15:38:21 +0000395
Hal Finkelb1fd3cd2013-05-15 21:37:41 +0000396 SmallVector<BasicBlock*, 4> ExitingBlocks;
397 L->getExitingBlocks(ExitingBlocks);
Hal Finkel99f823f2012-06-08 15:38:21 +0000398
Hal Finkelb1fd3cd2013-05-15 21:37:41 +0000399 BasicBlock *CountedExitBlock = 0;
400 const SCEV *ExitCount = 0;
401 BranchInst *CountedExitBranch = 0;
402 for (SmallVector<BasicBlock*, 4>::iterator I = ExitingBlocks.begin(),
403 IE = ExitingBlocks.end(); I != IE; ++I) {
404 const SCEV *EC = SE->getExitCount(L, *I);
405 DEBUG(dbgs() << "Exit Count for " << *L << " from block " <<
406 (*I)->getName() << ": " << *EC << "\n");
407 if (isa<SCEVCouldNotCompute>(EC))
408 continue;
409 if (const SCEVConstant *ConstEC = dyn_cast<SCEVConstant>(EC)) {
410 if (ConstEC->getValue()->isZero())
411 continue;
412 } else if (!SE->isLoopInvariant(EC, L))
413 continue;
Hal Finkel99f823f2012-06-08 15:38:21 +0000414
Hal Finkelb1fd3cd2013-05-15 21:37:41 +0000415 // We now have a loop-invariant count of loop iterations (which is not the
416 // constant zero) for which we know that this loop will not exit via this
417 // exisiting block.
Hal Finkel2741d2c2012-06-16 20:34:07 +0000418
Hal Finkelb1fd3cd2013-05-15 21:37:41 +0000419 // We need to make sure that this block will run on every loop iteration.
420 // For this to be true, we must dominate all blocks with backedges. Such
421 // blocks are in-loop predecessors to the header block.
422 bool NotAlways = false;
423 for (pred_iterator PI = pred_begin(L->getHeader()),
424 PIE = pred_end(L->getHeader()); PI != PIE; ++PI) {
425 if (!L->contains(*PI))
426 continue;
427
428 if (!DT->dominates(*I, *PI)) {
429 NotAlways = true;
430 break;
431 }
Hal Finkel99f823f2012-06-08 15:38:21 +0000432 }
Hal Finkel99f823f2012-06-08 15:38:21 +0000433
Hal Finkelb1fd3cd2013-05-15 21:37:41 +0000434 if (NotAlways)
435 continue;
Hal Finkel99f823f2012-06-08 15:38:21 +0000436
Hal Finkelb1fd3cd2013-05-15 21:37:41 +0000437 // Make sure this blocks ends with a conditional branch.
438 Instruction *TI = (*I)->getTerminator();
439 if (!TI)
440 continue;
441
442 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
443 if (!BI->isConditional())
444 continue;
445
446 CountedExitBranch = BI;
447 } else
448 continue;
449
450 // Note that this block may not be the loop latch block, even if the loop
451 // has a latch block.
452 CountedExitBlock = *I;
453 ExitCount = EC;
454 break;
Hal Finkel99f823f2012-06-08 15:38:21 +0000455 }
456
Hal Finkelb1fd3cd2013-05-15 21:37:41 +0000457 if (!CountedExitBlock)
458 return MadeChange;
Hal Finkel99f823f2012-06-08 15:38:21 +0000459
Hal Finkelb1fd3cd2013-05-15 21:37:41 +0000460 BasicBlock *Preheader = L->getLoopPreheader();
Hal Finkelc4824542013-05-16 19:58:38 +0000461
462 // If we don't have a preheader, then insert one. If we already have a
463 // preheader, then we can use it (except if the preheader contains a use of
464 // the CTR register because some such uses might be reordered by the
465 // selection DAG after the mtctr instruction).
466 if (!Preheader || mightUseCTR(TT, Preheader))
Hal Finkelb1fd3cd2013-05-15 21:37:41 +0000467 Preheader = InsertPreheaderForLoop(L);
468 if (!Preheader)
469 return MadeChange;
Hal Finkel99f823f2012-06-08 15:38:21 +0000470
Hal Finkelb1fd3cd2013-05-15 21:37:41 +0000471 DEBUG(dbgs() << "Preheader for exit count: " << Preheader->getName() << "\n");
Hal Finkel99f823f2012-06-08 15:38:21 +0000472
Hal Finkelb1fd3cd2013-05-15 21:37:41 +0000473 // Insert the count into the preheader and replace the condition used by the
474 // selected branch.
475 MadeChange = true;
Hal Finkel99f823f2012-06-08 15:38:21 +0000476
Hal Finkelb1fd3cd2013-05-15 21:37:41 +0000477 SCEVExpander SCEVE(*SE, "loopcnt");
478 LLVMContext &C = SE->getContext();
479 Type *CountType = TT.isArch64Bit() ? Type::getInt64Ty(C) :
480 Type::getInt32Ty(C);
481 if (!ExitCount->getType()->isPointerTy() &&
482 ExitCount->getType() != CountType)
483 ExitCount = SE->getZeroExtendExpr(ExitCount, CountType);
484 ExitCount = SE->getAddExpr(ExitCount,
485 SE->getConstant(CountType, 1));
486 Value *ECValue = SCEVE.expandCodeFor(ExitCount, CountType,
487 Preheader->getTerminator());
Hal Finkel99f823f2012-06-08 15:38:21 +0000488
Hal Finkelb1fd3cd2013-05-15 21:37:41 +0000489 IRBuilder<> CountBuilder(Preheader->getTerminator());
490 Module *M = Preheader->getParent()->getParent();
491 Value *MTCTRFunc = Intrinsic::getDeclaration(M, Intrinsic::ppc_mtctr,
492 CountType);
493 CountBuilder.CreateCall(MTCTRFunc, ECValue);
Hal Finkel99f823f2012-06-08 15:38:21 +0000494
Hal Finkelb1fd3cd2013-05-15 21:37:41 +0000495 IRBuilder<> CondBuilder(CountedExitBranch);
496 Value *DecFunc =
497 Intrinsic::getDeclaration(M, Intrinsic::ppc_is_decremented_ctr_nonzero);
498 Value *NewCond = CondBuilder.CreateCall(DecFunc);
499 Value *OldCond = CountedExitBranch->getCondition();
500 CountedExitBranch->setCondition(NewCond);
501
502 // The false branch must exit the loop.
503 if (!L->contains(CountedExitBranch->getSuccessor(0)))
504 CountedExitBranch->swapSuccessors();
505
506 // The old condition may be dead now, and may have even created a dead PHI
507 // (the original induction variable).
508 RecursivelyDeleteTriviallyDeadInstructions(OldCond);
509 DeleteDeadPHIs(CountedExitBlock);
Hal Finkel99f823f2012-06-08 15:38:21 +0000510
511 ++NumCTRLoops;
Hal Finkelb1fd3cd2013-05-15 21:37:41 +0000512 return MadeChange;
513}
514
515// FIXME: Copied from LoopSimplify.
516BasicBlock *PPCCTRLoops::InsertPreheaderForLoop(Loop *L) {
517 BasicBlock *Header = L->getHeader();
518
519 // Compute the set of predecessors of the loop that are not in the loop.
520 SmallVector<BasicBlock*, 8> OutsideBlocks;
521 for (pred_iterator PI = pred_begin(Header), PE = pred_end(Header);
522 PI != PE; ++PI) {
523 BasicBlock *P = *PI;
524 if (!L->contains(P)) { // Coming in from outside the loop?
525 // If the loop is branched to from an indirect branch, we won't
526 // be able to fully transform the loop, because it prohibits
527 // edge splitting.
528 if (isa<IndirectBrInst>(P->getTerminator())) return 0;
529
530 // Keep track of it.
531 OutsideBlocks.push_back(P);
532 }
533 }
534
535 // Split out the loop pre-header.
536 BasicBlock *PreheaderBB;
537 if (!Header->isLandingPad()) {
538 PreheaderBB = SplitBlockPredecessors(Header, OutsideBlocks, ".preheader",
539 this);
540 } else {
541 SmallVector<BasicBlock*, 2> NewBBs;
542 SplitLandingPadPredecessors(Header, OutsideBlocks, ".preheader",
543 ".split-lp", this, NewBBs);
544 PreheaderBB = NewBBs[0];
545 }
546
547 PreheaderBB->getTerminator()->setDebugLoc(
548 Header->getFirstNonPHI()->getDebugLoc());
549 DEBUG(dbgs() << "Creating pre-header "
550 << PreheaderBB->getName() << "\n");
551
552 // Make sure that NewBB is put someplace intelligent, which doesn't mess up
553 // code layout too horribly.
554 PlaceSplitBlockCarefully(PreheaderBB, OutsideBlocks, L);
555
556 return PreheaderBB;
557}
558
559void PPCCTRLoops::PlaceSplitBlockCarefully(BasicBlock *NewBB,
560 SmallVectorImpl<BasicBlock*> &SplitPreds,
561 Loop *L) {
562 // Check to see if NewBB is already well placed.
563 Function::iterator BBI = NewBB; --BBI;
564 for (unsigned i = 0, e = SplitPreds.size(); i != e; ++i) {
565 if (&*BBI == SplitPreds[i])
566 return;
567 }
568
569 // If it isn't already after an outside block, move it after one. This is
570 // always good as it makes the uncond branch from the outside block into a
571 // fall-through.
572
573 // Figure out *which* outside block to put this after. Prefer an outside
574 // block that neighbors a BB actually in the loop.
575 BasicBlock *FoundBB = 0;
576 for (unsigned i = 0, e = SplitPreds.size(); i != e; ++i) {
577 Function::iterator BBI = SplitPreds[i];
578 if (++BBI != NewBB->getParent()->end() &&
579 L->contains(BBI)) {
580 FoundBB = SplitPreds[i];
581 break;
582 }
583 }
584
585 // If our heuristic for a *good* bb to place this after doesn't find
586 // anything, just pick something. It's likely better than leaving it within
587 // the loop.
588 if (!FoundBB)
589 FoundBB = SplitPreds[0];
590 NewBB->moveAfter(FoundBB);
Hal Finkel99f823f2012-06-08 15:38:21 +0000591}
592
Hal Finkele50c8c12013-05-20 16:08:17 +0000593#ifndef NDEBUG
594static bool clobbersCTR(const MachineInstr *MI) {
595 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
596 const MachineOperand &MO = MI->getOperand(i);
597 if (MO.isReg()) {
598 if (MO.isDef() && (MO.getReg() == PPC::CTR || MO.getReg() == PPC::CTR8))
599 return true;
600 } else if (MO.isRegMask()) {
601 if (MO.clobbersPhysReg(PPC::CTR) || MO.clobbersPhysReg(PPC::CTR8))
602 return true;
603 }
604 }
605
606 return false;
607}
608
609static bool verifyCTRBranch(MachineBasicBlock *MBB,
610 MachineBasicBlock::iterator I) {
611 MachineBasicBlock::iterator BI = I;
612 SmallSet<MachineBasicBlock *, 16> Visited;
613 SmallVector<MachineBasicBlock *, 8> Preds;
614 bool CheckPreds;
615
616 if (I == MBB->begin()) {
617 Visited.insert(MBB);
618 goto queue_preds;
619 } else
620 --I;
621
622check_block:
623 Visited.insert(MBB);
624 if (I == MBB->end())
625 goto queue_preds;
626
627 CheckPreds = true;
628 for (MachineBasicBlock::iterator IE = MBB->begin();; --I) {
629 unsigned Opc = I->getOpcode();
630 if (Opc == PPC::MTCTRse || Opc == PPC::MTCTR8se) {
631 CheckPreds = false;
632 break;
633 }
634
635 if (I != BI && clobbersCTR(I)) {
636 DEBUG(dbgs() << "BB#" << MBB->getNumber() << " (" <<
637 MBB->getFullName() << ") instruction " << *I <<
638 " clobbers CTR, invalidating " << "BB#" <<
639 BI->getParent()->getNumber() << " (" <<
640 BI->getParent()->getFullName() << ") instruction " <<
641 *BI << "\n");
642 return false;
643 }
644
645 if (I == IE)
646 break;
647 }
648
649 if (!CheckPreds && Preds.empty())
650 return true;
651
652 if (CheckPreds) {
653queue_preds:
654 if (MachineFunction::iterator(MBB) == MBB->getParent()->begin()) {
655 DEBUG(dbgs() << "Unable to find a MTCTR instruction for BB#" <<
656 BI->getParent()->getNumber() << " (" <<
657 BI->getParent()->getFullName() << ") instruction " <<
658 *BI << "\n");
659 return false;
660 }
661
662 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
663 PIE = MBB->pred_end(); PI != PIE; ++PI)
664 Preds.push_back(*PI);
665 }
666
667 do {
668 MBB = Preds.pop_back_val();
669 if (!Visited.count(MBB)) {
670 I = MBB->getLastNonDebugInstr();
671 goto check_block;
672 }
673 } while (!Preds.empty());
674
675 return true;
676}
677
678bool PPCCTRLoopsVerify::runOnMachineFunction(MachineFunction &MF) {
679 MDT = &getAnalysis<MachineDominatorTree>();
680
681 // Verify that all bdnz/bdz instructions are dominated by a loop mtctr before
682 // any other instructions that might clobber the ctr register.
683 for (MachineFunction::iterator I = MF.begin(), IE = MF.end();
684 I != IE; ++I) {
685 MachineBasicBlock *MBB = I;
686 if (!MDT->isReachableFromEntry(MBB))
687 continue;
688
689 for (MachineBasicBlock::iterator MII = MBB->getFirstTerminator(),
690 MIIE = MBB->end(); MII != MIIE; ++MII) {
691 unsigned Opc = MII->getOpcode();
692 if (Opc == PPC::BDNZ8 || Opc == PPC::BDNZ ||
693 Opc == PPC::BDZ8 || Opc == PPC::BDZ)
694 if (!verifyCTRBranch(MBB, MII))
695 llvm_unreachable("Invalid PPC CTR loop!");
696 }
697 }
698
699 return false;
700}
701#endif // NDEBUG
702