[llvm-dev] Question about method SelectionDAG::FoldConstantArithmetic

wuhui1973 via llvm-dev llvm-dev at lists.llvm.org
Tue Feb 23 01:28:06 PST 2016


I find method SelectionDAG::FoldConstantArithmetic contains following code (path: lib/CodeGen/SelectionDAG/SelectionDAG.cpp)


SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, SDLoc DL, EVT VT,
                                             SDNode *Cst1, SDNode *Cst2) {
  // If the opcode is a target-specific ISD node, there's nothing we can
  // do here and the operand rules may not line up with the below, so
  // bail early.
  if (Opcode >= ISD::BUILTIN_OP_END)
    return SDValue();


  // Handle the case of two scalars.
  if (const ConstantSDNode *Scalar1 = dyn_cast<ConstantSDNode>(Cst1)) {
    if (const ConstantSDNode *Scalar2 = dyn_cast<ConstantSDNode>(Cst2)) {
      if (SDValue Folded =
          FoldConstantArithmetic(Opcode, DL, VT, Scalar1, Scalar2)) {
        if (!VT.isVector())
          return Folded;
        SmallVector<SDValue, 4> Outputs;
        // We may have a vector type but a scalar result. Create a splat.
        Outputs.resize(VT.getVectorNumElements(), Outputs.back());
        // Build a big vector out of the scalar elements we generated.
        return getNode(ISD::BUILD_VECTOR, SDLoc(), VT, Outputs);
      } else {
        return SDValue();
      }
    }
  }


The IF block enclosing the code marked in red tries to do constant folding for the two constant operands.
If it finds out that we get a scalar result, but the expected type is a vector, the code marked in red will be 
executed.
But it confuses me, for the Outputs is empty, first even get last element for an empty SmallVector 
will trigger assert, second we will use an array of empty SDValue instances as the operands for the 
BUILD_VECTOR operator. It may trigger crash when try to access the NULL SDNode pointer inside these 
SDValue instances (tons of points not checking the NULL pointer before access).


Should it be like this, make the scalar result just elements of the vector result (I don't fully understand what should do in this situation):


        SmallVector<SDValue, 4> Outputs;
        EVT SVT = VT.getScalarType();
        Outputs.push_back(getConstant(Folded.first, DL, SVT));
        // We may have a vector type but a scalar result. Create a splat.
        Outputs.resize(VT.getVectorNumElements(), Outputs.back());
        // Build a big vector out of the scalar elements we generated.
        return getNode(ISD::BUILD_VECTOR, SDLoc(), VT, Outputs);


Or may it just the case will not actually happen and can be removed?


Regards
Hui Wu
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/llvm-dev/attachments/20160223/1804eeda/attachment.html>


More information about the llvm-dev mailing list