<commit_before>//===-- PPC32ISelPattern.cpp - A pattern matching inst selector for PPC32 -===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by <NAME> and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines a pattern matching instruction selector for 32 bit PowerPC.
// Magic number generation for integer divide from the PowerPC Compiler Writer's
// Guide, section 3.2.3.5
//
//===----------------------------------------------------------------------===//

#include "PowerPC.h"
#include "PowerPCInstrBuilder.h"
#include "PowerPCInstrInfo.h"
#include "PPC32TargetMachine.h"
#include "PPC32ISelLowering.h"
#include "llvm/Constants.h"
#include "llvm/Function.h"
#include "llvm/CodeGen/MachineConstantPool.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineFrameInfo.h"
#include "llvm/CodeGen/SelectionDAG.h"
#include "llvm/CodeGen/SelectionDAGISel.h"
#include "llvm/CodeGen/SSARegMap.h"
#include "llvm/Target/TargetData.h"
#include "llvm/Target/TargetOptions.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/MathExtras.h"
#include "llvm/ADT/Statistic.h"
#include <set>
#include <algorithm>
using namespace llvm;

namespace {
Statistic<> Recorded("ppc-codegen", "Number of recording ops emitted");
Statistic<> FusedFP ("ppc-codegen", "Number of fused fp operations");
Statistic<> FrameOff("ppc-codegen", "Number of frame idx offsets collapsed");

//===--------------------------------------------------------------------===//
// ISel - PPC32 specific code to select PPC32 machine instructions for
// SelectionDAG operations.
//===--------------------------------------------------------------------===//

class ISel : public SelectionDAGISel {
  PPC32TargetLowering PPC32Lowering;
  SelectionDAG *ISelDAG;  // Hack to support us having a dag->dag transform
                          // for sdiv and udiv until it is put into the future
                          // dag combiner.

  /// ExprMap - As shared expressions are codegen'd, we keep track of which
  /// vreg the value is produced in, so we only emit one copy of each compiled
  /// tree.
  std::map<SDOperand, unsigned> ExprMap;

  unsigned GlobalBaseReg;
  bool GlobalBaseInitialized;
  bool RecordSuccess;
public:
  ISel(TargetMachine &TM) : SelectionDAGISel(PPC32Lowering), PPC32Lowering(TM),
                            ISelDAG(0) {}

  /// runOnFunction - Override this function in order to reset our per-function
  /// variables.
  virtual bool runOnFunction(Function &Fn) {
    // Make sure we re-emit a set of the global base reg if necessary
    GlobalBaseInitialized = false;
    return SelectionDAGISel::runOnFunction(Fn);
  }

  /// InstructionSelectBasicBlock - This callback is invoked by
  /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
  virtual void InstructionSelectBasicBlock(SelectionDAG &DAG) {
    DEBUG(BB->dump());
    // Codegen the basic block.
    ISelDAG = &DAG;
    Select(DAG.getRoot());

    // Clear state used for selection.
    ExprMap.clear();
    ISelDAG = 0;
  }

  // convenience functions for virtual register creation
  inline unsigned MakeIntReg() {
    return RegMap->createVirtualRegister(PPC32::GPRCRegisterClass);
  }
  inline unsigned MakeFPReg() {
    return RegMap->createVirtualRegister(PPC32::FPRCRegisterClass);
  }
  
  // dag -> dag expanders for integer divide by constant
  SDOperand BuildSDIVSequence(SDOperand N);
  SDOperand BuildUDIVSequence(SDOperand N);

  unsigned getGlobalBaseReg();
  void MoveCRtoGPR(unsigned CCReg, ISD::CondCode CC, unsigned Result);
  bool SelectBitfieldInsert(SDOperand OR, unsigned Result);
  unsigned FoldIfWideZeroExtend(SDOperand N);
  unsigned SelectCC(SDOperand LHS, SDOperand RHS, ISD::CondCode CC);
  bool SelectIntImmediateExpr(SDOperand N, unsigned Result,
                              unsigned OCHi, unsigned OCLo,
                              bool IsArithmetic = false, bool Negate = false);
  unsigned SelectExpr(SDOperand N, bool Recording=false);
  void Select(SDOperand N);

  unsigned SelectAddr(SDOperand N, unsigned& Reg, int& offset);
  void SelectBranchCC(SDOperand N);
  
  virtual const char *getPassName() const {
    return "PowerPC Pattern Instruction Selection";
  } 
};

// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
// any number of 0s on either side.  The 1s are allowed to wrap from LSB to
// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
// not, since all 1s are not contiguous.
static bool isRunOfOnes(unsigned Val, unsigned &MB, unsigned &ME) {
  if (isShiftedMask_32(Val)) {
    // look for the first non-zero bit
    MB = CountLeadingZeros_32(Val);
    // look for the first zero bit after the run of ones
    ME = CountLeadingZeros_32((Val - 1) ^ Val);
    return true;
  } else if (isShiftedMask_32(Val = ~Val)) { // invert mask
    // effectively look for the first zero bit
    ME = CountLeadingZeros_32(Val) - 1;
    // effectively look for the first one bit after the run of zeros
    MB = CountLeadingZeros_32((Val - 1) ^ Val) + 1;
    return true;
  }
  // no run present
  return false;
}

// isRotateAndMask - Returns true if Mask and Shift can be folded in to a rotate
// and mask opcode and mask operation.
static bool isRotateAndMask(unsigned Opcode, unsigned Shift, unsigned Mask,
                            bool IsShiftMask,
                            unsigned &SH, unsigned &MB, unsigned &ME) {
  if (Shift > 31) return false;
  unsigned Indeterminant = ~0;       // bit mask marking indeterminant results
  
  if (Opcode == ISD::SHL) { // shift left
    // apply shift to mask if it comes first
    if (IsShiftMask) Mask = Mask << Shift;
    // determine which bits are made indeterminant by shift
    Indeterminant = ~(0xFFFFFFFFu << Shift);
  } else if (Opcode == ISD::SRA || Opcode == ISD::SRL) { // shift rights
    // apply shift to mask if it comes first
    if (IsShiftMask) Mask = Mask >> Shift;
    // determine which bits are made indeterminant by shift
    Indeterminant = ~(0xFFFFFFFFu >> Shift);
    // adjust for the left rotate
    Shift = 32 - Shift;
  }
  
  // if the mask doesn't intersect any Indeterminant bits
  if (Mask && !(Mask & Indeterminant)) {
    SH = Shift;
    // make sure the mask is still a mask (wrap arounds may not be)
    return isRunOfOnes(Mask, MB, ME);
  }
  
  // can't do it
  return false;
}

// isIntImmediate - This method tests to see if a constant operand.
// If so Imm will receive the 32 bit value.
static bool isIntImmediate(SDOperand N, unsigned& Imm) {
  // test for constant
  if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
    // retrieve value
    Imm = (unsigned)CN->getValue();
    // passes muster
    return true;
  }
  // not a constant
  return false;
}

// isOpcWithIntImmediate - This method tests to see if the node is a specific
// opcode and that it has a immediate integer right operand.
// If so Imm will receive the 32 bit value.
static bool isOpcWithIntImmediate(SDOperand N, unsigned Opc, unsigned& Imm) {
  return N.getOpcode() == Opc && isIntImmediate(N.getOperand(1), Imm);
}

// isOprShiftImm - Returns true if the specified operand is a shift opcode with
// a immediate shift count less than 32.
static bool isOprShiftImm(SDOperand N, unsigned& Opc, unsigned& SH) {
  Opc = N.getOpcode();
  return (Opc == ISD::SHL || Opc == ISD::SRL || Opc == ISD::SRA) &&
         isIntImmediate(N.getOperand(1), SH) && SH < 32;
}

// isOprNot - Returns true if the specified operand is an xor with immediate -1.
static bool isOprNot(SDOperand N) {
  unsigned Imm;
  return isOpcWithIntImmediate(N, ISD::XOR, Imm) && (signed)Imm == -1;
}

// Immediate constant composers.
// Lo16 - grabs the lo 16 bits from a 32 bit constant.
// Hi16 - grabs the hi 16 bits from a 32 bit constant.
// HA16 - computes the hi bits required if the lo bits are add/subtracted in
// arithmethically.
static unsigned Lo16(unsigned x)  { return x & 0x0000FFFF; }
static unsigned Hi16(unsigned x)  { return Lo16(x >> 16); }
static unsigned HA16(unsigned x)  { return Hi16((signed)x - (signed short)x); }

/// NodeHasRecordingVariant - If SelectExpr can always produce code for
/// NodeOpcode that also sets CR0 as a side effect, return true.  Otherwise,
/// return false.
static bool NodeHasRecordingVariant(unsigned NodeOpcode) {
  switch(NodeOpcode) {
  default: return false;
  case ISD::AND:
  case ISD::OR:
    return true;
  }
}

/// getBCCForSetCC - Returns the PowerPC condition branch mnemonic corresponding
/// to Condition.
static unsigned getBCCForSetCC(ISD::CondCode CC) {
  switch (CC) {
  default: assert(0 && "Unknown condition!"); abort();
  case ISD::SETEQ:  return PPC::BEQ;
  case ISD::SETNE:  return PPC::BNE;
  case ISD::SETULT:
  case ISD::SETLT:  return PPC::BLT;
  case ISD::SETULE:
  case ISD::SETLE:  return PPC::BLE;
  case ISD::SETUGT:
  case ISD::SETGT:  return PPC::BGT;
  case ISD::SETUGE:
  case ISD::SETGE:  return PPC::BGE;
  }
  return 0;
}

/// getCRIdxForSetCC - Return the index of the condition register field
/// associated with the SetCC condition, and whether or not the field is
/// treated as inverted.  That is, lt = 0; ge = 0 inverted.
static unsigned getCRIdxForSetCC(ISD::CondCode CC, bool& Inv) {
  switch (CC) {
  default: assert(0 && "Unknown condition!"); abort();
  case ISD::SETULT:
  case ISD::SETLT:  Inv = false;  return 0;
  case ISD::SETUGE:
  case ISD::SETGE:  Inv = true;   return 0;
  case ISD::SETUGT:
  case ISD::SETGT:  Inv = false;  return 1;
  case ISD::SETULE:
  case ISD::SETLE:  Inv = true;   return 1;
  case ISD::SETEQ:  Inv = false;  return 2;
  case ISD::SETNE:  Inv = true;   return 2;
  }
  return 0;
}

/// IndexedOpForOp - Return the indexed variant for each of the PowerPC load
/// and store immediate instructions.
static unsigned IndexedOpForOp(unsigned Opcode) {
  switch(Opcode) {
  default: assert(0 && "Unknown opcode!"); abort();
  case PPC::LBZ: return PPC::LBZX;  case PPC::STB: return PPC::STBX;
  case PPC::LHZ: return PPC::LHZX;  case PPC::STH: return PPC::STHX;
  case PPC::LHA: return PPC::LHAX;  case PPC::STW: return PPC::STWX;
  case PPC::LWZ: return PPC::LWZX;  case PPC::STFS: return PPC::STFSX;
  case PPC::LFS: return PPC::LFSX;  case PPC::STFD: return PPC::STFDX;
  case PPC::LFD: return PPC::LFDX;
  }
  return 0;
}

// Structure used to return the necessary information to codegen an SDIV as
// a multiply.
struct ms {
  int m; // magic number
  int s; // shift amount
};

struct mu {
  unsigned int m; // magic number
  int a;          // add indicator
  int s;          // shift amount
};

/// magic - calculate the magic numbers required to codegen an integer sdiv as
/// a sequence of multiply and shifts.  Requires that the divisor not be 0, 1,
/// or -1.
static struct ms magic(int d) {
  int p;
  unsigned int ad, anc, delta, q1, r1, q2, r2, t;
  const unsigned int two31 = 0x80000000U;
  struct ms mag;

  ad = abs(d);
  t = two31 + ((unsigned int)d >> 31);
  anc = t - 1 - t%ad;   // absolute value of nc
  p = 31;               // initialize p
  q1 = two31/anc;       // initialize q1 = 2p/abs(nc)
  r1 = two31 - q1*anc;  // initialize r1 = rem(2p,abs(nc))
  q2 = two31/ad;        // initialize q2 = 2p/abs(d)
  r2 = two31 - q2*ad;   // initialize r2 = rem(2p,abs(d))
  do {
    p = p + 1;
    q1 = 2*q1;        // update q1 = 2p/abs(nc)
    r1 = 2*r1;        // update r1 = rem(2p/abs(nc))
    if (r1 >= anc) {  // must be unsigned comparison
      q1 = q1 + 1;
      r1 = r1 - anc;
    }
    q2 = 2*q2;        // update q2 = 2p/abs(d)
    r2 = 2*r2;        // update r2 = rem(2p/abs(d))
    if (r2 >= ad) {   // must be unsigned comparison
      q2 = q2 + 1;
      r2 = r2 - ad;
    }
    delta = ad - r2;
  } while (q1 < delta || (q1 == delta && r1 == 0));

  mag.m = q2 + 1;
  if (d < 0) mag.m = -mag.m; // resulting magic number
  mag.s = p - 32;            // resulting shift
  return mag;
}

/// magicu - calculate the magic numbers required to codegen an integer udiv as
/// a sequence of multiply, add and shifts.  Requires that the divisor not be 0.
static struct mu magicu(unsigned d)
{
  int p;
  unsigned int nc, delta, q1, r1, q2, r2;
  struct mu magu;
  magu.a = 0;               // initialize "add" indicator
  nc = - 1 - (-d)%d;
  p = 31;                   // initialize p
  q1 = 0x80000000/nc;       // initialize q1 = 2p/nc
  r1 = 0x80000000 - q1*nc;  // initialize r1 = rem(2p,nc)
  q2 = 0x7FFFFFFF/d;        // initialize q2 = (2p-1)/d
  r2 = 0x7FFFFFFF - q2*d;   // initialize r2 = rem((2p-1),d)
  do {
    p = p + 1;
    if (r1 >= nc - r1 ) {
      q1 = 2*q1 + 1;  // update q1
      r1 = 2*r1 - nc; // update r1
    }
    else {
      q1 = 2*q1; // update q1
      r1 = 2*r1; // update r1
    }
    if (r2 + 1 >= d - r2) {
      if (q2 >= 0x7FFFFFFF) magu.a = 1;
      q2 = 2*q2 + 1;     // update q2
      r2 = 2*r2 + 1 - d; // update r2
    }
    else {
      if (q2 >= 0x80000000) magu.a = 1;
      q2 = 2*q2;     // update q2
      r2 = 2*r2 + 1; // update r2
    }
    delta = d - 1 - r2;
  } while (p < 64 && (q1 < delta || (q1 == delta && r1 == 0)));
  magu.m = q2 + 1; // resulting magic number
  magu.s = p - 32;  // resulting shift
  return magu;
}
}

/// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
/// return a DAG expression to select that will generate the same value by
/// multiplying by a magic number.  See:
/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
SDOperand ISel::BuildSDIVSequence(SDOperand N) {
  int d = (int)cast<ConstantSDNode>(N.getOperand(1))->getSignExtended();
  ms magics = magic(d);
  // Multiply the numerator (operand 0) by the magic value
  SDOperand Q = ISelDAG->getNode(ISD::MULHS, MVT::i32, N.getOperand(0),
                                 ISelDAG->getConstant(magics.m, MVT::i32));
  // If d > 0 and m < 0, add the numerator
  if (d > 0 && magics.m < 0)
    Q = ISelDAG->getNode(ISD::ADD, MVT::i32, Q, N.getOperand(0));
  // If d < 0 and m > 0, subtract the numerator.
  if (d < 0 && magics.m > 0)
    Q = ISelDAG->getNode(ISD::SUB, MVT::i32, Q, N.getOperand(0));
  // Shift right algebraic if shift value is nonzero
  if (magics.s > 0)
    Q = ISelDAG->getNode(ISD::SRA, MVT::i32, Q,
                         ISelDAG->getConstant(magics.s, MVT::i32));
  // Extract the sign bit and add it to the quotient
  SDOperand T =
    ISelDAG->getNode(ISD::SRL, MVT::i32, Q, ISelDAG->getConstant(31, MVT::i32));
  return ISelDAG->getNode(ISD::ADD, MVT::i32, Q, T);
}

/// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
/// return a DAG expression to select that will generate the same value by
/// multiplying by a magic number.  See:
/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
SDOperand ISel::BuildUDIVSequence(SDOperand N) {
  unsigned d =
    (unsigned)cast<ConstantSDNode>(N.getOperand(1))->getSignExtended();
  mu magics = magicu(d);
  // Multiply the numerator (operand 0) by the magic value
  SDOperand Q = ISelDAG->getNode(ISD::MULHU, MVT::i32, N.getOperand(0),
                                 ISelDAG->getConstant(magics.m, MVT::i32));
  if (magics.a == 0) {
    Q = ISelDAG->getNode(ISD::SRL, MVT::i32, Q,
                         ISelDAG->getConstant(magics.s, MVT::i32));
  } else {
    SDOperand NPQ = ISelDAG->getNode(ISD::SUB, MVT::i32, N.getOperand(0), Q);
    NPQ = ISelDAG->getNode(ISD::SRL, MVT::i32, NPQ,
                           ISelDAG->getConstant(1, MVT::i32));
    NPQ = ISelDAG->getNode(ISD::ADD, MVT::i32, NPQ, Q);
    Q = ISelDAG->getNode(ISD::SRL, MVT::i32, NPQ,
                           ISelDAG->getConstant(magics.s-1, MVT::i32));
  }
  return Q;
}

/// getGlobalBaseReg - Output the instructions required to put the
/// base address to use for accessing globals into a register.
///
unsigned ISel::getGlobalBaseReg() {
  if (!GlobalBaseInitialized) {
    // Insert the set of GlobalBaseReg into the first MBB of the function
    MachineBasicBlock &FirstMBB = BB->getParent()->front();
    MachineBasicBlock::iterator MBBI = FirstMBB.begin();
    GlobalBaseReg = MakeIntReg();
    BuildMI(FirstMBB, MBBI, PPC::MovePCtoLR, 0, PPC::LR);
    BuildMI(FirstMBB, MBBI, PPC::MFLR, 1, GlobalBaseReg);
    GlobalBaseInitialized = true;
  }
  return GlobalBaseReg;
}

/// MoveCRtoGPR - Move CCReg[Idx] to the least significant bit of Result.  If
/// Inv is true, then invert the result.
void ISel::MoveCRtoGPR(unsigned CCReg, ISD::CondCode CC, unsigned Result){
  bool Inv;
  unsigned IntCR = MakeIntReg();
  unsigned Idx = getCRIdxForSetCC(CC, Inv);
  BuildMI(BB, PPC::MCRF, 1, PPC::CR7).addReg(CCReg);
  bool GPOpt =
    TLI.getTargetMachine().getSubtarget<PPCSubtarget>().isGigaProcessor();
  if (GPOpt)
    BuildMI(BB, PPC::MFOCRF, 1, IntCR).addReg(PPC::CR7);
  else
    BuildMI(BB, PPC::MFCR, 0, IntCR);
  if (Inv) {
    unsigned Tmp1 = MakeIntReg();
    BuildMI(BB, PPC::RLWINM, 4, Tmp1).addReg(IntCR).addImm(32-(3-Idx))
      .addImm(31).addImm(31);
    BuildMI(BB, PPC::XORI, 2, Result).addReg(Tmp1).addImm(1);
  } else {
    BuildMI(BB, PPC::RLWINM, 4, Result).addReg(IntCR).addImm(32-(3-Idx))
      .addImm(31).addImm(31);
  }
}

/// SelectBitfieldInsert - turn an or of two masked values into
/// the rotate left word immediate then mask insert (rlwimi) instruction.
/// Returns true on success, false if the caller still needs to select OR.
///
/// Patterns matched:
/// 1. or shl, and   5. or and, and
/// 2. or and, shl   6. or shl, shr
/// 3. or shr, and   7. or shr, shl
/// 4. or and, shr
bool ISel::SelectBitfieldInsert(SDOperand OR, unsigned Result) {
  bool IsRotate = false;
  unsigned TgtMask = 0xFFFFFFFF, InsMask = 0xFFFFFFFF, Amount = 0;
  unsigned Value;

  SDOperand Op0 = OR.getOperand(0);
  SDOperand Op1 = OR.getOperand(1);

  unsigned Op0Opc = Op0.getOpcode();
  unsigned Op1Opc = Op1.getOpcode();

  // Verify that we have the correct opcodes
  if (ISD::SHL != Op0Opc && ISD::SRL != Op0Opc && ISD::AND != Op0Opc)
    return false;
  if (ISD::SHL != Op1Opc && ISD::SRL != Op1Opc && ISD::AND != Op1Opc)
    return false;

  // Generate Mask value for Target
  if (isIntImmediate(Op0.getOperand(1), Value)) {
    switch(Op0Opc) {
    case ISD::SHL: TgtMask <<= Value; break;
    case ISD::SRL: TgtMask >>= Value; break;
    case ISD::AND: TgtMask &= Value; break;
    }
  } else {
    return false;
  }

  // Generate Mask value for Insert
  if (isIntImmediate(Op1.getOperand(1), Value)) {
    switch(Op1Opc) {
    case ISD::SHL:
      Amount = Value;
      InsMask <<= Amount;
      if (Op0Opc == ISD::SRL) IsRotate = true;
      break;
    case ISD::SRL:
      Amount = Value;
      InsMask >>= Amount;
      Amount = 32-Amount;
      if (Op0Opc == ISD::SHL) IsRotate = true;
      break;
    case ISD::AND:
      InsMask &= Value;
      break;
    }
  } else {
    return false;
  }

  unsigned Tmp3 = 0;

  // If both of the inputs are ANDs and one of them has a logical shift by
  // constant as its input, make that the inserted value so that we can combine
  // the shift into the rotate part of the rlwimi instruction
  if (Op0Opc == ISD::AND && Op1Opc == ISD::AND) {
    if (Op1.getOperand(0).getOpcode() == ISD::SHL ||
        Op1.getOperand(0).getOpcode() == ISD::SRL) {
      if (isIntImmediate(Op1.getOperand(0).getOperand(1), Value)) {
        Amount = Op1.getOperand(0).getOpcode() == ISD::SHL ?
          Value : 32 - Value;
        Tmp3 = SelectExpr(Op1.getOperand(0).getOperand(0));
      }
    } else if (Op0.getOperand(0).getOpcode() == ISD::SHL ||
               Op0.getOperand(0).getOpcode() == ISD::SRL) {
      if (isIntImmediate(Op0.getOperand(0).getOperand(1), Value)) {
        std::swap(Op0, Op1);
        std::swap(TgtMask, InsMask);
        Amount = Op1.getOperand(0).getOpcode() == ISD::SHL ?
          Value : 32 - Value;
        Tmp3 = SelectExpr(Op1.getOperand(0).getOperand(0));
      }
    }
  }

  // Verify that the Target mask and Insert mask together form a full word mask
  // and that the Insert mask is a run of set bits (which implies both are runs
  // of set bits).  Given that, Select the arguments and generate the rlwimi
  // instruction.
  unsigned MB, ME;
  if (((TgtMask & InsMask) == 0) && isRunOfOnes(InsMask, MB, ME)) {
    unsigned Tmp1, Tmp2;
    bool fullMask = (TgtMask ^ InsMask) == 0xFFFFFFFF;
    // Check for rotlwi / rotrwi here, a special case of bitfield insert
    // where both bitfield halves are sourced from the same value.
    if (IsRotate && fullMask &&
        OR.getOperand(0).getOperand(0) == OR.getOperand(1).getOperand(0)) {
      Tmp1 = SelectExpr(OR.getOperand(0).getOperand(0));
      BuildMI(BB, PPC::RLWINM, 4, Result).addReg(Tmp1).addImm(Amount)
        .addImm(0).addImm(31);
      return true;
    }
    if (Op0Opc == ISD::AND && fullMask)
      Tmp1 = SelectExpr(Op0.getOperand(0));
    else
      Tmp1 = SelectExpr(Op0);
    Tmp2 = Tmp3 ? Tmp3 : SelectExpr(Op1.getOperand(0));
    BuildMI(BB, PPC::RLWIMI, 5, Result).addReg(Tmp1).addReg(Tmp2)
      .addImm(Amount).addImm(MB).addImm(ME);
    return true;
  }
  return false;
}

/// FoldIfWideZeroExtend - 32 bit PowerPC implicit masks shift amounts to the
/// low six bits.  If the shift amount is an ISD::AND node with a mask that is
/// wider than the implicit mask, then we can get rid of the AND and let the
/// shift do the mask.
unsigned ISel::FoldIfWideZeroExtend(SDOperand N) {
  unsigned C;
  if (isOpcWithIntImmediate(N, ISD::AND, C) && isMask_32(C) && C > 63)
    return SelectExpr(N.getOperand(0));
  else
    return SelectExpr(N);
}

unsigned ISel::SelectCC(SDOperand LHS, SDOperand RHS, ISD::CondCode CC) {
  unsigned Result, Tmp1, Tmp2;
  bool AlreadySelected = false;
  static const unsigned CompareOpcodes[] =
    { PPC::FCMPU, PPC::FCMPU, PPC::CMPW, PPC::CMPLW };

  // Allocate a condition register for this expression
  Result = RegMap->createVirtualRegister(PPC32::CRRCRegisterClass);

  // Use U to determine whether the SETCC immediate range is signed or not.
  bool U = ISD::isUnsignedIntSetCC(CC);
  if (isIntImmediate(RHS, Tmp2) && 
      ((U && isUInt16(Tmp2)) || (!U && isInt16(Tmp2)))) {
    Tmp2 = Lo16(Tmp2);
    // For comparisons against zero, we can implicity set CR0 if a recording
    // variant (e.g. 'or.' instead of 'or') of the instruction that defines
    // operand zero of the SetCC node is available.
    if (Tmp2 == 0 &&
        NodeHasRecordingVariant(LHS.getOpcode()) && LHS.Val->hasOneUse()) {
      RecordSuccess = false;
      Tmp1 = SelectExpr(LHS, true);
      if (RecordSuccess) {
        ++Recorded;
        BuildMI(BB, PPC::MCRF, 1, Result).addReg(PPC::CR0);
        return Result;
      }
      AlreadySelected = true;
    }
    // If we could not implicitly set CR0, then emit a compare immediate
    // instead.
    if (!AlreadySelected) Tmp1 = SelectExpr(LHS);
    if (U)
      BuildMI(BB, PPC::CMPLWI, 2, Result).addReg(Tmp1).addImm(Tmp2);
    else
      BuildMI(BB, PPC::CMPWI, 2, Result).addReg(Tmp1).addSImm(Tmp2);
  } else {
    bool IsInteger = MVT::isInteger(LHS.getValueType());
    unsigned CompareOpc = CompareOpcodes[2 * IsInteger + U];
    Tmp1 = SelectExpr(LHS);
    Tmp2 = SelectExpr(RHS);
    BuildMI(BB, CompareOpc, 2, Result).addReg(Tmp1).addReg(Tmp2);
  }
  return Result;
}

/// Check to see if the load is a constant offset from a base register.
unsigned ISel::SelectAddr(SDOperand N, unsigned& Reg, int& offset)
{
  unsigned imm = 0, opcode = N.getOpcode();
  if (N.getOpcode() == ISD::ADD) {
    bool isFrame = N.getOperand(0).getOpcode() == ISD::FrameIndex;
    if (isIntImmediate(N.getOperand(1), imm) && isInt16(imm)) {
      offset = Lo16(imm);
      if (isFrame) {
        ++FrameOff;
        Reg = cast<FrameIndexSDNode>(N.getOperand(0))->getIndex();
        return 1;
      } else {
        Reg = SelectExpr(N.getOperand(0));
        return 0;
      }
    } else {
      Reg = SelectExpr(N.getOperand(0));
      offset = SelectExpr(N.getOperand(1));
      return 2;
    }
  }
  // Now check if we're dealing with a global, and whether or not we should emit
  // an optimized load or store for statics.
  if(GlobalAddressSDNode *GN = dyn_cast<GlobalAddressSDNode>(N)) {
    GlobalValue *GV = GN->getGlobal();
    if (!GV->hasWeakLinkage() && !GV->isExternal()) {
      unsigned GlobalHi = MakeIntReg();
      if (PICEnabled)
        BuildMI(BB, PPC::ADDIS, 2, GlobalHi).addReg(getGlobalBaseReg())
          .addGlobalAddress(GV);
      else
        BuildMI(BB, PPC::LIS, 1, GlobalHi).addGlobalAddress(GV);
      Reg = GlobalHi;
      offset = 0;
      return 3;
    }
  }
  Reg = SelectExpr(N);
  offset = 0;
  return 0;
}

void ISel::SelectBranchCC(SDOperand N)
{
  MachineBasicBlock *Dest =
    cast<BasicBlockSDNode>(N.getOperand(4))->getBasicBlock();

  Select(N.getOperand(0));  //chain
  ISD::CondCode CC = cast<CondCodeSDNode>(N.getOperand(1))->get();
  unsigned CCReg = SelectCC(N.getOperand(2), N.getOperand(3), CC);
  unsigned Opc = getBCCForSetCC(CC);

  // If this is a two way branch, then grab the fallthrough basic block argument
  // and build a PowerPC branch pseudo-op, suitable for long branch conversion
  // if necessary by the branch selection pass.  Otherwise, emit a standard
  // conditional branch.
  if (N.getOpcode() == ISD::BRTWOWAY_CC) {
    MachineBasicBlock *Fallthrough =
      cast<BasicBlockSDNode>(N.getOperand(5))->getBasicBlock();
    BuildMI(BB, PPC::COND_BRANCH, 4).addReg(CCReg).addImm(Opc)
      .addMBB(Dest).addMBB(Fallthrough);
    BuildMI(BB, PPC::B, 1).addMBB(Fallthrough);
  } else {
    // Iterate to the next basic block
    ilist<MachineBasicBlock>::iterator It = BB;
    ++It;

    // If the fallthrough path is off the end of the function, which would be
    // undefined behavior, set it to be the same as the current block because
    // we have nothing better to set it to, and leaving it alone will cause the
    // PowerPC Branch Selection pass to crash.
    if (It == BB->getParent()->end()) It = Dest;
    BuildMI(BB, PPC::COND_BRANCH, 4).addReg(CCReg).addImm(Opc)
      .addMBB(Dest).addMBB(It);
  }
  return;
}

// SelectIntImmediateExpr - Choose code for opcodes with immediate value.
bool ISel::SelectIntImmediateExpr(SDOperand N, unsigned Result,
                                  unsigned OCHi, unsigned OCLo,
                                  bool IsArithmetic, bool Negate) {
  // check constant
  ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1));
  // exit if not a constant
  if (!CN) return false;
  // extract immediate
  unsigned C = (unsigned)CN->getValue();
  // negate if required (ISD::SUB)
  if (Negate) C = -C;
  // get the hi and lo portions of constant
  unsigned Hi = IsArithmetic ? HA16(C) : Hi16(C);
  unsigned Lo = Lo16(C);
  // assume no intermediate result from lo instruction (same as final result)
  unsigned Tmp = Result;
  // check if two instructions are needed
  if (Hi && Lo) {
    // exit if usage indicates it would be better to load immediate into a 
    // register
    if (CN->use_size() > 2) return false;
    // need intermediate result for two instructions
    Tmp = MakeIntReg();
  }
  // get first operand
  unsigned Opr0 = SelectExpr(N.getOperand(0));
  // is a lo instruction needed
  if (Lo) {
    // generate instruction for lo portion
    BuildMI(BB, OCLo, 2, Tmp).addReg(Opr0).addImm(Lo);
    // need to switch out first operand for hi instruction
    Opr0 = Tmp;
  }
  // is a hi instruction needed
  if (Hi) {
    // generate instruction for hi portion
    BuildMI(BB, OCHi, 2, Result).addReg(Opr0).addImm(Hi);
  }
  return true;
}

unsigned ISel::SelectExpr(SDOperand N, bool Recording) {
  unsigned Result;
  unsigned Tmp1, Tmp2, Tmp3;
  unsigned Opc = 0;
  unsigned opcode = N.getOpcode();

  SDNode *Node = N.Val;
  MVT::ValueType DestType = N.getValueType();

  if (Node->getOpcode() == ISD::CopyFromReg) {
    unsigned Reg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
    // Just use the specified register as our input.
    if (MRegisterInfo::isVirtualRegister(Reg) || Reg == PPC::R1)
      return Reg;
  }

  unsigned &Reg = ExprMap[N];
  if (Reg) return Reg;

  switch (N.getOpcode()) {
  default:
    Reg = Result = (N.getValueType() != MVT::Other) ?
                            MakeReg(N.getValueType()) : 1;
    break;
  case ISD::TAILCALL:
  case ISD::CALL:
    // If this is a call instruction, make sure to prepare ALL of the result
    // values as well as the chain.
    if (Node->getNumValues() == 1)
      Reg = Result = 1;  // Void call, just a chain.
    else {
      Result = MakeReg(Node->getValueType(0));
      ExprMap[N.getValue(0)] = Result;
      for (unsigned i = 1, e = N.Val->getNumValues()-1; i != e; ++i)
        ExprMap[N.getValue(i)] = MakeReg(Node->getValueType(i));
      ExprMap[SDOperand(Node, Node->getNumValues()-1)] = 1;
    }
    break;
  case ISD::ADD_PARTS:
  case ISD::SUB_PARTS:
  case ISD::SHL_PARTS:
  case ISD::SRL_PARTS:
  case ISD::SRA_PARTS:
    Result = MakeReg(Node->getValueType(0));
    ExprMap[N.getValue(0)] = Result;
    for (unsigned i = 1, e = N.Val->getNumValues(); i != e; ++i)
      ExprMap[N.getValue(i)] = MakeReg(Node->getValueType(i));
    break;
  }

  switch (opcode) {<commit_msg>Handle AssertSext/AssertZext nodes, fixing the regressions last night.<commit_after>//===-- PPC32ISelPattern.cpp - A pattern matching inst selector for PPC32 -===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by <NAME> and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines a pattern matching instruction selector for 32 bit PowerPC.
// Magic number generation for integer divide from the PowerPC Compiler Writer's
// Guide, section 3.2.3.5
//
//===----------------------------------------------------------------------===//

#include "PowerPC.h"
#include "PowerPCInstrBuilder.h"
#include "PowerPCInstrInfo.h"
#include "PPC32TargetMachine.h"
#include "PPC32ISelLowering.h"
#include "llvm/Constants.h"
#include "llvm/Function.h"
#include "llvm/CodeGen/MachineConstantPool.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineFrameInfo.h"
#include "llvm/CodeGen/SelectionDAG.h"
#include "llvm/CodeGen/SelectionDAGISel.h"
#include "llvm/CodeGen/SSARegMap.h"
#include "llvm/Target/TargetData.h"
#include "llvm/Target/TargetOptions.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/MathExtras.h"
#include "llvm/ADT/Statistic.h"
#include <set>
#include <algorithm>
using namespace llvm;

namespace {
Statistic<> Recorded("ppc-codegen", "Number of recording ops emitted");
Statistic<> FusedFP ("ppc-codegen", "Number of fused fp operations");
Statistic<> FrameOff("ppc-codegen", "Number of frame idx offsets collapsed");

//===--------------------------------------------------------------------===//
// ISel - PPC32 specific code to select PPC32 machine instructions for
// SelectionDAG operations.
//===--------------------------------------------------------------------===//

class ISel : public SelectionDAGISel {
  PPC32TargetLowering PPC32Lowering;
  SelectionDAG *ISelDAG;  // Hack to support us having a dag->dag transform
                          // for sdiv and udiv until it is put into the future
                          // dag combiner.

  /// ExprMap - As shared expressions are codegen'd, we keep track of which
  /// vreg the value is produced in, so we only emit one copy of each compiled
  /// tree.
  std::map<SDOperand, unsigned> ExprMap;

  unsigned GlobalBaseReg;
  bool GlobalBaseInitialized;
  bool RecordSuccess;
public:
  ISel(TargetMachine &TM) : SelectionDAGISel(PPC32Lowering), PPC32Lowering(TM),
                            ISelDAG(0) {}

  /// runOnFunction - Override this function in order to reset our per-function
  /// variables.
  virtual bool runOnFunction(Function &Fn) {
    // Make sure we re-emit a set of the global base reg if necessary
    GlobalBaseInitialized = false;
    return SelectionDAGISel::runOnFunction(Fn);
  }

  /// InstructionSelectBasicBlock - This callback is invoked by
  /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
  virtual void InstructionSelectBasicBlock(SelectionDAG &DAG) {
    DEBUG(BB->dump());
    // Codegen the basic block.
    ISelDAG = &DAG;
    Select(DAG.getRoot());

    // Clear state used for selection.
    ExprMap.clear();
    ISelDAG = 0;
  }

  // convenience functions for virtual register creation
  inline unsigned MakeIntReg() {
    return RegMap->createVirtualRegister(PPC32::GPRCRegisterClass);
  }
  inline unsigned MakeFPReg() {
    return RegMap->createVirtualRegister(PPC32::FPRCRegisterClass);
  }
  
  // dag -> dag expanders for integer divide by constant
  SDOperand BuildSDIVSequence(SDOperand N);
  SDOperand BuildUDIVSequence(SDOperand N);

  unsigned getGlobalBaseReg();
  void MoveCRtoGPR(unsigned CCReg, ISD::CondCode CC, unsigned Result);
  bool SelectBitfieldInsert(SDOperand OR, unsigned Result);
  unsigned FoldIfWideZeroExtend(SDOperand N);
  unsigned SelectCC(SDOperand LHS, SDOperand RHS, ISD::CondCode CC);
  bool SelectIntImmediateExpr(SDOperand N, unsigned Result,
                              unsigned OCHi, unsigned OCLo,
                              bool IsArithmetic = false, bool Negate = false);
  unsigned SelectExpr(SDOperand N, bool Recording=false);
  void Select(SDOperand N);

  unsigned SelectAddr(SDOperand N, unsigned& Reg, int& offset);
  void SelectBranchCC(SDOperand N);
  
  virtual const char *getPassName() const {
    return "PowerPC Pattern Instruction Selection";
  } 
};

// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
// any number of 0s on either side.  The 1s are allowed to wrap from LSB to
// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
// not, since all 1s are not contiguous.
static bool isRunOfOnes(unsigned Val, unsigned &MB, unsigned &ME) {
  if (isShiftedMask_32(Val)) {
    // look for the first non-zero bit
    MB = CountLeadingZeros_32(Val);
    // look for the first zero bit after the run of ones
    ME = CountLeadingZeros_32((Val - 1) ^ Val);
    return true;
  } else if (isShiftedMask_32(Val = ~Val)) { // invert mask
    // effectively look for the first zero bit
    ME = CountLeadingZeros_32(Val) - 1;
    // effectively look for the first one bit after the run of zeros
    MB = CountLeadingZeros_32((Val - 1) ^ Val) + 1;
    return true;
  }
  // no run present
  return false;
}

// isRotateAndMask - Returns true if Mask and Shift can be folded in to a rotate
// and mask opcode and mask operation.
static bool isRotateAndMask(unsigned Opcode, unsigned Shift, unsigned Mask,
                            bool IsShiftMask,
                            unsigned &SH, unsigned &MB, unsigned &ME) {
  if (Shift > 31) return false;
  unsigned Indeterminant = ~0;       // bit mask marking indeterminant results
  
  if (Opcode == ISD::SHL) { // shift left
    // apply shift to mask if it comes first
    if (IsShiftMask) Mask = Mask << Shift;
    // determine which bits are made indeterminant by shift
    Indeterminant = ~(0xFFFFFFFFu << Shift);
  } else if (Opcode == ISD::SRA || Opcode == ISD::SRL) { // shift rights
    // apply shift to mask if it comes first
    if (IsShiftMask) Mask = Mask >> Shift;
    // determine which bits are made indeterminant by shift
    Indeterminant = ~(0xFFFFFFFFu >> Shift);
    // adjust for the left rotate
    Shift = 32 - Shift;
  }
  
  // if the mask doesn't intersect any Indeterminant bits
  if (Mask && !(Mask & Indeterminant)) {
    SH = Shift;
    // make sure the mask is still a mask (wrap arounds may not be)
    return isRunOfOnes(Mask, MB, ME);
  }
  
  // can't do it
  return false;
}

// isIntImmediate - This method tests to see if a constant operand.
// If so Imm will receive the 32 bit value.
static bool isIntImmediate(SDOperand N, unsigned& Imm) {
  // test for constant
  if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
    // retrieve value
    Imm = (unsigned)CN->getValue();
    // passes muster
    return true;
  }
  // not a constant
  return false;
}

// isOpcWithIntImmediate - This method tests to see if the node is a specific
// opcode and that it has a immediate integer right operand.
// If so Imm will receive the 32 bit value.
static bool isOpcWithIntImmediate(SDOperand N, unsigned Opc, unsigned& Imm) {
  return N.getOpcode() == Opc && isIntImmediate(N.getOperand(1), Imm);
}

// isOprShiftImm - Returns true if the specified operand is a shift opcode with
// a immediate shift count less than 32.
static bool isOprShiftImm(SDOperand N, unsigned& Opc, unsigned& SH) {
  Opc = N.getOpcode();
  return (Opc == ISD::SHL || Opc == ISD::SRL || Opc == ISD::SRA) &&
         isIntImmediate(N.getOperand(1), SH) && SH < 32;
}

// isOprNot - Returns true if the specified operand is an xor with immediate -1.
static bool isOprNot(SDOperand N) {
  unsigned Imm;
  return isOpcWithIntImmediate(N, ISD::XOR, Imm) && (signed)Imm == -1;
}

// Immediate constant composers.
// Lo16 - grabs the lo 16 bits from a 32 bit constant.
// Hi16 - grabs the hi 16 bits from a 32 bit constant.
// HA16 - computes the hi bits required if the lo bits are add/subtracted in
// arithmethically.
static unsigned Lo16(unsigned x)  { return x & 0x0000FFFF; }
static unsigned Hi16(unsigned x)  { return Lo16(x >> 16); }
static unsigned HA16(unsigned x)  { return Hi16((signed)x - (signed short)x); }

/// NodeHasRecordingVariant - If SelectExpr can always produce code for
/// NodeOpcode that also sets CR0 as a side effect, return true.  Otherwise,
/// return false.
static bool NodeHasRecordingVariant(unsigned NodeOpcode) {
  switch(NodeOpcode) {
  default: return false;
  case ISD::AND:
  case ISD::OR:
    return true;
  }
}

/// getBCCForSetCC - Returns the PowerPC condition branch mnemonic corresponding
/// to Condition.
static unsigned getBCCForSetCC(ISD::CondCode CC) {
  switch (CC) {
  default: assert(0 && "Unknown condition!"); abort();
  case ISD::SETEQ:  return PPC::BEQ;
  case ISD::SETNE:  return PPC::BNE;
  case ISD::SETULT:
  case ISD::SETLT:  return PPC::BLT;
  case ISD::SETULE:
  case ISD::SETLE:  return PPC::BLE;
  case ISD::SETUGT:
  case ISD::SETGT:  return PPC::BGT;
  case ISD::SETUGE:
  case ISD::SETGE:  return PPC::BGE;
  }
  return 0;
}

/// getCRIdxForSetCC - Return the index of the condition register field
/// associated with the SetCC condition, and whether or not the field is
/// treated as inverted.  That is, lt = 0; ge = 0 inverted.
static unsigned getCRIdxForSetCC(ISD::CondCode CC, bool& Inv) {
  switch (CC) {
  default: assert(0 && "Unknown condition!"); abort();
  case ISD::SETULT:
  case ISD::SETLT:  Inv = false;  return 0;
  case ISD::SETUGE:
  case ISD::SETGE:  Inv = true;   return 0;
  case ISD::SETUGT:
  case ISD::SETGT:  Inv = false;  return 1;
  case ISD::SETULE:
  case ISD::SETLE:  Inv = true;   return 1;
  case ISD::SETEQ:  Inv = false;  return 2;
  case ISD::SETNE:  Inv = true;   return 2;
  }
  return 0;
}

/// IndexedOpForOp - Return the indexed variant for each of the PowerPC load
/// and store immediate instructions.
static unsigned IndexedOpForOp(unsigned Opcode) {
  switch(Opcode) {
  default: assert(0 && "Unknown opcode!"); abort();
  case PPC::LBZ: return PPC::LBZX;  case PPC::STB: return PPC::STBX;
  case PPC::LHZ: return PPC::LHZX;  case PPC::STH: return PPC::STHX;
  case PPC::LHA: return PPC::LHAX;  case PPC::STW: return PPC::STWX;
  case PPC::LWZ: return PPC::LWZX;  case PPC::STFS: return PPC::STFSX;
  case PPC::LFS: return PPC::LFSX;  case PPC::STFD: return PPC::STFDX;
  case PPC::LFD: return PPC::LFDX;
  }
  return 0;
}

// Structure used to return the necessary information to codegen an SDIV as
// a multiply.
struct ms {
  int m; // magic number
  int s; // shift amount
};

struct mu {
  unsigned int m; // magic number
  int a;          // add indicator
  int s;          // shift amount
};

/// magic - calculate the magic numbers required to codegen an integer sdiv as
/// a sequence of multiply and shifts.  Requires that the divisor not be 0, 1,
/// or -1.
static struct ms magic(int d) {
  int p;
  unsigned int ad, anc, delta, q1, r1, q2, r2, t;
  const unsigned int two31 = 0x80000000U;
  struct ms mag;

  ad = abs(d);
  t = two31 + ((unsigned int)d >> 31);
  anc = t - 1 - t%ad;   // absolute value of nc
  p = 31;               // initialize p
  q1 = two31/anc;       // initialize q1 = 2p/abs(nc)
  r1 = two31 - q1*anc;  // initialize r1 = rem(2p,abs(nc))
  q2 = two31/ad;        // initialize q2 = 2p/abs(d)
  r2 = two31 - q2*ad;   // initialize r2 = rem(2p,abs(d))
  do {
    p = p + 1;
    q1 = 2*q1;        // update q1 = 2p/abs(nc)
    r1 = 2*r1;        // update r1 = rem(2p/abs(nc))
    if (r1 >= anc) {  // must be unsigned comparison
      q1 = q1 + 1;
      r1 = r1 - anc;
    }
    q2 = 2*q2;        // update q2 = 2p/abs(d)
    r2 = 2*r2;        // update r2 = rem(2p/abs(d))
    if (r2 >= ad) {   // must be unsigned comparison
      q2 = q2 + 1;
      r2 = r2 - ad;
    }
    delta = ad - r2;
  } while (q1 < delta || (q1 == delta && r1 == 0));

  mag.m = q2 + 1;
  if (d < 0) mag.m = -mag.m; // resulting magic number
  mag.s = p - 32;            // resulting shift
  return mag;
}

/// magicu - calculate the magic numbers required to codegen an integer udiv as
/// a sequence of multiply, add and shifts.  Requires that the divisor not be 0.
static struct mu magicu(unsigned d)
{
  int p;
  unsigned int nc, delta, q1, r1, q2, r2;
  struct mu magu;
  magu.a = 0;               // initialize "add" indicator
  nc = - 1 - (-d)%d;
  p = 31;                   // initialize p
  q1 = 0x80000000/nc;       // initialize q1 = 2p/nc
  r1 = 0x80000000 - q1*nc;  // initialize r1 = rem(2p,nc)
  q2 = 0x7FFFFFFF/d;        // initialize q2 = (2p-1)/d
  r2 = 0x7FFFFFFF - q2*d;   // initialize r2 = rem((2p-1),d)
  do {
    p = p + 1;
    if (r1 >= nc - r1 ) {
      q1 = 2*q1 + 1;  // update q1
      r1 = 2*r1 - nc; // update r1
    }
    else {
      q1 = 2*q1; // update q1
      r1 = 2*r1; // update r1
    }
    if (r2 + 1 >= d - r2) {
      if (q2 >= 0x7FFFFFFF) magu.a = 1;
      q2 = 2*q2 + 1;     // update q2
      r2 = 2*r2 + 1 - d; // update r2
    }
    else {
      if (q2 >= 0x80000000) magu.a = 1;
      q2 = 2*q2;     // update q2
      r2 = 2*r2 + 1; // update r2
    }
    delta = d - 1 - r2;
  } while (p < 64 && (q1 < delta || (q1 == delta && r1 == 0)));
  magu.m = q2 + 1; // resulting magic number
  magu.s = p - 32;  // resulting shift
  return magu;
}
}

/// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
/// return a DAG expression to select that will generate the same value by
/// multiplying by a magic number.  See:
/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
SDOperand ISel::BuildSDIVSequence(SDOperand N) {
  int d = (int)cast<ConstantSDNode>(N.getOperand(1))->getSignExtended();
  ms magics = magic(d);
  // Multiply the numerator (operand 0) by the magic value
  SDOperand Q = ISelDAG->getNode(ISD::MULHS, MVT::i32, N.getOperand(0),
                                 ISelDAG->getConstant(magics.m, MVT::i32));
  // If d > 0 and m < 0, add the numerator
  if (d > 0 && magics.m < 0)
    Q = ISelDAG->getNode(ISD::ADD, MVT::i32, Q, N.getOperand(0));
  // If d < 0 and m > 0, subtract the numerator.
  if (d < 0 && magics.m > 0)
    Q = ISelDAG->getNode(ISD::SUB, MVT::i32, Q, N.getOperand(0));
  // Shift right algebraic if shift value is nonzero
  if (magics.s > 0)
    Q = ISelDAG->getNode(ISD::SRA, MVT::i32, Q,
                         ISelDAG->getConstant(magics.s, MVT::i32));
  // Extract the sign bit and add it to the quotient
  SDOperand T =
    ISelDAG->getNode(ISD::SRL, MVT::i32, Q, ISelDAG->getConstant(31, MVT::i32));
  return ISelDAG->getNode(ISD::ADD, MVT::i32, Q, T);
}

/// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
/// return a DAG expression to select that will generate the same value by
/// multiplying by a magic number.  See:
/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
SDOperand ISel::BuildUDIVSequence(SDOperand N) {
  unsigned d =
    (unsigned)cast<ConstantSDNode>(N.getOperand(1))->getSignExtended();
  mu magics = magicu(d);
  // Multiply the numerator (operand 0) by the magic value
  SDOperand Q = ISelDAG->getNode(ISD::MULHU, MVT::i32, N.getOperand(0),
                                 ISelDAG->getConstant(magics.m, MVT::i32));
  if (magics.a == 0) {
    Q = ISelDAG->getNode(ISD::SRL, MVT::i32, Q,
                         ISelDAG->getConstant(magics.s, MVT::i32));
  } else {
    SDOperand NPQ = ISelDAG->getNode(ISD::SUB, MVT::i32, N.getOperand(0), Q);
    NPQ = ISelDAG->getNode(ISD::SRL, MVT::i32, NPQ,
                           ISelDAG->getConstant(1, MVT::i32));
    NPQ = ISelDAG->getNode(ISD::ADD, MVT::i32, NPQ, Q);
    Q = ISelDAG->getNode(ISD::SRL, MVT::i32, NPQ,
                           ISelDAG->getConstant(magics.s-1, MVT::i32));
  }
  return Q;
}

/// getGlobalBaseReg - Output the instructions required to put the
/// base address to use for accessing globals into a register.
///
unsigned ISel::getGlobalBaseReg() {
  if (!GlobalBaseInitialized) {
    // Insert the set of GlobalBaseReg into the first MBB of the function
    MachineBasicBlock &FirstMBB = BB->getParent()->front();
    MachineBasicBlock::iterator MBBI = FirstMBB.begin();
    GlobalBaseReg = MakeIntReg();
    BuildMI(FirstMBB, MBBI, PPC::MovePCtoLR, 0, PPC::LR);
    BuildMI(FirstMBB, MBBI, PPC::MFLR, 1, GlobalBaseReg);
    GlobalBaseInitialized = true;
  }
  return GlobalBaseReg;
}

/// MoveCRtoGPR - Move CCReg[Idx] to the least significant bit of Result.  If
/// Inv is true, then invert the result.
void ISel::MoveCRtoGPR(unsigned CCReg, ISD::CondCode CC, unsigned Result){
  bool Inv;
  unsigned IntCR = MakeIntReg();
  unsigned Idx = getCRIdxForSetCC(CC, Inv);
  BuildMI(BB, PPC::MCRF, 1, PPC::CR7).addReg(CCReg);
  bool GPOpt =
    TLI.getTargetMachine().getSubtarget<PPCSubtarget>().isGigaProcessor();
  if (GPOpt)
    BuildMI(BB, PPC::MFOCRF, 1, IntCR).addReg(PPC::CR7);
  else
    BuildMI(BB, PPC::MFCR, 0, IntCR);
  if (Inv) {
    unsigned Tmp1 = MakeIntReg();
    BuildMI(BB, PPC::RLWINM, 4, Tmp1).addReg(IntCR).addImm(32-(3-Idx))
      .addImm(31).addImm(31);
    BuildMI(BB, PPC::XORI, 2, Result).addReg(Tmp1).addImm(1);
  } else {
    BuildMI(BB, PPC::RLWINM, 4, Result).addReg(IntCR).addImm(32-(3-Idx))
      .addImm(31).addImm(31);
  }
}

/// SelectBitfieldInsert - turn an or of two masked values into
/// the rotate left word immediate then mask insert (rlwimi) instruction.
/// Returns true on success, false if the caller still needs to select OR.
///
/// Patterns matched:
/// 1. or shl, and   5. or and, and
/// 2. or and, shl   6. or shl, shr
/// 3. or shr, and   7. or shr, shl
/// 4. or and, shr
bool ISel::SelectBitfieldInsert(SDOperand OR, unsigned Result) {
  bool IsRotate = false;
  unsigned TgtMask = 0xFFFFFFFF, InsMask = 0xFFFFFFFF, Amount = 0;
  unsigned Value;

  SDOperand Op0 = OR.getOperand(0);
  SDOperand Op1 = OR.getOperand(1);

  unsigned Op0Opc = Op0.getOpcode();
  unsigned Op1Opc = Op1.getOpcode();

  // Verify that we have the correct opcodes
  if (ISD::SHL != Op0Opc && ISD::SRL != Op0Opc && ISD::AND != Op0Opc)
    return false;
  if (ISD::SHL != Op1Opc && ISD::SRL != Op1Opc && ISD::AND != Op1Opc)
    return false;

  // Generate Mask value for Target
  if (isIntImmediate(Op0.getOperand(1), Value)) {
    switch(Op0Opc) {
    case ISD::SHL: TgtMask <<= Value; break;
    case ISD::SRL: TgtMask >>= Value; break;
    case ISD::AND: TgtMask &= Value; break;
    }
  } else {
    return false;
  }

  // Generate Mask value for Insert
  if (isIntImmediate(Op1.getOperand(1), Value)) {
    switch(Op1Opc) {
    case ISD::SHL:
      Amount = Value;
      InsMask <<= Amount;
      if (Op0Opc == ISD::SRL) IsRotate = true;
      break;
    case ISD::SRL:
      Amount = Value;
      InsMask >>= Amount;
      Amount = 32-Amount;
      if (Op0Opc == ISD::SHL) IsRotate = true;
      break;
    case ISD::AND:
      InsMask &= Value;
      break;
    }
  } else {
    return false;
  }

  unsigned Tmp3 = 0;

  // If both of the inputs are ANDs and one of them has a logical shift by
  // constant as its input, make that the inserted value so that we can combine
  // the shift into the rotate part of the rlwimi instruction
  if (Op0Opc == ISD::AND && Op1Opc == ISD::AND) {
    if (Op1.getOperand(0).getOpcode() == ISD::SHL ||
        Op1.getOperand(0).getOpcode() == ISD::SRL) {
      if (isIntImmediate(Op1.getOperand(0).getOperand(1), Value)) {
        Amount = Op1.getOperand(0).getOpcode() == ISD::SHL ?
          Value : 32 - Value;
        Tmp3 = SelectExpr(Op1.getOperand(0).getOperand(0));
      }
    } else if (Op0.getOperand(0).getOpcode() == ISD::SHL ||
               Op0.getOperand(0).getOpcode() == ISD::SRL) {
      if (isIntImmediate(Op0.getOperand(0).getOperand(1), Value)) {
        std::swap(Op0, Op1);
        std::swap(TgtMask, InsMask);
        Amount = Op1.getOperand(0).getOpcode() == ISD::SHL ?
          Value : 32 - Value;
        Tmp3 = SelectExpr(Op1.getOperand(0).getOperand(0));
      }
    }
  }

  // Verify that the Target mask and Insert mask together form a full word mask
  // and that the Insert mask is a run of set bits (which implies both are runs
  // of set bits).  Given that, Select the arguments and generate the rlwimi
  // instruction.
  unsigned MB, ME;
  if (((TgtMask & InsMask) == 0) && isRunOfOnes(InsMask, MB, ME)) {
    unsigned Tmp1, Tmp2;
    bool fullMask = (TgtMask ^ InsMask) == 0xFFFFFFFF;
    // Check for rotlwi / rotrwi here, a special case of bitfield insert
    // where both bitfield halves are sourced from the same value.
    if (IsRotate && fullMask &&
        OR.getOperand(0).getOperand(0) == OR.getOperand(1).getOperand(0)) {
      Tmp1 = SelectExpr(OR.getOperand(0).getOperand(0));
      BuildMI(BB, PPC::RLWINM, 4, Result).addReg(Tmp1).addImm(Amount)
        .addImm(0).addImm(31);
      return true;
    }
    if (Op0Opc == ISD::AND && fullMask)
      Tmp1 = SelectExpr(Op0.getOperand(0));
    else
      Tmp1 = SelectExpr(Op0);
    Tmp2 = Tmp3 ? Tmp3 : SelectExpr(Op1.getOperand(0));
    BuildMI(BB, PPC::RLWIMI, 5, Result).addReg(Tmp1).addReg(Tmp2)
      .addImm(Amount).addImm(MB).addImm(ME);
    return true;
  }
  return false;
}

/// FoldIfWideZeroExtend - 32 bit PowerPC implicit masks shift amounts to the
/// low six bits.  If the shift amount is an ISD::AND node with a mask that is
/// wider than the implicit mask, then we can get rid of the AND and let the
/// shift do the mask.
unsigned ISel::FoldIfWideZeroExtend(SDOperand N) {
  unsigned C;
  if (isOpcWithIntImmediate(N, ISD::AND, C) && isMask_32(C) && C > 63)
    return SelectExpr(N.getOperand(0));
  else
    return SelectExpr(N);
}

unsigned ISel::SelectCC(SDOperand LHS, SDOperand RHS, ISD::CondCode CC) {
  unsigned Result, Tmp1, Tmp2;
  bool AlreadySelected = false;
  static const unsigned CompareOpcodes[] =
    { PPC::FCMPU, PPC::FCMPU, PPC::CMPW, PPC::CMPLW };

  // Allocate a condition register for this expression
  Result = RegMap->createVirtualRegister(PPC32::CRRCRegisterClass);

  // Use U to determine whether the SETCC immediate range is signed or not.
  bool U = ISD::isUnsignedIntSetCC(CC);
  if (isIntImmediate(RHS, Tmp2) && 
      ((U && isUInt16(Tmp2)) || (!U && isInt16(Tmp2)))) {
    Tmp2 = Lo16(Tmp2);
    // For comparisons against zero, we can implicity set CR0 if a recording
    // variant (e.g. 'or.' instead of 'or') of the instruction that defines
    // operand zero of the SetCC node is available.
    if (Tmp2 == 0 &&
        NodeHasRecordingVariant(LHS.getOpcode()) && LHS.Val->hasOneUse()) {
      RecordSuccess = false;
      Tmp1 = SelectExpr(LHS, true);
      if (RecordSuccess) {
        ++Recorded;
        BuildMI(BB, PPC::MCRF, 1, Result).addReg(PPC::CR0);
        return Result;
      }
      AlreadySelected = true;
    }
    // If we could not implicitly set CR0, then emit a compare immediate
    // instead.
    if (!AlreadySelected) Tmp1 = SelectExpr(LHS);
    if (U)
      BuildMI(BB, PPC::CMPLWI, 2, Result).addReg(Tmp1).addImm(Tmp2);
    else
      BuildMI(BB, PPC::CMPWI, 2, Result).addReg(Tmp1).addSImm(Tmp2);
  } else {
    bool IsInteger = MVT::isInteger(LHS.getValueType());
    unsigned CompareOpc = CompareOpcodes[2 * IsInteger + U];
    Tmp1 = SelectExpr(LHS);
    Tmp2 = SelectExpr(RHS);
    BuildMI(BB, CompareOpc, 2, Result).addReg(Tmp1).addReg(Tmp2);
  }
  return Result;
}

/// Check to see if the load is a constant offset from a base register.
unsigned ISel::SelectAddr(SDOperand N, unsigned& Reg, int& offset)
{
  unsigned imm = 0, opcode = N.getOpcode();
  if (N.getOpcode() == ISD::ADD) {
    bool isFrame = N.getOperand(0).getOpcode() == ISD::FrameIndex;
    if (isIntImmediate(N.getOperand(1), imm) && isInt16(imm)) {
      offset = Lo16(imm);
      if (isFrame) {
        ++FrameOff;
        Reg = cast<FrameIndexSDNode>(N.getOperand(0))->getIndex();
        return 1;
      } else {
        Reg = SelectExpr(N.getOperand(0));
        return 0;
      }
    } else {
      Reg = SelectExpr(N.getOperand(0));
      offset = SelectExpr(N.getOperand(1));
      return 2;
    }
  }
  // Now check if we're dealing with a global, and whether or not we should emit
  // an optimized load or store for statics.
  if(GlobalAddressSDNode *GN = dyn_cast<GlobalAddressSDNode>(N)) {
    GlobalValue *GV = GN->getGlobal();
    if (!GV->hasWeakLinkage() && !GV->isExternal()) {
      unsigned GlobalHi = MakeIntReg();
      if (PICEnabled)
        BuildMI(BB, PPC::ADDIS, 2, GlobalHi).addReg(getGlobalBaseReg())
          .addGlobalAddress(GV);
      else
        BuildMI(BB, PPC::LIS, 1, GlobalHi).addGlobalAddress(GV);
      Reg = GlobalHi;
      offset = 0;
      return 3;
    }
  }
  Reg = SelectExpr(N);
  offset = 0;
  return 0;
}

void ISel::SelectBranchCC(SDOperand N)
{
  MachineBasicBlock *Dest =
    cast<BasicBlockSDNode>(N.getOperand(4))->getBasicBlock();

  Select(N.getOperand(0));  //chain
  ISD::CondCode CC = cast<CondCodeSDNode>(N.getOperand(1))->get();
  unsigned CCReg = SelectCC(N.getOperand(2), N.getOperand(3), CC);
  unsigned Opc = getBCCForSetCC(CC);

  // If this is a two way branch, then grab the fallthrough basic block argument
  // and build a PowerPC branch pseudo-op, suitable for long branch conversion
  // if necessary by the branch selection pass.  Otherwise, emit a standard
  // conditional branch.
  if (N.getOpcode() == ISD::BRTWOWAY_CC) {
    MachineBasicBlock *Fallthrough =
      cast<BasicBlockSDNode>(N.getOperand(5))->getBasicBlock();
    BuildMI(BB, PPC::COND_BRANCH, 4).addReg(CCReg).addImm(Opc)
      .addMBB(Dest).addMBB(Fallthrough);
    BuildMI(BB, PPC::B, 1).addMBB(Fallthrough);
  } else {
    // Iterate to the next basic block
    ilist<MachineBasicBlock>::iterator It = BB;
    ++It;

    // If the fallthrough path is off the end of the function, which would be
    // undefined behavior, set it to be the same as the current block because
    // we have nothing better to set it to, and leaving it alone will cause the
    // PowerPC Branch Selection pass to crash.
    if (It == BB->getParent()->end()) It = Dest;
    BuildMI(BB, PPC::COND_BRANCH, 4).addReg(CCReg).addImm(Opc)
      .addMBB(Dest).addMBB(It);
  }
  return;
}

// SelectIntImmediateExpr - Choose code for opcodes with immediate value.
bool ISel::SelectIntImmediateExpr(SDOperand N, unsigned Result,
                                  unsigned OCHi, unsigned OCLo,
                                  bool IsArithmetic, bool Negate) {
  // check constant
  ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1));
  // exit if not a constant
  if (!CN) return false;
  // extract immediate
  unsigned C = (unsigned)CN->getValue();
  // negate if required (ISD::SUB)
  if (Negate) C = -C;
  // get the hi and lo portions of constant
  unsigned Hi = IsArithmetic ? HA16(C) : Hi16(C);
  unsigned Lo = Lo16(C);
  // assume no intermediate result from lo instruction (same as final result)
  unsigned Tmp = Result;
  // check if two instructions are needed
  if (Hi && Lo) {
    // exit if usage indicates it would be better to load immediate into a 
    // register
    if (CN->use_size() > 2) return false;
    // need intermediate result for two instructions
    Tmp = MakeIntReg();
  }
  // get first operand
  unsigned Opr0 = SelectExpr(N.getOperand(0));
  // is a lo instruction needed
  if (Lo) {
    // generate instruction for lo portion
    BuildMI(BB, OCLo, 2, Tmp).addReg(Opr0).addImm(Lo);
    // need to switch out first operand for hi instruction
    Opr0 = Tmp;
  }
  // is a hi instruction needed
  if (Hi) {
    // generate instruction for hi portion
    BuildMI(BB, OCHi, 2, Result).addReg(Opr0).addImm(Hi);
  }
  return true;
}

unsigned ISel::SelectExpr(SDOperand N, bool Recording) {
  unsigned Result;
  unsigned Tmp1, Tmp2, Tmp3;
  unsigned Opc = 0;
  unsigned opcode = N.getOpcode();

  SDNode *Node = N.Val;
  MVT::ValueType DestType = N.getValueType();

  if (Node->getOpcode() == ISD::CopyFromReg) {
    unsigned Reg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
    // Just use the specified register as our input.
    if (MRegisterInfo::isVirtualRegister(Reg) || Reg == PPC::R1)
      return Reg;
  }

  unsigned &Reg = ExprMap[N];
  if (Reg) return Reg;

  switch (N.getOpcode()) {
  default:
    Reg = Result = (N.getValueType() != MVT::Other) ?
                            MakeReg(N.getValueType()) : 1;
    break;
  case ISD::AssertSext:
  case ISD::AssertZext:
    // Don't allocate a vreg for these nodes.
    return Reg = SelectExpr(N.getOperand(0));
  case ISD::TAILCALL:
  case ISD::CALL:
    // If this is a call instruction, make sure to prepare ALL of the result
    // values as well as the chain.
    if (Node->getNumValues() == 1)
      Reg = Result = 1;  // Void call, just a chain.
    else {
      Result = MakeReg(Node->getValueType(0));
      ExprMap[N.getValue(0)] = Result;
      for (unsigned i = 1, e = N.Val->getNumValues()-1; i != e; ++i)
        ExprMap[N.getValue(i)] = MakeReg(Node->getValueType(i));
      ExprMap[SDOperand(Node, Node->getNumValues()-1)] = 1;
    }
    break;
  case ISD::ADD_PARTS:
  case ISD::SUB_PARTS:
  case ISD::SHL_PARTS:
  case ISD::SRL_PARTS:
  case ISD::SRA_PARTS:
    Result = MakeReg(Node->getValueType(0));
    ExprMap[N.getValue(0)] = Result;
    for (unsigned i = 1, e = N.Val->getNumValues(); i != e; ++i)
      ExprMap[N.getValue(i)] = MakeReg(Node->getValueType(i));
    break;
  }

  switch (opcode) {
{'fraction_non_alphanumeric': 0.13882324940924468, 'fraction_numerical': 0.021777195994763954, 'mean_word_length': 2.813302217036173, 'pattern_counts': {'":': 0, '<': 79, '<?xml version=': 0, '>': 203, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 2, 'substrings_counts': 24, 'word_list_counts': {'cursed_substrings.json': 26, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2872334', 'n_tokens_mistral': 20755, 'n_tokens_neox': 20250, 'n_words': 6055}