how to get basic block ID of a statement inside visit* methods - clang

How can we get basic block id (blockID) of a statement when we override
visit* methods?
e.g. for a basic block given below, when VisitIfStmt() is visited, how
to get blockID inside this visit method?
[B4]
1: x == 0
T: if [B4.1]
Preds (1): B6
Succs (2): B3 B2

Old question, but I had to answer the same lately. You can use the CFGStmtMap to query for the BBL of a statement:
const FunctionDecl* FD = ...;
const CFG* cfg = ...;
std::unique_ptr<ParentMap> PM = llvm::make_unique<ParentMap>(FD->getBody());
std::unique_ptr<CFGStmtMap> CM = llvm::make_unique<CFGStmtMap>(cfg, PM.get());
// do your traversal and for a given Stmt `stmt` you can get
// its containing block:
CFGBlock* stmt_block = CM->getBlock(stmt);
const unsigned int block_id = stmt_block->getBlockID();

You can try to use llvm::PHINode::getBasicBlockIndex ( const BasicBlock *BB).

Related

Building a DspComplex ROM in Chisel

I'm attempting to build a ROM-based Window function using DSPComplex and FixedPoint types, but seem to keep running into the following error:
chisel3.core.Binding$ExpectedHardwareException: vec element 'dsptools.numbers.DspComplex#32' must be hardware, not a bare Chisel type
The source code for my attempt at this looks like the following:
class TaylorWindow(len: Int, window: Seq[FixedPoint]) extends Module {
val io = IO(new Bundle {
val d_valid_in = Input(Bool())
val sample = Input(DspComplex(FixedPoint(16.W, 8.BP), FixedPoint(16.W, 8.BP)))
val windowed_sample = Output(DspComplex(FixedPoint(24.W, 8.BP), FixedPoint(24.W, 8.BP)))
val d_valid_out = Output(Bool())
})
val win_coeff = Vec(window.map(x=>DspComplex(x, FixedPoint(0, 16.W, 8.BP))).toSeq) // ROM storing our coefficients.
io.d_valid_out := io.d_valid_in
val counter = Reg(UInt(10.W))
// Implicit reset
io.windowed_sample:= io.sample * win_coeff(counter)
when(io.d_valid_in) {
counter := counter + 1.U
}
}
println(getVerilog(new TaylorWindow(1024, fp_seq)))
I'm actually reading the coefficients in from a file (this particular window has a complex generation function that I'm doing in Python elsewhere) with the following sequence of steps
val filename = "../generated/taylor_coeffs"
val coeff_file = Source.fromFile(filename).getLines
val double_coeffs = coeff_file.map(x => x.toDouble)
val fp_coeffs = double_coeffs.map(x => FixedPoint.fromDouble(x, 16.W, 8.BP))
val fp_seq = fp_coeffs.toSeq
Does this mean the DSPComplex type isn't able to be translated to Verilog?
Commenting out the win_coeff line seems to make the whole thing generate (but clearly doesn't do what I want it to do)
I think you should try using
val win_coeff = VecInit(window.map(x=>DspComplex.wire(x, FixedPoint.fromDouble(0.0, 16.W, 8.BP))).toSeq) // ROM storing our coefficients.
which will create hardware values like you want. The Vec just creates a Vec of the type specfied

Splitting a string using a delimiter in Groovy and avoiding IndexOutOfBoundsException

I want to split an input parameter inputDetails to unit level. I'm using tokenize for doing this. Here is my code:
Groovy Code:
def inputDetails = "1234-a0-12;1111-b0-34";
def cDesc = inputDetails.tokenize(";");
for (int i=0; i<cDesc.size(); ++i)
{
def cVer = cDesc.get(i);
def cNum = cVer.tokenize("-");
def a = cNum.get(0);
def b = cNum.get(1);
def c = cNum.get(2);
println (" DEBUG : Input details are, ${a} : ${b} : ${c} \n");
}
Output:
DEBUG : Input details are, 1234 : a0 : 12
DEBUG : Input details are, 1111 : b0 : 34
This output is correct and expected. But if I change the first line of Groovy code to following:
def inputDetails = "1234-a0-12;1111-b0";
I get following error message:
java.lang.IndexOutOfBoundsException: Index: 2, Size: 2
at java_util_List$get$6.call(Unknown Source)
at Script1.run(Script1.groovy:9)
How can I fix it to prevent getting IndexOutOfBoundsException while supporting both, 1234-a0-12;1111-b0-34 and 1234-a0-12;1111-b0 inputs?
You can use Groovy's multiple assignment feature to safely grab 3 values from the second tokenization. Consider following example:
def inputDetails = "1234-a0-12;1111-b0-34"
def cDesc = inputDetails.tokenize(";")
cDesc.each { part ->
def (p1, p2, p3) = part.tokenize('-')
println "DEBUG: Input details are, ${p1} : ${p2} : ${p3}"
}
Output:
DEBUG: Input details are, 1234 : a0 : 12
DEBUG: Input details are, 1111 : b0 : 34
The good thing is that this approach prevents IndexOutOfBoundsException or NullPointerException. If we change the first line to
def inputDetails = "1234-a0-12;1111-b0"
the result is:
DEBUG: Input details are, 1234 : a0 : 12
DEBUG: Input details are, 1111 : b0 : null
You can split the string into a 2D list by further splitting on '-':
def inputDetails = "1234-a0-12;1111-b0-34"
def elements = inputDetails.split(';').collect{it.split('-')}
elements is of type List<List<String>>. When printed, it yields:
[[1234, a0, 12], [1111, b0, 34]]
With this, you can afford more flexibility instead of hard-coding array indexes.
And with "1234-a0-12;1111-b0", it's split into [[1234, a0, 12], [1111, b0]]

Doors DXL filter ,

I have the following snip of dxl code,
I would like to copy the object ID with the filter F3 is on. :
I dont know what I am doing wrong it gives me (ID) of all the object.
string Id
int x=0;
int y=0;
Id = o."SourceID"
Filter f0 = hasNoLinks(linkFilterIncoming, "*")
Filter f1=attribute "_TraceTo" == "System"
Filter f2 = attribute "Object Type" == "requirement"
Filter f3 = f1&&f2&&f0
addFilter(m,f3,x,y)
print x ":\t" fullName(module(m)) "\n"
wOutKLHUntraced << Id "\t" fullName(module(m)) "\n"
First, you need to add the statement filtering on after adding the filter, so that the filter is applied. Then the filtered objects will be the only ones visible.
Then, you set "Id" way too early in the script. At line 4, "o" is set to
some object, I don't know which one, but certainly not the result of
your filter. Instead, after the statement filtering on, add statements
Object o = first m // the first object that is now visible
Id = o."SourceID"
My Script is running good, but gives different results : as I am running this script in a for loop for around 30 module :
Am I am setting somewhere wrong filters ?
Stream TbdUntraced;
string s
string d
Object o
string trac
int numReqs = 0;
string IdNum
string untraced
int x=0;
int y=0;
int a =0;
for o in m do
{
ensureInLinkedModulesLoaded(o,S_SATISFIES );
s = o."Object Type"
string Id
string Topic
Topic = o."_Topic"
numReqs++;
Filter f0 = hasNoLinks(linkFilterIncoming, "*")
Filter f1 = contains(attribute "_TraceTo", "TBD", false)
Filter f2 = attribute "Object Type" == "requirement"
Filter f3 = attribute "MMS5-Autoliv_Supplier_Status" == "agreed"
Filter f4 = attribute "MMS5-Autoliv_Supplier_Status" == "partly agreed"
Filter f7 = f0&&f2&&(f3||f4)&&f1
addFilter(m,f7,x,y)
filtering on
d = o."MMS5-Autoliv_OEM_Status"
Id = o."SourceID"
Topic = o."_Topic"
print x ":\t" name(module(m)) "\n"
TbdUntraced << Id "\t" Topic "\t"name(module(m)) "\n"
}

How do I get the table length of a lua table in c?

I have a c function that is called from lua. The first parameter is a table. That table is abused as an input array of numbers to an underlying api. So right now my code looks like this:
int n = 0;
lua_pushnil ( L );
while ( lua_next ( L, 2 ) ) {
n++;
lua_pop ( L, 1 );
}
int *flat = alloca ( n * 4 );
lua_pushnil ( L );
int i = 0;
while ( lua_next(L,2) ) {
flat[i++] = (int)lua_tonumber( L, -1 );
lua_pop ( L, 1 );
}
I typed the code blind, so please forgive errors. Also no error checking. But the problem is that I have to do the while loop twice. Is there an easy way to avoid that? I want to optimize for the case where the input is good - a table of ints.
The function you're looking for is unintuitively named lua_objlen, or in Lua 5.2, lua_len (there is a lua_rawlen if you wish to avoid metamethod invocations). It serves many roles (though some, like the length of a string, aren't very useful when you can just use lua_tolstring to get the string and its length), so you should be familiar with it.

How can I call this native function from F#? (LLVMCreateJITCompilerForModule)

I'm using the llvm-fs bindings and one method I would like to call is createJITCompilerForModule which is an extern to the native method LLVMCreateJITCompilerForModule in the LLVM C api. The author of llvm-fs has stated he can't make a 'nice' version of this function call in F#:
createJITCompilerForModule in llvm-fs:Generated.fs:
[<DllImport(
"LLVM-3.1.dll",
EntryPoint="LLVMCreateJITCompilerForModule",
CallingConvention=CallingConvention.Cdecl,
CharSet=CharSet.Ansi)>]
extern bool createJITCompilerForModuleNative(
void* (* LLVMExecutionEngineRef* *) OutJIT,
void* (* LLVMModuleRef *) M,
uint32 OptLevel,
void* OutError)
// I don't know how to generate an "F# friendly" version of LLVMCreateJITCompilerForModule
Do you know how I would call this function from F#, or even what the native one does? It looks like it has an 'out parameter' for OutJIT (as the native code reassigns a thing the void* points to). Here is the native function:
LLVMCreateJITCompilerForModule in llvm-c:ExecutionEngineBindings.cpp:
LLVMBool LLVMCreateJITCompilerForModule(LLVMExecutionEngineRef *OutJIT,
LLVMModuleRef M,
unsigned OptLevel,
char **OutError) {
std::string Error;
EngineBuilder builder(unwrap(M));
builder.setEngineKind(EngineKind::JIT)
.setErrorStr(&Error)
.setOptLevel((CodeGenOpt::Level)OptLevel);
if (ExecutionEngine *JIT = builder.create()) {
*OutJIT = wrap(JIT);
return 0;
}
*OutError = strdup(Error.c_str());
return 1;
}
The actual function I wanted to use was a special hand made one as it couldn't be generated. I've put it here as an example of how to call it:
llvm-fs:ExecutionEngine.fs
let private createEngineForModuleFromNativeFunc
(nativeFunc : (nativeint * nativeint * nativeint) -> bool)
(moduleRef : ModuleRef) =
use outEnginePtr = new NativePtrs([|0n|])
use outErrPtr = new NativePtrs([|0n|])
let createFailed =
nativeFunc (
outEnginePtr.Ptrs,
moduleRef.Ptr,
outErrPtr.Ptrs)
if createFailed then
let errStr = Marshal.PtrToStringAuto (Marshal.ReadIntPtr outErrPtr.Ptrs)
Marshal.FreeHGlobal (Marshal.ReadIntPtr outErrPtr.Ptrs)
failwith errStr
else
ExecutionEngineRef (Marshal.ReadIntPtr outEnginePtr.Ptrs)
let createJITCompilerForModule (modRef : ModuleRef) (optLvl : uint32) =
let f (engPtr, modPtr, outErrPtr) =
createJITCompilerForModuleNative (engPtr, modPtr, optLvl, outErrPtr)
createEngineForModuleFromNativeFunc f modRef

Resources