blob: 8784a83190292d5d92c95f8e90eff87c57f3e3ed [file] [log] [blame]
Hal Finkel96c2d4d2012-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 Finkel96c2d4d2012-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 Finkel96c2d4d2012-06-08 15:38:21 +000017//
18// Criteria for CTR loops:
19// - Countable loops (w/ ind. var for a trip count)
Hal Finkel96c2d4d2012-06-08 15:38:21 +000020// - Try inner-most loops first
21// - No nested CTR loops.
22// - No function calls in loops.
23//
Hal Finkel96c2d4d2012-06-08 15:38:21 +000024//===----------------------------------------------------------------------===//
25
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000026#include "PPC.h"
Eric Christopherb16eacf2017-06-29 23:28:45 +000027#include "PPCSubtarget.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000028#include "PPCTargetMachine.h"
Lei Huang0724fea2017-10-12 16:43:33 +000029#include "PPCTargetTransformInfo.h"
Hal Finkel25c19922013-05-15 21:37:41 +000030#include "llvm/ADT/STLExtras.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000031#include "llvm/ADT/Statistic.h"
Lei Huang0724fea2017-10-12 16:43:33 +000032#include "llvm/Analysis/AssumptionCache.h"
33#include "llvm/Analysis/CodeMetrics.h"
Hal Finkel25c19922013-05-15 21:37:41 +000034#include "llvm/Analysis/LoopInfo.h"
35#include "llvm/Analysis/ScalarEvolutionExpander.h"
Chandler Carruth62d42152015-01-15 02:16:27 +000036#include "llvm/Analysis/TargetLibraryInfo.h"
Lei Huang0724fea2017-10-12 16:43:33 +000037#include "llvm/Analysis/TargetTransformInfo.h"
Eric Christopherb16eacf2017-06-29 23:28:45 +000038#include "llvm/CodeGen/TargetPassConfig.h"
Lei Huang0724fea2017-10-12 16:43:33 +000039#include "llvm/CodeGen/TargetSchedule.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000040#include "llvm/IR/Constants.h"
Hal Finkel25c19922013-05-15 21:37:41 +000041#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000042#include "llvm/IR/Dominators.h"
Hal Finkel2f474f02013-05-18 09:20:39 +000043#include "llvm/IR/InlineAsm.h"
Hal Finkel25c19922013-05-15 21:37:41 +000044#include "llvm/IR/Instructions.h"
45#include "llvm/IR/IntrinsicInst.h"
46#include "llvm/IR/Module.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000047#include "llvm/IR/ValueHandle.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000048#include "llvm/PassSupport.h"
Hal Finkel25c19922013-05-15 21:37:41 +000049#include "llvm/Support/CommandLine.h"
Hal Finkel96c2d4d2012-06-08 15:38:21 +000050#include "llvm/Support/Debug.h"
51#include "llvm/Support/raw_ostream.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000052#include "llvm/Transforms/Scalar.h"
Hal Finkel25c19922013-05-15 21:37:41 +000053#include "llvm/Transforms/Utils/BasicBlockUtils.h"
54#include "llvm/Transforms/Utils/Local.h"
Hal Finkela969df82013-05-20 20:46:30 +000055#include "llvm/Transforms/Utils/LoopUtils.h"
Hal Finkel25c19922013-05-15 21:37:41 +000056
Hal Finkel8ca38842013-05-20 16:08:17 +000057#ifndef NDEBUG
58#include "llvm/CodeGen/MachineDominators.h"
59#include "llvm/CodeGen/MachineFunction.h"
60#include "llvm/CodeGen/MachineFunctionPass.h"
61#include "llvm/CodeGen/MachineRegisterInfo.h"
62#endif
63
Hal Finkel96c2d4d2012-06-08 15:38:21 +000064using namespace llvm;
65
Chandler Carruth84e68b22014-04-22 02:41:26 +000066#define DEBUG_TYPE "ctrloops"
67
Hal Finkel25c19922013-05-15 21:37:41 +000068#ifndef NDEBUG
69static cl::opt<int> CTRLoopLimit("ppc-max-ctrloop", cl::Hidden, cl::init(-1));
70#endif
71
Lei Huang0724fea2017-10-12 16:43:33 +000072// The latency of mtctr is only justified if there are more than 4
73// comparisons that will be removed as a result.
74static cl::opt<unsigned>
75SmallCTRLoopThreshold("min-ctr-loop-threshold", cl::init(4), cl::Hidden,
76 cl::desc("Loops with a constant trip count smaller than "
77 "this value will not use the count register."));
78
Hal Finkel96c2d4d2012-06-08 15:38:21 +000079STATISTIC(NumCTRLoops, "Number of loops converted to CTR loops");
80
Krzysztof Parzyszek2680b532013-02-13 17:40:07 +000081namespace llvm {
82 void initializePPCCTRLoopsPass(PassRegistry&);
Hal Finkel8ca38842013-05-20 16:08:17 +000083#ifndef NDEBUG
84 void initializePPCCTRLoopsVerifyPass(PassRegistry&);
85#endif
Krzysztof Parzyszek2680b532013-02-13 17:40:07 +000086}
87
Hal Finkel96c2d4d2012-06-08 15:38:21 +000088namespace {
Hal Finkel25c19922013-05-15 21:37:41 +000089 struct PPCCTRLoops : public FunctionPass {
90
91#ifndef NDEBUG
92 static int Counter;
93#endif
Hal Finkel96c2d4d2012-06-08 15:38:21 +000094
95 public:
Hal Finkel25c19922013-05-15 21:37:41 +000096 static char ID;
Hal Finkel96c2d4d2012-06-08 15:38:21 +000097
Eric Christopherb16eacf2017-06-29 23:28:45 +000098 PPCCTRLoops() : FunctionPass(ID) {
Krzysztof Parzyszek2680b532013-02-13 17:40:07 +000099 initializePPCCTRLoopsPass(*PassRegistry::getPassRegistry());
100 }
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000101
Craig Topper0d3fa922014-04-29 07:57:37 +0000102 bool runOnFunction(Function &F) override;
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000103
Craig Topper0d3fa922014-04-29 07:57:37 +0000104 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000105 AU.addRequired<LoopInfoWrapperPass>();
106 AU.addPreserved<LoopInfoWrapperPass>();
Chandler Carruth73523022014-01-13 13:07:17 +0000107 AU.addRequired<DominatorTreeWrapperPass>();
108 AU.addPreserved<DominatorTreeWrapperPass>();
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000109 AU.addRequired<ScalarEvolutionWrapperPass>();
Lei Huang0724fea2017-10-12 16:43:33 +0000110 AU.addRequired<AssumptionCacheTracker>();
111 AU.addRequired<TargetTransformInfoWrapperPass>();
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000112 }
113
114 private:
Eric Christopherb16eacf2017-06-29 23:28:45 +0000115 bool mightUseCTR(BasicBlock *BB);
Hal Finkel25c19922013-05-15 21:37:41 +0000116 bool convertToCTRLoop(Loop *L);
Hal Finkele6d7c282013-05-20 16:47:10 +0000117
Hal Finkel25c19922013-05-15 21:37:41 +0000118 private:
Eric Christopherb16eacf2017-06-29 23:28:45 +0000119 const PPCTargetMachine *TM;
120 const PPCSubtarget *STI;
121 const PPCTargetLowering *TLI;
122 const DataLayout *DL;
123 const TargetLibraryInfo *LibInfo;
Lei Huang0724fea2017-10-12 16:43:33 +0000124 const TargetTransformInfo *TTI;
Hal Finkel25c19922013-05-15 21:37:41 +0000125 LoopInfo *LI;
126 ScalarEvolution *SE;
Hal Finkel25c19922013-05-15 21:37:41 +0000127 DominatorTree *DT;
Justin Bogner843fb202015-12-15 19:40:57 +0000128 bool PreserveLCSSA;
Lei Huang0724fea2017-10-12 16:43:33 +0000129 TargetSchedModel SchedModel;
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000130 };
131
132 char PPCCTRLoops::ID = 0;
Hal Finkel25c19922013-05-15 21:37:41 +0000133#ifndef NDEBUG
134 int PPCCTRLoops::Counter = 0;
135#endif
Hal Finkel8ca38842013-05-20 16:08:17 +0000136
137#ifndef NDEBUG
138 struct PPCCTRLoopsVerify : public MachineFunctionPass {
139 public:
140 static char ID;
141
142 PPCCTRLoopsVerify() : MachineFunctionPass(ID) {
143 initializePPCCTRLoopsVerifyPass(*PassRegistry::getPassRegistry());
144 }
145
Craig Topper0d3fa922014-04-29 07:57:37 +0000146 void getAnalysisUsage(AnalysisUsage &AU) const override {
Hal Finkel8ca38842013-05-20 16:08:17 +0000147 AU.addRequired<MachineDominatorTree>();
148 MachineFunctionPass::getAnalysisUsage(AU);
149 }
150
Craig Topper0d3fa922014-04-29 07:57:37 +0000151 bool runOnMachineFunction(MachineFunction &MF) override;
Hal Finkel8ca38842013-05-20 16:08:17 +0000152
153 private:
154 MachineDominatorTree *MDT;
155 };
156
157 char PPCCTRLoopsVerify::ID = 0;
158#endif // NDEBUG
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000159} // end anonymous namespace
160
Krzysztof Parzyszek2680b532013-02-13 17:40:07 +0000161INITIALIZE_PASS_BEGIN(PPCCTRLoops, "ppc-ctr-loops", "PowerPC CTR Loops",
162 false, false)
Chandler Carruth73523022014-01-13 13:07:17 +0000163INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000164INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000165INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
Krzysztof Parzyszek2680b532013-02-13 17:40:07 +0000166INITIALIZE_PASS_END(PPCCTRLoops, "ppc-ctr-loops", "PowerPC CTR Loops",
167 false, false)
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000168
Eric Christopherb16eacf2017-06-29 23:28:45 +0000169FunctionPass *llvm::createPPCCTRLoops() { return new PPCCTRLoops(); }
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000170
Hal Finkel8ca38842013-05-20 16:08:17 +0000171#ifndef NDEBUG
172INITIALIZE_PASS_BEGIN(PPCCTRLoopsVerify, "ppc-ctr-loops-verify",
173 "PowerPC CTR Loops Verify", false, false)
174INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
175INITIALIZE_PASS_END(PPCCTRLoopsVerify, "ppc-ctr-loops-verify",
176 "PowerPC CTR Loops Verify", false, false)
177
178FunctionPass *llvm::createPPCCTRLoopsVerify() {
179 return new PPCCTRLoopsVerify();
180}
181#endif // NDEBUG
182
Hal Finkel25c19922013-05-15 21:37:41 +0000183bool PPCCTRLoops::runOnFunction(Function &F) {
Andrew Kaylor289bd5f2016-04-27 19:39:32 +0000184 if (skipFunction(F))
185 return false;
186
Eric Christopherb16eacf2017-06-29 23:28:45 +0000187 auto *TPC = getAnalysisIfAvailable<TargetPassConfig>();
188 if (!TPC)
189 return false;
190
191 TM = &TPC->getTM<PPCTargetMachine>();
192 STI = TM->getSubtargetImpl(F);
193 TLI = STI->getTargetLowering();
194
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000195 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000196 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Chandler Carruth73523022014-01-13 13:07:17 +0000197 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Lei Huang0724fea2017-10-12 16:43:33 +0000198 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
Mehdi Amini46a43552015-03-04 18:43:29 +0000199 DL = &F.getParent()->getDataLayout();
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000200 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
201 LibInfo = TLIP ? &TLIP->getTLI() : nullptr;
Justin Bogner843fb202015-12-15 19:40:57 +0000202 PreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000203
Hal Finkel25c19922013-05-15 21:37:41 +0000204 bool MadeChange = false;
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000205
Hal Finkel25c19922013-05-15 21:37:41 +0000206 for (LoopInfo::iterator I = LI->begin(), E = LI->end();
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000207 I != E; ++I) {
Hal Finkel25c19922013-05-15 21:37:41 +0000208 Loop *L = *I;
209 if (!L->getParentLoop())
210 MadeChange |= convertToCTRLoop(L);
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000211 }
212
Hal Finkel25c19922013-05-15 21:37:41 +0000213 return MadeChange;
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000214}
215
Hal Finkel22304042014-02-25 20:51:50 +0000216static bool isLargeIntegerTy(bool Is32Bit, Type *Ty) {
217 if (IntegerType *ITy = dyn_cast<IntegerType>(Ty))
Aaron Ballman3d69c5c2014-02-26 20:22:20 +0000218 return ITy->getBitWidth() > (Is32Bit ? 32U : 64U);
Hal Finkel22304042014-02-25 20:51:50 +0000219
220 return false;
221}
222
David Majnemerd0bcef22014-12-27 19:45:38 +0000223// Determining the address of a TLS variable results in a function call in
224// certain TLS models.
Eric Christopherb16eacf2017-06-29 23:28:45 +0000225static bool memAddrUsesCTR(const PPCTargetMachine &TM, const Value *MemAddr) {
David Majnemerd0bcef22014-12-27 19:45:38 +0000226 const auto *GV = dyn_cast<GlobalValue>(MemAddr);
Hal Finkel7d0e34e2015-10-28 23:43:00 +0000227 if (!GV) {
228 // Recurse to check for constants that refer to TLS global variables.
229 if (const auto *CV = dyn_cast<Constant>(MemAddr))
230 for (const auto &CO : CV->operands())
231 if (memAddrUsesCTR(TM, CO))
232 return true;
233
David Majnemerd0bcef22014-12-27 19:45:38 +0000234 return false;
Hal Finkel7d0e34e2015-10-28 23:43:00 +0000235 }
236
David Majnemerd0bcef22014-12-27 19:45:38 +0000237 if (!GV->isThreadLocal())
238 return false;
Eric Christopherb16eacf2017-06-29 23:28:45 +0000239 TLSModel::Model Model = TM.getTLSModel(GV);
David Majnemerd0bcef22014-12-27 19:45:38 +0000240 return Model == TLSModel::GeneralDynamic || Model == TLSModel::LocalDynamic;
241}
242
Eric Christopher56f481b2017-06-29 23:28:47 +0000243// Loop through the inline asm constraints and look for something that clobbers
244// ctr.
245static bool asmClobbersCTR(InlineAsm *IA) {
246 InlineAsm::ConstraintInfoVector CIV = IA->ParseConstraints();
247 for (unsigned i = 0, ie = CIV.size(); i < ie; ++i) {
248 InlineAsm::ConstraintInfo &C = CIV[i];
249 if (C.Type != InlineAsm::isInput)
250 for (unsigned j = 0, je = C.Codes.size(); j < je; ++j)
251 if (StringRef(C.Codes[j]).equals_lower("{ctr}"))
252 return true;
253 }
254 return false;
255}
256
Eric Christopherb16eacf2017-06-29 23:28:45 +0000257bool PPCCTRLoops::mightUseCTR(BasicBlock *BB) {
Hal Finkel5f587c52013-05-16 19:58:38 +0000258 for (BasicBlock::iterator J = BB->begin(), JE = BB->end();
259 J != JE; ++J) {
260 if (CallInst *CI = dyn_cast<CallInst>(J)) {
Eric Christopher56f481b2017-06-29 23:28:47 +0000261 // Inline ASM is okay, unless it clobbers the ctr register.
Hal Finkel2f474f02013-05-18 09:20:39 +0000262 if (InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue())) {
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +0000263 if (asmClobbersCTR(IA))
264 return true;
Hal Finkel2f474f02013-05-18 09:20:39 +0000265 continue;
266 }
267
Hal Finkel5f587c52013-05-16 19:58:38 +0000268 if (Function *F = CI->getCalledFunction()) {
269 // Most intrinsics don't become function calls, but some might.
270 // sin, cos, exp and log are always calls.
Hal Finkel0b371752016-03-27 05:40:56 +0000271 unsigned Opcode = 0;
Hal Finkel5f587c52013-05-16 19:58:38 +0000272 if (F->getIntrinsicID() != Intrinsic::not_intrinsic) {
273 switch (F->getIntrinsicID()) {
274 default: continue;
Eric Christopher71f6e2f2015-09-08 22:14:58 +0000275 // If we have a call to ppc_is_decremented_ctr_nonzero, or ppc_mtctr
276 // we're definitely using CTR.
277 case Intrinsic::ppc_is_decremented_ctr_nonzero:
NAKAMURA Takumi0a7d0ad2015-09-22 11:15:07 +0000278 case Intrinsic::ppc_mtctr:
279 return true;
Hal Finkel5f587c52013-05-16 19:58:38 +0000280
281// VisualStudio defines setjmp as _setjmp
282#if defined(_MSC_VER) && defined(setjmp) && \
283 !defined(setjmp_undefined_for_msvc)
284# pragma push_macro("setjmp")
285# undef setjmp
286# define setjmp_undefined_for_msvc
287#endif
288
289 case Intrinsic::setjmp:
290
291#if defined(_MSC_VER) && defined(setjmp_undefined_for_msvc)
292 // let's return it to _setjmp state
293# pragma pop_macro("setjmp")
294# undef setjmp_undefined_for_msvc
295#endif
296
297 case Intrinsic::longjmp:
Hal Finkel40f76d52013-07-17 05:35:44 +0000298
299 // Exclude eh_sjlj_setjmp; we don't need to exclude eh_sjlj_longjmp
300 // because, although it does clobber the counter register, the
301 // control can't then return to inside the loop unless there is also
302 // an eh_sjlj_setjmp.
303 case Intrinsic::eh_sjlj_setjmp:
304
Hal Finkel5f587c52013-05-16 19:58:38 +0000305 case Intrinsic::memcpy:
306 case Intrinsic::memmove:
307 case Intrinsic::memset:
308 case Intrinsic::powi:
309 case Intrinsic::log:
310 case Intrinsic::log2:
311 case Intrinsic::log10:
312 case Intrinsic::exp:
313 case Intrinsic::exp2:
314 case Intrinsic::pow:
315 case Intrinsic::sin:
316 case Intrinsic::cos:
317 return true;
Hal Finkel0c5c01aa2013-08-19 23:35:46 +0000318 case Intrinsic::copysign:
319 if (CI->getArgOperand(0)->getType()->getScalarType()->
320 isPPC_FP128Ty())
321 return true;
322 else
323 continue; // ISD::FCOPYSIGN is never a library call.
Hal Finkelcef9e522017-04-11 02:03:17 +0000324 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break;
325 case Intrinsic::floor: Opcode = ISD::FFLOOR; break;
326 case Intrinsic::ceil: Opcode = ISD::FCEIL; break;
327 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break;
328 case Intrinsic::rint: Opcode = ISD::FRINT; break;
329 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
330 case Intrinsic::round: Opcode = ISD::FROUND; break;
331 case Intrinsic::minnum: Opcode = ISD::FMINNUM; break;
332 case Intrinsic::maxnum: Opcode = ISD::FMAXNUM; break;
333 case Intrinsic::umul_with_overflow: Opcode = ISD::UMULO; break;
334 case Intrinsic::smul_with_overflow: Opcode = ISD::SMULO; break;
Hal Finkel5f587c52013-05-16 19:58:38 +0000335 }
336 }
337
338 // PowerPC does not use [US]DIVREM or other library calls for
339 // operations on regular types which are not otherwise library calls
340 // (i.e. soft float or atomics). If adapting for targets that do,
341 // additional care is required here.
342
David L. Jonesd21529f2017-01-23 23:16:46 +0000343 LibFunc Func;
Hal Finkel5f587c52013-05-16 19:58:38 +0000344 if (!F->hasLocalLinkage() && F->hasName() && LibInfo &&
345 LibInfo->getLibFunc(F->getName(), Func) &&
346 LibInfo->hasOptimizedCodeGen(Func)) {
347 // Non-read-only functions are never treated as intrinsics.
348 if (!CI->onlyReadsMemory())
349 return true;
350
351 // Conversion happens only for FP calls.
352 if (!CI->getArgOperand(0)->getType()->isFloatingPointTy())
353 return true;
354
355 switch (Func) {
356 default: return true;
David L. Jonesd21529f2017-01-23 23:16:46 +0000357 case LibFunc_copysign:
358 case LibFunc_copysignf:
Hal Finkel5f587c52013-05-16 19:58:38 +0000359 continue; // ISD::FCOPYSIGN is never a library call.
David L. Jonesd21529f2017-01-23 23:16:46 +0000360 case LibFunc_copysignl:
Hal Finkel1cf48ab2013-08-19 23:35:24 +0000361 return true;
David L. Jonesd21529f2017-01-23 23:16:46 +0000362 case LibFunc_fabs:
363 case LibFunc_fabsf:
364 case LibFunc_fabsl:
Hal Finkel5f587c52013-05-16 19:58:38 +0000365 continue; // ISD::FABS is never a library call.
David L. Jonesd21529f2017-01-23 23:16:46 +0000366 case LibFunc_sqrt:
367 case LibFunc_sqrtf:
368 case LibFunc_sqrtl:
Hal Finkel5f587c52013-05-16 19:58:38 +0000369 Opcode = ISD::FSQRT; break;
David L. Jonesd21529f2017-01-23 23:16:46 +0000370 case LibFunc_floor:
371 case LibFunc_floorf:
372 case LibFunc_floorl:
Hal Finkel5f587c52013-05-16 19:58:38 +0000373 Opcode = ISD::FFLOOR; break;
David L. Jonesd21529f2017-01-23 23:16:46 +0000374 case LibFunc_nearbyint:
375 case LibFunc_nearbyintf:
376 case LibFunc_nearbyintl:
Hal Finkel5f587c52013-05-16 19:58:38 +0000377 Opcode = ISD::FNEARBYINT; break;
David L. Jonesd21529f2017-01-23 23:16:46 +0000378 case LibFunc_ceil:
379 case LibFunc_ceilf:
380 case LibFunc_ceill:
Hal Finkel5f587c52013-05-16 19:58:38 +0000381 Opcode = ISD::FCEIL; break;
David L. Jonesd21529f2017-01-23 23:16:46 +0000382 case LibFunc_rint:
383 case LibFunc_rintf:
384 case LibFunc_rintl:
Hal Finkel5f587c52013-05-16 19:58:38 +0000385 Opcode = ISD::FRINT; break;
David L. Jonesd21529f2017-01-23 23:16:46 +0000386 case LibFunc_round:
387 case LibFunc_roundf:
388 case LibFunc_roundl:
Hal Finkel171817e2013-08-07 22:49:12 +0000389 Opcode = ISD::FROUND; break;
David L. Jonesd21529f2017-01-23 23:16:46 +0000390 case LibFunc_trunc:
391 case LibFunc_truncf:
392 case LibFunc_truncl:
Hal Finkel5f587c52013-05-16 19:58:38 +0000393 Opcode = ISD::FTRUNC; break;
David L. Jonesd21529f2017-01-23 23:16:46 +0000394 case LibFunc_fmin:
395 case LibFunc_fminf:
396 case LibFunc_fminl:
Hal Finkel0b371752016-03-27 05:40:56 +0000397 Opcode = ISD::FMINNUM; break;
David L. Jonesd21529f2017-01-23 23:16:46 +0000398 case LibFunc_fmax:
399 case LibFunc_fmaxf:
400 case LibFunc_fmaxl:
Hal Finkel0b371752016-03-27 05:40:56 +0000401 Opcode = ISD::FMAXNUM; break;
Hal Finkel5f587c52013-05-16 19:58:38 +0000402 }
Hal Finkel0b371752016-03-27 05:40:56 +0000403 }
Hal Finkel5f587c52013-05-16 19:58:38 +0000404
Hal Finkel0b371752016-03-27 05:40:56 +0000405 if (Opcode) {
Eric Christopherb16eacf2017-06-29 23:28:45 +0000406 MVT VTy = TLI->getSimpleValueType(
407 *DL, CI->getArgOperand(0)->getType(), true);
Hal Finkel5f587c52013-05-16 19:58:38 +0000408 if (VTy == MVT::Other)
409 return true;
NAKAMURA Takumia9cb5382015-09-22 11:14:39 +0000410
Hal Finkel5f587c52013-05-16 19:58:38 +0000411 if (TLI->isOperationLegalOrCustom(Opcode, VTy))
412 continue;
413 else if (VTy.isVector() &&
414 TLI->isOperationLegalOrCustom(Opcode, VTy.getScalarType()))
415 continue;
416
417 return true;
418 }
419 }
420
421 return true;
422 } else if (isa<BinaryOperator>(J) &&
423 J->getType()->getScalarType()->isPPC_FP128Ty()) {
424 // Most operations on ppc_f128 values become calls.
425 return true;
426 } else if (isa<UIToFPInst>(J) || isa<SIToFPInst>(J) ||
427 isa<FPToUIInst>(J) || isa<FPToSIInst>(J)) {
428 CastInst *CI = cast<CastInst>(J);
429 if (CI->getSrcTy()->getScalarType()->isPPC_FP128Ty() ||
430 CI->getDestTy()->getScalarType()->isPPC_FP128Ty() ||
Eric Christopherb16eacf2017-06-29 23:28:45 +0000431 isLargeIntegerTy(!TM->isPPC64(), CI->getSrcTy()->getScalarType()) ||
432 isLargeIntegerTy(!TM->isPPC64(), CI->getDestTy()->getScalarType()))
Hal Finkel5f587c52013-05-16 19:58:38 +0000433 return true;
Eric Christopherb16eacf2017-06-29 23:28:45 +0000434 } else if (isLargeIntegerTy(!TM->isPPC64(),
Hal Finkel22304042014-02-25 20:51:50 +0000435 J->getType()->getScalarType()) &&
Hal Finkelfa5f6f72013-06-07 22:16:19 +0000436 (J->getOpcode() == Instruction::UDiv ||
437 J->getOpcode() == Instruction::SDiv ||
438 J->getOpcode() == Instruction::URem ||
439 J->getOpcode() == Instruction::SRem)) {
440 return true;
Eric Christopherb16eacf2017-06-29 23:28:45 +0000441 } else if (!TM->isPPC64() &&
Hal Finkelc4c6c872014-05-11 16:23:29 +0000442 isLargeIntegerTy(false, J->getType()->getScalarType()) &&
443 (J->getOpcode() == Instruction::Shl ||
444 J->getOpcode() == Instruction::AShr ||
445 J->getOpcode() == Instruction::LShr)) {
446 // Only on PPC32, for 128-bit integers (specifically not 64-bit
447 // integers), these might be runtime calls.
448 return true;
Hal Finkel5f587c52013-05-16 19:58:38 +0000449 } else if (isa<IndirectBrInst>(J) || isa<InvokeInst>(J)) {
450 // On PowerPC, indirect jumps use the counter register.
451 return true;
452 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(J)) {
Eric Christopher79cc1e32014-09-02 22:28:02 +0000453 if (SI->getNumCases() + 1 >= (unsigned)TLI->getMinimumJumpTableEntries())
Hal Finkel5f587c52013-05-16 19:58:38 +0000454 return true;
455 }
Petar Jovanovic0b44f242016-03-17 17:11:33 +0000456
Eric Christopherb16eacf2017-06-29 23:28:45 +0000457 if (STI->useSoftFloat()) {
Petar Jovanovic0b44f242016-03-17 17:11:33 +0000458 switch(J->getOpcode()) {
459 case Instruction::FAdd:
460 case Instruction::FSub:
461 case Instruction::FMul:
462 case Instruction::FDiv:
463 case Instruction::FRem:
464 case Instruction::FPTrunc:
465 case Instruction::FPExt:
466 case Instruction::FPToUI:
467 case Instruction::FPToSI:
468 case Instruction::UIToFP:
469 case Instruction::SIToFP:
470 case Instruction::FCmp:
471 return true;
472 }
473 }
474
David Majnemerd0bcef22014-12-27 19:45:38 +0000475 for (Value *Operand : J->operands())
Eric Christopherb16eacf2017-06-29 23:28:45 +0000476 if (memAddrUsesCTR(*TM, Operand))
David Majnemerd0bcef22014-12-27 19:45:38 +0000477 return true;
Hal Finkel5f587c52013-05-16 19:58:38 +0000478 }
479
480 return false;
481}
Hal Finkel25c19922013-05-15 21:37:41 +0000482bool PPCCTRLoops::convertToCTRLoop(Loop *L) {
483 bool MadeChange = false;
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000484
Lei Huang0724fea2017-10-12 16:43:33 +0000485 // Do not convert small short loops to CTR loop.
486 unsigned ConstTripCount = SE->getSmallConstantTripCount(L);
487 if (ConstTripCount && ConstTripCount < SmallCTRLoopThreshold) {
488 SmallPtrSet<const Value *, 32> EphValues;
489 auto AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(
490 *L->getHeader()->getParent());
491 CodeMetrics::collectEphemeralValues(L, &AC, EphValues);
492 CodeMetrics Metrics;
493 for (BasicBlock *BB : L->blocks())
494 Metrics.analyzeBasicBlock(BB, *TTI, EphValues);
495 // 6 is an approximate latency for the mtctr instruction.
496 if (Metrics.NumInsts <= (6 * SchedModel.getIssueWidth()))
497 return false;
498 }
499
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000500 // Process nested loops first.
Hal Finkel25c19922013-05-15 21:37:41 +0000501 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I) {
502 MadeChange |= convertToCTRLoop(*I);
Eric Christopher71f6e2f2015-09-08 22:14:58 +0000503 DEBUG(dbgs() << "Nested loop converted\n");
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000504 }
Hal Finkel25c19922013-05-15 21:37:41 +0000505
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000506 // If a nested loop has been converted, then we can't convert this loop.
Hal Finkel25c19922013-05-15 21:37:41 +0000507 if (MadeChange)
508 return MadeChange;
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000509
Hal Finkel25c19922013-05-15 21:37:41 +0000510#ifndef NDEBUG
511 // Stop trying after reaching the limit (if any).
512 int Limit = CTRLoopLimit;
513 if (Limit >= 0) {
514 if (Counter >= CTRLoopLimit)
Hal Finkel21f2a432013-03-18 17:40:44 +0000515 return false;
Hal Finkel25c19922013-05-15 21:37:41 +0000516 Counter++;
Hal Finkel21f2a432013-03-18 17:40:44 +0000517 }
Hal Finkel25c19922013-05-15 21:37:41 +0000518#endif
Hal Finkel21f2a432013-03-18 17:40:44 +0000519
Hal Finkel25c19922013-05-15 21:37:41 +0000520 // We don't want to spill/restore the counter register, and so we don't
521 // want to use the counter register if the loop contains calls.
522 for (Loop::block_iterator I = L->block_begin(), IE = L->block_end();
Hal Finkel5f587c52013-05-16 19:58:38 +0000523 I != IE; ++I)
Eric Christopherb16eacf2017-06-29 23:28:45 +0000524 if (mightUseCTR(*I))
Hal Finkel5f587c52013-05-16 19:58:38 +0000525 return MadeChange;
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000526
Hal Finkel25c19922013-05-15 21:37:41 +0000527 SmallVector<BasicBlock*, 4> ExitingBlocks;
528 L->getExitingBlocks(ExitingBlocks);
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000529
Craig Topper062a2ba2014-04-25 05:30:21 +0000530 BasicBlock *CountedExitBlock = nullptr;
531 const SCEV *ExitCount = nullptr;
532 BranchInst *CountedExitBranch = nullptr;
Craig Topperaf0dea12013-07-04 01:31:24 +0000533 for (SmallVectorImpl<BasicBlock *>::iterator I = ExitingBlocks.begin(),
Hal Finkel25c19922013-05-15 21:37:41 +0000534 IE = ExitingBlocks.end(); I != IE; ++I) {
535 const SCEV *EC = SE->getExitCount(L, *I);
536 DEBUG(dbgs() << "Exit Count for " << *L << " from block " <<
537 (*I)->getName() << ": " << *EC << "\n");
538 if (isa<SCEVCouldNotCompute>(EC))
539 continue;
540 if (const SCEVConstant *ConstEC = dyn_cast<SCEVConstant>(EC)) {
541 if (ConstEC->getValue()->isZero())
542 continue;
543 } else if (!SE->isLoopInvariant(EC, L))
544 continue;
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000545
Eric Christopherb16eacf2017-06-29 23:28:45 +0000546 if (SE->getTypeSizeInBits(EC->getType()) > (TM->isPPC64() ? 64 : 32))
Hal Finkel25e4a0d2013-07-01 19:34:59 +0000547 continue;
548
Hal Finkel25c19922013-05-15 21:37:41 +0000549 // We now have a loop-invariant count of loop iterations (which is not the
550 // constant zero) for which we know that this loop will not exit via this
551 // exisiting block.
Hal Finkel6261c2d2012-06-16 20:34:07 +0000552
Hal Finkel25c19922013-05-15 21:37:41 +0000553 // We need to make sure that this block will run on every loop iteration.
554 // For this to be true, we must dominate all blocks with backedges. Such
555 // blocks are in-loop predecessors to the header block.
556 bool NotAlways = false;
557 for (pred_iterator PI = pred_begin(L->getHeader()),
558 PIE = pred_end(L->getHeader()); PI != PIE; ++PI) {
559 if (!L->contains(*PI))
560 continue;
561
562 if (!DT->dominates(*I, *PI)) {
563 NotAlways = true;
564 break;
565 }
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000566 }
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000567
Hal Finkel25c19922013-05-15 21:37:41 +0000568 if (NotAlways)
569 continue;
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000570
Hal Finkel25c19922013-05-15 21:37:41 +0000571 // Make sure this blocks ends with a conditional branch.
572 Instruction *TI = (*I)->getTerminator();
573 if (!TI)
574 continue;
575
576 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
577 if (!BI->isConditional())
578 continue;
579
580 CountedExitBranch = BI;
581 } else
582 continue;
583
584 // Note that this block may not be the loop latch block, even if the loop
585 // has a latch block.
586 CountedExitBlock = *I;
587 ExitCount = EC;
588 break;
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000589 }
590
Hal Finkel25c19922013-05-15 21:37:41 +0000591 if (!CountedExitBlock)
592 return MadeChange;
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000593
Hal Finkel25c19922013-05-15 21:37:41 +0000594 BasicBlock *Preheader = L->getLoopPreheader();
Hal Finkel5f587c52013-05-16 19:58:38 +0000595
596 // If we don't have a preheader, then insert one. If we already have a
597 // preheader, then we can use it (except if the preheader contains a use of
598 // the CTR register because some such uses might be reordered by the
599 // selection DAG after the mtctr instruction).
Eric Christopherb16eacf2017-06-29 23:28:45 +0000600 if (!Preheader || mightUseCTR(Preheader))
Justin Bogner843fb202015-12-15 19:40:57 +0000601 Preheader = InsertPreheaderForLoop(L, DT, LI, PreserveLCSSA);
Hal Finkel25c19922013-05-15 21:37:41 +0000602 if (!Preheader)
603 return MadeChange;
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000604
Hal Finkel25c19922013-05-15 21:37:41 +0000605 DEBUG(dbgs() << "Preheader for exit count: " << Preheader->getName() << "\n");
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000606
Hal Finkel25c19922013-05-15 21:37:41 +0000607 // Insert the count into the preheader and replace the condition used by the
608 // selected branch.
609 MadeChange = true;
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000610
Eric Christopherb16eacf2017-06-29 23:28:45 +0000611 SCEVExpander SCEVE(*SE, *DL, "loopcnt");
Hal Finkel25c19922013-05-15 21:37:41 +0000612 LLVMContext &C = SE->getContext();
Eric Christopherb16eacf2017-06-29 23:28:45 +0000613 Type *CountType = TM->isPPC64() ? Type::getInt64Ty(C) : Type::getInt32Ty(C);
Hal Finkel25c19922013-05-15 21:37:41 +0000614 if (!ExitCount->getType()->isPointerTy() &&
615 ExitCount->getType() != CountType)
616 ExitCount = SE->getZeroExtendExpr(ExitCount, CountType);
Sanjoy Das2aacc0e2015-09-23 01:59:04 +0000617 ExitCount = SE->getAddExpr(ExitCount, SE->getOne(CountType));
NAKAMURA Takumi70ad98a2015-09-22 11:13:55 +0000618 Value *ECValue =
619 SCEVE.expandCodeFor(ExitCount, CountType, Preheader->getTerminator());
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000620
Hal Finkel25c19922013-05-15 21:37:41 +0000621 IRBuilder<> CountBuilder(Preheader->getTerminator());
622 Module *M = Preheader->getParent()->getParent();
623 Value *MTCTRFunc = Intrinsic::getDeclaration(M, Intrinsic::ppc_mtctr,
624 CountType);
625 CountBuilder.CreateCall(MTCTRFunc, ECValue);
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000626
Hal Finkel25c19922013-05-15 21:37:41 +0000627 IRBuilder<> CondBuilder(CountedExitBranch);
628 Value *DecFunc =
629 Intrinsic::getDeclaration(M, Intrinsic::ppc_is_decremented_ctr_nonzero);
David Blaikieff6409d2015-05-18 22:13:54 +0000630 Value *NewCond = CondBuilder.CreateCall(DecFunc, {});
Hal Finkel25c19922013-05-15 21:37:41 +0000631 Value *OldCond = CountedExitBranch->getCondition();
632 CountedExitBranch->setCondition(NewCond);
633
634 // The false branch must exit the loop.
635 if (!L->contains(CountedExitBranch->getSuccessor(0)))
636 CountedExitBranch->swapSuccessors();
637
638 // The old condition may be dead now, and may have even created a dead PHI
639 // (the original induction variable).
640 RecursivelyDeleteTriviallyDeadInstructions(OldCond);
Sean Fertiled44cb182017-07-05 17:57:57 +0000641 // Run through the basic blocks of the loop and see if any of them have dead
642 // PHIs that can be removed.
643 for (auto I : L->blocks())
644 DeleteDeadPHIs(I);
Hal Finkel96c2d4d2012-06-08 15:38:21 +0000645
646 ++NumCTRLoops;
Hal Finkel25c19922013-05-15 21:37:41 +0000647 return MadeChange;
648}
649
Hal Finkel8ca38842013-05-20 16:08:17 +0000650#ifndef NDEBUG
Duncan P. N. Exon Smithe5a22f42016-07-27 13:24:16 +0000651static bool clobbersCTR(const MachineInstr &MI) {
652 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
653 const MachineOperand &MO = MI.getOperand(i);
Hal Finkel8ca38842013-05-20 16:08:17 +0000654 if (MO.isReg()) {
655 if (MO.isDef() && (MO.getReg() == PPC::CTR || MO.getReg() == PPC::CTR8))
656 return true;
657 } else if (MO.isRegMask()) {
658 if (MO.clobbersPhysReg(PPC::CTR) || MO.clobbersPhysReg(PPC::CTR8))
659 return true;
660 }
661 }
662
663 return false;
664}
665
666static bool verifyCTRBranch(MachineBasicBlock *MBB,
667 MachineBasicBlock::iterator I) {
668 MachineBasicBlock::iterator BI = I;
669 SmallSet<MachineBasicBlock *, 16> Visited;
670 SmallVector<MachineBasicBlock *, 8> Preds;
671 bool CheckPreds;
672
673 if (I == MBB->begin()) {
674 Visited.insert(MBB);
675 goto queue_preds;
676 } else
677 --I;
678
679check_block:
680 Visited.insert(MBB);
681 if (I == MBB->end())
682 goto queue_preds;
683
684 CheckPreds = true;
685 for (MachineBasicBlock::iterator IE = MBB->begin();; --I) {
686 unsigned Opc = I->getOpcode();
Hal Finkel0859ef22013-05-20 16:08:37 +0000687 if (Opc == PPC::MTCTRloop || Opc == PPC::MTCTR8loop) {
Hal Finkel8ca38842013-05-20 16:08:17 +0000688 CheckPreds = false;
689 break;
690 }
691
Duncan P. N. Exon Smithe5a22f42016-07-27 13:24:16 +0000692 if (I != BI && clobbersCTR(*I)) {
Hal Finkel8ca38842013-05-20 16:08:17 +0000693 DEBUG(dbgs() << "BB#" << MBB->getNumber() << " (" <<
694 MBB->getFullName() << ") instruction " << *I <<
695 " clobbers CTR, invalidating " << "BB#" <<
696 BI->getParent()->getNumber() << " (" <<
697 BI->getParent()->getFullName() << ") instruction " <<
698 *BI << "\n");
699 return false;
700 }
701
702 if (I == IE)
703 break;
704 }
705
706 if (!CheckPreds && Preds.empty())
707 return true;
708
709 if (CheckPreds) {
710queue_preds:
711 if (MachineFunction::iterator(MBB) == MBB->getParent()->begin()) {
712 DEBUG(dbgs() << "Unable to find a MTCTR instruction for BB#" <<
713 BI->getParent()->getNumber() << " (" <<
714 BI->getParent()->getFullName() << ") instruction " <<
715 *BI << "\n");
716 return false;
717 }
718
719 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
720 PIE = MBB->pred_end(); PI != PIE; ++PI)
721 Preds.push_back(*PI);
722 }
723
724 do {
725 MBB = Preds.pop_back_val();
726 if (!Visited.count(MBB)) {
727 I = MBB->getLastNonDebugInstr();
728 goto check_block;
729 }
730 } while (!Preds.empty());
731
732 return true;
733}
734
735bool PPCCTRLoopsVerify::runOnMachineFunction(MachineFunction &MF) {
736 MDT = &getAnalysis<MachineDominatorTree>();
737
738 // Verify that all bdnz/bdz instructions are dominated by a loop mtctr before
739 // any other instructions that might clobber the ctr register.
740 for (MachineFunction::iterator I = MF.begin(), IE = MF.end();
741 I != IE; ++I) {
Duncan P. N. Exon Smithac65b4c2015-10-20 01:07:37 +0000742 MachineBasicBlock *MBB = &*I;
Hal Finkel8ca38842013-05-20 16:08:17 +0000743 if (!MDT->isReachableFromEntry(MBB))
744 continue;
745
746 for (MachineBasicBlock::iterator MII = MBB->getFirstTerminator(),
747 MIIE = MBB->end(); MII != MIIE; ++MII) {
748 unsigned Opc = MII->getOpcode();
749 if (Opc == PPC::BDNZ8 || Opc == PPC::BDNZ ||
750 Opc == PPC::BDZ8 || Opc == PPC::BDZ)
751 if (!verifyCTRBranch(MBB, MII))
752 llvm_unreachable("Invalid PPC CTR loop!");
753 }
754 }
755
756 return false;
757}
758#endif // NDEBUG