//===-- AlphaISelDAGToDAG.cpp - Alpha pattern matching inst selector ------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by Andrew Lenharth 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 Alpha,
// converting from a legalized dag to a Alpha dag.
//
//===----------------------------------------------------------------------===//

#include "Alpha.h"
#include "AlphaTargetMachine.h"
#include "AlphaISelLowering.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/SSARegMap.h"
#include "llvm/CodeGen/SelectionDAG.h"
#include "llvm/CodeGen/SelectionDAGISel.h"
#include "llvm/Target/TargetOptions.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Constants.h"
#include "llvm/GlobalValue.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/MathExtras.h"
#include <algorithm>
using namespace llvm;

namespace {

  //===--------------------------------------------------------------------===//
  /// AlphaDAGToDAGISel - Alpha specific code to select Alpha machine
  /// instructions for SelectionDAG operations.
  ///
  class AlphaDAGToDAGISel : public SelectionDAGISel {
    AlphaTargetLowering AlphaLowering;

  public:
    AlphaDAGToDAGISel(TargetMachine &TM)
      : SelectionDAGISel(AlphaLowering), AlphaLowering(TM) {}

    /// getI64Imm - Return a target constant with the specified value, of type
    /// i64.
    inline SDOperand getI64Imm(int64_t Imm) {
      return CurDAG->getTargetConstant(Imm, MVT::i64);
    }

    // Select - Convert the specified operand from a target-independent to a
    // target-specific node if it hasn't already been changed.
    SDOperand Select(SDOperand Op);
    
    /// InstructionSelectBasicBlock - This callback is invoked by
    /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
    virtual void InstructionSelectBasicBlock(SelectionDAG &DAG);
    
    virtual const char *getPassName() const {
      return "Alpha DAG->DAG Pattern Instruction Selection";
    } 

// Include the pieces autogenerated from the target description.
#include "AlphaGenDAGISel.inc"
    
private:
    SDOperand getGlobalBaseReg();
    SDOperand SelectCALL(SDOperand Op);

  };
}

/// getGlobalBaseReg - Output the instructions required to put the
/// GOT address into a register.
///
SDOperand AlphaDAGToDAGISel::getGlobalBaseReg() {
  return CurDAG->getRegister(AlphaLowering.getVRegGP(), MVT::i64);
}

/// InstructionSelectBasicBlock - This callback is invoked by
/// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
void AlphaDAGToDAGISel::InstructionSelectBasicBlock(SelectionDAG &DAG) {
  DEBUG(BB->dump());
  
  // Select target instructions for the DAG.
  DAG.setRoot(Select(DAG.getRoot()));
  CodeGenMap.clear();
  DAG.RemoveDeadNodes();
  
  // Emit machine code to BB. 
  ScheduleAndEmitDAG(DAG);
}

// Select - Convert the specified operand from a target-independent to a
// target-specific node if it hasn't already been changed.
SDOperand AlphaDAGToDAGISel::Select(SDOperand Op) {
  SDNode *N = Op.Val;
  if (N->getOpcode() >= ISD::BUILTIN_OP_END &&
      N->getOpcode() < AlphaISD::FIRST_NUMBER)
    return Op;   // Already selected.

  // If this has already been converted, use it.
  std::map<SDOperand, SDOperand>::iterator CGMI = CodeGenMap.find(Op);
  if (CGMI != CodeGenMap.end()) return CGMI->second;
  
  switch (N->getOpcode()) {
  default: break;
  case ISD::TAILCALL:
  case ISD::CALL: return SelectCALL(Op);

  case ISD::DYNAMIC_STACKALLOC:
  case ISD::ADD_PARTS:
  case ISD::SUB_PARTS:
  case ISD::SETCC:
    assert(0 && "You want these too?");

  case ISD::BR: {
    CurDAG->SelectNodeTo(N, Alpha::BR_DAG, MVT::Other, N->getOperand(1),
                         Select(N->getOperand(0)));
    return SDOperand(N, 0);
  }

  case ISD::TokenFactor: {
    SDOperand New;
    if (N->getNumOperands() == 2) {
      SDOperand Op0 = Select(N->getOperand(0));
      SDOperand Op1 = Select(N->getOperand(1));
      New = CurDAG->getNode(ISD::TokenFactor, MVT::Other, Op0, Op1);
    } else {
      std::vector<SDOperand> Ops;
      for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
        Ops.push_back(Select(N->getOperand(i)));
      New = CurDAG->getNode(ISD::TokenFactor, MVT::Other, Ops);
    }
    
    CodeGenMap[Op] = New;
    return New;
  }
  case ISD::CopyFromReg: {
    SDOperand Chain = Select(N->getOperand(0));
    if (Chain == N->getOperand(0)) return Op; // No change
    SDOperand New = CurDAG->getCopyFromReg(Chain,
         cast<RegisterSDNode>(N->getOperand(1))->getReg(), N->getValueType(0));
    return New.getValue(Op.ResNo);
  }
  case ISD::CopyToReg: {
    SDOperand Chain = Select(N->getOperand(0));
    SDOperand Reg = N->getOperand(1);
    SDOperand Val = Select(N->getOperand(2));
    SDOperand New = CurDAG->getNode(ISD::CopyToReg, MVT::Other,
                                    Chain, Reg, Val);
    CodeGenMap[Op] = New;
    return New;
  }
  case ISD::UNDEF:
    if (N->getValueType(0) == MVT::i64)
      CurDAG->SelectNodeTo(N, Alpha::IDEF, MVT::i64);
//     else if (N->getValueType(0) == MVT::f32)
//       CurDAG->SelectNodeTo(N, PPC::IMPLICIT_DEF_F4, MVT::f32);
//     else 
//       CurDAG->SelectNodeTo(N, PPC::IMPLICIT_DEF_F8, MVT::f64);
    return SDOperand(N, 0);
  case ISD::FrameIndex: {
//     int FI = cast<FrameIndexSDNode>(N)->getIndex();
//     CurDAG->SelectNodeTo(N, Alpha::LDA, MVT::i64,
//                          CurDAG->getTargetFrameIndex(FI, MVT::i32),
//                          getI32Imm(0));
//     return SDOperand(N, 0);
    assert(0 && "Frame?, you are suppose to look through the window, not at the frame!");
  }
  case ISD::ConstantPool: {
//     Constant *C = cast<ConstantPoolSDNode>(N)->get();
//     SDOperand Tmp, CPI = CurDAG->getTargetConstantPool(C, MVT::i32);
//     if (PICEnabled)
//       Tmp = CurDAG->getTargetNode(PPC::ADDIS, MVT::i32, getGlobalBaseReg(),CPI);
//     else
//       Tmp = CurDAG->getTargetNode(PPC::LIS, MVT::i32, CPI);
//     CurDAG->SelectNodeTo(N, PPC::LA, MVT::i32, Tmp, CPI);
//     return SDOperand(N, 0);
    assert(0 && "Constants are overrated");
  }
  case ISD::GlobalAddress: {
    GlobalValue *GV = cast<GlobalAddressSDNode>(N)->getGlobal();
    SDOperand GA = CurDAG->getTargetGlobalAddress(GV, MVT::i64);
    CurDAG->SelectNodeTo(N, Alpha::LDQl, MVT::i64, GA, getGlobalBaseReg());
    return SDOperand(N, 0);
  }

  case ISD::CALLSEQ_START:
  case ISD::CALLSEQ_END: {
    unsigned Amt = cast<ConstantSDNode>(N->getOperand(1))->getValue();
    unsigned Opc = N->getOpcode() == ISD::CALLSEQ_START ?
                       Alpha::ADJUSTSTACKDOWN : Alpha::ADJUSTSTACKUP;
    CurDAG->SelectNodeTo(N, Opc, MVT::Other,
                         getI64Imm(Amt), Select(N->getOperand(0)));
    return SDOperand(N, 0);
  }
  case ISD::RET: {
    SDOperand Chain = Select(N->getOperand(0));     // Token chain.

    if (N->getNumOperands() == 2) {
      SDOperand Val = Select(N->getOperand(1));
      if (N->getOperand(1).getValueType() == MVT::i64) {
        Chain = CurDAG->getCopyToReg(Chain, Alpha::R0, Val);
      }
    }
    //BuildMI(BB, Alpha::RET, 2, Alpha::R31).addReg(Alpha::R26).addImm(1);

    // FIXME: add restoring of the RA to R26 to the chain
    // Finally, select this to a ret instruction.
    CurDAG->SelectNodeTo(N, Alpha::RETDAG, MVT::Other, Chain);
    return SDOperand(N, 0);
  }



  }
  
  return SelectCode(Op);
}

SDOperand AlphaDAGToDAGISel::SelectCALL(SDOperand Op) {
  SDNode *N = Op.Val;
  SDOperand Chain = Select(N->getOperand(0));
  SDOperand InFlag;  // Null incoming flag value.
  SDOperand Addr = Select(N->getOperand(1));

//   unsigned CallOpcode;
   std::vector<SDOperand> CallOperands;
   std::vector<MVT::ValueType> TypeOperands;
  
   CallOperands.push_back(CurDAG->getCopyToReg(Chain, Alpha::R27, Addr));
   CallOperands.push_back(getI64Imm(0));

   //grab the arguments
   for(int i = 2, e = N->getNumOperands(); i < e; ++i) {
     CallOperands.push_back(Select(N->getOperand(i)));
     TypeOperands.push_back(N->getOperand(i).getValueType());
   }
   static const unsigned args_int[] = {Alpha::R16, Alpha::R17, Alpha::R18,
                                       Alpha::R19, Alpha::R20, Alpha::R21};
   static const unsigned args_float[] = {Alpha::F16, Alpha::F17, Alpha::F18,
                                         Alpha::F19, Alpha::F20, Alpha::F21};
   
   for (unsigned i = 0; i < std::min((size_t)6, CallOperands.size()); ++i) {
     if (MVT::isInteger(TypeOperands[i])) {
       Chain = CurDAG->getCopyToReg(Chain, args_int[i], CallOperands[i], InFlag);
       InFlag = Chain.getValue(1);
       CallOperands.push_back(CurDAG->getRegister(args_int[i], TypeOperands[i]));
     } else {
       assert(0 && "No FP support yet");
     }
   }
   assert(CallOperands.size() <= 6 && "Too big a call");

   // Finally, once everything is in registers to pass to the call, emit the
   // call itself.
   if (InFlag.Val)
     CallOperands.push_back(InFlag);   // Strong dep on register copies.
   else
     CallOperands.push_back(Chain);    // Weak dep on whatever occurs before
   Chain = CurDAG->getTargetNode(Alpha::JSR, MVT::Other, MVT::Flag, CallOperands);
  
   std::vector<SDOperand> CallResults;
  
   switch (N->getValueType(0)) {
   default: assert(0 && "Unexpected ret value!");
     case MVT::Other: break;
   case MVT::i64:
     Chain = CurDAG->getCopyFromReg(Chain, Alpha::R0, MVT::i64,
                                    Chain.getValue(1)).getValue(1);
     CallResults.push_back(Chain.getValue(0));
     break;
   }

   CallResults.push_back(Chain);
   for (unsigned i = 0, e = CallResults.size(); i != e; ++i)
     CodeGenMap[Op.getValue(i)] = CallResults[i];
   return CallResults[Op.ResNo];
}


/// createAlphaISelDag - This pass converts a legalized DAG into a 
/// Alpha-specific DAG, ready for instruction scheduling.
///
FunctionPass *llvm::createAlphaISelDag(TargetMachine &TM) {
  return new AlphaDAGToDAGISel(TM);
}
