[ARM64,C++11] Tidy up branch relaxation a bit w/ c++11.
[oota-llvm.git] / lib / Target / ARM64 / ARM64BranchRelaxation.cpp
1 //===-- ARM64BranchRelaxation.cpp - ARM64 branch relaxation ---------------===//
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 //===----------------------------------------------------------------------===//
11
12 #define DEBUG_TYPE "arm64-branch-relax"
13 #include "ARM64.h"
14 #include "ARM64InstrInfo.h"
15 #include "ARM64MachineFunctionInfo.h"
16 #include "llvm/ADT/SmallVector.h"
17 #include "llvm/CodeGen/MachineFunctionPass.h"
18 #include "llvm/CodeGen/MachineInstrBuilder.h"
19 #include "llvm/Support/Debug.h"
20 #include "llvm/Support/ErrorHandling.h"
21 #include "llvm/Support/Format.h"
22 #include "llvm/Support/raw_ostream.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/Support/CommandLine.h"
25 using namespace llvm;
26
27 static cl::opt<bool>
28 BranchRelaxation("arm64-branch-relax", cl::Hidden, cl::init(true),
29                  cl::desc("Relax out of range conditional branches"));
30
31 static cl::opt<unsigned>
32 TBZDisplacementBits("arm64-tbz-offset-bits", cl::Hidden, cl::init(14),
33                     cl::desc("Restrict range of TB[N]Z instructions (DEBUG)"));
34
35 static cl::opt<unsigned>
36 CBZDisplacementBits("arm64-cbz-offset-bits", cl::Hidden, cl::init(19),
37                     cl::desc("Restrict range of CB[N]Z instructions (DEBUG)"));
38
39 static cl::opt<unsigned>
40 BCCDisplacementBits("arm64-bcc-offset-bits", cl::Hidden, cl::init(19),
41                     cl::desc("Restrict range of Bcc instructions (DEBUG)"));
42
43 STATISTIC(NumSplit, "Number of basic blocks split");
44 STATISTIC(NumRelaxed, "Number of conditional branches relaxed");
45
46 namespace {
47 class ARM64BranchRelaxation : public MachineFunctionPass {
48   /// BasicBlockInfo - Information about the offset and size of a single
49   /// basic block.
50   struct BasicBlockInfo {
51     /// Offset - Distance from the beginning of the function to the beginning
52     /// of this basic block.
53     ///
54     /// The offset is always aligned as required by the basic block.
55     unsigned Offset;
56
57     /// Size - Size of the basic block in bytes.  If the block contains
58     /// inline assembly, this is a worst case estimate.
59     ///
60     /// The size does not include any alignment padding whether from the
61     /// beginning of the block, or from an aligned jump table at the end.
62     unsigned Size;
63
64     BasicBlockInfo() : Offset(0), Size(0) {}
65
66     /// Compute the offset immediately following this block.  If LogAlign is
67     /// specified, return the offset the successor block will get if it has
68     /// this alignment.
69     unsigned postOffset(unsigned LogAlign = 0) const {
70       unsigned PO = Offset + Size;
71       unsigned Align = 1 << LogAlign;
72       return (PO + Align - 1) / Align * Align;
73     }
74   };
75
76   SmallVector<BasicBlockInfo, 16> BlockInfo;
77
78   MachineFunction *MF;
79   const ARM64InstrInfo *TII;
80
81   bool relaxBranchInstructions();
82   void scanFunction();
83   MachineBasicBlock *splitBlockBeforeInstr(MachineInstr *MI);
84   void adjustBlockOffsets(MachineBasicBlock &MBB);
85   bool isBlockInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
86   bool fixupConditionalBranch(MachineInstr *MI);
87   void computeBlockSize(const MachineBasicBlock &MBB);
88   unsigned getInstrOffset(MachineInstr *MI) const;
89   void dumpBBs();
90   void verify();
91
92 public:
93   static char ID;
94   ARM64BranchRelaxation() : MachineFunctionPass(ID) {}
95
96   virtual bool runOnMachineFunction(MachineFunction &MF);
97
98   virtual const char *getPassName() const {
99     return "ARM64 branch relaxation pass";
100   }
101 };
102 char ARM64BranchRelaxation::ID = 0;
103 }
104
105 /// verify - check BBOffsets, BBSizes, alignment of islands
106 void ARM64BranchRelaxation::verify() {
107 #ifndef NDEBUG
108   unsigned PrevNum = MF->begin()->getNumber();
109   for (MachineBasicBlock &MBB : *MF) {
110     unsigned Align = MBB.getAlignment();
111     unsigned Num = MBB.getNumber();
112     assert(BlockInfo[Num].Offset % (1u << Align) == 0);
113     assert(!Num || BlockInfo[PrevNum].postOffset() <= BlockInfo[Num].Offset);
114     PrevNum = Num;
115   }
116 #endif
117 }
118
119 /// print block size and offset information - debugging
120 void ARM64BranchRelaxation::dumpBBs() {
121   for (auto &MBB : *MF) {
122     const BasicBlockInfo &BBI = BlockInfo[MBB.getNumber()];
123     dbgs() << format("BB#%u\toffset=%08x\t", MBB.getNumber(), BBI.Offset)
124            << format("size=%#x\n", BBI.Size);
125   }
126 }
127
128 /// BBHasFallthrough - Return true if the specified basic block can fallthrough
129 /// into the block immediately after it.
130 static bool BBHasFallthrough(MachineBasicBlock *MBB) {
131   // Get the next machine basic block in the function.
132   MachineFunction::iterator MBBI = MBB;
133   // Can't fall off end of function.
134   MachineBasicBlock *NextBB = std::next(MBBI);
135   if (NextBB == MBB->getParent()->end())
136     return false;
137
138   for (MachineBasicBlock *S : MBB->successors()) 
139     if (S == NextBB)
140       return true;
141
142   return false;
143 }
144
145 /// scanFunction - Do the initial scan of the function, building up
146 /// information about each block.
147 void ARM64BranchRelaxation::scanFunction() {
148   BlockInfo.clear();
149   BlockInfo.resize(MF->getNumBlockIDs());
150
151   // First thing, compute the size of all basic blocks, and see if the function
152   // has any inline assembly in it. If so, we have to be conservative about
153   // alignment assumptions, as we don't know for sure the size of any
154   // instructions in the inline assembly.
155   for (MachineBasicBlock &MBB : *MF)
156     computeBlockSize(MBB);
157
158   // Compute block offsets and known bits.
159   adjustBlockOffsets(*MF->begin());
160 }
161
162 /// computeBlockSize - Compute the size for MBB.
163 /// This function updates BlockInfo directly.
164 void ARM64BranchRelaxation::computeBlockSize(const MachineBasicBlock &MBB) {
165   unsigned Size = 0;
166   for (const MachineInstr &MI : MBB)
167     Size += TII->GetInstSizeInBytes(&MI);
168   BlockInfo[MBB.getNumber()].Size = Size;
169 }
170
171 /// getInstrOffset - Return the current offset of the specified machine
172 /// instruction from the start of the function.  This offset changes as stuff is
173 /// moved around inside the function.
174 unsigned ARM64BranchRelaxation::getInstrOffset(MachineInstr *MI) const {
175   MachineBasicBlock *MBB = MI->getParent();
176
177   // The offset is composed of two things: the sum of the sizes of all MBB's
178   // before this instruction's block, and the offset from the start of the block
179   // it is in.
180   unsigned Offset = BlockInfo[MBB->getNumber()].Offset;
181
182   // Sum instructions before MI in MBB.
183   for (MachineBasicBlock::iterator I = MBB->begin(); &*I != MI; ++I) {
184     assert(I != MBB->end() && "Didn't find MI in its own basic block?");
185     Offset += TII->GetInstSizeInBytes(I);
186   }
187   return Offset;
188 }
189
190 void ARM64BranchRelaxation::adjustBlockOffsets(MachineBasicBlock &Start) {
191   unsigned PrevNum = Start.getNumber();
192   for (auto &MBB : make_range(MachineFunction::iterator(Start), MF->end())) {
193     unsigned Num = MBB.getNumber();
194     if (!Num) // block zero is never changed from offset zero.
195       continue;
196     // Get the offset and known bits at the end of the layout predecessor.
197     // Include the alignment of the current block.
198     unsigned LogAlign = MBB.getAlignment();
199     BlockInfo[Num].Offset = BlockInfo[PrevNum].postOffset(LogAlign);
200     PrevNum = Num;
201   }
202 }
203
204 /// Split the basic block containing MI into two blocks, which are joined by
205 /// an unconditional branch.  Update data structures and renumber blocks to
206 /// account for this change and returns the newly created block.
207 /// NOTE: Successor list of the original BB is out of date after this function,
208 /// and must be updated by the caller! Other transforms follow using this
209 /// utility function, so no point updating now rather than waiting.
210 MachineBasicBlock *
211 ARM64BranchRelaxation::splitBlockBeforeInstr(MachineInstr *MI) {
212   MachineBasicBlock *OrigBB = MI->getParent();
213
214   // Create a new MBB for the code after the OrigBB.
215   MachineBasicBlock *NewBB =
216       MF->CreateMachineBasicBlock(OrigBB->getBasicBlock());
217   MachineFunction::iterator MBBI = OrigBB;
218   ++MBBI;
219   MF->insert(MBBI, NewBB);
220
221   // Splice the instructions starting with MI over to NewBB.
222   NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
223
224   // Add an unconditional branch from OrigBB to NewBB.
225   // Note the new unconditional branch is not being recorded.
226   // There doesn't seem to be meaningful DebugInfo available; this doesn't
227   // correspond to anything in the source.
228   BuildMI(OrigBB, DebugLoc(), TII->get(ARM64::B)).addMBB(NewBB);
229
230   // Insert an entry into BlockInfo to align it properly with the block numbers.
231   BlockInfo.insert(BlockInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
232
233   // Figure out how large the OrigBB is.  As the first half of the original
234   // block, it cannot contain a tablejump.  The size includes
235   // the new jump we added.  (It should be possible to do this without
236   // recounting everything, but it's very confusing, and this is rarely
237   // executed.)
238   computeBlockSize(*OrigBB);
239
240   // Figure out how large the NewMBB is.  As the second half of the original
241   // block, it may contain a tablejump.
242   computeBlockSize(*NewBB);
243
244   // All BBOffsets following these blocks must be modified.
245   adjustBlockOffsets(*OrigBB);
246
247   ++NumSplit;
248
249   return NewBB;
250 }
251
252 /// isBlockInRange - Returns true if the distance between specific MI and
253 /// specific BB can fit in MI's displacement field.
254 bool ARM64BranchRelaxation::isBlockInRange(MachineInstr *MI,
255                                            MachineBasicBlock *DestBB,
256                                            unsigned Bits) {
257   unsigned MaxOffs = ((1 << (Bits - 1)) - 1) << 2;
258   unsigned BrOffset = getInstrOffset(MI);
259   unsigned DestOffset = BlockInfo[DestBB->getNumber()].Offset;
260
261   DEBUG(dbgs() << "Branch of destination BB#" << DestBB->getNumber()
262                << " from BB#" << MI->getParent()->getNumber()
263                << " max delta=" << MaxOffs << " from " << getInstrOffset(MI)
264                << " to " << DestOffset << " offset "
265                << int(DestOffset - BrOffset) << "\t" << *MI);
266
267   // Branch before the Dest.
268   if (BrOffset <= DestOffset)
269     return (DestOffset - BrOffset <= MaxOffs);
270   return (BrOffset - DestOffset <= MaxOffs);
271 }
272
273 static bool isConditionalBranch(unsigned Opc) {
274   switch (Opc) {
275   default:
276     return false;
277   case ARM64::TBZ:
278   case ARM64::TBNZ:
279   case ARM64::CBZW:
280   case ARM64::CBNZW:
281   case ARM64::CBZX:
282   case ARM64::CBNZX:
283   case ARM64::Bcc:
284     return true;
285   }
286 }
287
288 static MachineBasicBlock *getDestBlock(MachineInstr *MI) {
289   switch (MI->getOpcode()) {
290   default:
291     assert(0 && "unexpected opcode!");
292   case ARM64::TBZ:
293   case ARM64::TBNZ:
294     return MI->getOperand(2).getMBB();
295   case ARM64::CBZW:
296   case ARM64::CBNZW:
297   case ARM64::CBZX:
298   case ARM64::CBNZX:
299   case ARM64::Bcc:
300     return MI->getOperand(1).getMBB();
301   }
302 }
303
304 static unsigned getOppositeConditionOpcode(unsigned Opc) {
305   switch (Opc) {
306   default:
307     assert(0 && "unexpected opcode!");
308   case ARM64::TBNZ:    return ARM64::TBZ;
309   case ARM64::TBZ:     return ARM64::TBNZ;
310   case ARM64::CBNZW:   return ARM64::CBZW;
311   case ARM64::CBNZX:   return ARM64::CBZX;
312   case ARM64::CBZW:    return ARM64::CBNZW;
313   case ARM64::CBZX:    return ARM64::CBNZX;
314   case ARM64::Bcc:     return ARM64::Bcc; // Condition is an operand for Bcc.
315   }
316 }
317
318 static unsigned getBranchDisplacementBits(unsigned Opc) {
319   switch (Opc) {
320   default:
321     assert(0 && "unexpected opcode!");
322   case ARM64::TBNZ:
323   case ARM64::TBZ:
324     return TBZDisplacementBits;
325   case ARM64::CBNZW:
326   case ARM64::CBZW:
327   case ARM64::CBNZX:
328   case ARM64::CBZX:
329     return CBZDisplacementBits;
330   case ARM64::Bcc:
331     return BCCDisplacementBits;
332   }
333 }
334
335 static inline void invertBccCondition(MachineInstr *MI) {
336   assert(MI->getOpcode() == ARM64::Bcc && "Unexpected opcode!");
337   ARM64CC::CondCode CC = (ARM64CC::CondCode)MI->getOperand(0).getImm();
338   CC = ARM64CC::getInvertedCondCode(CC);
339   MI->getOperand(0).setImm((int64_t)CC);
340 }
341
342 /// fixupConditionalBranch - Fix up a conditional branch whose destination is
343 /// too far away to fit in its displacement field. It is converted to an inverse
344 /// conditional branch + an unconditional branch to the destination.
345 bool ARM64BranchRelaxation::fixupConditionalBranch(MachineInstr *MI) {
346   MachineBasicBlock *DestBB = getDestBlock(MI);
347
348   // Add an unconditional branch to the destination and invert the branch
349   // condition to jump over it:
350   // tbz L1
351   // =>
352   // tbnz L2
353   // b   L1
354   // L2:
355
356   // If the branch is at the end of its MBB and that has a fall-through block,
357   // direct the updated conditional branch to the fall-through block. Otherwise,
358   // split the MBB before the next instruction.
359   MachineBasicBlock *MBB = MI->getParent();
360   MachineInstr *BMI = &MBB->back();
361   bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
362
363   if (BMI != MI) {
364     if (std::next(MachineBasicBlock::iterator(MI)) ==
365             std::prev(MBB->getLastNonDebugInstr()) &&
366         BMI->getOpcode() == ARM64::B) {
367       // Last MI in the BB is an unconditional branch. Can we simply invert the
368       // condition and swap destinations:
369       // beq L1
370       // b   L2
371       // =>
372       // bne L2
373       // b   L1
374       MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
375       if (isBlockInRange(MI, NewDest,
376                          getBranchDisplacementBits(MI->getOpcode()))) {
377         DEBUG(dbgs() << "  Invert condition and swap its destination with "
378                      << *BMI);
379         BMI->getOperand(0).setMBB(DestBB);
380         unsigned OpNum =
381             (MI->getOpcode() == ARM64::TBZ || MI->getOpcode() == ARM64::TBNZ)
382                 ? 2
383                 : 1;
384         MI->getOperand(OpNum).setMBB(NewDest);
385         MI->setDesc(TII->get(getOppositeConditionOpcode(MI->getOpcode())));
386         if (MI->getOpcode() == ARM64::Bcc)
387           invertBccCondition(MI);
388         return true;
389       }
390     }
391   }
392
393   if (NeedSplit) {
394     // Analyze the branch so we know how to update the successor lists.
395     MachineBasicBlock *TBB, *FBB;
396     SmallVector<MachineOperand, 2> Cond;
397     TII->AnalyzeBranch(*MBB, TBB, FBB, Cond, false);
398
399     MachineBasicBlock *NewBB = splitBlockBeforeInstr(MI);
400     // No need for the branch to the next block. We're adding an unconditional
401     // branch to the destination.
402     int delta = TII->GetInstSizeInBytes(&MBB->back());
403     BlockInfo[MBB->getNumber()].Size -= delta;
404     MBB->back().eraseFromParent();
405     // BlockInfo[SplitBB].Offset is wrong temporarily, fixed below
406
407     // Update the successor lists according to the transformation to follow.
408     // Do it here since if there's no split, no update is needed.
409     MBB->replaceSuccessor(FBB, NewBB);
410     NewBB->addSuccessor(FBB);
411   }
412   MachineBasicBlock *NextBB = std::next(MachineFunction::iterator(MBB));
413
414   DEBUG(dbgs() << "  Insert B to BB#" << DestBB->getNumber()
415                << ", invert condition and change dest. to BB#"
416                << NextBB->getNumber() << "\n");
417
418   // Insert a new conditional branch and a new unconditional branch.
419   MachineInstrBuilder MIB = BuildMI(
420       MBB, DebugLoc(), TII->get(getOppositeConditionOpcode(MI->getOpcode())))
421                                 .addOperand(MI->getOperand(0));
422   if (MI->getOpcode() == ARM64::TBZ || MI->getOpcode() == ARM64::TBNZ)
423     MIB.addOperand(MI->getOperand(1));
424   if (MI->getOpcode() == ARM64::Bcc)
425     invertBccCondition(MIB);
426   MIB.addMBB(NextBB);
427   BlockInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
428   BuildMI(MBB, DebugLoc(), TII->get(ARM64::B)).addMBB(DestBB);
429   BlockInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
430
431   // Remove the old conditional branch.  It may or may not still be in MBB.
432   BlockInfo[MI->getParent()->getNumber()].Size -= TII->GetInstSizeInBytes(MI);
433   MI->eraseFromParent();
434
435   // Finally, keep the block offsets up to date.
436   adjustBlockOffsets(*MBB);
437   return true;
438 }
439
440 bool ARM64BranchRelaxation::relaxBranchInstructions() {
441   bool Changed = false;
442   // Relaxing branches involves creating new basic blocks, so re-eval
443   // end() for termination.
444   for (auto &MBB : *MF) {
445     MachineInstr *MI = MBB.getFirstTerminator();
446     if (isConditionalBranch(MI->getOpcode()) &&
447         !isBlockInRange(MI, getDestBlock(MI),
448                         getBranchDisplacementBits(MI->getOpcode()))) {
449       fixupConditionalBranch(MI);
450       ++NumRelaxed;
451       Changed = true;
452     }
453   }
454   return Changed;
455 }
456
457 bool ARM64BranchRelaxation::runOnMachineFunction(MachineFunction &mf) {
458   MF = &mf;
459
460   // If the pass is disabled, just bail early.
461   if (!BranchRelaxation)
462     return false;
463
464   DEBUG(dbgs() << "***** ARM64BranchRelaxation *****\n");
465
466   TII = (const ARM64InstrInfo *)MF->getTarget().getInstrInfo();
467
468   // Renumber all of the machine basic blocks in the function, guaranteeing that
469   // the numbers agree with the position of the block in the function.
470   MF->RenumberBlocks();
471
472   // Do the initial scan of the function, building up information about the
473   // sizes of each block.
474   scanFunction();
475
476   DEBUG(dbgs() << "  Basic blocks before relaxation\n");
477   DEBUG(dumpBBs());
478
479   bool MadeChange = false;
480   while (relaxBranchInstructions())
481     MadeChange = true;
482
483   // After a while, this might be made debug-only, but it is not expensive.
484   verify();
485
486   DEBUG(dbgs() << "  Basic blocks after relaxation\n");
487   DEBUG(dbgs() << '\n'; dumpBBs());
488
489   BlockInfo.clear();
490
491   return MadeChange;
492 }
493
494 /// createARM64BranchRelaxation - returns an instance of the constpool
495 /// island pass.
496 FunctionPass *llvm::createARM64BranchRelaxation() {
497   return new ARM64BranchRelaxation();
498 }