Skip to content

[Hexagon] Add Loop Alignment pass. #83379

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Feb 29, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion clang/test/CodeGen/builtins-hexagon.c
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// REQUIRES: hexagon-registered-target
// RUN: %clang_cc1 -triple hexagon-unknown-elf -target-cpu hexagonv65 -target-feature +hvxv65 -emit-llvm %s -o - | FileCheck %s
// RUN: %clang_cc1 -triple hexagon-unknown-elf -target-cpu hexagonv65 -target-feature +hvxv65 -target-feature +hvx-length128b -emit-llvm %s -o - | FileCheck %s

void test() {
int v64 __attribute__((__vector_size__(64)));
Expand Down
1 change: 1 addition & 0 deletions llvm/lib/Target/Hexagon/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ add_llvm_target(HexagonCodeGen
HexagonISelDAGToDAGHVX.cpp
HexagonISelLowering.cpp
HexagonISelLoweringHVX.cpp
HexagonLoopAlign.cpp
HexagonLoopIdiomRecognition.cpp
HexagonMachineFunctionInfo.cpp
HexagonMachineScheduler.cpp
Expand Down
216 changes: 216 additions & 0 deletions llvm/lib/Target/Hexagon/HexagonLoopAlign.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,216 @@
//===----- HexagonLoopAlign.cpp - Generate loop alignment directives -----===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// Inspect a basic block and if its single basic block loop with a small
// number of instructions, set the prefLoopAlignment to 32 bytes (5).
//===----------------------------------------------------------------------===//

#define DEBUG_TYPE "hexagon-loop-align"

#include "HexagonTargetMachine.h"
#include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
#include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
#include "llvm/CodeGen/SchedulerRegistry.h"
#include "llvm/Support/Debug.h"

using namespace llvm;

static cl::opt<bool>
DisableLoopAlign("disable-hexagon-loop-align", cl::Hidden,
cl::desc("Disable Hexagon loop alignment pass"));

static cl::opt<uint32_t> HVXLoopAlignLimitUB(
"hexagon-hvx-loop-align-limit-ub", cl::Hidden, cl::init(16),
cl::desc("Set hexagon hvx loop upper bound align limit"));

static cl::opt<uint32_t> TinyLoopAlignLimitUB(
"hexagon-tiny-loop-align-limit-ub", cl::Hidden, cl::init(16),
cl::desc("Set hexagon tiny-core loop upper bound align limit"));

static cl::opt<uint32_t>
LoopAlignLimitUB("hexagon-loop-align-limit-ub", cl::Hidden, cl::init(8),
cl::desc("Set hexagon loop upper bound align limit"));

static cl::opt<uint32_t>
LoopAlignLimitLB("hexagon-loop-align-limit-lb", cl::Hidden, cl::init(4),
cl::desc("Set hexagon loop lower bound align limit"));

static cl::opt<uint32_t>
LoopBndlAlignLimit("hexagon-loop-bundle-align-limit", cl::Hidden,
cl::init(4),
cl::desc("Set hexagon loop align bundle limit"));

static cl::opt<uint32_t> TinyLoopBndlAlignLimit(
"hexagon-tiny-loop-bundle-align-limit", cl::Hidden, cl::init(8),
cl::desc("Set hexagon tiny-core loop align bundle limit"));

static cl::opt<uint32_t>
LoopEdgeThreshold("hexagon-loop-edge-threshold", cl::Hidden, cl::init(7500),
cl::desc("Set hexagon loop align edge theshold"));

namespace llvm {
FunctionPass *createHexagonLoopAlign();
void initializeHexagonLoopAlignPass(PassRegistry &);
} // namespace llvm

namespace {

class HexagonLoopAlign : public MachineFunctionPass {
const HexagonSubtarget *HST = nullptr;
const TargetMachine *HTM = nullptr;
const HexagonInstrInfo *HII = nullptr;

public:
static char ID;
HexagonLoopAlign() : MachineFunctionPass(ID) {
initializeHexagonLoopAlignPass(*PassRegistry::getPassRegistry());
}
bool shouldBalignLoop(MachineBasicBlock &BB, bool AboveThres);
bool isSingleLoop(MachineBasicBlock &MBB);
bool attemptToBalignSmallLoop(MachineFunction &MF, MachineBasicBlock &MBB);

void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.addRequired<MachineBranchProbabilityInfo>();
AU.addRequired<MachineBlockFrequencyInfo>();
MachineFunctionPass::getAnalysisUsage(AU);
}

StringRef getPassName() const override { return "Hexagon LoopAlign pass"; }
bool runOnMachineFunction(MachineFunction &MF) override;
};

char HexagonLoopAlign::ID = 0;

bool HexagonLoopAlign::shouldBalignLoop(MachineBasicBlock &BB,
bool AboveThres) {
bool isVec = false;
unsigned InstCnt = 0;
unsigned BndlCnt = 0;

for (MachineBasicBlock::instr_iterator II = BB.instr_begin(),
IE = BB.instr_end();
II != IE; ++II) {

// End if the instruction is endloop.
if (HII->isEndLoopN(II->getOpcode()))
break;
// Count the number of bundles.
if (II->isBundle()) {
BndlCnt++;
continue;
}
// Skip over debug instructions.
if (II->isDebugInstr())
continue;
// Check if there are any HVX instructions in loop.
isVec |= HII->isHVXVec(*II);
// Count the number of instructions.
InstCnt++;
}

LLVM_DEBUG({
dbgs() << "Bundle Count : " << BndlCnt << "\n";
dbgs() << "Instruction Count : " << InstCnt << "\n";
});

unsigned LimitUB = 0;
unsigned LimitBndl = LoopBndlAlignLimit;
// The conditions in the order of priority.
if (HST->isTinyCore()) {
LimitUB = TinyLoopAlignLimitUB;
LimitBndl = TinyLoopBndlAlignLimit;
} else if (isVec)
LimitUB = HVXLoopAlignLimitUB;
else if (AboveThres)
LimitUB = LoopAlignLimitUB;

// if the upper bound is not set to a value, implies we didn't meet
// the criteria.
if (LimitUB == 0)
return false;

return InstCnt >= LoopAlignLimitLB && InstCnt <= LimitUB &&
BndlCnt <= LimitBndl;
}

bool HexagonLoopAlign::isSingleLoop(MachineBasicBlock &MBB) {
int Succs = MBB.succ_size();
return (MBB.isSuccessor(&MBB) && (Succs == 2));
}

bool HexagonLoopAlign::attemptToBalignSmallLoop(MachineFunction &MF,
MachineBasicBlock &MBB) {
if (!isSingleLoop(MBB))
return false;

const MachineBranchProbabilityInfo *MBPI =
&getAnalysis<MachineBranchProbabilityInfo>();
const MachineBlockFrequencyInfo *MBFI =
&getAnalysis<MachineBlockFrequencyInfo>();

// Compute frequency of back edge,
BlockFrequency BlockFreq = MBFI->getBlockFreq(&MBB);
BranchProbability BrProb = MBPI->getEdgeProbability(&MBB, &MBB);
BlockFrequency EdgeFreq = BlockFreq * BrProb;
LLVM_DEBUG({
dbgs() << "Loop Align Pass:\n";
dbgs() << "\tedge with freq(" << EdgeFreq.getFrequency() << ")\n";
});

bool AboveThres = EdgeFreq.getFrequency() > LoopEdgeThreshold;
if (shouldBalignLoop(MBB, AboveThres)) {
// We found a loop, change its alignment to be 32 (5).
MBB.setAlignment(llvm::Align(1 << 5));
return true;
}
return false;
}

// Inspect each basic block, and if its a single BB loop, see if it
// meets the criteria for increasing alignment to 32.

bool HexagonLoopAlign::runOnMachineFunction(MachineFunction &MF) {

HST = &MF.getSubtarget<HexagonSubtarget>();
HII = HST->getInstrInfo();
HTM = &MF.getTarget();

if (skipFunction(MF.getFunction()))
return false;
if (DisableLoopAlign)
return false;

// This optimization is performed at
// i) -O2 and above, and when the loop has a HVX instruction.
// ii) -O3
if (HST->useHVXOps()) {
if (HTM->getOptLevel() < CodeGenOptLevel::Default)
return false;
} else {
if (HTM->getOptLevel() < CodeGenOptLevel::Aggressive)
return false;
}

bool Changed = false;
for (MachineFunction::iterator MBBi = MF.begin(), MBBe = MF.end();
MBBi != MBBe; ++MBBi) {
MachineBasicBlock &MBB = *MBBi;
Changed |= attemptToBalignSmallLoop(MF, MBB);
}
return Changed;
}

} // namespace

INITIALIZE_PASS(HexagonLoopAlign, "hexagon-loop-align",
"Hexagon LoopAlign pass", false, false)

//===----------------------------------------------------------------------===//
// Public Constructor Functions
//===----------------------------------------------------------------------===//

FunctionPass *llvm::createHexagonLoopAlign() { return new HexagonLoopAlign(); }
9 changes: 8 additions & 1 deletion llvm/lib/Target/Hexagon/HexagonTargetMachine.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,7 @@ namespace llvm {
void initializeHexagonGenMuxPass(PassRegistry&);
void initializeHexagonHardwareLoopsPass(PassRegistry&);
void initializeHexagonLoopIdiomRecognizeLegacyPassPass(PassRegistry &);
void initializeHexagonLoopAlignPass(PassRegistry &);
void initializeHexagonNewValueJumpPass(PassRegistry&);
void initializeHexagonOptAddrModePass(PassRegistry&);
void initializeHexagonPacketizerPass(PassRegistry&);
Expand Down Expand Up @@ -194,6 +195,7 @@ namespace llvm {
FunctionPass *createHexagonHardwareLoops();
FunctionPass *createHexagonISelDag(HexagonTargetMachine &TM,
CodeGenOptLevel OptLevel);
FunctionPass *createHexagonLoopAlign();
FunctionPass *createHexagonLoopRescheduling();
FunctionPass *createHexagonNewValueJump();
FunctionPass *createHexagonOptAddrMode();
Expand Down Expand Up @@ -256,8 +258,10 @@ HexagonTargetMachine::HexagonTargetMachine(const Target &T, const Triple &TT,
TT, CPU, FS, Options, getEffectiveRelocModel(RM),
getEffectiveCodeModel(CM, CodeModel::Small),
(HexagonNoOpt ? CodeGenOptLevel::None : OL)),
TLOF(std::make_unique<HexagonTargetObjectFile>()) {
TLOF(std::make_unique<HexagonTargetObjectFile>()),
Subtarget(Triple(TT), CPU, FS, *this) {
initializeHexagonExpandCondsetsPass(*PassRegistry::getPassRegistry());
initializeHexagonLoopAlignPass(*PassRegistry::getPassRegistry());
initializeHexagonTfrCleanupPass(*PassRegistry::getPassRegistry());
initAsmInfo();
}
Expand Down Expand Up @@ -476,6 +480,9 @@ void HexagonPassConfig::addPreEmitPass() {
// Packetization is mandatory: it handles gather/scatter at all opt levels.
addPass(createHexagonPacketizer(NoOpt));

if (!NoOpt)
addPass(createHexagonLoopAlign());

if (EnableVectorPrint)
addPass(createHexagonVectorPrint());

Expand Down
1 change: 1 addition & 0 deletions llvm/lib/Target/Hexagon/HexagonTargetMachine.h
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ namespace llvm {

class HexagonTargetMachine : public LLVMTargetMachine {
std::unique_ptr<TargetLoweringObjectFile> TLOF;
HexagonSubtarget Subtarget;
mutable StringMap<std::unique_ptr<HexagonSubtarget>> SubtargetMap;

public:
Expand Down
91 changes: 91 additions & 0 deletions llvm/test/CodeGen/Hexagon/loop-balign.ll
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
; RUN: llc -march=hexagon -O3 < %s | FileCheck %s -check-prefix=BALIGN
; BALIGN: .p2align{{.*}}5

; The test for checking the alignment of 'for.body4.for.body4_crit_edge' basic block

define dso_local void @foo(i32 %nCol, i32 %nRow, ptr nocapture %resMat) local_unnamed_addr {
entry:
%shl = shl i32 %nRow, 2
%cmp36 = icmp sgt i32 %nRow, 0
%0 = add i32 %nCol, -1
%.inv = icmp slt i32 %0, 1
%1 = select i1 %.inv, i32 1, i32 %nCol
br label %Outerloop

Outerloop: ; preds = %for.end7, %entry
%r12.0 = phi i32 [ 0, %entry ], [ %inc8, %for.end7 ]
%r7_6.0 = phi i64 [ undef, %entry ], [ %r7_6.1.lcssa, %for.end7 ]
%r0i.0 = phi i32 [ undef, %entry ], [ %r0i.1.lcssa, %for.end7 ]
%r5.0 = phi ptr [ %resMat, %entry ], [ %r5.1.lcssa, %for.end7 ]
%r8.0 = phi i32 [ %shl, %entry ], [ %r8.1.lcssa, %for.end7 ]
br i1 %cmp36, label %for.body.lr.ph, label %for.end7

for.body.lr.ph: ; preds = %Outerloop
%cmp332 = icmp eq i32 %r12.0, 0
%exitcond.peel = icmp eq i32 %r12.0, 1
br label %for.body

for.body: ; preds = %for.end, %for.body.lr.ph
%r8.141 = phi i32 [ %r8.0, %for.body.lr.ph ], [ %add, %for.end ]
%r5.140 = phi ptr [ %r5.0, %for.body.lr.ph ], [ %add.ptr, %for.end ]
%i.039 = phi i32 [ 0, %for.body.lr.ph ], [ %inc6, %for.end ]
%r0i.138 = phi i32 [ %r0i.0, %for.body.lr.ph ], [ %4, %for.end ]
%r7_6.137 = phi i64 [ %r7_6.0, %for.body.lr.ph ], [ %r7_6.2.lcssa, %for.end ]
%add = add nsw i32 %r8.141, %shl
br i1 %cmp332, label %for.end, label %for.body4.peel

for.body4.peel: ; preds = %for.body
%r1i.0.in.peel = inttoptr i32 %r8.141 to ptr
%r1i.0.peel = load i32, ptr %r1i.0.in.peel, align 4
%2 = tail call i64 @llvm.hexagon.M2.dpmpyss.nac.s0(i64 %r7_6.137, i32 %r1i.0.peel, i32 %r0i.138)
br i1 %exitcond.peel, label %for.end, label %for.body4.preheader.peel.newph

for.body4.preheader.peel.newph: ; preds = %for.body4.peel
%r1i.0.in = inttoptr i32 %add to ptr
%r1i.0 = load i32, ptr %r1i.0.in, align 4
br label %for.body4

for.body4: ; preds = %for.body4.for.body4_crit_edge, %for.body4.preheader.peel.newph
%inc.phi = phi i32 [ %inc.0, %for.body4.for.body4_crit_edge ], [ 2, %for.body4.preheader.peel.newph ]
%r7_6.233 = phi i64 [ %3, %for.body4.for.body4_crit_edge ], [ %2, %for.body4.preheader.peel.newph ]
%3 = tail call i64 @llvm.hexagon.M2.dpmpyss.nac.s0(i64 %r7_6.233, i32 %r1i.0, i32 %r0i.138)
%exitcond = icmp eq i32 %inc.phi, %r12.0
br i1 %exitcond, label %for.end.loopexit, label %for.body4.for.body4_crit_edge

for.body4.for.body4_crit_edge: ; preds = %for.body4
%inc.0 = add nuw nsw i32 %inc.phi, 1
br label %for.body4

for.end.loopexit: ; preds = %for.body4
br label %for.end

for.end: ; preds = %for.end.loopexit, %for.body4.peel, %for.body
%r7_6.2.lcssa = phi i64 [ %r7_6.137, %for.body ], [ %2, %for.body4.peel ], [ %3, %for.end.loopexit ]
%4 = tail call i32 @llvm.hexagon.S2.clbp(i64 %r7_6.2.lcssa)
store i32 %4, ptr %r5.140, align 4
%add.ptr = getelementptr inbounds i8, ptr %r5.140, i32 undef
%inc6 = add nuw nsw i32 %i.039, 1
%exitcond47 = icmp eq i32 %inc6, %nRow
br i1 %exitcond47, label %for.end7.loopexit, label %for.body

for.end7.loopexit: ; preds = %for.end
br label %for.end7

for.end7: ; preds = %for.end7.loopexit, %Outerloop
%r7_6.1.lcssa = phi i64 [ %r7_6.0, %Outerloop ], [ %r7_6.2.lcssa, %for.end7.loopexit ]
%r0i.1.lcssa = phi i32 [ %r0i.0, %Outerloop ], [ %4, %for.end7.loopexit ]
%r5.1.lcssa = phi ptr [ %r5.0, %Outerloop ], [ %add.ptr, %for.end7.loopexit ]
%r8.1.lcssa = phi i32 [ %r8.0, %Outerloop ], [ %add, %for.end7.loopexit ]
%inc8 = add nuw i32 %r12.0, 1
%exitcond48 = icmp eq i32 %inc8, %1
br i1 %exitcond48, label %if.end, label %Outerloop

if.end: ; preds = %for.end7
ret void
}

; Function Attrs: nounwind readnone
declare i64 @llvm.hexagon.M2.dpmpyss.nac.s0(i64, i32, i32)

; Function Attrs: nounwind readnone
declare i32 @llvm.hexagon.S2.clbp(i64)
Loading