Loading [MathJax]/extensions/tex2jax.js
CIRCT 22.0.0git
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
LowerArcToLLVM.cpp
Go to the documentation of this file.
1//===- LowerArcToLLVM.cpp -------------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
18#include "mlir/Conversion/ArithToLLVM/ArithToLLVM.h"
19#include "mlir/Conversion/ControlFlowToLLVM/ControlFlowToLLVM.h"
20#include "mlir/Conversion/FuncToLLVM/ConvertFuncToLLVM.h"
21#include "mlir/Conversion/IndexToLLVM/IndexToLLVM.h"
22#include "mlir/Conversion/LLVMCommon/ConversionTarget.h"
23#include "mlir/Conversion/LLVMCommon/TypeConverter.h"
24#include "mlir/Conversion/SCFToControlFlow/SCFToControlFlow.h"
25#include "mlir/Dialect/ControlFlow/IR/ControlFlow.h"
26#include "mlir/Dialect/Func/IR/FuncOps.h"
27#include "mlir/Dialect/Index/IR/IndexOps.h"
28#include "mlir/Dialect/LLVMIR/FunctionCallUtils.h"
29#include "mlir/Dialect/LLVMIR/LLVMAttrs.h"
30#include "mlir/Dialect/LLVMIR/LLVMDialect.h"
31#include "mlir/Dialect/SCF/IR/SCF.h"
32#include "mlir/IR/BuiltinDialect.h"
33#include "mlir/Pass/Pass.h"
34#include "mlir/Transforms/DialectConversion.h"
35#include "llvm/Support/Debug.h"
36
37#define DEBUG_TYPE "lower-arc-to-llvm"
38
39namespace circt {
40#define GEN_PASS_DEF_LOWERARCTOLLVM
41#include "circt/Conversion/Passes.h.inc"
42} // namespace circt
43
44using namespace mlir;
45using namespace circt;
46using namespace arc;
47using namespace hw;
48
49//===----------------------------------------------------------------------===//
50// Lowering Patterns
51//===----------------------------------------------------------------------===//
52
53static llvm::Twine evalSymbolFromModelName(StringRef modelName) {
54 return modelName + "_eval";
55}
56
57namespace {
58
59struct ModelOpLowering : public OpConversionPattern<arc::ModelOp> {
60 using OpConversionPattern::OpConversionPattern;
61 LogicalResult
62 matchAndRewrite(arc::ModelOp op, OpAdaptor adaptor,
63 ConversionPatternRewriter &rewriter) const final {
64 {
65 IRRewriter::InsertionGuard guard(rewriter);
66 rewriter.setInsertionPointToEnd(&op.getBodyBlock());
67 func::ReturnOp::create(rewriter, op.getLoc());
68 }
69 auto funcName =
70 rewriter.getStringAttr(evalSymbolFromModelName(op.getName()));
71 auto funcType =
72 rewriter.getFunctionType(op.getBody().getArgumentTypes(), {});
73 auto func =
74 mlir::func::FuncOp::create(rewriter, op.getLoc(), funcName, funcType);
75 rewriter.inlineRegionBefore(op.getRegion(), func.getBody(), func.end());
76 rewriter.eraseOp(op);
77 return success();
78 }
79};
80
81struct AllocStorageOpLowering
82 : public OpConversionPattern<arc::AllocStorageOp> {
83 using OpConversionPattern::OpConversionPattern;
84 LogicalResult
85 matchAndRewrite(arc::AllocStorageOp op, OpAdaptor adaptor,
86 ConversionPatternRewriter &rewriter) const final {
87 auto type = typeConverter->convertType(op.getType());
88 if (!op.getOffset().has_value())
89 return failure();
90 rewriter.replaceOpWithNewOp<LLVM::GEPOp>(op, type, rewriter.getI8Type(),
91 adaptor.getInput(),
92 LLVM::GEPArg(*op.getOffset()));
93 return success();
94 }
95};
96
97template <class ConcreteOp>
98struct AllocStateLikeOpLowering : public OpConversionPattern<ConcreteOp> {
100 using OpConversionPattern<ConcreteOp>::typeConverter;
101 using OpAdaptor = typename ConcreteOp::Adaptor;
102
103 LogicalResult
104 matchAndRewrite(ConcreteOp op, OpAdaptor adaptor,
105 ConversionPatternRewriter &rewriter) const final {
106 // Get a pointer to the correct offset in the storage.
107 auto offsetAttr = op->template getAttrOfType<IntegerAttr>("offset");
108 if (!offsetAttr)
109 return failure();
110 Value ptr = LLVM::GEPOp::create(
111 rewriter, op->getLoc(), adaptor.getStorage().getType(),
112 rewriter.getI8Type(), adaptor.getStorage(),
113 LLVM::GEPArg(offsetAttr.getValue().getZExtValue()));
114 rewriter.replaceOp(op, ptr);
115 return success();
116 }
117};
118
119struct StateReadOpLowering : public OpConversionPattern<arc::StateReadOp> {
120 using OpConversionPattern::OpConversionPattern;
121 LogicalResult
122 matchAndRewrite(arc::StateReadOp op, OpAdaptor adaptor,
123 ConversionPatternRewriter &rewriter) const final {
124 auto type = typeConverter->convertType(op.getType());
125 rewriter.replaceOpWithNewOp<LLVM::LoadOp>(op, type, adaptor.getState());
126 return success();
127 }
128};
129
130struct StateWriteOpLowering : public OpConversionPattern<arc::StateWriteOp> {
131 using OpConversionPattern::OpConversionPattern;
132 LogicalResult
133 matchAndRewrite(arc::StateWriteOp op, OpAdaptor adaptor,
134 ConversionPatternRewriter &rewriter) const final {
135 if (adaptor.getCondition()) {
136 rewriter.replaceOpWithNewOp<scf::IfOp>(
137 op, adaptor.getCondition(), [&](auto &builder, auto loc) {
138 LLVM::StoreOp::create(builder, loc, adaptor.getValue(),
139 adaptor.getState());
140 scf::YieldOp::create(builder, loc);
141 });
142 } else {
143 rewriter.replaceOpWithNewOp<LLVM::StoreOp>(op, adaptor.getValue(),
144 adaptor.getState());
145 }
146 return success();
147 }
148};
149
150struct AllocMemoryOpLowering : public OpConversionPattern<arc::AllocMemoryOp> {
151 using OpConversionPattern::OpConversionPattern;
152 LogicalResult
153 matchAndRewrite(arc::AllocMemoryOp op, OpAdaptor adaptor,
154 ConversionPatternRewriter &rewriter) const final {
155 auto offsetAttr = op->getAttrOfType<IntegerAttr>("offset");
156 if (!offsetAttr)
157 return failure();
158 Value ptr = LLVM::GEPOp::create(
159 rewriter, op.getLoc(), adaptor.getStorage().getType(),
160 rewriter.getI8Type(), adaptor.getStorage(),
161 LLVM::GEPArg(offsetAttr.getValue().getZExtValue()));
162
163 rewriter.replaceOp(op, ptr);
164 return success();
165 }
166};
167
168struct StorageGetOpLowering : public OpConversionPattern<arc::StorageGetOp> {
169 using OpConversionPattern::OpConversionPattern;
170 LogicalResult
171 matchAndRewrite(arc::StorageGetOp op, OpAdaptor adaptor,
172 ConversionPatternRewriter &rewriter) const final {
173 Value offset = LLVM::ConstantOp::create(
174 rewriter, op.getLoc(), rewriter.getI32Type(), op.getOffsetAttr());
175 Value ptr = LLVM::GEPOp::create(
176 rewriter, op.getLoc(), adaptor.getStorage().getType(),
177 rewriter.getI8Type(), adaptor.getStorage(), offset);
178 rewriter.replaceOp(op, ptr);
179 return success();
180 }
181};
182
183struct MemoryAccess {
184 Value ptr;
185 Value withinBounds;
186};
187
188static MemoryAccess prepareMemoryAccess(Location loc, Value memory,
189 Value address, MemoryType type,
190 ConversionPatternRewriter &rewriter) {
191 auto zextAddrType = rewriter.getIntegerType(
192 cast<IntegerType>(address.getType()).getWidth() + 1);
193 Value addr = LLVM::ZExtOp::create(rewriter, loc, zextAddrType, address);
194 Value addrLimit =
195 LLVM::ConstantOp::create(rewriter, loc, zextAddrType,
196 rewriter.getI32IntegerAttr(type.getNumWords()));
197 Value withinBounds = LLVM::ICmpOp::create(
198 rewriter, loc, LLVM::ICmpPredicate::ult, addr, addrLimit);
199 Value ptr = LLVM::GEPOp::create(
200 rewriter, loc, LLVM::LLVMPointerType::get(memory.getContext()),
201 rewriter.getIntegerType(type.getStride() * 8), memory, ValueRange{addr});
202 return {ptr, withinBounds};
203}
204
205struct MemoryReadOpLowering : public OpConversionPattern<arc::MemoryReadOp> {
206 using OpConversionPattern::OpConversionPattern;
207 LogicalResult
208 matchAndRewrite(arc::MemoryReadOp op, OpAdaptor adaptor,
209 ConversionPatternRewriter &rewriter) const final {
210 auto type = typeConverter->convertType(op.getType());
211 auto memoryType = cast<MemoryType>(op.getMemory().getType());
212 auto access =
213 prepareMemoryAccess(op.getLoc(), adaptor.getMemory(),
214 adaptor.getAddress(), memoryType, rewriter);
215
216 // Only attempt to read the memory if the address is within bounds,
217 // otherwise produce a zero value.
218 rewriter.replaceOpWithNewOp<scf::IfOp>(
219 op, access.withinBounds,
220 [&](auto &builder, auto loc) {
221 Value loadOp = LLVM::LoadOp::create(
222 builder, loc, memoryType.getWordType(), access.ptr);
223 scf::YieldOp::create(builder, loc, loadOp);
224 },
225 [&](auto &builder, auto loc) {
226 Value zeroValue = LLVM::ConstantOp::create(
227 builder, loc, type, builder.getI64IntegerAttr(0));
228 scf::YieldOp::create(builder, loc, zeroValue);
229 });
230 return success();
231 }
232};
233
234struct MemoryWriteOpLowering : public OpConversionPattern<arc::MemoryWriteOp> {
235 using OpConversionPattern::OpConversionPattern;
236 LogicalResult
237 matchAndRewrite(arc::MemoryWriteOp op, OpAdaptor adaptor,
238 ConversionPatternRewriter &rewriter) const final {
239 auto access = prepareMemoryAccess(
240 op.getLoc(), adaptor.getMemory(), adaptor.getAddress(),
241 cast<MemoryType>(op.getMemory().getType()), rewriter);
242 auto enable = access.withinBounds;
243 if (adaptor.getEnable())
244 enable = LLVM::AndOp::create(rewriter, op.getLoc(), adaptor.getEnable(),
245 enable);
246
247 // Only attempt to write the memory if the address is within bounds.
248 rewriter.replaceOpWithNewOp<scf::IfOp>(
249 op, enable, [&](auto &builder, auto loc) {
250 LLVM::StoreOp::create(builder, loc, adaptor.getData(), access.ptr);
251 scf::YieldOp::create(builder, loc);
252 });
253 return success();
254 }
255};
256
257/// A dummy lowering for clock gates to an AND gate.
258struct ClockGateOpLowering : public OpConversionPattern<seq::ClockGateOp> {
259 using OpConversionPattern::OpConversionPattern;
260 LogicalResult
261 matchAndRewrite(seq::ClockGateOp op, OpAdaptor adaptor,
262 ConversionPatternRewriter &rewriter) const final {
263 rewriter.replaceOpWithNewOp<LLVM::AndOp>(op, adaptor.getInput(),
264 adaptor.getEnable());
265 return success();
266 }
267};
268
269/// Lower 'seq.clock_inv x' to 'llvm.xor x true'
270struct ClockInvOpLowering : public OpConversionPattern<seq::ClockInverterOp> {
271 using OpConversionPattern::OpConversionPattern;
272 LogicalResult
273 matchAndRewrite(seq::ClockInverterOp op, OpAdaptor adaptor,
274 ConversionPatternRewriter &rewriter) const final {
275 auto constTrue = LLVM::ConstantOp::create(rewriter, op->getLoc(),
276 rewriter.getI1Type(), 1);
277 rewriter.replaceOpWithNewOp<LLVM::XOrOp>(op, adaptor.getInput(), constTrue);
278 return success();
279 }
280};
281
282struct ZeroCountOpLowering : public OpConversionPattern<arc::ZeroCountOp> {
283 using OpConversionPattern::OpConversionPattern;
284 LogicalResult
285 matchAndRewrite(arc::ZeroCountOp op, OpAdaptor adaptor,
286 ConversionPatternRewriter &rewriter) const override {
287 // Use poison when input is zero.
288 IntegerAttr isZeroPoison = rewriter.getBoolAttr(true);
289
290 if (op.getPredicate() == arc::ZeroCountPredicate::leading) {
291 rewriter.replaceOpWithNewOp<LLVM::CountLeadingZerosOp>(
292 op, adaptor.getInput().getType(), adaptor.getInput(), isZeroPoison);
293 return success();
294 }
295
296 rewriter.replaceOpWithNewOp<LLVM::CountTrailingZerosOp>(
297 op, adaptor.getInput().getType(), adaptor.getInput(), isZeroPoison);
298 return success();
299 }
300};
301
302struct SeqConstClockLowering : public OpConversionPattern<seq::ConstClockOp> {
303 using OpConversionPattern::OpConversionPattern;
304 LogicalResult
305 matchAndRewrite(seq::ConstClockOp op, OpAdaptor adaptor,
306 ConversionPatternRewriter &rewriter) const override {
307 rewriter.replaceOpWithNewOp<LLVM::ConstantOp>(
308 op, rewriter.getI1Type(), static_cast<int64_t>(op.getValue()));
309 return success();
310 }
311};
312
313template <typename OpTy>
314struct ReplaceOpWithInputPattern : public OpConversionPattern<OpTy> {
316 using OpAdaptor = typename OpTy::Adaptor;
317 LogicalResult
318 matchAndRewrite(OpTy op, OpAdaptor adaptor,
319 ConversionPatternRewriter &rewriter) const override {
320 rewriter.replaceOp(op, adaptor.getInput());
321 return success();
322 }
323};
324
325} // namespace
326
327//===----------------------------------------------------------------------===//
328// Simulation Orchestration Lowering Patterns
329//===----------------------------------------------------------------------===//
330
331namespace {
332
333struct ModelInfoMap {
334 size_t numStateBytes;
335 llvm::DenseMap<StringRef, StateInfo> states;
336 mlir::FlatSymbolRefAttr initialFnSymbol;
337 mlir::FlatSymbolRefAttr finalFnSymbol;
338};
339
340template <typename OpTy>
341struct ModelAwarePattern : public OpConversionPattern<OpTy> {
342 ModelAwarePattern(const TypeConverter &typeConverter, MLIRContext *context,
343 llvm::DenseMap<StringRef, ModelInfoMap> &modelInfo)
344 : OpConversionPattern<OpTy>(typeConverter, context),
345 modelInfo(modelInfo) {}
346
347protected:
348 Value createPtrToPortState(ConversionPatternRewriter &rewriter, Location loc,
349 Value state, const StateInfo &port) const {
350 MLIRContext *ctx = rewriter.getContext();
351 return LLVM::GEPOp::create(rewriter, loc, LLVM::LLVMPointerType::get(ctx),
352 IntegerType::get(ctx, 8), state,
353 LLVM::GEPArg(port.offset));
354 }
355
356 llvm::DenseMap<StringRef, ModelInfoMap> &modelInfo;
357};
358
359/// Lowers SimInstantiateOp to a malloc and memset call. This pattern will
360/// mutate the global module.
361struct SimInstantiateOpLowering
362 : public ModelAwarePattern<arc::SimInstantiateOp> {
363 using ModelAwarePattern::ModelAwarePattern;
364
365 LogicalResult
366 matchAndRewrite(arc::SimInstantiateOp op, OpAdaptor adaptor,
367 ConversionPatternRewriter &rewriter) const final {
368 auto modelIt = modelInfo.find(
369 cast<SimModelInstanceType>(op.getBody().getArgument(0).getType())
370 .getModel()
371 .getValue());
372 ModelInfoMap &model = modelIt->second;
373
374 ModuleOp moduleOp = op->getParentOfType<ModuleOp>();
375 if (!moduleOp)
376 return failure();
377
378 ConversionPatternRewriter::InsertionGuard guard(rewriter);
379
380 // FIXME: like the rest of MLIR, this assumes sizeof(intptr_t) ==
381 // sizeof(size_t) on the target architecture.
382 Type convertedIndex = typeConverter->convertType(rewriter.getIndexType());
383
384 FailureOr<LLVM::LLVMFuncOp> mallocFunc =
385 LLVM::lookupOrCreateMallocFn(rewriter, moduleOp, convertedIndex);
386 if (failed(mallocFunc))
387 return mallocFunc;
388
389 FailureOr<LLVM::LLVMFuncOp> freeFunc =
390 LLVM::lookupOrCreateFreeFn(rewriter, moduleOp);
391 if (failed(freeFunc))
392 return freeFunc;
393
394 Location loc = op.getLoc();
395 Value numStateBytes = LLVM::ConstantOp::create(
396 rewriter, loc, convertedIndex, model.numStateBytes);
397 Value allocated = LLVM::CallOp::create(rewriter, loc, mallocFunc.value(),
398 ValueRange{numStateBytes})
399 .getResult();
400 Value zero =
401 LLVM::ConstantOp::create(rewriter, loc, rewriter.getI8Type(), 0);
402 LLVM::MemsetOp::create(rewriter, loc, allocated, zero, numStateBytes,
403 false);
404
405 // Call the model's 'initial' function if present.
406 if (model.initialFnSymbol) {
407 auto initialFnType = LLVM::LLVMFunctionType::get(
408 LLVM::LLVMVoidType::get(op.getContext()),
409 {LLVM::LLVMPointerType::get(op.getContext())});
410 LLVM::CallOp::create(rewriter, loc, initialFnType, model.initialFnSymbol,
411 ValueRange{allocated});
412 }
413
414 // Execute the body.
415 rewriter.inlineBlockBefore(&adaptor.getBody().getBlocks().front(), op,
416 {allocated});
417
418 // Call the model's 'final' function if present.
419 if (model.finalFnSymbol) {
420 auto finalFnType = LLVM::LLVMFunctionType::get(
421 LLVM::LLVMVoidType::get(op.getContext()),
422 {LLVM::LLVMPointerType::get(op.getContext())});
423 LLVM::CallOp::create(rewriter, loc, finalFnType, model.finalFnSymbol,
424 ValueRange{allocated});
425 }
426
427 LLVM::CallOp::create(rewriter, loc, freeFunc.value(),
428 ValueRange{allocated});
429 rewriter.eraseOp(op);
430
431 return success();
432 }
433};
434
435struct SimSetInputOpLowering : public ModelAwarePattern<arc::SimSetInputOp> {
436 using ModelAwarePattern::ModelAwarePattern;
437
438 LogicalResult
439 matchAndRewrite(arc::SimSetInputOp op, OpAdaptor adaptor,
440 ConversionPatternRewriter &rewriter) const final {
441 auto modelIt =
442 modelInfo.find(cast<SimModelInstanceType>(op.getInstance().getType())
443 .getModel()
444 .getValue());
445 ModelInfoMap &model = modelIt->second;
446
447 auto portIt = model.states.find(op.getInput());
448 if (portIt == model.states.end()) {
449 // If the port is not found in the state, it means the model does not
450 // actually use it. Thus this operation is a no-op.
451 rewriter.eraseOp(op);
452 return success();
453 }
454
455 StateInfo &port = portIt->second;
456 Value statePtr = createPtrToPortState(rewriter, op.getLoc(),
457 adaptor.getInstance(), port);
458 rewriter.replaceOpWithNewOp<LLVM::StoreOp>(op, adaptor.getValue(),
459 statePtr);
460
461 return success();
462 }
463};
464
465struct SimGetPortOpLowering : public ModelAwarePattern<arc::SimGetPortOp> {
466 using ModelAwarePattern::ModelAwarePattern;
467
468 LogicalResult
469 matchAndRewrite(arc::SimGetPortOp op, OpAdaptor adaptor,
470 ConversionPatternRewriter &rewriter) const final {
471 auto modelIt =
472 modelInfo.find(cast<SimModelInstanceType>(op.getInstance().getType())
473 .getModel()
474 .getValue());
475 ModelInfoMap &model = modelIt->second;
476
477 auto type = typeConverter->convertType(op.getValue().getType());
478 if (!type)
479 return failure();
480 auto portIt = model.states.find(op.getPort());
481 if (portIt == model.states.end()) {
482 // If the port is not found in the state, it means the model does not
483 // actually set it. Thus this operation returns 0.
484 rewriter.replaceOpWithNewOp<LLVM::ConstantOp>(op, type, 0);
485 return success();
486 }
487
488 StateInfo &port = portIt->second;
489 Value statePtr = createPtrToPortState(rewriter, op.getLoc(),
490 adaptor.getInstance(), port);
491 rewriter.replaceOpWithNewOp<LLVM::LoadOp>(op, type, statePtr);
492
493 return success();
494 }
495};
496
497struct SimStepOpLowering : public ModelAwarePattern<arc::SimStepOp> {
498 using ModelAwarePattern::ModelAwarePattern;
499
500 LogicalResult
501 matchAndRewrite(arc::SimStepOp op, OpAdaptor adaptor,
502 ConversionPatternRewriter &rewriter) const final {
503 StringRef modelName = cast<SimModelInstanceType>(op.getInstance().getType())
504 .getModel()
505 .getValue();
506
507 StringAttr evalFunc =
508 rewriter.getStringAttr(evalSymbolFromModelName(modelName));
509 rewriter.replaceOpWithNewOp<LLVM::CallOp>(op, mlir::TypeRange(), evalFunc,
510 adaptor.getInstance());
511
512 return success();
513 }
514};
515
516/// Lowers SimEmitValueOp to a printf call. The integer will be printed in its
517/// entirety if it is of size up to size_t, and explicitly truncated otherwise.
518/// This pattern will mutate the global module.
519struct SimEmitValueOpLowering
520 : public OpConversionPattern<arc::SimEmitValueOp> {
521 using OpConversionPattern::OpConversionPattern;
522
523 LogicalResult
524 matchAndRewrite(arc::SimEmitValueOp op, OpAdaptor adaptor,
525 ConversionPatternRewriter &rewriter) const final {
526 auto valueType = dyn_cast<IntegerType>(adaptor.getValue().getType());
527 if (!valueType)
528 return failure();
529
530 Location loc = op.getLoc();
531
532 ModuleOp moduleOp = op->getParentOfType<ModuleOp>();
533 if (!moduleOp)
534 return failure();
535
536 // Cast the value to a size_t.
537 // FIXME: like the rest of MLIR, this assumes sizeof(intptr_t) ==
538 // sizeof(size_t) on the target architecture.
539 Value toPrint = adaptor.getValue();
540 DataLayout layout = DataLayout::closest(op);
541 llvm::TypeSize sizeOfSizeT =
542 layout.getTypeSizeInBits(rewriter.getIndexType());
543 assert(!sizeOfSizeT.isScalable() &&
544 sizeOfSizeT.getFixedValue() <= std::numeric_limits<unsigned>::max());
545 bool truncated = false;
546 if (valueType.getWidth() > sizeOfSizeT) {
547 toPrint = LLVM::TruncOp::create(
548 rewriter, loc,
549 IntegerType::get(getContext(), sizeOfSizeT.getFixedValue()), toPrint);
550 truncated = true;
551 } else if (valueType.getWidth() < sizeOfSizeT)
552 toPrint = LLVM::ZExtOp::create(
553 rewriter, loc,
554 IntegerType::get(getContext(), sizeOfSizeT.getFixedValue()), toPrint);
555
556 // Lookup of create printf function symbol.
557 auto printfFunc = LLVM::lookupOrCreateFn(
558 rewriter, moduleOp, "printf", LLVM::LLVMPointerType::get(getContext()),
559 LLVM::LLVMVoidType::get(getContext()), true);
560 if (failed(printfFunc))
561 return printfFunc;
562
563 // Insert the format string if not already available.
564 SmallString<16> formatStrName{"_arc_sim_emit_"};
565 formatStrName.append(truncated ? "trunc_" : "full_");
566 formatStrName.append(adaptor.getValueName());
567 LLVM::GlobalOp formatStrGlobal;
568 if (!(formatStrGlobal =
569 moduleOp.lookupSymbol<LLVM::GlobalOp>(formatStrName))) {
570 ConversionPatternRewriter::InsertionGuard insertGuard(rewriter);
571
572 SmallString<16> formatStr = adaptor.getValueName();
573 formatStr.append(" = ");
574 if (truncated)
575 formatStr.append("(truncated) ");
576 formatStr.append("%zx\n");
577 SmallVector<char> formatStrVec{formatStr.begin(), formatStr.end()};
578 formatStrVec.push_back(0);
579
580 rewriter.setInsertionPointToStart(moduleOp.getBody());
581 auto globalType =
582 LLVM::LLVMArrayType::get(rewriter.getI8Type(), formatStrVec.size());
583 formatStrGlobal = LLVM::GlobalOp::create(
584 rewriter, loc, globalType, /*isConstant=*/true,
585 LLVM::Linkage::Internal,
586 /*name=*/formatStrName, rewriter.getStringAttr(formatStrVec),
587 /*alignment=*/0);
588 }
589
590 Value formatStrGlobalPtr =
591 LLVM::AddressOfOp::create(rewriter, loc, formatStrGlobal);
592 rewriter.replaceOpWithNewOp<LLVM::CallOp>(
593 op, printfFunc.value(), ValueRange{formatStrGlobalPtr, toPrint});
594
595 return success();
596 }
597};
598
599} // namespace
600
601//===----------------------------------------------------------------------===//
602// Pass Implementation
603//===----------------------------------------------------------------------===//
604
605namespace {
606struct LowerArcToLLVMPass
607 : public circt::impl::LowerArcToLLVMBase<LowerArcToLLVMPass> {
608 void runOnOperation() override;
609};
610} // namespace
611
612void LowerArcToLLVMPass::runOnOperation() {
613 // Replace any `i0` values with an `hw.constant 0 : i0` to avoid later issues
614 // in LLVM conversion.
615 {
616 DenseMap<Region *, hw::ConstantOp> zeros;
617 getOperation().walk([&](Operation *op) {
618 if (op->hasTrait<OpTrait::ConstantLike>())
619 return;
620 for (auto result : op->getResults()) {
621 auto type = dyn_cast<IntegerType>(result.getType());
622 if (!type || type.getWidth() != 0)
623 continue;
624 auto *region = op->getParentRegion();
625 auto &zero = zeros[region];
626 if (!zero) {
627 auto builder = OpBuilder::atBlockBegin(&region->front());
628 zero = hw::ConstantOp::create(builder, result.getLoc(),
629 APInt::getZero(0));
630 }
631 result.replaceAllUsesWith(zero);
632 }
633 });
634 }
635
636 // Collect the symbols in the root op such that the HW-to-LLVM lowering can
637 // create LLVM globals with non-colliding names.
638 Namespace globals;
639 SymbolCache cache;
640 cache.addDefinitions(getOperation());
641 globals.add(cache);
642
643 // Setup the conversion target. Explicitly mark `scf.yield` legal since it
644 // does not have a conversion itself, which would cause it to fail
645 // legalization and for the conversion to abort. (It relies on its parent op's
646 // conversion to remove it.)
647 LLVMConversionTarget target(getContext());
648 target.addLegalOp<mlir::ModuleOp>();
649 target.addLegalOp<scf::YieldOp>(); // quirk of SCF dialect conversion
650
651 // Setup the arc dialect type conversion.
652 LLVMTypeConverter converter(&getContext());
653 converter.addConversion([&](seq::ClockType type) {
654 return IntegerType::get(type.getContext(), 1);
655 });
656 converter.addConversion([&](StorageType type) {
657 return LLVM::LLVMPointerType::get(type.getContext());
658 });
659 converter.addConversion([&](MemoryType type) {
660 return LLVM::LLVMPointerType::get(type.getContext());
661 });
662 converter.addConversion([&](StateType type) {
663 return LLVM::LLVMPointerType::get(type.getContext());
664 });
665 converter.addConversion([&](SimModelInstanceType type) {
666 return LLVM::LLVMPointerType::get(type.getContext());
667 });
668
669 // Setup the conversion patterns.
670 RewritePatternSet patterns(&getContext());
671
672 // MLIR patterns.
673 populateSCFToControlFlowConversionPatterns(patterns);
674 populateFuncToLLVMConversionPatterns(converter, patterns);
675 cf::populateControlFlowToLLVMConversionPatterns(converter, patterns);
676 arith::populateArithToLLVMConversionPatterns(converter, patterns);
677 index::populateIndexToLLVMConversionPatterns(converter, patterns);
678 populateAnyFunctionOpInterfaceTypeConversionPattern(patterns, converter);
679
680 // CIRCT patterns.
681 DenseMap<std::pair<Type, ArrayAttr>, LLVM::GlobalOp> constAggregateGlobalsMap;
683 constAggregateGlobalsMap);
687
688 // Arc patterns.
689 // clang-format off
690 patterns.add<
691 AllocMemoryOpLowering,
692 AllocStateLikeOpLowering<arc::AllocStateOp>,
693 AllocStateLikeOpLowering<arc::RootInputOp>,
694 AllocStateLikeOpLowering<arc::RootOutputOp>,
695 AllocStorageOpLowering,
696 ClockGateOpLowering,
697 ClockInvOpLowering,
698 MemoryReadOpLowering,
699 MemoryWriteOpLowering,
700 ModelOpLowering,
701 ReplaceOpWithInputPattern<seq::ToClockOp>,
702 ReplaceOpWithInputPattern<seq::FromClockOp>,
703 SeqConstClockLowering,
704 SimEmitValueOpLowering,
705 StateReadOpLowering,
706 StateWriteOpLowering,
707 StorageGetOpLowering,
708 ZeroCountOpLowering
709 >(converter, &getContext());
710 // clang-format on
711
712 SmallVector<ModelInfo> models;
713 if (failed(collectModels(getOperation(), models))) {
714 signalPassFailure();
715 return;
716 }
717
718 llvm::DenseMap<StringRef, ModelInfoMap> modelMap(models.size());
719 for (ModelInfo &modelInfo : models) {
720 llvm::DenseMap<StringRef, StateInfo> states(modelInfo.states.size());
721 for (StateInfo &stateInfo : modelInfo.states)
722 states.insert({stateInfo.name, stateInfo});
723 modelMap.insert(
724 {modelInfo.name,
725 ModelInfoMap{modelInfo.numStateBytes, std::move(states),
726 modelInfo.initialFnSym, modelInfo.finalFnSym}});
727 }
728
729 patterns.add<SimInstantiateOpLowering, SimSetInputOpLowering,
730 SimGetPortOpLowering, SimStepOpLowering>(
731 converter, &getContext(), modelMap);
732
733 // Apply the conversion.
734 ConversionConfig config;
735 config.allowPatternRollback = false;
736 if (failed(applyFullConversion(getOperation(), target, std::move(patterns),
737 config)))
738 signalPassFailure();
739}
740
741std::unique_ptr<OperationPass<ModuleOp>> circt::createLowerArcToLLVMPass() {
742 return std::make_unique<LowerArcToLLVMPass>();
743}
assert(baseType &&"element must be base type")
static llvm::Twine evalSymbolFromModelName(StringRef modelName)
A namespace that is used to store existing names and generate new names in some scope within the IR.
Definition Namespace.h:30
void add(mlir::ModuleOp module)
Definition Namespace.h:48
void addDefinitions(mlir::Operation *top)
Populate the symbol cache with all symbol-defining operations within the 'top' operation.
Definition SymCache.cpp:23
Default symbol cache implementation; stores associations between names (StringAttr's) to mlir::Operat...
Definition SymCache.h:85
create(data_type, value)
Definition hw.py:433
mlir::LogicalResult collectModels(mlir::ModuleOp module, llvm::SmallVector< ModelInfo > &models)
Collects information about all Arc models in the provided module, and adds it to models.
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.
void populateHWToLLVMConversionPatterns(mlir::LLVMTypeConverter &converter, RewritePatternSet &patterns, Namespace &globals, DenseMap< std::pair< Type, ArrayAttr >, mlir::LLVM::GlobalOp > &constAggregateGlobalsMap)
Get the HW to LLVM conversion patterns.
void populateCombToArithConversionPatterns(TypeConverter &converter, RewritePatternSet &patterns)
void populateCombToLLVMConversionPatterns(mlir::LLVMTypeConverter &converter, RewritePatternSet &patterns)
Get the Comb to LLVM conversion patterns.
void populateHWToLLVMTypeConversions(mlir::LLVMTypeConverter &converter)
Get the HW to LLVM type conversions.
std::unique_ptr< OperationPass< ModuleOp > > createLowerArcToLLVMPass()
Definition hw.py:1
Gathers information about a given Arc model.
Definition ModelInfo.h:35
Gathers information about a given Arc state.
Definition ModelInfo.h:25