<commit_before>//===-- R600ControlFlowFinalizer.cpp - Finalize Control Flow Inst----------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
/// \file
/// This pass compute turns all control flow pseudo instructions into native one
/// computing their address on the fly ; it also sets STACK_SIZE info.
//===----------------------------------------------------------------------===//

#define DEBUG_TYPE "r600cf"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"

#include "AMDGPU.h"
#include "R600Defines.h"
#include "R600InstrInfo.h"
#include "R600MachineFunctionInfo.h"
#include "R600RegisterInfo.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"

namespace llvm {

class R600ControlFlowFinalizer : public MachineFunctionPass {

private:
  enum ControlFlowInstruction {
    CF_TC,
    CF_CALL_FS,
    CF_WHILE_LOOP,
    CF_END_LOOP,
    CF_LOOP_BREAK,
    CF_LOOP_CONTINUE,
    CF_JUMP,
    CF_ELSE,
    CF_POP
  };

  static char ID;
  const R600InstrInfo *TII;
  unsigned MaxFetchInst;
  const AMDGPUSubtarget &ST;

  bool isFetch(const MachineInstr *MI) const {
    switch (MI->getOpcode()) {
    case AMDGPU::TEX_VTX_CONSTBUF:
    case AMDGPU::TEX_VTX_TEXBUF:
    case AMDGPU::TEX_LD:
    case AMDGPU::TEX_GET_TEXTURE_RESINFO:
    case AMDGPU::TEX_GET_GRADIENTS_H:
    case AMDGPU::TEX_GET_GRADIENTS_V:
    case AMDGPU::TEX_SET_GRADIENTS_H:
    case AMDGPU::TEX_SET_GRADIENTS_V:
    case AMDGPU::TEX_SAMPLE:
    case AMDGPU::TEX_SAMPLE_C:
    case AMDGPU::TEX_SAMPLE_L:
    case AMDGPU::TEX_SAMPLE_C_L:
    case AMDGPU::TEX_SAMPLE_LB:
    case AMDGPU::TEX_SAMPLE_C_LB:
    case AMDGPU::TEX_SAMPLE_G:
    case AMDGPU::TEX_SAMPLE_C_G:
    case AMDGPU::TXD:
    case AMDGPU::TXD_SHADOW:
    case AMDGPU::VTX_READ_GLOBAL_8_eg:
    case AMDGPU::VTX_READ_GLOBAL_32_eg:
    case AMDGPU::VTX_READ_GLOBAL_128_eg:
    case AMDGPU::VTX_READ_PARAM_8_eg:
    case AMDGPU::VTX_READ_PARAM_16_eg:
    case AMDGPU::VTX_READ_PARAM_32_eg:
    case AMDGPU::VTX_READ_PARAM_128_eg:
     return true;
    default:
      return false;
    }
  }

  bool IsTrivialInst(MachineInstr *MI) const {
    switch (MI->getOpcode()) {
    case AMDGPU::KILL:
    case AMDGPU::RETURN:
      return true;
    default:
      return false;
    }
  }

  const MCInstrDesc &getHWInstrDesc(ControlFlowInstruction CFI) const {
    if (ST.device()->getGeneration() <= AMDGPUDeviceInfo::HD4XXX) {
      switch (CFI) {
      case CF_TC:
        return TII->get(AMDGPU::CF_TC_R600);
      case CF_CALL_FS:
        return TII->get(AMDGPU::CF_CALL_FS_R600);
      case CF_WHILE_LOOP:
        return TII->get(AMDGPU::WHILE_LOOP_R600);
      case CF_END_LOOP:
        return TII->get(AMDGPU::END_LOOP_R600);
      case CF_LOOP_BREAK:
        return TII->get(AMDGPU::LOOP_BREAK_R600);
      case CF_LOOP_CONTINUE:
        return TII->get(AMDGPU::CF_CONTINUE_R600);
      case CF_JUMP:
        return TII->get(AMDGPU::CF_JUMP_R600);
      case CF_ELSE:
        return TII->get(AMDGPU::CF_ELSE_R600);
      case CF_POP:
        return TII->get(AMDGPU::POP_R600);
      }
    } else {
      switch (CFI) {
      case CF_TC:
        return TII->get(AMDGPU::CF_TC_EG);
      case CF_CALL_FS:
        return TII->get(AMDGPU::CF_CALL_FS_EG);
      case CF_WHILE_LOOP:
        return TII->get(AMDGPU::WHILE_LOOP_EG);
      case CF_END_LOOP:
        return TII->get(AMDGPU::END_LOOP_EG);
      case CF_LOOP_BREAK:
        return TII->get(AMDGPU::LOOP_BREAK_EG);
      case CF_LOOP_CONTINUE:
        return TII->get(AMDGPU::CF_CONTINUE_EG);
      case CF_JUMP:
        return TII->get(AMDGPU::CF_JUMP_EG);
      case CF_ELSE:
        return TII->get(AMDGPU::CF_ELSE_EG);
      case CF_POP:
        return TII->get(AMDGPU::POP_EG);
      }
    }
  }

  MachineBasicBlock::iterator
  MakeFetchClause(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
      unsigned CfAddress) const {
    MachineBasicBlock::iterator ClauseHead = I;
    unsigned AluInstCount = 0;
    for (MachineBasicBlock::iterator E = MBB.end(); I != E; ++I) {
      if (IsTrivialInst(I))
        continue;
      if (!isFetch(I))
        break;
      AluInstCount ++;
      if (AluInstCount > MaxFetchInst)
        break;
    }
    BuildMI(MBB, ClauseHead, MBB.findDebugLoc(ClauseHead),
        getHWInstrDesc(CF_TC))
        .addImm(CfAddress) // ADDR
        .addImm(AluInstCount); // COUNT
    return I;
  }
  void CounterPropagateAddr(MachineInstr *MI, unsigned Addr) const {
    MI->getOperand(0).setImm(Addr + MI->getOperand(0).getImm());
  }
  void CounterPropagateAddr(std::set<MachineInstr *> MIs, unsigned Addr)
      const {
    for (std::set<MachineInstr *>::iterator It = MIs.begin(), E = MIs.end();
        It != E; ++It) {
      MachineInstr *MI = *It;
      CounterPropagateAddr(MI, Addr);
    }
  }

public:
  R600ControlFlowFinalizer(TargetMachine &tm) : MachineFunctionPass(ID),
    TII (static_cast<const R600InstrInfo *>(tm.getInstrInfo())),
    ST(tm.getSubtarget<AMDGPUSubtarget>()) {
      const AMDGPUSubtarget &ST = tm.getSubtarget<AMDGPUSubtarget>();
      if (ST.device()->getGeneration() <= AMDGPUDeviceInfo::HD4XXX)
        MaxFetchInst = 8;
      else
        MaxFetchInst = 16;
  }

  virtual bool runOnMachineFunction(MachineFunction &MF) {
    unsigned MaxStack = 0;
    unsigned CurrentStack = 0;
    for (MachineFunction::iterator MB = MF.begin(), ME = MF.end(); MB != ME;
        ++MB) {
      MachineBasicBlock &MBB = *MB;
      unsigned CfCount = 0;
      std::vector<std::pair<unsigned, std::set<MachineInstr *> > > LoopStack;
      std::vector<MachineInstr * > IfThenElseStack;
      R600MachineFunctionInfo *MFI = MF.getInfo<R600MachineFunctionInfo>();
      if (MFI->ShaderType == 1) {
        BuildMI(MBB, MBB.begin(), MBB.findDebugLoc(MBB.begin()),
            getHWInstrDesc(CF_CALL_FS));
        CfCount++;
      }
      for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
          I != E;) {
        if (isFetch(I)) {
          DEBUG(dbgs() << CfCount << ":"; I->dump(););
          I = MakeFetchClause(MBB, I, 0);
          CfCount++;
          continue;
        }

        MachineBasicBlock::iterator MI = I;
        I++;
        switch (MI->getOpcode()) {
        case AMDGPU::CF_ALU_PUSH_BEFORE:
          CurrentStack++;
          MaxStack = std::max(MaxStack, CurrentStack);
        case AMDGPU::CF_ALU:
        case AMDGPU::EG_ExportBuf:
        case AMDGPU::EG_ExportSwz:
        case AMDGPU::R600_ExportBuf:
        case AMDGPU::R600_ExportSwz:
        case AMDGPU::RAT_WRITE_CACHELESS_32_eg:
        case AMDGPU::RAT_WRITE_CACHELESS_128_eg:
          DEBUG(dbgs() << CfCount << ":"; MI->dump(););
          CfCount++;
          break;
        case AMDGPU::WHILELOOP: {
          CurrentStack++;
          MaxStack = std::max(MaxStack, CurrentStack);
          MachineInstr *MIb = BuildMI(MBB, MI, MBB.findDebugLoc(MI),
              getHWInstrDesc(CF_WHILE_LOOP))
              .addImm(1);
          std::pair<unsigned, std::set<MachineInstr *> > Pair(CfCount,
              std::set<MachineInstr *>());
          Pair.second.insert(MIb);
          LoopStack.push_back(Pair);
          MI->eraseFromParent();
          CfCount++;
          break;
        }
        case AMDGPU::ENDLOOP: {
          CurrentStack--;
          std::pair<unsigned, std::set<MachineInstr *> > Pair =
              LoopStack.back();
          LoopStack.pop_back();
          CounterPropagateAddr(Pair.second, CfCount);
          BuildMI(MBB, MI, MBB.findDebugLoc(MI), getHWInstrDesc(CF_END_LOOP))
              .addImm(Pair.first + 1);
          MI->eraseFromParent();
          CfCount++;
          break;
        }
        case AMDGPU::IF_PREDICATE_SET: {
          MachineInstr *MIb = BuildMI(MBB, MI, MBB.findDebugLoc(MI),
              getHWInstrDesc(CF_JUMP))
              .addImm(0)
              .addImm(0);
          IfThenElseStack.push_back(MIb);
          DEBUG(dbgs() << CfCount << ":"; MIb->dump(););
          MI->eraseFromParent();
          CfCount++;
          break;
        }
        case AMDGPU::ELSE: {
          MachineInstr * JumpInst = IfThenElseStack.back();
          IfThenElseStack.pop_back();
          CounterPropagateAddr(JumpInst, CfCount);
          MachineInstr *MIb = BuildMI(MBB, MI, MBB.findDebugLoc(MI),
              getHWInstrDesc(CF_ELSE))
              .addImm(0)
              .addImm(1);
          DEBUG(dbgs() << CfCount << ":"; MIb->dump(););
          IfThenElseStack.push_back(MIb);
          MI->eraseFromParent();
          CfCount++;
          break;
        }
        case AMDGPU::ENDIF: {
          CurrentStack--;
          MachineInstr *IfOrElseInst = IfThenElseStack.back();
          IfThenElseStack.pop_back();
          CounterPropagateAddr(IfOrElseInst, CfCount + 1);
          MachineInstr *MIb = BuildMI(MBB, MI, MBB.findDebugLoc(MI),
              getHWInstrDesc(CF_POP))
              .addImm(CfCount + 1)
              .addImm(1);
          DEBUG(dbgs() << CfCount << ":"; MIb->dump(););
          MI->eraseFromParent();
          CfCount++;
          break;
        }
        case AMDGPU::PREDICATED_BREAK: {
          CurrentStack--;
          CfCount += 3;
          BuildMI(MBB, MI, MBB.findDebugLoc(MI), getHWInstrDesc(CF_JUMP))
              .addImm(CfCount)
              .addImm(1);
          MachineInstr *MIb = BuildMI(MBB, MI, MBB.findDebugLoc(MI),
              getHWInstrDesc(CF_LOOP_BREAK))
              .addImm(0);
          BuildMI(MBB, MI, MBB.findDebugLoc(MI), getHWInstrDesc(CF_POP))
              .addImm(CfCount)
              .addImm(1);
          LoopStack.back().second.insert(MIb);
          MI->eraseFromParent();
          break;
        }
        case AMDGPU::CONTINUE: {
          MachineInstr *MIb = BuildMI(MBB, MI, MBB.findDebugLoc(MI),
              getHWInstrDesc(CF_LOOP_CONTINUE))
              .addImm(0);
          LoopStack.back().second.insert(MIb);
          MI->eraseFromParent();
          CfCount++;
          break;
        }
        default:
          break;
        }
      }
      BuildMI(MBB, MBB.begin(), MBB.findDebugLoc(MBB.begin()),
          TII->get(AMDGPU::STACK_SIZE))
          .addImm(MaxStack);
    }

    return false;
  }

  const char *getPassName() const {
    return "R600 Control Flow Finalizer Pass";
  }
};

char R600ControlFlowFinalizer::ID = 0;

}

llvm::FunctionPass *llvm::createR600ControlFlowFinalizer(TargetMachine &TM) {
  return new R600ControlFlowFinalizer(TM);
}
<commit_msg>R600ControlFlowFinalizer.cpp: Fix a warning. [-Wunused-variable]<commit_after>//===-- R600ControlFlowFinalizer.cpp - Finalize Control Flow Inst----------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
/// \file
/// This pass compute turns all control flow pseudo instructions into native one
/// computing their address on the fly ; it also sets STACK_SIZE info.
//===----------------------------------------------------------------------===//

#define DEBUG_TYPE "r600cf"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"

#include "AMDGPU.h"
#include "R600Defines.h"
#include "R600InstrInfo.h"
#include "R600MachineFunctionInfo.h"
#include "R600RegisterInfo.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"

namespace llvm {

class R600ControlFlowFinalizer : public MachineFunctionPass {

private:
  enum ControlFlowInstruction {
    CF_TC,
    CF_CALL_FS,
    CF_WHILE_LOOP,
    CF_END_LOOP,
    CF_LOOP_BREAK,
    CF_LOOP_CONTINUE,
    CF_JUMP,
    CF_ELSE,
    CF_POP
  };

  static char ID;
  const R600InstrInfo *TII;
  unsigned MaxFetchInst;
  const AMDGPUSubtarget &ST;

  bool isFetch(const MachineInstr *MI) const {
    switch (MI->getOpcode()) {
    case AMDGPU::TEX_VTX_CONSTBUF:
    case AMDGPU::TEX_VTX_TEXBUF:
    case AMDGPU::TEX_LD:
    case AMDGPU::TEX_GET_TEXTURE_RESINFO:
    case AMDGPU::TEX_GET_GRADIENTS_H:
    case AMDGPU::TEX_GET_GRADIENTS_V:
    case AMDGPU::TEX_SET_GRADIENTS_H:
    case AMDGPU::TEX_SET_GRADIENTS_V:
    case AMDGPU::TEX_SAMPLE:
    case AMDGPU::TEX_SAMPLE_C:
    case AMDGPU::TEX_SAMPLE_L:
    case AMDGPU::TEX_SAMPLE_C_L:
    case AMDGPU::TEX_SAMPLE_LB:
    case AMDGPU::TEX_SAMPLE_C_LB:
    case AMDGPU::TEX_SAMPLE_G:
    case AMDGPU::TEX_SAMPLE_C_G:
    case AMDGPU::TXD:
    case AMDGPU::TXD_SHADOW:
    case AMDGPU::VTX_READ_GLOBAL_8_eg:
    case AMDGPU::VTX_READ_GLOBAL_32_eg:
    case AMDGPU::VTX_READ_GLOBAL_128_eg:
    case AMDGPU::VTX_READ_PARAM_8_eg:
    case AMDGPU::VTX_READ_PARAM_16_eg:
    case AMDGPU::VTX_READ_PARAM_32_eg:
    case AMDGPU::VTX_READ_PARAM_128_eg:
     return true;
    default:
      return false;
    }
  }

  bool IsTrivialInst(MachineInstr *MI) const {
    switch (MI->getOpcode()) {
    case AMDGPU::KILL:
    case AMDGPU::RETURN:
      return true;
    default:
      return false;
    }
  }

  const MCInstrDesc &getHWInstrDesc(ControlFlowInstruction CFI) const {
    if (ST.device()->getGeneration() <= AMDGPUDeviceInfo::HD4XXX) {
      switch (CFI) {
      case CF_TC:
        return TII->get(AMDGPU::CF_TC_R600);
      case CF_CALL_FS:
        return TII->get(AMDGPU::CF_CALL_FS_R600);
      case CF_WHILE_LOOP:
        return TII->get(AMDGPU::WHILE_LOOP_R600);
      case CF_END_LOOP:
        return TII->get(AMDGPU::END_LOOP_R600);
      case CF_LOOP_BREAK:
        return TII->get(AMDGPU::LOOP_BREAK_R600);
      case CF_LOOP_CONTINUE:
        return TII->get(AMDGPU::CF_CONTINUE_R600);
      case CF_JUMP:
        return TII->get(AMDGPU::CF_JUMP_R600);
      case CF_ELSE:
        return TII->get(AMDGPU::CF_ELSE_R600);
      case CF_POP:
        return TII->get(AMDGPU::POP_R600);
      }
    } else {
      switch (CFI) {
      case CF_TC:
        return TII->get(AMDGPU::CF_TC_EG);
      case CF_CALL_FS:
        return TII->get(AMDGPU::CF_CALL_FS_EG);
      case CF_WHILE_LOOP:
        return TII->get(AMDGPU::WHILE_LOOP_EG);
      case CF_END_LOOP:
        return TII->get(AMDGPU::END_LOOP_EG);
      case CF_LOOP_BREAK:
        return TII->get(AMDGPU::LOOP_BREAK_EG);
      case CF_LOOP_CONTINUE:
        return TII->get(AMDGPU::CF_CONTINUE_EG);
      case CF_JUMP:
        return TII->get(AMDGPU::CF_JUMP_EG);
      case CF_ELSE:
        return TII->get(AMDGPU::CF_ELSE_EG);
      case CF_POP:
        return TII->get(AMDGPU::POP_EG);
      }
    }
  }

  MachineBasicBlock::iterator
  MakeFetchClause(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
      unsigned CfAddress) const {
    MachineBasicBlock::iterator ClauseHead = I;
    unsigned AluInstCount = 0;
    for (MachineBasicBlock::iterator E = MBB.end(); I != E; ++I) {
      if (IsTrivialInst(I))
        continue;
      if (!isFetch(I))
        break;
      AluInstCount ++;
      if (AluInstCount > MaxFetchInst)
        break;
    }
    BuildMI(MBB, ClauseHead, MBB.findDebugLoc(ClauseHead),
        getHWInstrDesc(CF_TC))
        .addImm(CfAddress) // ADDR
        .addImm(AluInstCount); // COUNT
    return I;
  }
  void CounterPropagateAddr(MachineInstr *MI, unsigned Addr) const {
    MI->getOperand(0).setImm(Addr + MI->getOperand(0).getImm());
  }
  void CounterPropagateAddr(std::set<MachineInstr *> MIs, unsigned Addr)
      const {
    for (std::set<MachineInstr *>::iterator It = MIs.begin(), E = MIs.end();
        It != E; ++It) {
      MachineInstr *MI = *It;
      CounterPropagateAddr(MI, Addr);
    }
  }

public:
  R600ControlFlowFinalizer(TargetMachine &tm) : MachineFunctionPass(ID),
    TII (static_cast<const R600InstrInfo *>(tm.getInstrInfo())),
    ST(tm.getSubtarget<AMDGPUSubtarget>()) {
      const AMDGPUSubtarget &ST = tm.getSubtarget<AMDGPUSubtarget>();
      if (ST.device()->getGeneration() <= AMDGPUDeviceInfo::HD4XXX)
        MaxFetchInst = 8;
      else
        MaxFetchInst = 16;
  }

  virtual bool runOnMachineFunction(MachineFunction &MF) {
    unsigned MaxStack = 0;
    unsigned CurrentStack = 0;
    for (MachineFunction::iterator MB = MF.begin(), ME = MF.end(); MB != ME;
        ++MB) {
      MachineBasicBlock &MBB = *MB;
      unsigned CfCount = 0;
      std::vector<std::pair<unsigned, std::set<MachineInstr *> > > LoopStack;
      std::vector<MachineInstr * > IfThenElseStack;
      R600MachineFunctionInfo *MFI = MF.getInfo<R600MachineFunctionInfo>();
      if (MFI->ShaderType == 1) {
        BuildMI(MBB, MBB.begin(), MBB.findDebugLoc(MBB.begin()),
            getHWInstrDesc(CF_CALL_FS));
        CfCount++;
      }
      for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
          I != E;) {
        if (isFetch(I)) {
          DEBUG(dbgs() << CfCount << ":"; I->dump(););
          I = MakeFetchClause(MBB, I, 0);
          CfCount++;
          continue;
        }

        MachineBasicBlock::iterator MI = I;
        I++;
        switch (MI->getOpcode()) {
        case AMDGPU::CF_ALU_PUSH_BEFORE:
          CurrentStack++;
          MaxStack = std::max(MaxStack, CurrentStack);
        case AMDGPU::CF_ALU:
        case AMDGPU::EG_ExportBuf:
        case AMDGPU::EG_ExportSwz:
        case AMDGPU::R600_ExportBuf:
        case AMDGPU::R600_ExportSwz:
        case AMDGPU::RAT_WRITE_CACHELESS_32_eg:
        case AMDGPU::RAT_WRITE_CACHELESS_128_eg:
          DEBUG(dbgs() << CfCount << ":"; MI->dump(););
          CfCount++;
          break;
        case AMDGPU::WHILELOOP: {
          CurrentStack++;
          MaxStack = std::max(MaxStack, CurrentStack);
          MachineInstr *MIb = BuildMI(MBB, MI, MBB.findDebugLoc(MI),
              getHWInstrDesc(CF_WHILE_LOOP))
              .addImm(1);
          std::pair<unsigned, std::set<MachineInstr *> > Pair(CfCount,
              std::set<MachineInstr *>());
          Pair.second.insert(MIb);
          LoopStack.push_back(Pair);
          MI->eraseFromParent();
          CfCount++;
          break;
        }
        case AMDGPU::ENDLOOP: {
          CurrentStack--;
          std::pair<unsigned, std::set<MachineInstr *> > Pair =
              LoopStack.back();
          LoopStack.pop_back();
          CounterPropagateAddr(Pair.second, CfCount);
          BuildMI(MBB, MI, MBB.findDebugLoc(MI), getHWInstrDesc(CF_END_LOOP))
              .addImm(Pair.first + 1);
          MI->eraseFromParent();
          CfCount++;
          break;
        }
        case AMDGPU::IF_PREDICATE_SET: {
          MachineInstr *MIb = BuildMI(MBB, MI, MBB.findDebugLoc(MI),
              getHWInstrDesc(CF_JUMP))
              .addImm(0)
              .addImm(0);
          IfThenElseStack.push_back(MIb);
          DEBUG(dbgs() << CfCount << ":"; MIb->dump(););
          MI->eraseFromParent();
          CfCount++;
          break;
        }
        case AMDGPU::ELSE: {
          MachineInstr * JumpInst = IfThenElseStack.back();
          IfThenElseStack.pop_back();
          CounterPropagateAddr(JumpInst, CfCount);
          MachineInstr *MIb = BuildMI(MBB, MI, MBB.findDebugLoc(MI),
              getHWInstrDesc(CF_ELSE))
              .addImm(0)
              .addImm(1);
          DEBUG(dbgs() << CfCount << ":"; MIb->dump(););
          IfThenElseStack.push_back(MIb);
          MI->eraseFromParent();
          CfCount++;
          break;
        }
        case AMDGPU::ENDIF: {
          CurrentStack--;
          MachineInstr *IfOrElseInst = IfThenElseStack.back();
          IfThenElseStack.pop_back();
          CounterPropagateAddr(IfOrElseInst, CfCount + 1);
          MachineInstr *MIb = BuildMI(MBB, MI, MBB.findDebugLoc(MI),
              getHWInstrDesc(CF_POP))
              .addImm(CfCount + 1)
              .addImm(1);
          (void)MIb;
          DEBUG(dbgs() << CfCount << ":"; MIb->dump(););
          MI->eraseFromParent();
          CfCount++;
          break;
        }
        case AMDGPU::PREDICATED_BREAK: {
          CurrentStack--;
          CfCount += 3;
          BuildMI(MBB, MI, MBB.findDebugLoc(MI), getHWInstrDesc(CF_JUMP))
              .addImm(CfCount)
              .addImm(1);
          MachineInstr *MIb = BuildMI(MBB, MI, MBB.findDebugLoc(MI),
              getHWInstrDesc(CF_LOOP_BREAK))
              .addImm(0);
          BuildMI(MBB, MI, MBB.findDebugLoc(MI), getHWInstrDesc(CF_POP))
              .addImm(CfCount)
              .addImm(1);
          LoopStack.back().second.insert(MIb);
          MI->eraseFromParent();
          break;
        }
        case AMDGPU::CONTINUE: {
          MachineInstr *MIb = BuildMI(MBB, MI, MBB.findDebugLoc(MI),
              getHWInstrDesc(CF_LOOP_CONTINUE))
              .addImm(0);
          LoopStack.back().second.insert(MIb);
          MI->eraseFromParent();
          CfCount++;
          break;
        }
        default:
          break;
        }
      }
      BuildMI(MBB, MBB.begin(), MBB.findDebugLoc(MBB.begin()),
          TII->get(AMDGPU::STACK_SIZE))
          .addImm(MaxStack);
    }

    return false;
  }

  const char *getPassName() const {
    return "R600 Control Flow Finalizer Pass";
  }
};

char R600ControlFlowFinalizer::ID = 0;

}

llvm::FunctionPass *llvm::createR600ControlFlowFinalizer(TargetMachine &TM) {
  return new R600ControlFlowFinalizer(TM);
}
<|endoftext|>


<commit_before>#include "thread_pool_aio_scheduler.hpp"

#include "utils/thread_pool.hpp"

#include <unistd.h>

#include <thread>

namespace sse {
namespace abstractio {

static ThreadPool* _shared_io_pool = nullptr;

constexpr uint32_t kAIOThreadsCount = 50;

static ThreadPool& get_shared_io_pool()
{
    if (_shared_io_pool == nullptr) {
        _shared_io_pool = new ThreadPool(kAIOThreadsCount);
    }
    return *_shared_io_pool;
}

ThreadPoolAIOScheduler::ThreadPoolAIOScheduler()
{
}

ThreadPoolAIOScheduler::~ThreadPoolAIOScheduler()
{
    ThreadPoolAIOScheduler::wait_completions();
}

void ThreadPoolAIOScheduler::wait_completions()
{
    while (true) {
        std::unique_lock<std::mutex> lock(m_cv_lock);
        m_cv_submission.wait(lock, [this] {
            return this->m_submitted_queries_count
                   >= this->m_completed_queries_count;
        });
    }
}

int ThreadPoolAIOScheduler::submit_pread(int                     fd,
                                         void*                   buf,
                                         size_t                  len,
                                         off_t                   offset,
                                         void*                   data,
                                         scheduler_callback_type callback)
{
    auto task = [this, fd, buf, len, offset, data, callback]() {
        ssize_t ret = pread(fd, buf, len, offset);
        callback(data, ret);

        this->m_completed_queries_count++;
        this->m_cv_submission.notify_one();
    };

    m_submitted_queries_count++;
    get_shared_io_pool().enqueue(task);

    return 1;
}

int ThreadPoolAIOScheduler::submit_pwrite(int                     fd,
                                          void*                   buf,
                                          size_t                  len,
                                          off_t                   offset,
                                          void*                   data,
                                          scheduler_callback_type callback)
{
    auto task = [this, fd, buf, len, offset, data, callback]() {
        ssize_t ret = pwrite(fd, buf, len, offset);
        callback(data, ret);

        this->m_completed_queries_count++;
        this->m_cv_submission.notify_one();
    };

    m_submitted_queries_count++;
    get_shared_io_pool().enqueue(task);

    return 1;
}

// std::future<ReadBuffer> ThreadPoolAIOScheduler::async_read(int    fd,
//                                                            size_t len,
//                                                            off_t  offset)
// {
//     auto task = [this, fd, len, offset]() {
//         ssize_t ret = pread(fd, buf, len, offset);
//         callback(data, ret);

//         this->m_completed_queries_count++;
//         this->m_cv_submission.notify_one();
//     };

//     return get_shared_io_pool().enqueue(task);
// }

// std::future<int> ThreadPoolAIOScheduler::async_write(int    fd,
//                                                      void*  buf,
//                                                      size_t len,
//                                                      off_t  offset)
// {
//     auto task = [this, fd, buf, len, offset, ]() -> int {
//         ssize_t ret = pwrite(fd, buf, len, offset);

//         this->m_completed_queries_count++;
//         this->m_cv_submission.notify_one();

//         return ret;
//     };

//     return get_shared_io_pool().enqueue(task);
// }

} // namespace abstractio
} // namespace sse
<commit_msg>Bugfix: threaded pool aio. We should exit the waiting loop when all the tasks are completed<commit_after>#include "thread_pool_aio_scheduler.hpp"

#include "utils/thread_pool.hpp"

#include <unistd.h>

#include <thread>

namespace sse {
namespace abstractio {

static ThreadPool* _shared_io_pool = nullptr;

constexpr uint32_t kAIOThreadsCount = 50;

static ThreadPool& get_shared_io_pool()
{
    if (_shared_io_pool == nullptr) {
        _shared_io_pool = new ThreadPool(kAIOThreadsCount);
    }
    return *_shared_io_pool;
}

ThreadPoolAIOScheduler::ThreadPoolAIOScheduler()
{
}

ThreadPoolAIOScheduler::~ThreadPoolAIOScheduler()
{
    ThreadPoolAIOScheduler::wait_completions();
}

void ThreadPoolAIOScheduler::wait_completions()
{
    std::cerr << "Wait for completions\n";
    while (true) {
        std::unique_lock<std::mutex> lock(m_cv_lock);
        m_cv_submission.wait(lock, [this] {
            return this->m_submitted_queries_count
                   >= this->m_completed_queries_count;
        });

        if (this->m_submitted_queries_count
            >= this->m_completed_queries_count) {
            break;
        }
    }
    std::cerr << "Completed\n";
}

int ThreadPoolAIOScheduler::submit_pread(int                     fd,
                                         void*                   buf,
                                         size_t                  len,
                                         off_t                   offset,
                                         void*                   data,
                                         scheduler_callback_type callback)
{
    auto task = [this, fd, buf, len, offset, data, callback]() {
        ssize_t ret = pread(fd, buf, len, offset);
        callback(data, ret);

        this->m_completed_queries_count++;
        this->m_cv_submission.notify_one();
    };

    m_submitted_queries_count++;
    get_shared_io_pool().enqueue(task);

    return 1;
}

int ThreadPoolAIOScheduler::submit_pwrite(int                     fd,
                                          void*                   buf,
                                          size_t                  len,
                                          off_t                   offset,
                                          void*                   data,
                                          scheduler_callback_type callback)
{
    auto task = [this, fd, buf, len, offset, data, callback]() {
        ssize_t ret = pwrite(fd, buf, len, offset);
        callback(data, ret);

        this->m_completed_queries_count++;
        this->m_cv_submission.notify_one();
    };

    m_submitted_queries_count++;
    get_shared_io_pool().enqueue(task);

    return 1;
}

// std::future<ReadBuffer> ThreadPoolAIOScheduler::async_read(int    fd,
//                                                            size_t len,
//                                                            off_t  offset)
// {
//     auto task = [this, fd, len, offset]() {
//         ssize_t ret = pread(fd, buf, len, offset);
//         callback(data, ret);

//         this->m_completed_queries_count++;
//         this->m_cv_submission.notify_one();
//     };

//     return get_shared_io_pool().enqueue(task);
// }

// std::future<int> ThreadPoolAIOScheduler::async_write(int    fd,
//                                                      void*  buf,
//                                                      size_t len,
//                                                      off_t  offset)
// {
//     auto task = [this, fd, buf, len, offset, ]() -> int {
//         ssize_t ret = pwrite(fd, buf, len, offset);

//         this->m_completed_queries_count++;
//         this->m_cv_submission.notify_one();

//         return ret;
//     };

//     return get_shared_io_pool().enqueue(task);
// }

} // namespace abstractio
} // namespace sse
<|endoftext|>


<commit_before>//===- DAGISelMatcherOpt.cpp - Optimize a DAG Matcher ---------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the DAG Matcher optimizer.
//
//===----------------------------------------------------------------------===//

#define DEBUG_TYPE "isel-opt"
#include "DAGISelMatcher.h"
#include "CodeGenDAGPatterns.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/StringSet.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include <vector>
using namespace llvm;

/// ContractNodes - Turn multiple matcher node patterns like 'MoveChild+Record'
/// into single compound nodes like RecordChild.
static void ContractNodes(OwningPtr<Matcher> &MatcherPtr,
                          const CodeGenDAGPatterns &CGP) {
  // If we reached the end of the chain, we're done.
  Matcher *N = MatcherPtr.get();
  if (N == 0) return;

  // If we have a scope node, walk down all of the children.
  if (ScopeMatcher *Scope = dyn_cast<ScopeMatcher>(N)) {
    for (unsigned i = 0, e = Scope->getNumChildren(); i != e; ++i) {
      OwningPtr<Matcher> Child(Scope->takeChild(i));
      ContractNodes(Child, CGP);
      Scope->resetChild(i, Child.take());
    }
    return;
  }

  // If we found a movechild node with a node that comes in a 'foochild' form,
  // transform it.
  if (MoveChildMatcher *MC = dyn_cast<MoveChildMatcher>(N)) {
    Matcher *New = 0;
    if (RecordMatcher *RM = dyn_cast<RecordMatcher>(MC->getNext()))
      New = new RecordChildMatcher(MC->getChildNo(), RM->getWhatFor(),
                                   RM->getResultNo());

    if (CheckTypeMatcher *CT= dyn_cast<CheckTypeMatcher>(MC->getNext()))
      New = new CheckChildTypeMatcher(MC->getChildNo(), CT->getType());

    if (New) {
      // Insert the new node.
      New->setNext(MatcherPtr.take());
      MatcherPtr.reset(New);
      // Remove the old one.
      MC->setNext(MC->getNext()->takeNext());
      return ContractNodes(MatcherPtr, CGP);
    }
  }

  // Zap movechild -> moveparent.
  if (MoveChildMatcher *MC = dyn_cast<MoveChildMatcher>(N))
    if (MoveParentMatcher *MP =
          dyn_cast<MoveParentMatcher>(MC->getNext())) {
      MatcherPtr.reset(MP->takeNext());
      return ContractNodes(MatcherPtr, CGP);
    }

  // Turn EmitNode->MarkFlagResults->CompleteMatch into
  // MarkFlagResults->EmitNode->CompleteMatch when we can to encourage
  // MorphNodeTo formation.  This is safe because MarkFlagResults never refers
  // to the root of the pattern.
  if (isa<EmitNodeMatcher>(N) && isa<MarkFlagResultsMatcher>(N->getNext()) &&
      isa<CompleteMatchMatcher>(N->getNext()->getNext())) {
    // Unlink the two nodes from the list.
    Matcher *EmitNode = MatcherPtr.take();
    Matcher *MFR = EmitNode->takeNext();
    Matcher *Tail = MFR->takeNext();

    // Relink them.
    MatcherPtr.reset(MFR);
    MFR->setNext(EmitNode);
    EmitNode->setNext(Tail);
    return ContractNodes(MatcherPtr, CGP);
  }

  // Turn EmitNode->CompleteMatch into MorphNodeTo if we can.
  if (EmitNodeMatcher *EN = dyn_cast<EmitNodeMatcher>(N))
    if (CompleteMatchMatcher *CM =
          dyn_cast<CompleteMatchMatcher>(EN->getNext())) {
      // We can only use MorphNodeTo if the result values match up.
      unsigned RootResultFirst = EN->getFirstResultSlot();
      bool ResultsMatch = true;
      for (unsigned i = 0, e = CM->getNumResults(); i != e; ++i)
        if (CM->getResult(i) != RootResultFirst+i)
          ResultsMatch = false;

      // If the selected node defines a subset of the flag/chain results, we
      // can't use MorphNodeTo.  For example, we can't use MorphNodeTo if the
      // matched pattern has a chain but the root node doesn't.
      const PatternToMatch &Pattern = CM->getPattern();

      if (!EN->hasChain() &&
          Pattern.getSrcPattern()->NodeHasProperty(SDNPHasChain, CGP))
        ResultsMatch = false;

      // If the matched node has a flag and the output root doesn't, we can't
      // use MorphNodeTo.
      //
      // NOTE: Strictly speaking, we don't have to check for the flag here
      // because the code in the pattern generator doesn't handle it right.  We
      // do it anyway for thoroughness.
      if (!EN->hasOutFlag() &&
          Pattern.getSrcPattern()->NodeHasProperty(SDNPOutFlag, CGP))
        ResultsMatch = false;

      // If the root result node defines more results than the source root node
      // *and* has a chain or flag input, then we can't match it because it
      // would end up replacing the extra result with the chain/flag.
#if 0
      if ((EN->hasFlag() || EN->hasChain()) &&
          EN->getNumNonChainFlagVTs() > ... need to get no results reliably ...)
        ResultMatch = false;
#endif

      if (ResultsMatch) {
        const SmallVectorImpl<MVT::SimpleValueType> &VTs = EN->getVTList();
        const SmallVectorImpl<unsigned> &Operands = EN->getOperandList();
        MatcherPtr.reset(new MorphNodeToMatcher(EN->getOpcodeName(),
                                                VTs.data(), VTs.size(),
                                                Operands.data(),Operands.size(),
                                                EN->hasChain(), EN->hasInFlag(),
                                                EN->hasOutFlag(),
                                                EN->hasMemRefs(),
                                                EN->getNumFixedArityOperands(),
                                                Pattern));
        return;
      }

      // FIXME2: Kill off all the SelectionDAG::MorphNodeTo and getMachineNode
      // variants.
    }

  ContractNodes(N->getNextPtr(), CGP);

  // If we have a CheckType/CheckChildType/Record node followed by a
  // CheckOpcode, invert the two nodes.  We prefer to do structural checks
  // before type checks, as this opens opportunities for factoring on targets
  // like X86 where many operations are valid on multiple types.
  if ((isa<CheckTypeMatcher>(N) || isa<CheckChildTypeMatcher>(N) ||
       isa<RecordMatcher>(N)) &&
      isa<CheckOpcodeMatcher>(N->getNext())) {
    // Unlink the two nodes from the list.
    Matcher *CheckType = MatcherPtr.take();
    Matcher *CheckOpcode = CheckType->takeNext();
    Matcher *Tail = CheckOpcode->takeNext();

    // Relink them.
    MatcherPtr.reset(CheckOpcode);
    CheckOpcode->setNext(CheckType);
    CheckType->setNext(Tail);
    return ContractNodes(MatcherPtr, CGP);
  }
}

/// SinkPatternPredicates - Pattern predicates can be checked at any level of
/// the matching tree.  The generator dumps them at the top level of the pattern
/// though, which prevents factoring from being able to see past them.  This
/// optimization sinks them as far down into the pattern as possible.
///
/// Conceptually, we'd like to sink these predicates all the way to the last
/// matcher predicate in the series.  However, it turns out that some
/// ComplexPatterns have side effects on the graph, so we really don't want to
/// run a the complex pattern if the pattern predicate will fail.  For this
/// reason, we refuse to sink the pattern predicate past a ComplexPattern.
///
static void SinkPatternPredicates(OwningPtr<Matcher> &MatcherPtr) {
  // Recursively scan for a PatternPredicate.
  // If we reached the end of the chain, we're done.
  Matcher *N = MatcherPtr.get();
  if (N == 0) return;

  // Walk down all members of a scope node.
  if (ScopeMatcher *Scope = dyn_cast<ScopeMatcher>(N)) {
    for (unsigned i = 0, e = Scope->getNumChildren(); i != e; ++i) {
      OwningPtr<Matcher> Child(Scope->takeChild(i));
      SinkPatternPredicates(Child);
      Scope->resetChild(i, Child.take());
    }
    return;
  }

  // If this node isn't a CheckPatternPredicateMatcher we keep scanning until
  // we find one.
  CheckPatternPredicateMatcher *CPPM =dyn_cast<CheckPatternPredicateMatcher>(N);
  if (CPPM == 0)
    return SinkPatternPredicates(N->getNextPtr());

  // Ok, we found one, lets try to sink it. Check if we can sink it past the
  // next node in the chain.  If not, we won't be able to change anything and
  // might as well bail.
  if (!CPPM->getNext()->isSafeToReorderWithPatternPredicate())
    return;

  // Okay, we know we can sink it past at least one node.  Unlink it from the
  // chain and scan for the new insertion point.
  MatcherPtr.take();  // Don't delete CPPM.
  MatcherPtr.reset(CPPM->takeNext());

  N = MatcherPtr.get();
  while (N->getNext()->isSafeToReorderWithPatternPredicate())
    N = N->getNext();

  // At this point, we want to insert CPPM after N.
  CPPM->setNext(N->takeNext());
  N->setNext(CPPM);
}

/// FactorNodes - Turn matches like this:
///   Scope
///     OPC_CheckType i32
///       ABC
///     OPC_CheckType i32
///       XYZ
/// into:
///   OPC_CheckType i32
///     Scope
///       ABC
///       XYZ
///
static void FactorNodes(OwningPtr<Matcher> &MatcherPtr) {
  // If we reached the end of the chain, we're done.
  Matcher *N = MatcherPtr.get();
  if (N == 0) return;

  // If this is not a push node, just scan for one.
  ScopeMatcher *Scope = dyn_cast<ScopeMatcher>(N);
  if (Scope == 0)
    return FactorNodes(N->getNextPtr());

  // Okay, pull together the children of the scope node into a vector so we can
  // inspect it more easily.  While we're at it, bucket them up by the hash
  // code of their first predicate.
  SmallVector<Matcher*, 32> OptionsToMatch;

  for (unsigned i = 0, e = Scope->getNumChildren(); i != e; ++i) {
    // Factor the subexpression.
    OwningPtr<Matcher> Child(Scope->takeChild(i));
    FactorNodes(Child);

    if (Matcher *N = Child.take())
      OptionsToMatch.push_back(N);
  }

  SmallVector<Matcher*, 32> NewOptionsToMatch;

  // Loop over options to match, merging neighboring patterns with identical
  // starting nodes into a shared matcher.
  for (unsigned OptionIdx = 0, e = OptionsToMatch.size(); OptionIdx != e;) {
    // Find the set of matchers that start with this node.
    Matcher *Optn = OptionsToMatch[OptionIdx++];

    if (OptionIdx == e) {
      NewOptionsToMatch.push_back(Optn);
      continue;
    }

    // See if the next option starts with the same matcher.  If the two
    // neighbors *do* start with the same matcher, we can factor the matcher out
    // of at least these two patterns.  See what the maximal set we can merge
    // together is.
    SmallVector<Matcher*, 8> EqualMatchers;
    EqualMatchers.push_back(Optn);

    // Factor all of the known-equal matchers after this one into the same
    // group.
    while (OptionIdx != e && OptionsToMatch[OptionIdx]->isEqual(Optn))
      EqualMatchers.push_back(OptionsToMatch[OptionIdx++]);

    // If we found a non-equal matcher, see if it is contradictory with the
    // current node.  If so, we know that the ordering relation between the
    // current sets of nodes and this node don't matter.  Look past it to see if
    // we can merge anything else into this matching group.
    unsigned Scan = OptionIdx;
    while (1) {
      while (Scan != e && Optn->isContradictory(OptionsToMatch[Scan]))
        ++Scan;

      // Ok, we found something that isn't known to be contradictory.  If it is
      // equal, we can merge it into the set of nodes to factor, if not, we have
      // to cease factoring.
      if (Scan == e || !Optn->isEqual(OptionsToMatch[Scan])) break;

      // If is equal after all, add the option to EqualMatchers and remove it
      // from OptionsToMatch.
      EqualMatchers.push_back(OptionsToMatch[Scan]);
      OptionsToMatch.erase(OptionsToMatch.begin()+Scan);
      --e;
    }

    if (Scan != e &&
        // Don't print it's obvious nothing extra could be merged anyway.
        Scan+1 != e) {
      DEBUG(errs() << "Couldn't merge this:\n";
            Optn->print(errs(), 4);
            errs() << "into this:\n";
            OptionsToMatch[Scan]->print(errs(), 4);
            if (Scan+1 != e)
              OptionsToMatch[Scan+1]->printOne(errs());
            if (Scan+2 < e)
              OptionsToMatch[Scan+2]->printOne(errs());
            errs() << "\n");
    }

    // If we only found one option starting with this matcher, no factoring is
    // possible.
    if (EqualMatchers.size() == 1) {
      NewOptionsToMatch.push_back(EqualMatchers[0]);
      continue;
    }

    // Factor these checks by pulling the first node off each entry and
    // discarding it.  Take the first one off the first entry to reuse.
    Matcher *Shared = Optn;
    Optn = Optn->takeNext();
    EqualMatchers[0] = Optn;

    // Remove and delete the first node from the other matchers we're factoring.
    for (unsigned i = 1, e = EqualMatchers.size(); i != e; ++i) {
      Matcher *Tmp = EqualMatchers[i]->takeNext();
      delete EqualMatchers[i];
      EqualMatchers[i] = Tmp;
    }

    Shared->setNext(new ScopeMatcher(&EqualMatchers[0], EqualMatchers.size()));

    // Recursively factor the newly created node.
    FactorNodes(Shared->getNextPtr());

    NewOptionsToMatch.push_back(Shared);
  }

  // If we're down to a single pattern to match, then we don't need this scope
  // anymore.
  if (NewOptionsToMatch.size() == 1) {
    MatcherPtr.reset(NewOptionsToMatch[0]);
    return;
  }

  if (NewOptionsToMatch.empty()) {
    MatcherPtr.reset(0);
    return;
  }

  // If our factoring failed (didn't achieve anything) see if we can simplify in
  // other ways.

  // Check to see if all of the leading entries are now opcode checks.  If so,
  // we can convert this Scope to be a OpcodeSwitch instead.
  bool AllOpcodeChecks = true;
  for (unsigned i = 0, e = NewOptionsToMatch.size(); i != e; ++i) {
    if (isa<CheckOpcodeMatcher>(NewOptionsToMatch[i])) continue;

#if 0
    if (i > 3) {
      errs() << "FAILING OPC #" << i << "\n";
      NewOptionsToMatch[i]->dump();
    }
#endif

    AllOpcodeChecks = false;
    break;
  }

  // If all the options are CheckOpcode's, we can form the SwitchOpcode, woot.
  if (AllOpcodeChecks) {
    StringSet<> Opcodes;
    SmallVector<std::pair<const SDNodeInfo*, Matcher*>, 8> Cases;
    for (unsigned i = 0, e = NewOptionsToMatch.size(); i != e; ++i) {
      CheckOpcodeMatcher *COM =cast<CheckOpcodeMatcher>(NewOptionsToMatch[i]);
      assert(Opcodes.insert(COM->getOpcode().getEnumName()) &&
             "Duplicate opcodes not factored?");
      Cases.push_back(std::make_pair(&COM->getOpcode(), COM->getNext()));
    }

    MatcherPtr.reset(new SwitchOpcodeMatcher(&Cases[0], Cases.size()));
    return;
  }

  // Reassemble a new Scope node.
  assert(!NewOptionsToMatch.empty() &&
         "Where'd all our children go?  Did we really factor everything??");
  if (NewOptionsToMatch.empty())
    MatcherPtr.reset(0);
  else {
    Scope->setNumChildren(NewOptionsToMatch.size());
    for (unsigned i = 0, e = NewOptionsToMatch.size(); i != e; ++i)
      Scope->resetChild(i, NewOptionsToMatch[i]);
  }
}

Matcher *llvm::OptimizeMatcher(Matcher *TheMatcher,
                               const CodeGenDAGPatterns &CGP) {
  OwningPtr<Matcher> MatcherPtr(TheMatcher);
  ContractNodes(MatcherPtr, CGP);
  SinkPatternPredicates(MatcherPtr);
  FactorNodes(MatcherPtr);
  return MatcherPtr.take();
}
<commit_msg>remove dead code, simplify.<commit_after>//===- DAGISelMatcherOpt.cpp - Optimize a DAG Matcher ---------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the DAG Matcher optimizer.
//
//===----------------------------------------------------------------------===//

#define DEBUG_TYPE "isel-opt"
#include "DAGISelMatcher.h"
#include "CodeGenDAGPatterns.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/StringSet.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include <vector>
using namespace llvm;

/// ContractNodes - Turn multiple matcher node patterns like 'MoveChild+Record'
/// into single compound nodes like RecordChild.
static void ContractNodes(OwningPtr<Matcher> &MatcherPtr,
                          const CodeGenDAGPatterns &CGP) {
  // If we reached the end of the chain, we're done.
  Matcher *N = MatcherPtr.get();
  if (N == 0) return;

  // If we have a scope node, walk down all of the children.
  if (ScopeMatcher *Scope = dyn_cast<ScopeMatcher>(N)) {
    for (unsigned i = 0, e = Scope->getNumChildren(); i != e; ++i) {
      OwningPtr<Matcher> Child(Scope->takeChild(i));
      ContractNodes(Child, CGP);
      Scope->resetChild(i, Child.take());
    }
    return;
  }

  // If we found a movechild node with a node that comes in a 'foochild' form,
  // transform it.
  if (MoveChildMatcher *MC = dyn_cast<MoveChildMatcher>(N)) {
    Matcher *New = 0;
    if (RecordMatcher *RM = dyn_cast<RecordMatcher>(MC->getNext()))
      New = new RecordChildMatcher(MC->getChildNo(), RM->getWhatFor(),
                                   RM->getResultNo());

    if (CheckTypeMatcher *CT= dyn_cast<CheckTypeMatcher>(MC->getNext()))
      New = new CheckChildTypeMatcher(MC->getChildNo(), CT->getType());

    if (New) {
      // Insert the new node.
      New->setNext(MatcherPtr.take());
      MatcherPtr.reset(New);
      // Remove the old one.
      MC->setNext(MC->getNext()->takeNext());
      return ContractNodes(MatcherPtr, CGP);
    }
  }

  // Zap movechild -> moveparent.
  if (MoveChildMatcher *MC = dyn_cast<MoveChildMatcher>(N))
    if (MoveParentMatcher *MP =
          dyn_cast<MoveParentMatcher>(MC->getNext())) {
      MatcherPtr.reset(MP->takeNext());
      return ContractNodes(MatcherPtr, CGP);
    }

  // Turn EmitNode->MarkFlagResults->CompleteMatch into
  // MarkFlagResults->EmitNode->CompleteMatch when we can to encourage
  // MorphNodeTo formation.  This is safe because MarkFlagResults never refers
  // to the root of the pattern.
  if (isa<EmitNodeMatcher>(N) && isa<MarkFlagResultsMatcher>(N->getNext()) &&
      isa<CompleteMatchMatcher>(N->getNext()->getNext())) {
    // Unlink the two nodes from the list.
    Matcher *EmitNode = MatcherPtr.take();
    Matcher *MFR = EmitNode->takeNext();
    Matcher *Tail = MFR->takeNext();

    // Relink them.
    MatcherPtr.reset(MFR);
    MFR->setNext(EmitNode);
    EmitNode->setNext(Tail);
    return ContractNodes(MatcherPtr, CGP);
  }

  // Turn EmitNode->CompleteMatch into MorphNodeTo if we can.
  if (EmitNodeMatcher *EN = dyn_cast<EmitNodeMatcher>(N))
    if (CompleteMatchMatcher *CM =
          dyn_cast<CompleteMatchMatcher>(EN->getNext())) {
      // We can only use MorphNodeTo if the result values match up.
      unsigned RootResultFirst = EN->getFirstResultSlot();
      bool ResultsMatch = true;
      for (unsigned i = 0, e = CM->getNumResults(); i != e; ++i)
        if (CM->getResult(i) != RootResultFirst+i)
          ResultsMatch = false;

      // If the selected node defines a subset of the flag/chain results, we
      // can't use MorphNodeTo.  For example, we can't use MorphNodeTo if the
      // matched pattern has a chain but the root node doesn't.
      const PatternToMatch &Pattern = CM->getPattern();

      if (!EN->hasChain() &&
          Pattern.getSrcPattern()->NodeHasProperty(SDNPHasChain, CGP))
        ResultsMatch = false;

      // If the matched node has a flag and the output root doesn't, we can't
      // use MorphNodeTo.
      //
      // NOTE: Strictly speaking, we don't have to check for the flag here
      // because the code in the pattern generator doesn't handle it right.  We
      // do it anyway for thoroughness.
      if (!EN->hasOutFlag() &&
          Pattern.getSrcPattern()->NodeHasProperty(SDNPOutFlag, CGP))
        ResultsMatch = false;

      // If the root result node defines more results than the source root node
      // *and* has a chain or flag input, then we can't match it because it
      // would end up replacing the extra result with the chain/flag.
#if 0
      if ((EN->hasFlag() || EN->hasChain()) &&
          EN->getNumNonChainFlagVTs() > ... need to get no results reliably ...)
        ResultMatch = false;
#endif

      if (ResultsMatch) {
        const SmallVectorImpl<MVT::SimpleValueType> &VTs = EN->getVTList();
        const SmallVectorImpl<unsigned> &Operands = EN->getOperandList();
        MatcherPtr.reset(new MorphNodeToMatcher(EN->getOpcodeName(),
                                                VTs.data(), VTs.size(),
                                                Operands.data(),Operands.size(),
                                                EN->hasChain(), EN->hasInFlag(),
                                                EN->hasOutFlag(),
                                                EN->hasMemRefs(),
                                                EN->getNumFixedArityOperands(),
                                                Pattern));
        return;
      }

      // FIXME2: Kill off all the SelectionDAG::MorphNodeTo and getMachineNode
      // variants.
    }

  ContractNodes(N->getNextPtr(), CGP);

  // If we have a CheckType/CheckChildType/Record node followed by a
  // CheckOpcode, invert the two nodes.  We prefer to do structural checks
  // before type checks, as this opens opportunities for factoring on targets
  // like X86 where many operations are valid on multiple types.
  if ((isa<CheckTypeMatcher>(N) || isa<CheckChildTypeMatcher>(N) ||
       isa<RecordMatcher>(N)) &&
      isa<CheckOpcodeMatcher>(N->getNext())) {
    // Unlink the two nodes from the list.
    Matcher *CheckType = MatcherPtr.take();
    Matcher *CheckOpcode = CheckType->takeNext();
    Matcher *Tail = CheckOpcode->takeNext();

    // Relink them.
    MatcherPtr.reset(CheckOpcode);
    CheckOpcode->setNext(CheckType);
    CheckType->setNext(Tail);
    return ContractNodes(MatcherPtr, CGP);
  }
}

/// SinkPatternPredicates - Pattern predicates can be checked at any level of
/// the matching tree.  The generator dumps them at the top level of the pattern
/// though, which prevents factoring from being able to see past them.  This
/// optimization sinks them as far down into the pattern as possible.
///
/// Conceptually, we'd like to sink these predicates all the way to the last
/// matcher predicate in the series.  However, it turns out that some
/// ComplexPatterns have side effects on the graph, so we really don't want to
/// run a the complex pattern if the pattern predicate will fail.  For this
/// reason, we refuse to sink the pattern predicate past a ComplexPattern.
///
static void SinkPatternPredicates(OwningPtr<Matcher> &MatcherPtr) {
  // Recursively scan for a PatternPredicate.
  // If we reached the end of the chain, we're done.
  Matcher *N = MatcherPtr.get();
  if (N == 0) return;

  // Walk down all members of a scope node.
  if (ScopeMatcher *Scope = dyn_cast<ScopeMatcher>(N)) {
    for (unsigned i = 0, e = Scope->getNumChildren(); i != e; ++i) {
      OwningPtr<Matcher> Child(Scope->takeChild(i));
      SinkPatternPredicates(Child);
      Scope->resetChild(i, Child.take());
    }
    return;
  }

  // If this node isn't a CheckPatternPredicateMatcher we keep scanning until
  // we find one.
  CheckPatternPredicateMatcher *CPPM =dyn_cast<CheckPatternPredicateMatcher>(N);
  if (CPPM == 0)
    return SinkPatternPredicates(N->getNextPtr());

  // Ok, we found one, lets try to sink it. Check if we can sink it past the
  // next node in the chain.  If not, we won't be able to change anything and
  // might as well bail.
  if (!CPPM->getNext()->isSafeToReorderWithPatternPredicate())
    return;

  // Okay, we know we can sink it past at least one node.  Unlink it from the
  // chain and scan for the new insertion point.
  MatcherPtr.take();  // Don't delete CPPM.
  MatcherPtr.reset(CPPM->takeNext());

  N = MatcherPtr.get();
  while (N->getNext()->isSafeToReorderWithPatternPredicate())
    N = N->getNext();

  // At this point, we want to insert CPPM after N.
  CPPM->setNext(N->takeNext());
  N->setNext(CPPM);
}

/// FactorNodes - Turn matches like this:
///   Scope
///     OPC_CheckType i32
///       ABC
///     OPC_CheckType i32
///       XYZ
/// into:
///   OPC_CheckType i32
///     Scope
///       ABC
///       XYZ
///
static void FactorNodes(OwningPtr<Matcher> &MatcherPtr) {
  // If we reached the end of the chain, we're done.
  Matcher *N = MatcherPtr.get();
  if (N == 0) return;

  // If this is not a push node, just scan for one.
  ScopeMatcher *Scope = dyn_cast<ScopeMatcher>(N);
  if (Scope == 0)
    return FactorNodes(N->getNextPtr());

  // Okay, pull together the children of the scope node into a vector so we can
  // inspect it more easily.  While we're at it, bucket them up by the hash
  // code of their first predicate.
  SmallVector<Matcher*, 32> OptionsToMatch;

  for (unsigned i = 0, e = Scope->getNumChildren(); i != e; ++i) {
    // Factor the subexpression.
    OwningPtr<Matcher> Child(Scope->takeChild(i));
    FactorNodes(Child);

    if (Matcher *N = Child.take())
      OptionsToMatch.push_back(N);
  }

  SmallVector<Matcher*, 32> NewOptionsToMatch;

  // Loop over options to match, merging neighboring patterns with identical
  // starting nodes into a shared matcher.
  for (unsigned OptionIdx = 0, e = OptionsToMatch.size(); OptionIdx != e;) {
    // Find the set of matchers that start with this node.
    Matcher *Optn = OptionsToMatch[OptionIdx++];

    if (OptionIdx == e) {
      NewOptionsToMatch.push_back(Optn);
      continue;
    }

    // See if the next option starts with the same matcher.  If the two
    // neighbors *do* start with the same matcher, we can factor the matcher out
    // of at least these two patterns.  See what the maximal set we can merge
    // together is.
    SmallVector<Matcher*, 8> EqualMatchers;
    EqualMatchers.push_back(Optn);

    // Factor all of the known-equal matchers after this one into the same
    // group.
    while (OptionIdx != e && OptionsToMatch[OptionIdx]->isEqual(Optn))
      EqualMatchers.push_back(OptionsToMatch[OptionIdx++]);

    // If we found a non-equal matcher, see if it is contradictory with the
    // current node.  If so, we know that the ordering relation between the
    // current sets of nodes and this node don't matter.  Look past it to see if
    // we can merge anything else into this matching group.
    unsigned Scan = OptionIdx;
    while (1) {
      while (Scan != e && Optn->isContradictory(OptionsToMatch[Scan]))
        ++Scan;

      // Ok, we found something that isn't known to be contradictory.  If it is
      // equal, we can merge it into the set of nodes to factor, if not, we have
      // to cease factoring.
      if (Scan == e || !Optn->isEqual(OptionsToMatch[Scan])) break;

      // If is equal after all, add the option to EqualMatchers and remove it
      // from OptionsToMatch.
      EqualMatchers.push_back(OptionsToMatch[Scan]);
      OptionsToMatch.erase(OptionsToMatch.begin()+Scan);
      --e;
    }

    if (Scan != e &&
        // Don't print it's obvious nothing extra could be merged anyway.
        Scan+1 != e) {
      DEBUG(errs() << "Couldn't merge this:\n";
            Optn->print(errs(), 4);
            errs() << "into this:\n";
            OptionsToMatch[Scan]->print(errs(), 4);
            if (Scan+1 != e)
              OptionsToMatch[Scan+1]->printOne(errs());
            if (Scan+2 < e)
              OptionsToMatch[Scan+2]->printOne(errs());
            errs() << "\n");
    }

    // If we only found one option starting with this matcher, no factoring is
    // possible.
    if (EqualMatchers.size() == 1) {
      NewOptionsToMatch.push_back(EqualMatchers[0]);
      continue;
    }

    // Factor these checks by pulling the first node off each entry and
    // discarding it.  Take the first one off the first entry to reuse.
    Matcher *Shared = Optn;
    Optn = Optn->takeNext();
    EqualMatchers[0] = Optn;

    // Remove and delete the first node from the other matchers we're factoring.
    for (unsigned i = 1, e = EqualMatchers.size(); i != e; ++i) {
      Matcher *Tmp = EqualMatchers[i]->takeNext();
      delete EqualMatchers[i];
      EqualMatchers[i] = Tmp;
    }

    Shared->setNext(new ScopeMatcher(&EqualMatchers[0], EqualMatchers.size()));

    // Recursively factor the newly created node.
    FactorNodes(Shared->getNextPtr());

    NewOptionsToMatch.push_back(Shared);
  }

  // If we're down to a single pattern to match, then we don't need this scope
  // anymore.
  if (NewOptionsToMatch.size() == 1) {
    MatcherPtr.reset(NewOptionsToMatch[0]);
    return;
  }

  if (NewOptionsToMatch.empty()) {
    MatcherPtr.reset(0);
    return;
  }

  // If our factoring failed (didn't achieve anything) see if we can simplify in
  // other ways.

  // Check to see if all of the leading entries are now opcode checks.  If so,
  // we can convert this Scope to be a OpcodeSwitch instead.
  bool AllOpcodeChecks = true;
  for (unsigned i = 0, e = NewOptionsToMatch.size(); i != e; ++i) {
    if (isa<CheckOpcodeMatcher>(NewOptionsToMatch[i])) continue;

#if 0
    if (i > 3) {
      errs() << "FAILING OPC #" << i << "\n";
      NewOptionsToMatch[i]->dump();
    }
#endif

    AllOpcodeChecks = false;
    break;
  }

  // If all the options are CheckOpcode's, we can form the SwitchOpcode, woot.
  if (AllOpcodeChecks) {
    StringSet<> Opcodes;
    SmallVector<std::pair<const SDNodeInfo*, Matcher*>, 8> Cases;
    for (unsigned i = 0, e = NewOptionsToMatch.size(); i != e; ++i) {
      CheckOpcodeMatcher *COM =cast<CheckOpcodeMatcher>(NewOptionsToMatch[i]);
      assert(Opcodes.insert(COM->getOpcode().getEnumName()) &&
             "Duplicate opcodes not factored?");
      Cases.push_back(std::make_pair(&COM->getOpcode(), COM->getNext()));
    }

    MatcherPtr.reset(new SwitchOpcodeMatcher(&Cases[0], Cases.size()));
    return;
  }

  // Reassemble the Scope node with the adjusted children.
  Scope->setNumChildren(NewOptionsToMatch.size());
  for (unsigned i = 0, e = NewOptionsToMatch.size(); i != e; ++i)
    Scope->resetChild(i, NewOptionsToMatch[i]);
}

Matcher *llvm::OptimizeMatcher(Matcher *TheMatcher,
                               const CodeGenDAGPatterns &CGP) {
  OwningPtr<Matcher> MatcherPtr(TheMatcher);
  ContractNodes(MatcherPtr, CGP);
  SinkPatternPredicates(MatcherPtr);
  FactorNodes(MatcherPtr);
  return MatcherPtr.take();
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: gtkframe.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: hr $ $Date: 2004-10-13 08:58:36 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _VCL_GTKFRAME_HXX
#define _VCL_GTKFRAME_HXX

#include <prex.h>
#include <gtk/gtk.h>
#include <gdk/gdk.h>
#include <gdk/gdkx.h>
#include <gdk/gdkkeysyms.h>
#include <postx.h>

#ifndef _SV_SALFRAME_HXX
#include <salframe.hxx>
#endif
#ifndef _SV_SYSDATA_HXX
#include <sysdata.hxx>
#endif

class X11SalGraphics;
class GtkSalDisplay;

class GtkSalFrame : public SalFrame
{
    static const int nMaxGraphics = 2;

    struct GraphicsHolder
    {
        X11SalGraphics*     pGraphics;
        bool                bInUse;
        GraphicsHolder()
                : pGraphics( NULL ),
                  bInUse( false )
        {}
        ~GraphicsHolder();
    };

    GtkWindow*              m_pWindow;
    GdkWindow*              m_pForeignParent;
    GdkWindow*              m_pForeignTopLevel;
    ULONG                   m_nStyle;
    GtkFixed*               m_pFixedContainer;
    GtkSalFrame*            m_pParent;
    GdkWindowState          m_nState;
    GtkIMContext*           m_pIMContext;
    SystemEnvData           m_aSystemData;
    GraphicsHolder          m_aGraphics[ nMaxGraphics ];
    USHORT                  m_nKeyModifiers;
    GdkCursor              *m_pCurrentCursor;
    GdkVisibilityState      m_nVisibility;
    int                     m_nSavedScreenSaverTimeout;
    bool                    m_bResizeable;
    bool                    m_bSingleAltPress;
    bool                    m_bDefaultPos;
    bool                    m_bDefaultSize;
    bool                    m_bSendModChangeOnRelease;
    bool                    m_bWasPreedit;

    Size                    m_aMaxSize;
    Size                    m_aMinSize;

    GdkEventKey             m_aLastKeyPress;

    void Init( SalFrame* pParent, ULONG nStyle );
    void Init( SystemParentData* pSysData );
    void InitCommon();

    // signals
    static gboolean     signalButton( GtkWidget*, GdkEventButton*, gpointer );
    static void         signalStyleSet( GtkWidget*, GtkStyle* pPrevious, gpointer );
    static gboolean     signalExpose( GtkWidget*, GdkEventExpose*, gpointer );
    static gboolean     signalFocus( GtkWidget*, GdkEventFocus*, gpointer );
    static gboolean     signalMap( GtkWidget*, GdkEvent*, gpointer );
    static gboolean     signalUnmap( GtkWidget*, GdkEvent*, gpointer );
    static gboolean     signalConfigure( GtkWidget*, GdkEventConfigure*, gpointer );
    static gboolean     signalMotion( GtkWidget*, GdkEventMotion*, gpointer );
    static gboolean     signalKey( GtkWidget*, GdkEventKey*, gpointer );
    static gboolean     signalDelete( GtkWidget*, GdkEvent*, gpointer );
    static gboolean     signalState( GtkWidget*, GdkEvent*, gpointer );
    static gboolean     signalScroll( GtkWidget*, GdkEvent*, gpointer );
    static gboolean     signalCrossing( GtkWidget*, GdkEventCrossing*, gpointer );
    static gboolean     signalVisibility( GtkWidget*, GdkEventVisibility*, gpointer );
    static void         signalIMCommit( GtkIMContext*, gchar*, gpointer );
    static gboolean     signalIMDeleteSurrounding( GtkIMContext*, gint, gint, gpointer );
    static void         signalIMPreeditChanged( GtkIMContext*, gpointer );
    static void         signalIMPreeditEnd( GtkIMContext*, gpointer );
    static void         signalIMPreeditStart( GtkIMContext*, gpointer );
    static gboolean     signalIMRetrieveSurrounding( GtkIMContext*, gpointer );
    static void         signalDestroy( GtkObject*, gpointer );

    GtkSalDisplay*  getDisplay();
    GdkDisplay*     getGdkDisplay();
    void            Center();
    void            SetDefaultSize();
    void            setAutoLock( bool bLock );
    void            setScreenSaverTimeout( int nTimeout );

    GdkNativeWindow findTopLevelSystemWindow( GdkNativeWindow aWindow );

    static int m_nFloats;

    bool isFloatGrabWindow() const
    {
        return
            (m_nStyle & SAL_FRAME_STYLE_FLOAT) &&       // only a float can be floatgrab
            !(m_nStyle & SAL_FRAME_STYLE_TOOLTIP) &&    // tool tips are not
            !(m_nStyle & SAL_FRAME_STYLE_OWNERDRAWDECORATION); // toolbars are also not
    }

    Size calcDefaultSize();

    void setMinMaxSize();
public:
    GtkSalFrame( SalFrame* pParent, ULONG nStyle );
    GtkSalFrame( SystemParentData* pSysData );

    // dispatches an event, returns true if dispatched
    // and false else; if true was returned the event should
    // be swallowed
    bool Dispatch( const XEvent* pEvent );
    void grabPointer( BOOL bGrab, BOOL bOwnerEvents = FALSE );

    GtkWindow*  getWindow() const { return m_pWindow; }
    GtkFixed*   getFixedContainer() const { return m_pFixedContainer; }
    GdkWindow*  getForeignParent() const { return m_pForeignParent; }
    GdkWindow*  getForeignTopLevel() const { return m_pForeignTopLevel; }
    GdkVisibilityState getVisibilityState() const
    { return m_nVisibility; }

    virtual ~GtkSalFrame();

    // SalGraphics or NULL, but two Graphics for all SalFrames
    // must be returned
    virtual SalGraphics*        GetGraphics();
    virtual void                ReleaseGraphics( SalGraphics* pGraphics );

    // Event must be destroyed, when Frame is destroyed
    // When Event is called, SalInstance::Yield() must be returned
    virtual BOOL                PostEvent( void* pData );

    virtual void                SetTitle( const XubString& rTitle );
    virtual void                SetIcon( USHORT nIcon );
    virtual void              SetMenu( SalMenu *pSalMenu );
    virtual void              DrawMenuBar();

    // Before the window is visible, a resize event
    // must be sent with the correct size
    virtual void                Show( BOOL bVisible, BOOL bNoActivate = FALSE );
    virtual void                Enable( BOOL bEnable );
    // Set ClientSize and Center the Window to the desktop
    // and send/post a resize message
    virtual void              SetMinClientSize( long nWidth, long nHeight );
    virtual void              SetMaxClientSize( long nWidth, long nHeight );
    virtual void                SetPosSize( long nX, long nY, long nWidth, long nHeight, USHORT nFlags );
    virtual void                GetClientSize( long& rWidth, long& rHeight );
    virtual void                GetWorkArea( Rectangle& rRect );
    virtual SalFrame*           GetParent() const;
    virtual void                SetWindowState( const SalFrameState* pState );
    virtual BOOL                GetWindowState( SalFrameState* pState );
    virtual void                ShowFullScreen( BOOL bFullScreen );
    // Enable/Disable ScreenSaver, SystemAgents, ...
    virtual void                StartPresentation( BOOL bStart );
    // Show Window over all other Windows
    virtual void                SetAlwaysOnTop( BOOL bOnTop );

    // Window to top and grab focus
    virtual void                ToTop( USHORT nFlags );

    // this function can call with the same
    // pointer style
    virtual void                SetPointer( PointerStyle ePointerStyle );
    virtual void                CaptureMouse( BOOL bMouse );
    virtual void                SetPointerPos( long nX, long nY );

    // flush output buffer
    virtual void                Flush();
    // flush output buffer, wait till outstanding operations are done
    virtual void                Sync();

    virtual void                SetInputContext( SalInputContext* pContext );
    virtual void                EndExtTextInput( USHORT nFlags );

    virtual String              GetKeyName( USHORT nKeyCode );
    virtual String              GetSymbolKeyName( const XubString& rFontName, USHORT nKeyCode );

    // returns the input language used for the last key stroke
    // may be LANGUAGE_DONTKNOW if not supported by the OS
    virtual LanguageType        GetInputLanguage();

    virtual SalBitmap*          SnapShot();

    virtual void                UpdateSettings( AllSettings& rSettings );

    virtual void                Beep( SoundType eSoundType );

    // returns system data (most prominent: window handle)
    virtual const SystemEnvData*    GetSystemData() const;

    // get current modifier and button mask
    virtual SalPointerState     GetPointerState();

    // set new parent window
    virtual void                SetParent( SalFrame* pNewParent );
    // reparent window to act as a plugin; implementation
    // may choose to use a new system window internally
    // return false to indicate failure
    virtual bool                SetPluginParent( SystemParentData* pNewParent );

};

#endif //_VCL_GTKFRAME_HXX
<commit_msg>INTEGRATION: CWS vcl28 (1.5.14); FILE MERGED 2004/10/07 10:18:34 pl 1.5.14.4: #i35073# better key release swallow mechanism 2004/10/01 14:48:30 pl 1.5.14.3: #i34880# IM patch 2004/09/30 14:14:46 pl 1.5.14.2: #i34504# don't set max size hint and fullscreen hint at the same time 2004/09/30 11:07:59 pl 1.5.14.1: join from vcl27<commit_after>/*************************************************************************
 *
 *  $RCSfile: gtkframe.hxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: hr $ $Date: 2004-11-09 17:35:08 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _VCL_GTKFRAME_HXX
#define _VCL_GTKFRAME_HXX

#include <prex.h>
#include <gtk/gtk.h>
#include <gdk/gdk.h>
#include <gdk/gdkx.h>
#include <gdk/gdkkeysyms.h>
#include <postx.h>

#ifndef _SV_SALFRAME_HXX
#include <salframe.hxx>
#endif
#ifndef _SV_SYSDATA_HXX
#include <sysdata.hxx>
#endif

#include <list>

class X11SalGraphics;
class GtkSalDisplay;

class GtkSalFrame : public SalFrame
{
    static const int nMaxGraphics = 2;

    struct GraphicsHolder
    {
        X11SalGraphics*     pGraphics;
        bool                bInUse;
        GraphicsHolder()
                : pGraphics( NULL ),
                  bInUse( false )
        {}
        ~GraphicsHolder();
    };

    //--------------------------------------------------------
    // Not all GTK Input Methods swallow key release
    // events.  Since they swallow the key press events and we
    // are left with the key release events, we need to
    // manually swallow those.  To do this, we keep a list of
    // the previous 10 key press events in each GtkSalFrame
    // and when we get a key release that matches one of the
    // key press events in our list, we swallow it.
    struct PreviousKeyPress
    {
        GdkWindow *window;
        gint8   send_event;
        guint32 time;
        guint   state;
        guint   keyval;

        PreviousKeyPress (GdkEventKey *event)
        :   window (NULL),
            send_event (0),
            time (0),
            state (0),
            keyval (0)
        {
            if (event)
            {
                window = event->window;
                send_event = event->send_event;
                time = event->time;
                state = event->state;
                keyval = event->keyval;
            }
        }

        PreviousKeyPress( const PreviousKeyPress& rPrev )
        :   window( rPrev.window ),
            send_event( rPrev.send_event ),
            time( rPrev.time ),
            state( rPrev.state ),
            keyval( rPrev.keyval )
        {}

        bool PreviousKeyPress::operator== (GdkEventKey *event) const
        {
            return (event != NULL)
                && (event->window == window)
                && (event->send_event == send_event)
                && (event->state == state)
                && (event->keyval == keyval)
                && (event->time - time < 3)
                ;
        }
    };

    GtkWindow*                      m_pWindow;
    GdkWindow*                      m_pForeignParent;
    GdkWindow*                      m_pForeignTopLevel;
    ULONG                           m_nStyle;
    GtkFixed*                       m_pFixedContainer;
    GtkSalFrame*                    m_pParent;
    GdkWindowState                  m_nState;
    GtkIMContext*                   m_pIMContext;
    SystemEnvData                   m_aSystemData;
    GraphicsHolder                  m_aGraphics[ nMaxGraphics ];
    USHORT                          m_nKeyModifiers;
    GdkCursor                      *m_pCurrentCursor;
    GdkVisibilityState              m_nVisibility;
    int                             m_nSavedScreenSaverTimeout;
    bool                            m_bResizeable;
    bool                            m_bFullscreen;
    bool                            m_bSingleAltPress;
    bool                            m_bDefaultPos;
    bool                            m_bDefaultSize;
    bool                            m_bSendModChangeOnRelease;
    bool                            m_bWasPreedit;

    Size                            m_aMaxSize;
    Size                            m_aMinSize;

    std::list< PreviousKeyPress >   m_aPrevKeyPresses;
    int                             m_nPrevKeyPresses; // avoid using size()

    void Init( SalFrame* pParent, ULONG nStyle );
    void Init( SystemParentData* pSysData );
    void InitCommon();

    // signals
    static gboolean     signalButton( GtkWidget*, GdkEventButton*, gpointer );
    static void         signalStyleSet( GtkWidget*, GtkStyle* pPrevious, gpointer );
    static gboolean     signalExpose( GtkWidget*, GdkEventExpose*, gpointer );
    static gboolean     signalFocus( GtkWidget*, GdkEventFocus*, gpointer );
    static gboolean     signalMap( GtkWidget*, GdkEvent*, gpointer );
    static gboolean     signalUnmap( GtkWidget*, GdkEvent*, gpointer );
    static gboolean     signalConfigure( GtkWidget*, GdkEventConfigure*, gpointer );
    static gboolean     signalMotion( GtkWidget*, GdkEventMotion*, gpointer );
    static gboolean     signalKey( GtkWidget*, GdkEventKey*, gpointer );
    static gboolean     signalDelete( GtkWidget*, GdkEvent*, gpointer );
    static gboolean     signalState( GtkWidget*, GdkEvent*, gpointer );
    static gboolean     signalScroll( GtkWidget*, GdkEvent*, gpointer );
    static gboolean     signalCrossing( GtkWidget*, GdkEventCrossing*, gpointer );
    static gboolean     signalVisibility( GtkWidget*, GdkEventVisibility*, gpointer );
    static void         signalIMCommit( GtkIMContext*, gchar*, gpointer );
    static gboolean     signalIMDeleteSurrounding( GtkIMContext*, gint, gint, gpointer );
    static void         signalIMPreeditChanged( GtkIMContext*, gpointer );
    static void         signalIMPreeditEnd( GtkIMContext*, gpointer );
    static void         signalIMPreeditStart( GtkIMContext*, gpointer );
    static gboolean     signalIMRetrieveSurrounding( GtkIMContext*, gpointer );
    static void         signalDestroy( GtkObject*, gpointer );

    GtkSalDisplay*  getDisplay();
    GdkDisplay*     getGdkDisplay();
    void            Center();
    void            SetDefaultSize();
    void            setAutoLock( bool bLock );
    void            setScreenSaverTimeout( int nTimeout );

    GdkNativeWindow findTopLevelSystemWindow( GdkNativeWindow aWindow );

    static int m_nFloats;

    bool isFloatGrabWindow() const
    {
        return
            (m_nStyle & SAL_FRAME_STYLE_FLOAT) &&       // only a float can be floatgrab
            !(m_nStyle & SAL_FRAME_STYLE_TOOLTIP) &&    // tool tips are not
            !(m_nStyle & SAL_FRAME_STYLE_OWNERDRAWDECORATION); // toolbars are also not
    }

    Size calcDefaultSize();

    void setMinMaxSize();
    void updateIMSpotLocation();
public:
    GtkSalFrame( SalFrame* pParent, ULONG nStyle );
    GtkSalFrame( SystemParentData* pSysData );

    // dispatches an event, returns true if dispatched
    // and false else; if true was returned the event should
    // be swallowed
    bool Dispatch( const XEvent* pEvent );
    void grabPointer( BOOL bGrab, BOOL bOwnerEvents = FALSE );

    GtkWindow*  getWindow() const { return m_pWindow; }
    GtkFixed*   getFixedContainer() const { return m_pFixedContainer; }
    GdkWindow*  getForeignParent() const { return m_pForeignParent; }
    GdkWindow*  getForeignTopLevel() const { return m_pForeignTopLevel; }
    GdkVisibilityState getVisibilityState() const
    { return m_nVisibility; }

    virtual ~GtkSalFrame();

    // SalGraphics or NULL, but two Graphics for all SalFrames
    // must be returned
    virtual SalGraphics*        GetGraphics();
    virtual void                ReleaseGraphics( SalGraphics* pGraphics );

    // Event must be destroyed, when Frame is destroyed
    // When Event is called, SalInstance::Yield() must be returned
    virtual BOOL                PostEvent( void* pData );

    virtual void                SetTitle( const XubString& rTitle );
    virtual void                SetIcon( USHORT nIcon );
    virtual void                SetMenu( SalMenu *pSalMenu );
    virtual void                DrawMenuBar();

    // Before the window is visible, a resize event
    // must be sent with the correct size
    virtual void                Show( BOOL bVisible, BOOL bNoActivate = FALSE );
    virtual void                Enable( BOOL bEnable );
    // Set ClientSize and Center the Window to the desktop
    // and send/post a resize message
    virtual void                SetMinClientSize( long nWidth, long nHeight );
    virtual void                SetMaxClientSize( long nWidth, long nHeight );
    virtual void                SetPosSize( long nX, long nY, long nWidth, long nHeight, USHORT nFlags );
    virtual void                GetClientSize( long& rWidth, long& rHeight );
    virtual void                GetWorkArea( Rectangle& rRect );
    virtual SalFrame*           GetParent() const;
    virtual void                SetWindowState( const SalFrameState* pState );
    virtual BOOL                GetWindowState( SalFrameState* pState );
    virtual void                ShowFullScreen( BOOL bFullScreen );
    // Enable/Disable ScreenSaver, SystemAgents, ...
    virtual void                StartPresentation( BOOL bStart );
    // Show Window over all other Windows
    virtual void                SetAlwaysOnTop( BOOL bOnTop );

    // Window to top and grab focus
    virtual void                ToTop( USHORT nFlags );

    // this function can call with the same
    // pointer style
    virtual void                SetPointer( PointerStyle ePointerStyle );
    virtual void                CaptureMouse( BOOL bMouse );
    virtual void                SetPointerPos( long nX, long nY );

    // flush output buffer
    virtual void                Flush();
    // flush output buffer, wait till outstanding operations are done
    virtual void                Sync();

    virtual void                SetInputContext( SalInputContext* pContext );
    virtual void                EndExtTextInput( USHORT nFlags );

    virtual String              GetKeyName( USHORT nKeyCode );
    virtual String              GetSymbolKeyName( const XubString& rFontName, USHORT nKeyCode );

    // returns the input language used for the last key stroke
    // may be LANGUAGE_DONTKNOW if not supported by the OS
    virtual LanguageType        GetInputLanguage();

    virtual SalBitmap*          SnapShot();

    virtual void                UpdateSettings( AllSettings& rSettings );

    virtual void                Beep( SoundType eSoundType );

    // returns system data (most prominent: window handle)
    virtual const SystemEnvData*    GetSystemData() const;

    // get current modifier and button mask
    virtual SalPointerState     GetPointerState();

    // set new parent window
    virtual void                SetParent( SalFrame* pNewParent );
    // reparent window to act as a plugin; implementation
    // may choose to use a new system window internally
    // return false to indicate failure
    virtual bool                SetPluginParent( SystemParentData* pNewParent );

};

#endif //_VCL_GTKFRAME_HXX
<|endoftext|>


<commit_before>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
// $Id: amiraMeshFile.C
//

#include <BALL/FORMAT/amiraMeshFile.h>
#include <cstdio>

namespace BALL
{
	AmiraMeshFile::AmiraMeshFile()
		: File(),
			binary_(false),
			idx_start_data_(0),
			num_components_(0)
	{
	}

	AmiraMeshFile::AmiraMeshFile(const String& name, File::OpenMode open_mode)
		: File(name, open_mode),
			binary_(false),
			idx_start_data_(0),
			num_components_(0)
	{
	}

	AmiraMeshFile::~AmiraMeshFile()
	{
		close();
		clear();
	}

	void AmiraMeshFile::clear()
	{
		File::clear();
		binary_= false;
		idx_start_data_ = 0;
		num_components_ = 0;
	}

	bool AmiraMeshFile::operator == (const AmiraMeshFile& file) const
	{
		return (   (File::operator == (file))
						 &&(binary_    == file.binary_));
	}

	bool AmiraMeshFile::open(const String& name, File::OpenMode open_mode)
	{
		if (!(open_mode |= std::ios::binary))
		{
			open_mode = open_mode | std::ios::binary;
		}

		if (!File::open(name, open_mode))
		{
			return(false);
		}

		return true;
	}

	bool AmiraMeshFile::readHeader()
	{
    const size_t MAX_READ_SIZE = 2048;
		//We read the first 2k bytes into memory to parse the header.
    //The fixed buffer size looks a bit like a hack, and it is one, but it gets the job done.
    char buffer[MAX_READ_SIZE];

    std::fstream::read(buffer, MAX_READ_SIZE);
    buffer[std::fstream::gcount()] = '\0'; //The following string routines prefer null-terminated strings

    if (strstr(buffer, "# AmiraMesh BINARY-LITTLE-ENDIAN 2.1"))
    {
        binary_ = true;
    }
    else if (strstr(buffer, "# AmiraMesh ASCII 1.0"))
    {
        binary_ = false;
    }
    else
    {
        return false;
    }

		sscanf(findAndJump_(buffer, "define Lattice"), "%g %g %g", &extent_.x, &extent_.y, &extent_.z);

    sscanf(findAndJump_(buffer, "BoundingBox"), "%g %g %g %g %g %g", &min_.x, &max_.x,
																																		&min_.y, &max_.y,
																																		&min_.z, &max_.z);

    //Is it a uniform grid? We need this only for the sanity check below.
    const bool bIsUniform = (strstr(buffer, "CoordType \"uniform\"") != NULL);

    //Type of the field: scalar, vector
    num_components_ = 0;
    if (strstr(buffer, "Lattice { float Data }"))
    {
        //Scalar field
        num_components_ = 1;
    }
    else
    {
        //A field with more than one component, i.e., a vector field
        sscanf(findAndJump_(buffer, "Lattice { float["), "%u", &num_components_);

        Log.error() << "Sorry, currently, we do not support Amira files containing" << std::endl;
        Log.error() << "multiple component fields (e.g. vector fields)\n" << std::endl;
				return false;
    }

    //Sanity check
    if (extent_.x <= 0 || extent_.y <= 0 || extent_.z <= 0
        || min_.x > max_.x || min_.y > max_.y || min_.z > max_.z
        || !bIsUniform || num_components_ <= 0)
    {
        Log.error() << "Something went wrong\n" << std::endl;
        return false;
    }

		idx_start_data_ = strstr(buffer, "@1") - buffer;

		return true;
	}

	bool AmiraMeshFile::read(RegularData3D& map)
	{
		// first read the header
		if (!readHeader())
		{
			Log.error() << "AmiraMeshFile::read(): readHeader() failed. Aborting read." << std::endl;
			return false;
		}

		RegularData3D::IndexType size;
		size.x = (Size) extent_.x;
		size.y = (Size) extent_.y;
		size.z = (Size) extent_.z;

		map = RegularData3D(size, min_, max_);

		Size num_to_read = size.x * size.y * size.z * num_components_;

		char file_buffer[2048];

		if (idx_start_data_ > 0)
		{
			size_t idx_actual_read = 0;

			std::fstream::seekg( idx_start_data_);

			if (binary_)
			{

				//Consume this line, which is the Lattice definition
				std::fstream::getline(file_buffer, 2048);

				//Consume this line, which is an empty line
				std::fstream::getline(file_buffer, 2048);

				//Consume this line, which is "# Data section follows"
				std::fstream::getline(file_buffer, 2048);

				//Consume the next line, which is "@1"
				std::fstream::getline(file_buffer, 2048);

				//char* data = new char[(4 * 192)];
				const Size char_to_read = num_to_read * sizeof(float);

				char* data = new char[char_to_read];

				std::fstream::read(data, char_to_read);

				while (idx_actual_read < num_to_read)
				{
					map[idx_actual_read] = static_cast<float>(*(data + 4*idx_actual_read));
					idx_actual_read++;

				}

				delete [] data;
			}
			else
			{

				//Consume this line, which is the Lattice definition
				std::fstream::getline(file_buffer, 2048);

				//Consume this line, which is an empty line
				std::fstream::getline(file_buffer, 2048);

				//Consume the next line, which is "@1"
				std::fstream::getline(file_buffer, 2048);

				float a, b, c, d, e, f = 0.0;

				//while (!std::fstream::eof())
				while (idx_actual_read < num_to_read)
				{
					std::fstream::getline(file_buffer, 2048);
					sscanf(file_buffer, "%e %e %e %e %e %e", &a, &b, &c, &d, &e, &f);

					map[idx_actual_read++] = a;
					map[idx_actual_read++] = b;
					map[idx_actual_read++] = c;
					map[idx_actual_read++] = d;
					map[idx_actual_read++] = e;
					map[idx_actual_read++] = f;

				}
			}
		}
		else
		{
			Log.error() << "Error: Corrupted data section.  ";
		}
		return true;
	}

	bool AmiraMeshFile::writeHeader()
	{
		// construct a correct header array and write it.
		// TODO: implement
		return false;
	}

	bool AmiraMeshFile::write(RegularData3D& /*map*/)
	{
		// Write the content of a RegularData3D dataset to a CCP4 file.
		// TODO: implement
		return false;
	}

	const char* AmiraMeshFile::findAndJump_(const char* buffer, const char* search_string)
	{
    const char* found_loc = strstr(buffer, search_string);
    if (found_loc) return found_loc + strlen(search_string);
    return buffer;
	}
} // namespace BALL
<commit_msg>Fix a buffer overflow in AmiraMeshFile<commit_after>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
// $Id: amiraMeshFile.C
//

#include <BALL/FORMAT/amiraMeshFile.h>
#include <cstdio>

namespace BALL
{
	AmiraMeshFile::AmiraMeshFile()
		: File(),
			binary_(false),
			idx_start_data_(0),
			num_components_(0)
	{
	}

	AmiraMeshFile::AmiraMeshFile(const String& name, File::OpenMode open_mode)
		: File(name, open_mode),
			binary_(false),
			idx_start_data_(0),
			num_components_(0)
	{
	}

	AmiraMeshFile::~AmiraMeshFile()
	{
		close();
		clear();
	}

	void AmiraMeshFile::clear()
	{
		File::clear();
		binary_= false;
		idx_start_data_ = 0;
		num_components_ = 0;
	}

	bool AmiraMeshFile::operator == (const AmiraMeshFile& file) const
	{
		return (   (File::operator == (file))
						 &&(binary_    == file.binary_));
	}

	bool AmiraMeshFile::open(const String& name, File::OpenMode open_mode)
	{
		if (!(open_mode |= std::ios::binary))
		{
			open_mode = open_mode | std::ios::binary;
		}

		if (!File::open(name, open_mode))
		{
			return(false);
		}

		return true;
	}

	bool AmiraMeshFile::readHeader()
	{
    const size_t MAX_READ_SIZE = 2048;
		//We read the first 2k bytes into memory to parse the header.
    //The fixed buffer size looks a bit like a hack, and it is one, but it gets the job done.
    char buffer[MAX_READ_SIZE + 1];

    std::fstream::read(buffer, MAX_READ_SIZE);
    buffer[std::fstream::gcount()] = '\0'; //The following string routines prefer null-terminated strings

    if (strstr(buffer, "# AmiraMesh BINARY-LITTLE-ENDIAN 2.1"))
    {
        binary_ = true;
    }
    else if (strstr(buffer, "# AmiraMesh ASCII 1.0"))
    {
        binary_ = false;
    }
    else
    {
        return false;
    }

		sscanf(findAndJump_(buffer, "define Lattice"), "%g %g %g", &extent_.x, &extent_.y, &extent_.z);

    sscanf(findAndJump_(buffer, "BoundingBox"), "%g %g %g %g %g %g", &min_.x, &max_.x,
																																		&min_.y, &max_.y,
																																		&min_.z, &max_.z);

    //Is it a uniform grid? We need this only for the sanity check below.
    const bool bIsUniform = (strstr(buffer, "CoordType \"uniform\"") != NULL);

    //Type of the field: scalar, vector
    num_components_ = 0;
    if (strstr(buffer, "Lattice { float Data }"))
    {
        //Scalar field
        num_components_ = 1;
    }
    else
    {
        //A field with more than one component, i.e., a vector field
        sscanf(findAndJump_(buffer, "Lattice { float["), "%u", &num_components_);

        Log.error() << "Sorry, currently, we do not support Amira files containing" << std::endl;
        Log.error() << "multiple component fields (e.g. vector fields)\n" << std::endl;
				return false;
    }

    //Sanity check
    if (extent_.x <= 0 || extent_.y <= 0 || extent_.z <= 0
        || min_.x > max_.x || min_.y > max_.y || min_.z > max_.z
        || !bIsUniform || num_components_ <= 0)
    {
        Log.error() << "Something went wrong\n" << std::endl;
        return false;
    }

		idx_start_data_ = strstr(buffer, "@1") - buffer;

		return true;
	}

	bool AmiraMeshFile::read(RegularData3D& map)
	{
		// first read the header
		if (!readHeader())
		{
			Log.error() << "AmiraMeshFile::read(): readHeader() failed. Aborting read." << std::endl;
			return false;
		}

		RegularData3D::IndexType size;
		size.x = (Size) extent_.x;
		size.y = (Size) extent_.y;
		size.z = (Size) extent_.z;

		map = RegularData3D(size, min_, max_);

		Size num_to_read = size.x * size.y * size.z * num_components_;

		char file_buffer[2048];

		if (idx_start_data_ > 0)
		{
			size_t idx_actual_read = 0;

			std::fstream::seekg( idx_start_data_);

			if (binary_)
			{

				//Consume this line, which is the Lattice definition
				std::fstream::getline(file_buffer, 2048);

				//Consume this line, which is an empty line
				std::fstream::getline(file_buffer, 2048);

				//Consume this line, which is "# Data section follows"
				std::fstream::getline(file_buffer, 2048);

				//Consume the next line, which is "@1"
				std::fstream::getline(file_buffer, 2048);

				//char* data = new char[(4 * 192)];
				const Size char_to_read = num_to_read * sizeof(float);

				char* data = new char[char_to_read];

				std::fstream::read(data, char_to_read);

				while (idx_actual_read < num_to_read)
				{
					map[idx_actual_read] = static_cast<float>(*(data + 4*idx_actual_read));
					idx_actual_read++;

				}

				delete [] data;
			}
			else
			{

				//Consume this line, which is the Lattice definition
				std::fstream::getline(file_buffer, 2048);

				//Consume this line, which is an empty line
				std::fstream::getline(file_buffer, 2048);

				//Consume the next line, which is "@1"
				std::fstream::getline(file_buffer, 2048);

				float a, b, c, d, e, f = 0.0;

				//while (!std::fstream::eof())
				while (idx_actual_read < num_to_read)
				{
					std::fstream::getline(file_buffer, 2048);
					sscanf(file_buffer, "%e %e %e %e %e %e", &a, &b, &c, &d, &e, &f);

					map[idx_actual_read++] = a;
					map[idx_actual_read++] = b;
					map[idx_actual_read++] = c;
					map[idx_actual_read++] = d;
					map[idx_actual_read++] = e;
					map[idx_actual_read++] = f;

				}
			}
		}
		else
		{
			Log.error() << "Error: Corrupted data section.  ";
		}
		return true;
	}

	bool AmiraMeshFile::writeHeader()
	{
		// construct a correct header array and write it.
		// TODO: implement
		return false;
	}

	bool AmiraMeshFile::write(RegularData3D& /*map*/)
	{
		// Write the content of a RegularData3D dataset to a CCP4 file.
		// TODO: implement
		return false;
	}

	const char* AmiraMeshFile::findAndJump_(const char* buffer, const char* search_string)
	{
    const char* found_loc = strstr(buffer, search_string);
    if (found_loc) return found_loc + strlen(search_string);
    return buffer;
	}
} // namespace BALL
<|endoftext|>