blob: c5c4cab6afd67283da238381a69edf969a702b04 [file] [log] [blame]
Richard Sandiford312425f2013-05-20 14:23:08 +00001//===-- SystemZLongBranch.cpp - Branch lengthening for SystemZ ------------===//
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//
Richard Sandifordbdbb8af2013-08-05 10:58:53 +000010// This pass makes sure that all branches are in range. There are several ways
11// in which this could be done. One aggressive approach is to assume that all
12// branches are in range and successively replace those that turn out not
13// to be in range with a longer form (branch relaxation). A simple
14// implementation is to continually walk through the function relaxing
15// branches until no more changes are needed and a fixed point is reached.
16// However, in the pathological worst case, this implementation is
17// quadratic in the number of blocks; relaxing branch N can make branch N-1
18// go out of range, which in turn can make branch N-2 go out of range,
19// and so on.
Richard Sandiford312425f2013-05-20 14:23:08 +000020//
21// An alternative approach is to assume that all branches must be
22// converted to their long forms, then reinstate the short forms of
23// branches that, even under this pessimistic assumption, turn out to be
24// in range (branch shortening). This too can be implemented as a function
25// walk that is repeated until a fixed point is reached. In general,
26// the result of shortening is not as good as that of relaxation, and
27// shortening is also quadratic in the worst case; shortening branch N
28// can bring branch N-1 in range of the short form, which in turn can do
29// the same for branch N-2, and so on. The main advantage of shortening
30// is that each walk through the function produces valid code, so it is
31// possible to stop at any point after the first walk. The quadraticness
32// could therefore be handled with a maximum pass count, although the
33// question then becomes: what maximum count should be used?
34//
35// On SystemZ, long branches are only needed for functions bigger than 64k,
36// which are relatively rare to begin with, and the long branch sequences
37// are actually relatively cheap. It therefore doesn't seem worth spending
38// much compilation time on the problem. Instead, the approach we take is:
39//
Richard Sandiford03528f32013-05-22 09:57:57 +000040// (1) Work out the address that each block would have if no branches
41// need relaxing. Exit the pass early if all branches are in range
42// according to this assumption.
43//
44// (2) Work out the address that each block would have if all branches
45// need relaxing.
46//
47// (3) Walk through the block calculating the final address of each instruction
48// and relaxing those that need to be relaxed. For backward branches,
49// this check uses the final address of the target block, as calculated
50// earlier in the walk. For forward branches, this check uses the
51// address of the target block that was calculated in (2). Both checks
52// give a conservatively-correct range.
Richard Sandiford312425f2013-05-20 14:23:08 +000053//
54//===----------------------------------------------------------------------===//
55
56#define DEBUG_TYPE "systemz-long-branch"
57
58#include "SystemZTargetMachine.h"
59#include "llvm/ADT/Statistic.h"
60#include "llvm/CodeGen/MachineFunctionPass.h"
61#include "llvm/CodeGen/MachineInstrBuilder.h"
62#include "llvm/IR/Function.h"
63#include "llvm/Support/CommandLine.h"
64#include "llvm/Support/MathExtras.h"
65#include "llvm/Target/TargetInstrInfo.h"
66#include "llvm/Target/TargetMachine.h"
67#include "llvm/Target/TargetRegisterInfo.h"
68
69using namespace llvm;
70
71STATISTIC(LongBranches, "Number of long branches.");
72
73namespace {
Richard Sandiford312425f2013-05-20 14:23:08 +000074 // Represents positional information about a basic block.
75 struct MBBInfo {
Richard Sandiford03528f32013-05-22 09:57:57 +000076 // The address that we currently assume the block has.
Richard Sandiford312425f2013-05-20 14:23:08 +000077 uint64_t Address;
78
79 // The size of the block in bytes, excluding terminators.
80 // This value never changes.
81 uint64_t Size;
82
83 // The minimum alignment of the block, as a log2 value.
84 // This value never changes.
85 unsigned Alignment;
86
87 // The number of terminators in this block. This value never changes.
88 unsigned NumTerminators;
89
90 MBBInfo()
91 : Address(0), Size(0), Alignment(0), NumTerminators(0) {}
92 };
93
94 // Represents the state of a block terminator.
95 struct TerminatorInfo {
96 // If this terminator is a relaxable branch, this points to the branch
97 // instruction, otherwise it is null.
98 MachineInstr *Branch;
99
Richard Sandiford03528f32013-05-22 09:57:57 +0000100 // The address that we currently assume the terminator has.
Richard Sandiford312425f2013-05-20 14:23:08 +0000101 uint64_t Address;
102
103 // The current size of the terminator in bytes.
104 uint64_t Size;
105
106 // If Branch is nonnull, this is the number of the target block,
107 // otherwise it is unused.
108 unsigned TargetBlock;
109
110 // If Branch is nonnull, this is the length of the longest relaxed form,
111 // otherwise it is zero.
112 unsigned ExtraRelaxSize;
113
114 TerminatorInfo() : Branch(0), Size(0), TargetBlock(0), ExtraRelaxSize(0) {}
115 };
116
117 // Used to keep track of the current position while iterating over the blocks.
118 struct BlockPosition {
Richard Sandiford03528f32013-05-22 09:57:57 +0000119 // The address that we assume this position has.
Richard Sandiford312425f2013-05-20 14:23:08 +0000120 uint64_t Address;
121
122 // The number of low bits in Address that are known to be the same
123 // as the runtime address.
124 unsigned KnownBits;
125
126 BlockPosition(unsigned InitialAlignment)
127 : Address(0), KnownBits(InitialAlignment) {}
128 };
129
130 class SystemZLongBranch : public MachineFunctionPass {
131 public:
132 static char ID;
133 SystemZLongBranch(const SystemZTargetMachine &tm)
Bill Wendling637d97d2013-06-07 20:42:15 +0000134 : MachineFunctionPass(ID), TII(0) {}
Richard Sandiford312425f2013-05-20 14:23:08 +0000135
136 virtual const char *getPassName() const {
137 return "SystemZ Long Branch";
138 }
139
140 bool runOnMachineFunction(MachineFunction &F);
141
142 private:
143 void skipNonTerminators(BlockPosition &Position, MBBInfo &Block);
144 void skipTerminator(BlockPosition &Position, TerminatorInfo &Terminator,
145 bool AssumeRelaxed);
146 TerminatorInfo describeTerminator(MachineInstr *MI);
147 uint64_t initMBBInfo();
Richard Sandiford03528f32013-05-22 09:57:57 +0000148 bool mustRelaxBranch(const TerminatorInfo &Terminator, uint64_t Address);
Richard Sandiford312425f2013-05-20 14:23:08 +0000149 bool mustRelaxABranch();
150 void setWorstCaseAddresses();
Richard Sandiford0fb90ab2013-05-28 10:41:11 +0000151 void splitCompareBranch(MachineInstr *MI, unsigned CompareOpcode);
Richard Sandiford312425f2013-05-20 14:23:08 +0000152 void relaxBranch(TerminatorInfo &Terminator);
153 void relaxBranches();
154
155 const SystemZInstrInfo *TII;
156 MachineFunction *MF;
157 SmallVector<MBBInfo, 16> MBBs;
158 SmallVector<TerminatorInfo, 16> Terminators;
159 };
160
161 char SystemZLongBranch::ID = 0;
162
163 const uint64_t MaxBackwardRange = 0x10000;
164 const uint64_t MaxForwardRange = 0xfffe;
165} // end of anonymous namespace
166
167FunctionPass *llvm::createSystemZLongBranchPass(SystemZTargetMachine &TM) {
168 return new SystemZLongBranch(TM);
169}
170
171// Position describes the state immediately before Block. Update Block
172// accordingly and move Position to the end of the block's non-terminator
173// instructions.
174void SystemZLongBranch::skipNonTerminators(BlockPosition &Position,
175 MBBInfo &Block) {
176 if (Block.Alignment > Position.KnownBits) {
177 // When calculating the address of Block, we need to conservatively
178 // assume that Block had the worst possible misalignment.
179 Position.Address += ((uint64_t(1) << Block.Alignment) -
180 (uint64_t(1) << Position.KnownBits));
181 Position.KnownBits = Block.Alignment;
182 }
183
184 // Align the addresses.
185 uint64_t AlignMask = (uint64_t(1) << Block.Alignment) - 1;
186 Position.Address = (Position.Address + AlignMask) & ~AlignMask;
187
188 // Record the block's position.
189 Block.Address = Position.Address;
190
191 // Move past the non-terminators in the block.
192 Position.Address += Block.Size;
193}
194
195// Position describes the state immediately before Terminator.
196// Update Terminator accordingly and move Position past it.
197// Assume that Terminator will be relaxed if AssumeRelaxed.
198void SystemZLongBranch::skipTerminator(BlockPosition &Position,
199 TerminatorInfo &Terminator,
200 bool AssumeRelaxed) {
201 Terminator.Address = Position.Address;
202 Position.Address += Terminator.Size;
203 if (AssumeRelaxed)
204 Position.Address += Terminator.ExtraRelaxSize;
205}
206
207// Return a description of terminator instruction MI.
208TerminatorInfo SystemZLongBranch::describeTerminator(MachineInstr *MI) {
209 TerminatorInfo Terminator;
210 Terminator.Size = TII->getInstSizeInBytes(MI);
211 if (MI->isConditionalBranch() || MI->isUnconditionalBranch()) {
Richard Sandiford312425f2013-05-20 14:23:08 +0000212 switch (MI->getOpcode()) {
213 case SystemZ::J:
214 // Relaxes to JG, which is 2 bytes longer.
Richard Sandiford312425f2013-05-20 14:23:08 +0000215 Terminator.ExtraRelaxSize = 2;
216 break;
217 case SystemZ::BRC:
Richard Sandiford53c9efd2013-05-28 10:13:54 +0000218 // Relaxes to BRCL, which is 2 bytes longer.
Richard Sandiford312425f2013-05-20 14:23:08 +0000219 Terminator.ExtraRelaxSize = 2;
220 break;
Richard Sandiford0fb90ab2013-05-28 10:41:11 +0000221 case SystemZ::CRJ:
222 // Relaxes to a CR/BRCL sequence, which is 2 bytes longer.
223 Terminator.ExtraRelaxSize = 2;
224 break;
225 case SystemZ::CGRJ:
226 // Relaxes to a CGR/BRCL sequence, which is 4 bytes longer.
227 Terminator.ExtraRelaxSize = 4;
228 break;
Richard Sandiforde1d9f002013-05-29 11:58:52 +0000229 case SystemZ::CIJ:
230 case SystemZ::CGIJ:
231 // Relaxes to a C(G)HI/BRCL sequence, which is 4 bytes longer.
232 Terminator.ExtraRelaxSize = 4;
233 break;
Richard Sandiford312425f2013-05-20 14:23:08 +0000234 default:
235 llvm_unreachable("Unrecognized branch instruction");
236 }
Richard Sandiford53c9efd2013-05-28 10:13:54 +0000237 Terminator.Branch = MI;
238 Terminator.TargetBlock =
239 TII->getBranchInfo(MI).Target->getMBB()->getNumber();
Richard Sandiford312425f2013-05-20 14:23:08 +0000240 }
241 return Terminator;
242}
243
244// Fill MBBs and Terminators, setting the addresses on the assumption
245// that no branches need relaxation. Return the size of the function under
246// this assumption.
247uint64_t SystemZLongBranch::initMBBInfo() {
248 MF->RenumberBlocks();
249 unsigned NumBlocks = MF->size();
250
251 MBBs.clear();
252 MBBs.resize(NumBlocks);
253
254 Terminators.clear();
255 Terminators.reserve(NumBlocks);
256
257 BlockPosition Position(MF->getAlignment());
258 for (unsigned I = 0; I < NumBlocks; ++I) {
259 MachineBasicBlock *MBB = MF->getBlockNumbered(I);
260 MBBInfo &Block = MBBs[I];
261
262 // Record the alignment, for quick access.
263 Block.Alignment = MBB->getAlignment();
264
265 // Calculate the size of the fixed part of the block.
266 MachineBasicBlock::iterator MI = MBB->begin();
267 MachineBasicBlock::iterator End = MBB->end();
268 while (MI != End && !MI->isTerminator()) {
Richard Sandifordbdbb8af2013-08-05 10:58:53 +0000269 Block.Size += TII->getInstSizeInBytes(MI);
Richard Sandiford312425f2013-05-20 14:23:08 +0000270 ++MI;
271 }
272 skipNonTerminators(Position, Block);
273
274 // Add the terminators.
275 while (MI != End) {
276 if (!MI->isDebugValue()) {
277 assert(MI->isTerminator() && "Terminator followed by non-terminator");
278 Terminators.push_back(describeTerminator(MI));
279 skipTerminator(Position, Terminators.back(), false);
280 ++Block.NumTerminators;
281 }
282 ++MI;
283 }
284 }
285
286 return Position.Address;
287}
288
Richard Sandiford03528f32013-05-22 09:57:57 +0000289// Return true if, under current assumptions, Terminator would need to be
290// relaxed if it were placed at address Address.
291bool SystemZLongBranch::mustRelaxBranch(const TerminatorInfo &Terminator,
292 uint64_t Address) {
Richard Sandiford312425f2013-05-20 14:23:08 +0000293 if (!Terminator.Branch)
294 return false;
295
296 const MBBInfo &Target = MBBs[Terminator.TargetBlock];
Richard Sandiford03528f32013-05-22 09:57:57 +0000297 if (Address >= Target.Address) {
298 if (Address - Target.Address <= MaxBackwardRange)
Richard Sandiford312425f2013-05-20 14:23:08 +0000299 return false;
300 } else {
Richard Sandiford03528f32013-05-22 09:57:57 +0000301 if (Target.Address - Address <= MaxForwardRange)
Richard Sandiford312425f2013-05-20 14:23:08 +0000302 return false;
303 }
304
305 return true;
306}
307
308// Return true if, under current assumptions, any terminator needs
309// to be relaxed.
310bool SystemZLongBranch::mustRelaxABranch() {
Craig Topperaf0dea12013-07-04 01:31:24 +0000311 for (SmallVectorImpl<TerminatorInfo>::iterator TI = Terminators.begin(),
Richard Sandiford312425f2013-05-20 14:23:08 +0000312 TE = Terminators.end(); TI != TE; ++TI)
Richard Sandiford03528f32013-05-22 09:57:57 +0000313 if (mustRelaxBranch(*TI, TI->Address))
Richard Sandiford312425f2013-05-20 14:23:08 +0000314 return true;
315 return false;
316}
317
318// Set the address of each block on the assumption that all branches
319// must be long.
320void SystemZLongBranch::setWorstCaseAddresses() {
321 SmallVector<TerminatorInfo, 16>::iterator TI = Terminators.begin();
322 BlockPosition Position(MF->getAlignment());
Craig Topperaf0dea12013-07-04 01:31:24 +0000323 for (SmallVectorImpl<MBBInfo>::iterator BI = MBBs.begin(), BE = MBBs.end();
Richard Sandiford312425f2013-05-20 14:23:08 +0000324 BI != BE; ++BI) {
325 skipNonTerminators(Position, *BI);
326 for (unsigned BTI = 0, BTE = BI->NumTerminators; BTI != BTE; ++BTI) {
327 skipTerminator(Position, *TI, true);
328 ++TI;
329 }
330 }
331}
332
Richard Sandiford0fb90ab2013-05-28 10:41:11 +0000333// Split MI into the comparison given by CompareOpcode followed
334// a BRCL on the result.
335void SystemZLongBranch::splitCompareBranch(MachineInstr *MI,
336 unsigned CompareOpcode) {
337 MachineBasicBlock *MBB = MI->getParent();
338 DebugLoc DL = MI->getDebugLoc();
339 BuildMI(*MBB, MI, DL, TII->get(CompareOpcode))
340 .addOperand(MI->getOperand(0))
341 .addOperand(MI->getOperand(1));
342 MachineInstr *BRCL = BuildMI(*MBB, MI, DL, TII->get(SystemZ::BRCL))
Richard Sandiford3d768e32013-07-31 12:30:20 +0000343 .addImm(SystemZ::CCMASK_ICMP)
Richard Sandiford0fb90ab2013-05-28 10:41:11 +0000344 .addOperand(MI->getOperand(2))
345 .addOperand(MI->getOperand(3));
346 // The implicit use of CC is a killing use.
Richard Sandiford3d768e32013-07-31 12:30:20 +0000347 BRCL->addRegisterKilled(SystemZ::CC, &TII->getRegisterInfo());
Richard Sandiford0fb90ab2013-05-28 10:41:11 +0000348 MI->eraseFromParent();
349}
350
Richard Sandiford312425f2013-05-20 14:23:08 +0000351// Relax the branch described by Terminator.
352void SystemZLongBranch::relaxBranch(TerminatorInfo &Terminator) {
353 MachineInstr *Branch = Terminator.Branch;
354 switch (Branch->getOpcode()) {
Richard Sandiford3b105a02013-05-21 08:48:24 +0000355 case SystemZ::J:
356 Branch->setDesc(TII->get(SystemZ::JG));
357 break;
358 case SystemZ::BRC:
359 Branch->setDesc(TII->get(SystemZ::BRCL));
360 break;
Richard Sandiford0fb90ab2013-05-28 10:41:11 +0000361 case SystemZ::CRJ:
362 splitCompareBranch(Branch, SystemZ::CR);
363 break;
364 case SystemZ::CGRJ:
365 splitCompareBranch(Branch, SystemZ::CGR);
366 break;
Richard Sandiforde1d9f002013-05-29 11:58:52 +0000367 case SystemZ::CIJ:
368 splitCompareBranch(Branch, SystemZ::CHI);
369 break;
370 case SystemZ::CGIJ:
371 splitCompareBranch(Branch, SystemZ::CGHI);
372 break;
Richard Sandiford3b105a02013-05-21 08:48:24 +0000373 default:
374 llvm_unreachable("Unrecognized branch");
375 }
Richard Sandiford312425f2013-05-20 14:23:08 +0000376
377 Terminator.Size += Terminator.ExtraRelaxSize;
378 Terminator.ExtraRelaxSize = 0;
379 Terminator.Branch = 0;
380
381 ++LongBranches;
382}
383
Richard Sandiford03528f32013-05-22 09:57:57 +0000384// Run a shortening pass and relax any branches that need to be relaxed.
Richard Sandiford312425f2013-05-20 14:23:08 +0000385void SystemZLongBranch::relaxBranches() {
Richard Sandiford03528f32013-05-22 09:57:57 +0000386 SmallVector<TerminatorInfo, 16>::iterator TI = Terminators.begin();
387 BlockPosition Position(MF->getAlignment());
Craig Topperaf0dea12013-07-04 01:31:24 +0000388 for (SmallVectorImpl<MBBInfo>::iterator BI = MBBs.begin(), BE = MBBs.end();
Richard Sandiford03528f32013-05-22 09:57:57 +0000389 BI != BE; ++BI) {
390 skipNonTerminators(Position, *BI);
391 for (unsigned BTI = 0, BTE = BI->NumTerminators; BTI != BTE; ++BTI) {
392 assert(Position.Address <= TI->Address &&
393 "Addresses shouldn't go forwards");
394 if (mustRelaxBranch(*TI, Position.Address))
395 relaxBranch(*TI);
396 skipTerminator(Position, *TI, false);
397 ++TI;
398 }
399 }
Richard Sandiford312425f2013-05-20 14:23:08 +0000400}
401
402bool SystemZLongBranch::runOnMachineFunction(MachineFunction &F) {
Bill Wendling637d97d2013-06-07 20:42:15 +0000403 TII = static_cast<const SystemZInstrInfo *>(F.getTarget().getInstrInfo());
Richard Sandiford312425f2013-05-20 14:23:08 +0000404 MF = &F;
405 uint64_t Size = initMBBInfo();
406 if (Size <= MaxForwardRange || !mustRelaxABranch())
407 return false;
408
409 setWorstCaseAddresses();
410 relaxBranches();
411 return true;
412}