Skip to content
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

Bit optim #1

Merged
merged 71 commits into from
May 30, 2023
Merged
Show file tree
Hide file tree
Changes from 63 commits
Commits
Show all changes
71 commits
Select commit Hold shift + click to select a range
b560c22
initialize for bit Optimize
yuxwang99 Mar 23, 2023
f904ad8
Merge remote-tracking branch 'origin/main' into bitOptim
yuxwang99 Mar 23, 2023
1249931
merge new features from main
yuxwang99 Mar 23, 2023
4c4a944
initialize file created for bits optimization
yuxwang99 Mar 24, 2023
fb92e71
merge circt update
yuxwang99 Mar 24, 2023
4b966a2
init bits optimization pass
yuxwang99 Mar 27, 2023
954f9d0
Merge branch 'main' of github.com:EPFL-LAP/dynamatic into bitOptim
yuxwang99 Mar 27, 2023
92e4321
merge submodule circt from main
yuxwang99 Mar 27, 2023
f5324eb
Merge branch 'bitOptim' of github.com:EPFL-LAP/dynamatic into bitOptim
yuxwang99 Mar 27, 2023
dad2289
update bits optimize initialization
yuxwang99 Mar 27, 2023
d320a05
attach circt to branch bitOptim
yuxwang99 Mar 27, 2023
39872b4
Merge branch 'main' of github.com:EPFL-LAP/dynamatic into bitOptim
yuxwang99 Mar 27, 2023
9f83eb9
infrastructure for forward pass
yuxwang99 Mar 27, 2023
74bc628
methods to convert operation type
yuxwang99 Mar 28, 2023
869bac0
add opname
yuxwang99 Mar 28, 2023
03416b0
init op-function map
yuxwang99 Mar 30, 2023
408e22c
init recursive settype
yuxwang99 Mar 31, 2023
bfbb468
conversion type for bits optimize
yuxwang99 Apr 2, 2023
86e9260
init recursive update pass for d_store
yuxwang99 Apr 4, 2023
c883258
delete patternconversion style implementation
yuxwang99 Apr 4, 2023
eb22554
prepare to pull circt
yuxwang99 Apr 6, 2023
2cb7920
merge circt update
yuxwang99 Apr 6, 2023
25a7e6b
register the arith dialect
yuxwang99 Apr 7, 2023
8d26980
split index init and cst init pass
yuxwang99 Apr 10, 2023
746245a
add new features of bit width forward computation
yuxwang99 Apr 11, 2023
45d00a6
update the utils header and source file
yuxwang99 Apr 11, 2023
22afac9
use function to set different update operation strategy
yuxwang99 Apr 11, 2023
4e9bec7
update update op flag
yuxwang99 Apr 14, 2023
14bda82
Merge branch 'main' of github.com:EPFL-LAP/dynamatic into bitOptim
yuxwang99 Apr 14, 2023
8ccbd06
update mergecontrol
yuxwang99 Apr 14, 2023
46df002
legalizee initindex pass
yuxwang99 Apr 17, 2023
b7d4d06
legalize init constant pass
yuxwang99 Apr 17, 2023
bd9537b
change to avoid warning during compilation
yuxwang99 Apr 18, 2023
98ce134
init bitsoptimize pass
yuxwang99 Apr 18, 2023
4ebcb4a
split forward update function
yuxwang99 Apr 18, 2023
41fd3b1
init backward
yuxwang99 Apr 19, 2023
4055f4f
add todo for backward function map
yuxwang99 Apr 19, 2023
7e7fa6e
init forward-backward loop
yuxwang99 Apr 21, 2023
ec2aab8
init constant widths without optimizing
yuxwang99 Apr 22, 2023
fa44c96
init --optimize-bits pass
yuxwang99 Apr 23, 2023
bed3bfa
add two test cases
yuxwang99 May 1, 2023
07adc11
add multi loop times test cases
yuxwang99 May 4, 2023
b1ea8cf
merge with main
yuxwang99 May 4, 2023
726e723
add description for the pass
yuxwang99 May 4, 2023
02c81cd
add comments for control merge index
yuxwang99 May 4, 2023
602caed
revise controlmerge index bit width computation
yuxwang99 May 5, 2023
ff97ca9
delete unnecessary CMakeCache
yuxwang99 May 5, 2023
01f3c21
remove aborted function
yuxwang99 May 5, 2023
ea509e2
clang-formatting
yuxwang99 May 8, 2023
0a0b8dd
merge forward backward update namespace into dynamatic
yuxwang99 May 8, 2023
1c3ca05
rename optimize bits pass
yuxwang99 May 9, 2023
93b8db4
config clang-format for header files
yuxwang99 May 9, 2023
575ccb0
adapt utils for merge
yuxwang99 May 9, 2023
bbf5c3e
apply clang-format on lib src files
yuxwang99 May 9, 2023
b21198d
merge main=theirs
yuxwang99 May 9, 2023
2922aba
Update .gitignore
yuxwang99 May 9, 2023
207339d
Update .gitignore
yuxwang99 May 9, 2023
cfc19e8
Update .gitignore
yuxwang99 May 9, 2023
9eb4abe
cancel output of bits saving
yuxwang99 May 9, 2023
36aec81
Merge branch 'bitOptim' of github.com:EPFL-LAP/dynamatic into bitOptim
yuxwang99 May 9, 2023
910b692
cancel output style of bits saving
yuxwang99 May 9, 2023
6f5e707
merge main
yuxwang99 May 10, 2023
48d0817
change handshake selectOp to arith selectOp
yuxwang99 May 11, 2023
dfa6481
edit format
yuxwang99 May 12, 2023
ec01912
use llvm::typeswitch to set flags
yuxwang99 May 13, 2023
45d2911
simplify replaceWithPredecessor implementation
yuxwang99 May 13, 2023
39c4f08
update vairable name after camelCase
yuxwang99 May 13, 2023
3d139f7
change to llvm_debug info
yuxwang99 May 19, 2023
121d633
define debug type
yuxwang99 May 30, 2023
091e76d
fix generate .mlir file with new PR
yuxwang99 May 30, 2023
1660931
Merge branch 'main' into bitOptim
May 30, 2023
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 .gitignore
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The .gitignore file should not be changed.

Original file line number Diff line number Diff line change
Expand Up @@ -34,4 +34,4 @@
# Build-related directories
build/
bin/
.cache/
.cache/
18 changes: 18 additions & 0 deletions include/dynamatic/Transforms/InitCstWidth.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
//===- InitCstWidth.h - Reduce the constant bits width ----------*- C++ -*-===//
//
// This file declares the --init-cstwidth pass.
//
//===----------------------------------------------------------------------===//

#ifndef DYNAMATIC_TRANSFORMS_INITCSTWIDTH_H
#define DYNAMATIC_TRANSFORMS_INITCSTWIDTH_H

#include "dynamatic/Transforms/UtilsBitsUpdate.h"

namespace dynamatic {

std::unique_ptr<mlir::OperationPass<mlir::ModuleOp>> createInitCstWidthPass();

} // namespace dynamatic

#endif // DYNAMATIC_TRANSFORMS_INITCSTWIDTH_H
18 changes: 18 additions & 0 deletions include/dynamatic/Transforms/InitIndexType.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
//===- InitIndexType.h - Transform IndexType to IntegerType -----*- C++ -*-===//
//
// This file declares the --init-indextype pass.
//
//===----------------------------------------------------------------------===//

#ifndef DYNAMATIC_TRANSFORMS_INITINDTYPE_H
#define DYNAMATIC_TRANSFORMS_INITINDTYPE_H

#include "dynamatic/Transforms/UtilsBitsUpdate.h"

namespace dynamatic {

std::unique_ptr<mlir::OperationPass<mlir::ModuleOp>> createInitIndTypePass();

} // namespace dynamatic

#endif // DYNAMATIC_TRANSFORMS_INITINDTYPE_H
18 changes: 18 additions & 0 deletions include/dynamatic/Transforms/OptimizeBits.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
//===- BitsOptimize.h - Optimize bits widths --------------------*- C++ -*-===//
//
// This file declares the --optimize-bits pass.
//
//===----------------------------------------------------------------------===//

#ifndef DYNAMATIC_TRANSFORMS_OPTIMIZEBITS_H
#define DYNAMATIC_TRANSFORMS_OPTIMIZEBITS_H

#include "dynamatic/Transforms/UtilsBitsUpdate.h"

namespace dynamatic {

std::unique_ptr<mlir::OperationPass<mlir::ModuleOp>> createOptimizeBitsPass();

} // namespace dynamatic

#endif // DYNAMATIC_TRANSFORMS_OPTIMIZEBITS_H
5 changes: 4 additions & 1 deletion include/dynamatic/Transforms/Passes.h
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,12 @@

#include "dynamatic/Support/LLVM.h"
#include "dynamatic/Transforms/AnalyzeMemoryAccesses.h"
#include "dynamatic/Transforms/OptimizeBits.h"
#include "dynamatic/Transforms/FlattenMemRefRowMajor.h"
#include "dynamatic/Transforms/HandshakeInferBasicBlocks.h"
#include "dynamatic/Transforms/HandshakePrepareForLegacy.h"
#include "dynamatic/Transforms/InitCstWidth.h"
#include "dynamatic/Transforms/InitIndexType.h"
#include "dynamatic/Transforms/NameMemoryOps.h"
#include "dynamatic/Transforms/PushConstants.h"
#include "mlir/Pass/Pass.h"
Expand All @@ -24,4 +27,4 @@ namespace dynamatic {

} // namespace dynamatic

#endif // DYNAMATIC_TRANSFORMS_PASSES_H
#endif // DYNAMATIC_TRANSFORMS_PASSES_H
28 changes: 28 additions & 0 deletions include/dynamatic/Transforms/Passes.td
Original file line number Diff line number Diff line change
Expand Up @@ -113,4 +113,32 @@ def PushConstants : Pass<"push-constants", "mlir::ModuleOp"> {
let constructor = "dynamatic::createPushConstantsPass()";
}

def HandshakeOptimizeBits : Pass<"optimize-bits" , "mlir::ModuleOp"> {
let summary = "Optimize bits width that can be reduced.";
let description = [{
This pass goes through all operations inside handshake levels, and optimize the bit width through the forward (from first operation to last), and backward(from last operation to first) loop process.
The loop continues until no more optimization can be done.
}];
let constructor = "dynamatic::createOptimizeBitsPass()";
let dependentDialects = ["mlir::arith::ArithDialect"];
}

def HandshakeInitIndType : Pass<"init-indtype", "mlir::ModuleOp"> {
let summary = "Initialize the index type of the module.";
let description = [{
This pass change all the index type within operands and result operands to integer type with platform dependent bit width.
}];
let constructor = "dynamatic::createInitIndTypePass()";
}

def HandshakeInitCstWidth : Pass<"init-cstwidth", "mlir::ModuleOp"> {
let summary = "Initialize the constant bit witth of the module.";
let description = [{
This pass rewrites constant operation with the minimum required bit width according to the value of the constant. To ensure the consistency with the user of the constant operation, the pass inserts a extension operation if necessary.
}];
let constructor = "dynamatic::createInitCstWidthPass()";
let dependentDialects = ["mlir::arith::ArithDialect"];

}

#endif // DYNAMATIC_TRANSFORMS_PASSES_TD
79 changes: 79 additions & 0 deletions include/dynamatic/Transforms/UtilsBitsUpdate.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
//===- UtilsBitsUpdate.h - Utils support bits optimization ------*- C++ -*-===//
//
// This file declares supports for --optimize-bits pass.
//
//===----------------------------------------------------------------------===//

#ifndef DYNAMATIC_TRANSFORMS_UTILSBITSUPDATE_H
#define DYNAMATIC_TRANSFORMS_UTILSBITSUPDATE_H

#include "circt/Dialect/Handshake/HandshakeOps.h"
#include "dynamatic/Support/LLVM.h"
#include <optional>

using namespace mlir;
using namespace circt;
using namespace circt::handshake;
using namespace dynamatic;

const unsigned CPP_MAX_WIDTH = 64;
const unsigned ADDRESS_WIDTH = 32;

IntegerType getNewType(Value opType, unsigned bitswidth, bool signless = false);

IntegerType getNewType(Value opType, unsigned bitswidth,
IntegerType::SignednessSemantics ifSign);

std::optional<Operation *> insertWidthMatchOp(Operation *newOp, int opInd,
Type newType, MLIRContext *ctx);

namespace dynamatic::update {
yuxwang99 marked this conversation as resolved.
Show resolved Hide resolved

// Construct the functions w.r.t. the operation name in the forward process
yuxwang99 marked this conversation as resolved.
Show resolved Hide resolved
void constructForwardFuncMap(
DenseMap<StringRef,
std::function<unsigned(Operation::operand_range vecOperands)>>
&mapOpNameWidth);

// Construct the functions w.r.t. the operation name in the backward process
void constructBackwardFuncMap(
DenseMap<StringRef,
std::function<unsigned(Operation::result_range vecResults)>>
&mapOpNameWidth);

// Construct the functions w.r.t. the operation name in the validation process
void constructUpdateFuncMap(
DenseMap<mlir::StringRef,
std::function<unsigned(Operation::operand_range vecOperands)>>
&mapOpNameWidth);

// Propagate the bits width of the operands to the result
// For branch and conditional branch operations
bool propType(Operation *Op);

// Insert width match operations (extension or truncation) for the operands and
// the results
void matchOpResWidth(Operation *Op, MLIRContext *ctx,
SmallVector<Operation *> &newMatchedOps);

// Replace the operation's operand with the its successor
void replaceWithSuccessor(Operation *Op);

// Replace the operation's operand with the its successor
// Set the operation's resultOp according to its successor's resultOp type
void replaceWithSuccessor(Operation *Op, Type resType);

// Validate the truncation and extension operation in case its operand and
// result operand width are not consistent by reverting or deleting the
// operations
void revertTruncOrExt(Operation *Op, MLIRContext *ctx);

// Set the validation method flags to validate the operations
void setValidateType(Operation *Op, bool &passtype, bool &match, bool &revert);

// Validate the operations after bits optimization to generate .mlir file
void validateOp(Operation *Op, MLIRContext *ctx,
SmallVector<Operation *> &newMatchedOps);
} // namespace dynamatic::update

#endif // DYNAMATIC_TRANSFORMS_UTILSBITSUPDATE_H
4 changes: 4 additions & 0 deletions lib/Transforms/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@ add_dynamatic_library(DynamaticTransforms
HandshakeInferBasicBlocks.cpp
NameMemoryOps.cpp
PushConstants.cpp
UtilsBitsUpdate.cpp
OptimizeBits.cpp
InitIndexType.cpp
InitCstWidth.cpp

DEPENDS
DynamaticTransformsPassIncGen
Expand Down
107 changes: 107 additions & 0 deletions lib/Transforms/InitCstWidth.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
//===- InitCstWidth.cpp - Reduce the constant bits width --------*- C++ -*-===//
//
// This file contains the implementation of the init-cstwidth pass.
//
//===----------------------------------------------------------------------===//

#include "dynamatic/Transforms/InitCstWidth.h"
#include "circt/Dialect/Handshake/HandshakeOps.h"
#include "dynamatic/Transforms/PassDetails.h"
#include "mlir/Dialect/Arith/IR/Arith.h"
#include "mlir/Dialect/Func/IR/FuncOps.h"
#include "mlir/IR/Dialect.h"
#include "mlir/Support/LogicalResult.h"

#include "mlir/IR/OperationSupport.h"
#include "mlir/Support/IndentedOstream.h"

static LogicalResult initCstOpBitsWidth(handshake::FuncOp funcOp,
MLIRContext *ctx) {
OpBuilder builder(ctx);
SmallVector<handshake::ConstantOp> cstOps;

int savedBits = 0;

for (auto op :
llvm::make_early_inc_range(funcOp.getOps<handshake::ConstantOp>())) {
unsigned cstBitWidth = CPP_MAX_WIDTH;
IntegerType::SignednessSemantics ifSign =
IntegerType::SignednessSemantics::Signless;
// skip the bool value constant operation
if (isa<BoolAttr>(op.getValue()))
yuxwang99 marked this conversation as resolved.
Show resolved Hide resolved
continue;

// get the attribute value
if (auto intAttr = dyn_cast<mlir::IntegerAttr>(op.getValue())) {
if (int cstVal = intAttr.getValue().getZExtValue(); cstVal > 0)
cstBitWidth = log2(cstVal) + 2;
lucas-rami marked this conversation as resolved.
Show resolved Hide resolved
else if (int cstVal = intAttr.getValue().getZExtValue(); cstVal < 0) {
cstBitWidth = log2(-cstVal) + 2;
} else
cstBitWidth = 2;
}

if (cstBitWidth < op.getResult().getType().getIntOrFloatBitWidth()) {
// Get the new type of calculated bitwidth
Type newType = getNewType(op.getResult(), cstBitWidth, ifSign);

// Update the constant operator for both ValueAttr and result Type
builder.setInsertionPointAfter(op);
handshake::ConstantOp newCstOp = builder.create<handshake::ConstantOp>(
op.getLoc(), newType, op.getValue(), op.getCtrl());

// Determine the proper representation of the constant value
int intVal = op.getValue().cast<IntegerAttr>().getInt();
intVal =
((1 << op.getValue().getType().getIntOrFloatBitWidth()) - 1 + intVal);
newCstOp.setValueAttr(IntegerAttr::get(newType, intVal));
lucas-rami marked this conversation as resolved.
Show resolved Hide resolved
// save the original bb
newCstOp->setAttr("bb", op->getAttr("bb"));

// recursively replace the uses of the old constant operation with the new
// one Value opVal = op.getResult();
savedBits +=
op.getResult().getType().getIntOrFloatBitWidth() - cstBitWidth;
auto extOp = builder.create<mlir::arith::ExtSIOp>(
newCstOp.getLoc(), op.getResult().getType(), newCstOp.getResult());

// replace the constant operation (default width)
// with new constant operation (optimized width)
op->replaceAllUsesWith(newCstOp);
yuxwang99 marked this conversation as resolved.
Show resolved Hide resolved

// update the user of constant operation
SmallVector<Operation *> userOps;
for (auto &user : newCstOp.getResult().getUses())
userOps.push_back(user.getOwner());

for (auto updateOp : userOps)
if (!isa<mlir::arith::ExtSIOp>(*updateOp))
updateOp->replaceUsesOfWith(newCstOp.getResult(),
extOp->getResult(0));

builder.clearInsertionPoint();
op->erase();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No need to erase the original operation. It will be taken care of by MLIR's dead-code elimination in the end.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I see the operation is still remained in the handshake level .mlir file. Is it completely fine to let a dead code here?

}
}
// llvm::errs() << "Constant saved bits " << savedBits << "\n";
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Feel free to use LLVM_DEBUG here, for example

LLVM_DEBUG(llvm::dbgs() << "Number of saved bits is `" << savedBits << "\n");


return success();
}

struct HandshakeInitCstWidthPass
: public HandshakeInitCstWidthBase<HandshakeInitCstWidthPass> {

void runOnOperation() override {
auto *ctx = &getContext();

ModuleOp m = getOperation();
for (auto funcOp : m.getOps<handshake::FuncOp>())
if (failed(initCstOpBitsWidth(funcOp, ctx)))
return signalPassFailure();
};
};

std::unique_ptr<mlir::OperationPass<mlir::ModuleOp>>
dynamatic::createInitCstWidthPass() {
return std::make_unique<HandshakeInitCstWidthPass>();
}
Loading