<commit_before>//===-- AArch64CondBrTuning.cpp --- Conditional branch tuning for AArch64 -===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
/// \file
/// This file contains a pass that transforms CBZ/CBNZ/TBZ/TBNZ instructions
/// into a conditional branch (B.cond), when the NZCV flags can be set for
/// "free".  This is preferred on targets that have more flexibility when
/// scheduling B.cond instructions as compared to CBZ/CBNZ/TBZ/TBNZ (assuming
/// all other variables are equal).  This can also reduce register pressure.
///
/// A few examples:
///
/// 1) add w8, w0, w1  -> cmn w0, w1             ; CMN is an alias of ADDS.
///    cbz w8, .LBB_2  -> b.eq .LBB0_2
///
/// 2) add w8, w0, w1  -> adds w8, w0, w1        ; w8 has multiple uses.
///    cbz w8, .LBB1_2 -> b.eq .LBB1_2
///
/// 3) sub w8, w0, w1       -> subs w8, w0, w1   ; w8 has multiple uses.
///    tbz w8, #31, .LBB6_2 -> b.pl .LBB6_2
///
//===----------------------------------------------------------------------===//

#include "AArch64.h"
#include "AArch64Subtarget.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/CodeGen/MachineTraceMetrics.h"
#include "llvm/CodeGen/Passes.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Target/TargetInstrInfo.h"
#include "llvm/Target/TargetRegisterInfo.h"
#include "llvm/Target/TargetSubtargetInfo.h"

using namespace llvm;

#define DEBUG_TYPE "aarch64-cond-br-tuning"
#define AARCH64_CONDBR_TUNING_NAME "AArch64 Conditional Branch Tuning"

namespace {
class AArch64CondBrTuning : public MachineFunctionPass {
  const AArch64InstrInfo *TII;
  const TargetRegisterInfo *TRI;

  MachineRegisterInfo *MRI;

public:
  static char ID;
  AArch64CondBrTuning() : MachineFunctionPass(ID) {
    initializeAArch64CondBrTuningPass(*PassRegistry::getPassRegistry());
  }
  void getAnalysisUsage(AnalysisUsage &AU) const override;
  bool runOnMachineFunction(MachineFunction &MF) override;
  StringRef getPassName() const override { return AARCH64_CONDBR_TUNING_NAME; }

private:
  MachineInstr *getOperandDef(const MachineOperand &MO);
  MachineInstr *convertToFlagSetting(MachineInstr &MI, bool IsFlagSetting);
  MachineInstr *convertToCondBr(MachineInstr &MI);
  bool tryToTuneBranch(MachineInstr &MI, MachineInstr &DefMI);
};
} // end anonymous namespace

char AArch64CondBrTuning::ID = 0;

INITIALIZE_PASS(AArch64CondBrTuning, "aarch64-cond-br-tuning",
                AARCH64_CONDBR_TUNING_NAME, false, false)

void AArch64CondBrTuning::getAnalysisUsage(AnalysisUsage &AU) const {
  AU.setPreservesCFG();
  MachineFunctionPass::getAnalysisUsage(AU);
}

MachineInstr *AArch64CondBrTuning::getOperandDef(const MachineOperand &MO) {
  if (!TargetRegisterInfo::isVirtualRegister(MO.getReg()))
    return nullptr;
  return MRI->getUniqueVRegDef(MO.getReg());
}

MachineInstr *AArch64CondBrTuning::convertToFlagSetting(MachineInstr &MI,
                                                        bool IsFlagSetting) {
  // If this is already the flag setting version of the instruction (e.g., SUBS)
  // just make sure the implicit-def of NZCV isn't marked dead.
  if (IsFlagSetting) {
    for (unsigned I = MI.getNumExplicitOperands(), E = MI.getNumOperands();
         I != E; ++I) {
      MachineOperand &MO = MI.getOperand(I);
      if (MO.isReg() && MO.isDead() && MO.getReg() == AArch64::NZCV)
        MO.setIsDead(false);
    }
    return &MI;
  }
  bool Is64Bit;
  unsigned NewOpc = TII->convertToFlagSettingOpc(MI.getOpcode(), Is64Bit);
  unsigned NewDestReg = MI.getOperand(0).getReg();
  if (MRI->hasOneNonDBGUse(MI.getOperand(0).getReg()))
    NewDestReg = Is64Bit ? AArch64::XZR : AArch64::WZR;

  MachineInstrBuilder MIB = BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
                                    TII->get(NewOpc), NewDestReg);
  for (unsigned I = 1, E = MI.getNumOperands(); I != E; ++I)
    MIB.add(MI.getOperand(I));

  return MIB;
}

MachineInstr *AArch64CondBrTuning::convertToCondBr(MachineInstr &MI) {
  AArch64CC::CondCode CC;
  MachineBasicBlock *TargetMBB = TII->getBranchDestBlock(MI);
  switch (MI.getOpcode()) {
  default:
    llvm_unreachable("Unexpected opcode!");

  case AArch64::CBZW:
  case AArch64::CBZX:
    CC = AArch64CC::EQ;
    break;
  case AArch64::CBNZW:
  case AArch64::CBNZX:
    CC = AArch64CC::NE;
    break;
  case AArch64::TBZW:
  case AArch64::TBZX:
    CC = AArch64CC::PL;
    break;
  case AArch64::TBNZW:
  case AArch64::TBNZX:
    CC = AArch64CC::MI;
    break;
  }
  return BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), TII->get(AArch64::Bcc))
      .addImm(CC)
      .addMBB(TargetMBB);
}

bool AArch64CondBrTuning::tryToTuneBranch(MachineInstr &MI,
                                          MachineInstr &DefMI) {
  // We don't want NZCV bits live across blocks.
  if (MI.getParent() != DefMI.getParent())
    return false;

  bool IsFlagSetting = true;
  unsigned MIOpc = MI.getOpcode();
  MachineInstr *NewCmp = nullptr, *NewBr = nullptr;
  switch (DefMI.getOpcode()) {
  default:
    return false;
  case AArch64::ADDWri:
  case AArch64::ADDWrr:
  case AArch64::ADDWrs:
  case AArch64::ADDWrx:
  case AArch64::ANDWri:
  case AArch64::ANDWrr:
  case AArch64::ANDWrs:
  case AArch64::BICWrr:
  case AArch64::BICWrs:
  case AArch64::SUBWri:
  case AArch64::SUBWrr:
  case AArch64::SUBWrs:
  case AArch64::SUBWrx:
    IsFlagSetting = false;
  case AArch64::ADDSWri:
  case AArch64::ADDSWrr:
  case AArch64::ADDSWrs:
  case AArch64::ADDSWrx:
  case AArch64::ANDSWri:
  case AArch64::ANDSWrr:
  case AArch64::ANDSWrs:
  case AArch64::BICSWrr:
  case AArch64::BICSWrs:
  case AArch64::SUBSWri:
  case AArch64::SUBSWrr:
  case AArch64::SUBSWrs:
  case AArch64::SUBSWrx:
    switch (MIOpc) {
    default:
      llvm_unreachable("Unexpected opcode!");

    case AArch64::CBZW:
    case AArch64::CBNZW:
    case AArch64::TBZW:
    case AArch64::TBNZW:
      // Check to see if the TBZ/TBNZ is checking the sign bit.
      if ((MIOpc == AArch64::TBZW || MIOpc == AArch64::TBNZW) &&
          MI.getOperand(1).getImm() != 31)
        return false;

      // There must not be any instruction between DefMI and MI that clobbers or
      // reads NZCV.
      MachineBasicBlock::iterator I(DefMI), E(MI);
      for (I = std::next(I); I != E; ++I) {
        if (I->modifiesRegister(AArch64::NZCV, TRI) ||
            I->readsRegister(AArch64::NZCV, TRI))
          return false;
      }
      DEBUG(dbgs() << "  Replacing instructions:\n    ");
      DEBUG(DefMI.print(dbgs()));
      DEBUG(dbgs() << "    ");
      DEBUG(MI.print(dbgs()));

      NewCmp = convertToFlagSetting(DefMI, IsFlagSetting);
      NewBr = convertToCondBr(MI);
      break;
    }
    break;

  case AArch64::ADDXri:
  case AArch64::ADDXrr:
  case AArch64::ADDXrs:
  case AArch64::ADDXrx:
  case AArch64::ANDXri:
  case AArch64::ANDXrr:
  case AArch64::ANDXrs:
  case AArch64::BICXrr:
  case AArch64::BICXrs:
  case AArch64::SUBXri:
  case AArch64::SUBXrr:
  case AArch64::SUBXrs:
  case AArch64::SUBXrx:
    IsFlagSetting = false;
  case AArch64::ADDSXri:
  case AArch64::ADDSXrr:
  case AArch64::ADDSXrs:
  case AArch64::ADDSXrx:
  case AArch64::ANDSXri:
  case AArch64::ANDSXrr:
  case AArch64::ANDSXrs:
  case AArch64::BICSXrr:
  case AArch64::BICSXrs:
  case AArch64::SUBSXri:
  case AArch64::SUBSXrr:
  case AArch64::SUBSXrs:
  case AArch64::SUBSXrx:
    switch (MIOpc) {
    default:
      llvm_unreachable("Unexpected opcode!");

    case AArch64::CBZX:
    case AArch64::CBNZX:
    case AArch64::TBZX:
    case AArch64::TBNZX: {
      // Check to see if the TBZ/TBNZ is checking the sign bit.
      if ((MIOpc == AArch64::TBZX || MIOpc == AArch64::TBNZX) &&
          MI.getOperand(1).getImm() != 63)
        return false;
      // There must not be any instruction between DefMI and MI that clobbers or
      // reads NZCV.
      MachineBasicBlock::iterator I(DefMI), E(MI);
      for (I = std::next(I); I != E; ++I) {
        if (I->modifiesRegister(AArch64::NZCV, TRI) ||
            I->readsRegister(AArch64::NZCV, TRI))
          return false;
      }
      DEBUG(dbgs() << "  Replacing instructions:\n    ");
      DEBUG(DefMI.print(dbgs()));
      DEBUG(dbgs() << "    ");
      DEBUG(MI.print(dbgs()));

      NewCmp = convertToFlagSetting(DefMI, IsFlagSetting);
      NewBr = convertToCondBr(MI);
      break;
    }
    }
    break;
  }
  assert(NewCmp && NewBr && "Expected new instructions.");

  DEBUG(dbgs() << "  with instruction:\n    ");
  DEBUG(NewCmp->print(dbgs()));
  DEBUG(dbgs() << "    ");
  DEBUG(NewBr->print(dbgs()));

  // If this was a flag setting version of the instruction, we use the original
  // instruction by just clearing the dead marked on the implicit-def of NCZV.
  // Therefore, we should not erase this instruction.
  if (!IsFlagSetting)
    DefMI.eraseFromParent();
  MI.eraseFromParent();
  return true;
}

bool AArch64CondBrTuning::runOnMachineFunction(MachineFunction &MF) {
  if (skipFunction(*MF.getFunction()))
    return false;

  DEBUG(dbgs() << "********** AArch64 Conditional Branch Tuning  **********\n"
               << "********** Function: " << MF.getName() << '\n');

  TII = static_cast<const AArch64InstrInfo *>(MF.getSubtarget().getInstrInfo());
  TRI = MF.getSubtarget().getRegisterInfo();
  MRI = &MF.getRegInfo();

  bool Changed = false;
  for (MachineBasicBlock &MBB : MF) {
    bool LocalChange = false;
    for (MachineBasicBlock::iterator I = MBB.getFirstTerminator(),
                                     E = MBB.end();
         I != E; ++I) {
      MachineInstr &MI = *I;
      switch (MI.getOpcode()) {
      default:
        break;
      case AArch64::CBZW:
      case AArch64::CBZX:
      case AArch64::CBNZW:
      case AArch64::CBNZX:
      case AArch64::TBZW:
      case AArch64::TBZX:
      case AArch64::TBNZW:
      case AArch64::TBNZX:
        MachineInstr *DefMI = getOperandDef(MI.getOperand(0));
        LocalChange = (DefMI && tryToTuneBranch(MI, *DefMI));
        break;
      }
      // If the optimization was successful, we can't optimize any other
      // branches because doing so would clobber the NZCV flags.
      if (LocalChange) {
        Changed = true;
        break;
      }
    }
  }
  return Changed;
}

FunctionPass *llvm::createAArch64CondBrTuning() {
  return new AArch64CondBrTuning();
}
<commit_msg>[AArch64] Silence an unused variable warning in Release builds. NFC.<commit_after>//===-- AArch64CondBrTuning.cpp --- Conditional branch tuning for AArch64 -===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
/// \file
/// This file contains a pass that transforms CBZ/CBNZ/TBZ/TBNZ instructions
/// into a conditional branch (B.cond), when the NZCV flags can be set for
/// "free".  This is preferred on targets that have more flexibility when
/// scheduling B.cond instructions as compared to CBZ/CBNZ/TBZ/TBNZ (assuming
/// all other variables are equal).  This can also reduce register pressure.
///
/// A few examples:
///
/// 1) add w8, w0, w1  -> cmn w0, w1             ; CMN is an alias of ADDS.
///    cbz w8, .LBB_2  -> b.eq .LBB0_2
///
/// 2) add w8, w0, w1  -> adds w8, w0, w1        ; w8 has multiple uses.
///    cbz w8, .LBB1_2 -> b.eq .LBB1_2
///
/// 3) sub w8, w0, w1       -> subs w8, w0, w1   ; w8 has multiple uses.
///    tbz w8, #31, .LBB6_2 -> b.pl .LBB6_2
///
//===----------------------------------------------------------------------===//

#include "AArch64.h"
#include "AArch64Subtarget.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/CodeGen/MachineTraceMetrics.h"
#include "llvm/CodeGen/Passes.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Target/TargetInstrInfo.h"
#include "llvm/Target/TargetRegisterInfo.h"
#include "llvm/Target/TargetSubtargetInfo.h"

using namespace llvm;

#define DEBUG_TYPE "aarch64-cond-br-tuning"
#define AARCH64_CONDBR_TUNING_NAME "AArch64 Conditional Branch Tuning"

namespace {
class AArch64CondBrTuning : public MachineFunctionPass {
  const AArch64InstrInfo *TII;
  const TargetRegisterInfo *TRI;

  MachineRegisterInfo *MRI;

public:
  static char ID;
  AArch64CondBrTuning() : MachineFunctionPass(ID) {
    initializeAArch64CondBrTuningPass(*PassRegistry::getPassRegistry());
  }
  void getAnalysisUsage(AnalysisUsage &AU) const override;
  bool runOnMachineFunction(MachineFunction &MF) override;
  StringRef getPassName() const override { return AARCH64_CONDBR_TUNING_NAME; }

private:
  MachineInstr *getOperandDef(const MachineOperand &MO);
  MachineInstr *convertToFlagSetting(MachineInstr &MI, bool IsFlagSetting);
  MachineInstr *convertToCondBr(MachineInstr &MI);
  bool tryToTuneBranch(MachineInstr &MI, MachineInstr &DefMI);
};
} // end anonymous namespace

char AArch64CondBrTuning::ID = 0;

INITIALIZE_PASS(AArch64CondBrTuning, "aarch64-cond-br-tuning",
                AARCH64_CONDBR_TUNING_NAME, false, false)

void AArch64CondBrTuning::getAnalysisUsage(AnalysisUsage &AU) const {
  AU.setPreservesCFG();
  MachineFunctionPass::getAnalysisUsage(AU);
}

MachineInstr *AArch64CondBrTuning::getOperandDef(const MachineOperand &MO) {
  if (!TargetRegisterInfo::isVirtualRegister(MO.getReg()))
    return nullptr;
  return MRI->getUniqueVRegDef(MO.getReg());
}

MachineInstr *AArch64CondBrTuning::convertToFlagSetting(MachineInstr &MI,
                                                        bool IsFlagSetting) {
  // If this is already the flag setting version of the instruction (e.g., SUBS)
  // just make sure the implicit-def of NZCV isn't marked dead.
  if (IsFlagSetting) {
    for (unsigned I = MI.getNumExplicitOperands(), E = MI.getNumOperands();
         I != E; ++I) {
      MachineOperand &MO = MI.getOperand(I);
      if (MO.isReg() && MO.isDead() && MO.getReg() == AArch64::NZCV)
        MO.setIsDead(false);
    }
    return &MI;
  }
  bool Is64Bit;
  unsigned NewOpc = TII->convertToFlagSettingOpc(MI.getOpcode(), Is64Bit);
  unsigned NewDestReg = MI.getOperand(0).getReg();
  if (MRI->hasOneNonDBGUse(MI.getOperand(0).getReg()))
    NewDestReg = Is64Bit ? AArch64::XZR : AArch64::WZR;

  MachineInstrBuilder MIB = BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
                                    TII->get(NewOpc), NewDestReg);
  for (unsigned I = 1, E = MI.getNumOperands(); I != E; ++I)
    MIB.add(MI.getOperand(I));

  return MIB;
}

MachineInstr *AArch64CondBrTuning::convertToCondBr(MachineInstr &MI) {
  AArch64CC::CondCode CC;
  MachineBasicBlock *TargetMBB = TII->getBranchDestBlock(MI);
  switch (MI.getOpcode()) {
  default:
    llvm_unreachable("Unexpected opcode!");

  case AArch64::CBZW:
  case AArch64::CBZX:
    CC = AArch64CC::EQ;
    break;
  case AArch64::CBNZW:
  case AArch64::CBNZX:
    CC = AArch64CC::NE;
    break;
  case AArch64::TBZW:
  case AArch64::TBZX:
    CC = AArch64CC::PL;
    break;
  case AArch64::TBNZW:
  case AArch64::TBNZX:
    CC = AArch64CC::MI;
    break;
  }
  return BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), TII->get(AArch64::Bcc))
      .addImm(CC)
      .addMBB(TargetMBB);
}

bool AArch64CondBrTuning::tryToTuneBranch(MachineInstr &MI,
                                          MachineInstr &DefMI) {
  // We don't want NZCV bits live across blocks.
  if (MI.getParent() != DefMI.getParent())
    return false;

  bool IsFlagSetting = true;
  unsigned MIOpc = MI.getOpcode();
  MachineInstr *NewCmp = nullptr, *NewBr = nullptr;
  switch (DefMI.getOpcode()) {
  default:
    return false;
  case AArch64::ADDWri:
  case AArch64::ADDWrr:
  case AArch64::ADDWrs:
  case AArch64::ADDWrx:
  case AArch64::ANDWri:
  case AArch64::ANDWrr:
  case AArch64::ANDWrs:
  case AArch64::BICWrr:
  case AArch64::BICWrs:
  case AArch64::SUBWri:
  case AArch64::SUBWrr:
  case AArch64::SUBWrs:
  case AArch64::SUBWrx:
    IsFlagSetting = false;
  case AArch64::ADDSWri:
  case AArch64::ADDSWrr:
  case AArch64::ADDSWrs:
  case AArch64::ADDSWrx:
  case AArch64::ANDSWri:
  case AArch64::ANDSWrr:
  case AArch64::ANDSWrs:
  case AArch64::BICSWrr:
  case AArch64::BICSWrs:
  case AArch64::SUBSWri:
  case AArch64::SUBSWrr:
  case AArch64::SUBSWrs:
  case AArch64::SUBSWrx:
    switch (MIOpc) {
    default:
      llvm_unreachable("Unexpected opcode!");

    case AArch64::CBZW:
    case AArch64::CBNZW:
    case AArch64::TBZW:
    case AArch64::TBNZW:
      // Check to see if the TBZ/TBNZ is checking the sign bit.
      if ((MIOpc == AArch64::TBZW || MIOpc == AArch64::TBNZW) &&
          MI.getOperand(1).getImm() != 31)
        return false;

      // There must not be any instruction between DefMI and MI that clobbers or
      // reads NZCV.
      MachineBasicBlock::iterator I(DefMI), E(MI);
      for (I = std::next(I); I != E; ++I) {
        if (I->modifiesRegister(AArch64::NZCV, TRI) ||
            I->readsRegister(AArch64::NZCV, TRI))
          return false;
      }
      DEBUG(dbgs() << "  Replacing instructions:\n    ");
      DEBUG(DefMI.print(dbgs()));
      DEBUG(dbgs() << "    ");
      DEBUG(MI.print(dbgs()));

      NewCmp = convertToFlagSetting(DefMI, IsFlagSetting);
      NewBr = convertToCondBr(MI);
      break;
    }
    break;

  case AArch64::ADDXri:
  case AArch64::ADDXrr:
  case AArch64::ADDXrs:
  case AArch64::ADDXrx:
  case AArch64::ANDXri:
  case AArch64::ANDXrr:
  case AArch64::ANDXrs:
  case AArch64::BICXrr:
  case AArch64::BICXrs:
  case AArch64::SUBXri:
  case AArch64::SUBXrr:
  case AArch64::SUBXrs:
  case AArch64::SUBXrx:
    IsFlagSetting = false;
  case AArch64::ADDSXri:
  case AArch64::ADDSXrr:
  case AArch64::ADDSXrs:
  case AArch64::ADDSXrx:
  case AArch64::ANDSXri:
  case AArch64::ANDSXrr:
  case AArch64::ANDSXrs:
  case AArch64::BICSXrr:
  case AArch64::BICSXrs:
  case AArch64::SUBSXri:
  case AArch64::SUBSXrr:
  case AArch64::SUBSXrs:
  case AArch64::SUBSXrx:
    switch (MIOpc) {
    default:
      llvm_unreachable("Unexpected opcode!");

    case AArch64::CBZX:
    case AArch64::CBNZX:
    case AArch64::TBZX:
    case AArch64::TBNZX: {
      // Check to see if the TBZ/TBNZ is checking the sign bit.
      if ((MIOpc == AArch64::TBZX || MIOpc == AArch64::TBNZX) &&
          MI.getOperand(1).getImm() != 63)
        return false;
      // There must not be any instruction between DefMI and MI that clobbers or
      // reads NZCV.
      MachineBasicBlock::iterator I(DefMI), E(MI);
      for (I = std::next(I); I != E; ++I) {
        if (I->modifiesRegister(AArch64::NZCV, TRI) ||
            I->readsRegister(AArch64::NZCV, TRI))
          return false;
      }
      DEBUG(dbgs() << "  Replacing instructions:\n    ");
      DEBUG(DefMI.print(dbgs()));
      DEBUG(dbgs() << "    ");
      DEBUG(MI.print(dbgs()));

      NewCmp = convertToFlagSetting(DefMI, IsFlagSetting);
      NewBr = convertToCondBr(MI);
      break;
    }
    }
    break;
  }
  (void)NewCmp; (void)NewBr;
  assert(NewCmp && NewBr && "Expected new instructions.");

  DEBUG(dbgs() << "  with instruction:\n    ");
  DEBUG(NewCmp->print(dbgs()));
  DEBUG(dbgs() << "    ");
  DEBUG(NewBr->print(dbgs()));

  // If this was a flag setting version of the instruction, we use the original
  // instruction by just clearing the dead marked on the implicit-def of NCZV.
  // Therefore, we should not erase this instruction.
  if (!IsFlagSetting)
    DefMI.eraseFromParent();
  MI.eraseFromParent();
  return true;
}

bool AArch64CondBrTuning::runOnMachineFunction(MachineFunction &MF) {
  if (skipFunction(*MF.getFunction()))
    return false;

  DEBUG(dbgs() << "********** AArch64 Conditional Branch Tuning  **********\n"
               << "********** Function: " << MF.getName() << '\n');

  TII = static_cast<const AArch64InstrInfo *>(MF.getSubtarget().getInstrInfo());
  TRI = MF.getSubtarget().getRegisterInfo();
  MRI = &MF.getRegInfo();

  bool Changed = false;
  for (MachineBasicBlock &MBB : MF) {
    bool LocalChange = false;
    for (MachineBasicBlock::iterator I = MBB.getFirstTerminator(),
                                     E = MBB.end();
         I != E; ++I) {
      MachineInstr &MI = *I;
      switch (MI.getOpcode()) {
      default:
        break;
      case AArch64::CBZW:
      case AArch64::CBZX:
      case AArch64::CBNZW:
      case AArch64::CBNZX:
      case AArch64::TBZW:
      case AArch64::TBZX:
      case AArch64::TBNZW:
      case AArch64::TBNZX:
        MachineInstr *DefMI = getOperandDef(MI.getOperand(0));
        LocalChange = (DefMI && tryToTuneBranch(MI, *DefMI));
        break;
      }
      // If the optimization was successful, we can't optimize any other
      // branches because doing so would clobber the NZCV flags.
      if (LocalChange) {
        Changed = true;
        break;
      }
    }
  }
  return Changed;
}

FunctionPass *llvm::createAArch64CondBrTuning() {
  return new AArch64CondBrTuning();
}
<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkProcessObject.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
#include "vtkProcessObject.h"

#include "vtkObjectFactory.h"
#include "vtkDataObject.h"
#include "vtkErrorCode.h"
#include "vtkCommand.h"

vtkCxxRevisionMacro(vtkProcessObject, "1.36");

// Instantiate object with no start, end, or progress methods.
vtkProcessObject::vtkProcessObject()
{
  this->AbortExecute = 0;
  this->Progress = 0.0;
  this->ProgressText = NULL;
  this->NumberOfInputs = 0;
  this->NumberOfRequiredInputs = 0;
  this->Inputs = NULL;
  this->SortedInputs = NULL;
  this->SortedInputs2 = NULL;
  this->ErrorCode = 0;
}

// Destructor for the vtkProcessObject class
vtkProcessObject::~vtkProcessObject()
{
  int idx;

  for (idx = 0; idx < this->NumberOfInputs; ++idx)
    {
    if (this->Inputs[idx])
      {
      this->Inputs[idx]->RemoveConsumer(this);
      this->Inputs[idx]->UnRegister(this);
      this->Inputs[idx] = NULL;
      }
    if (this->SortedInputs[idx])
      {
      this->SortedInputs[idx]= NULL;
      }
    if (this->SortedInputs2[idx])
      {
      this->SortedInputs2[idx]= NULL;
      }
    }
  if (this->Inputs)
    {
    delete [] this->Inputs;
    this->Inputs = NULL;
    this->NumberOfInputs = 0;
    }
  if (this->SortedInputs)
    {
    delete [] this->SortedInputs;
    this->SortedInputs = NULL;
    }
  if (this->SortedInputs2)
    {
    delete [] this->SortedInputs2;
    this->SortedInputs2 = NULL;
    }
  delete [] this->ProgressText;
  this->ProgressText = NULL;
}

typedef vtkDataObject *vtkDataObjectPointer;
//----------------------------------------------------------------------------
// Called by constructor to set up input array.
void vtkProcessObject::SetNumberOfInputs(int num)
{
  int idx;
  vtkDataObjectPointer *inputs;

  // in case nothing has changed.
  if (num == this->NumberOfInputs)
    {
    return;
    }

  // Allocate new arrays.
  inputs = new vtkDataObjectPointer[num];

  // Initialize with NULLs.
  for (idx = 0; idx < num; ++idx)
    {
    inputs[idx] = NULL;
    }

  // Copy old inputs
  for (idx = 0; idx < num && idx < this->NumberOfInputs; ++idx)
    {
    inputs[idx] = this->Inputs[idx];
    }

  // delete the previous arrays
  delete [] this->Inputs;
  this->Inputs = NULL;
  this->NumberOfInputs = 0;

  delete [] this->SortedInputs;
  this->SortedInputs = NULL;

  delete [] this->SortedInputs2;
  this->SortedInputs2 = NULL;

  // Set the new arrays
  this->Inputs = inputs;
  this->SortedInputs = new vtkDataObjectPointer[num];
  this->SortedInputs2 = new vtkDataObjectPointer[num];

  this->NumberOfInputs = num;
  this->Modified();
}

//----------------------------------------------------------------------------
// Adds an input to the first null position in the input list.
// Expands the list memory if necessary
void vtkProcessObject::AddInput(vtkDataObject *input)
{
  int idx;

  if (input)
    {
    input->AddConsumer(this);
    input->Register(this);
    }
  this->Modified();

  for (idx = 0; idx < this->NumberOfInputs; ++idx)
    {
    if (this->Inputs[idx] == NULL)
      {
      this->Inputs[idx] = input;
      return;
      }
    }

  this->SetNumberOfInputs(this->NumberOfInputs + 1);
  this->Inputs[this->NumberOfInputs - 1] = input;
}

//----------------------------------------------------------------------------
// Adds an input to the first null position in the input list.
// Expands the list memory if necessary
void vtkProcessObject::RemoveInput(vtkDataObject *input)
{
  int idx, loc;

  if (!input)
    {
    return;
    }

  // find the input in the list of inputs
  loc = -1;
  for (idx = 0; idx < this->NumberOfInputs; ++idx)
    {
    if (this->Inputs[idx] == input)
      {
      loc = idx;
      }
    }
  if (loc == -1)
    {
    vtkDebugMacro("tried to remove an input that was not in the list");
    return;
    }

  this->Inputs[loc]->RemoveConsumer(this);
  this->Inputs[loc]->UnRegister(this);
  this->Inputs[loc] = NULL;

  // if that was the last input, then shrink the list
  if (loc == this->NumberOfInputs - 1)
    {
    this->SetNumberOfInputs(this->NumberOfInputs - 1);
    }

  this->Modified();
}

//----------------------------------------------------------------------------
// Adds an input to the first null position in the input list.
// Expands the list memory if necessary
void vtkProcessObject::SqueezeInputArray()
{
  int idx, loc;

  // move NULL entries to the end
  for (idx = 0; idx < this->NumberOfInputs; ++idx)
    {
    if (this->Inputs[idx] == NULL)
      {
      for (loc = idx+1; loc < this->NumberOfInputs; loc++)
        {
        this->Inputs[loc-1] = this->Inputs[loc];
        }
      this->Inputs[this->NumberOfInputs -1] = NULL;
      }
    }

  // adjust the size of the array
  loc = -1;
  for (idx = 0; idx < this->NumberOfInputs; ++idx)
    {
    if (loc == -1 && this->Inputs[idx] == NULL)
      {
      loc = idx;
      }
    }
  if (loc > 0)
    {
    this->SetNumberOfInputs(loc);
    }
}

//----------------------------------------------------------------------------
// Set an Input of this filter.
void vtkProcessObject::SetNthInput(int idx, vtkDataObject *input)
{
  if (idx < 0)
    {
    vtkErrorMacro(<< "SetNthInput: " << idx << ", cannot set input. ");
    return;
    }
  // Expand array if necessary.
  if (idx >= this->NumberOfInputs)
    {
    this->SetNumberOfInputs(idx + 1);
    }

  // does this change anything?
  if (input == this->Inputs[idx])
    {
    return;
    }

  if (this->Inputs[idx])
    {
    this->Inputs[idx]->RemoveConsumer(this);
    this->Inputs[idx]->UnRegister(this);
    this->Inputs[idx] = NULL;
    }

  if (input)
    {
    input->AddConsumer(this);
    input->Register(this);
    }

  this->Inputs[idx] = input;
  this->Modified();
}

// Update the progress of the process object. If a ProgressMethod exists,
// executes it. Then set the Progress ivar to amount. The parameter amount
// should range between (0,1).
void vtkProcessObject::UpdateProgress(double amount)
{
  this->Progress = amount;
  this->InvokeEvent(vtkCommand::ProgressEvent,(void *)&amount);
}

void vtkProcessObject::RemoveAllInputs()
{
  if ( this->Inputs )
    {
    for (int idx = 0; idx < this->NumberOfInputs; ++idx)
      {
      if ( this->Inputs[idx] )
        {
        this->Inputs[idx]->UnRegister(this);
        this->Inputs[idx] = NULL;
        }
      }
    delete [] this->Inputs;
    this->Inputs = NULL;
    this->NumberOfInputs = 0;
    this->Modified();
    }
}

void vtkProcessObject::SortInputsByLocality()
{
  int i1, i2;
  int l1, l2;
  // length starts at 1 and doubles every pass.
  int length;
  vtkDataObject **tmp;

  // Copy inputs over to sorted array.
  memcpy(this->SortedInputs, this->Inputs,
         this->NumberOfInputs * sizeof(void*));

  length = 1;
  while (length < this->NumberOfInputs)
    {
    i1 = 0;
    while (i1 < this->NumberOfInputs)
      {
      l1 = length;
      i2 = i1 + l1;
      if (i2 > this->NumberOfInputs)
        { // Piece one has all the remaining entries.
        l1 = this->NumberOfInputs - i1;
        i2 = this->NumberOfInputs;
        l2 = 0;
        }
      else
        { // l2 is the smaller of the remainder or the current length.
        l2 = this->NumberOfInputs - i2;
        if (l2 > length)
          {
          l2 = length;
          }
        }
      this->SortMerge(this->SortedInputs+i1, l1,
                      this->SortedInputs+i2, l2,
                      this->SortedInputs2+i1);
      i1 = i2 + l2;
      }
    // swap the two arrays
    tmp = this->SortedInputs;
    this->SortedInputs = this->SortedInputs2;
    this->SortedInputs2 = tmp;
    length *= 2;
    }
}

void vtkProcessObject::SortMerge(vtkDataObject **a1, int l1,
                                 vtkDataObject **a2, int l2,
                                 vtkDataObject **results)
{
  while (l1 > 0 || l2 > 0)
    {
    // When the second list is empty, finish the first.
    if (l2 == 0)
      {
      *results++ = *a1++;
      --l1;
      }
    // When the first list is empty, finish the second.
    else if (l1 == 0 || *a1 == NULL)
      {
      *results++ = *a2++;
      --l2;
      }
    // Handle NULL pointers (put them at the end).
    else if (*a2 == NULL)
      {
      *results++ = *a1++;
      --l1;
      }
    else if (*a1 == NULL)
      {
      *results++ = *a2++;
      --l2;
      }
    // Sort by locality.
    else if ((*a1)->GetLocality() < (*a2)->GetLocality())
      {
      *results++ = *a1++;
      --l1;
      }
    else
      {
      *results++ = *a2++;
      --l2;
      }
    }
}

void vtkProcessObject::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os,indent);

  os << indent << "Number Of Required Inputs: "
     << this->NumberOfRequiredInputs << endl;

  if ( this->NumberOfInputs)
    {
    int idx;
    for (idx = 0; idx < this->NumberOfInputs; ++idx)
      {
      os << indent << "Input " << idx << ": (" << this->Inputs[idx] << ")\n";
      }
    }
  else
    {
    os << indent <<"No Inputs\n";
    }

  os << indent << "AbortExecute: " << (this->AbortExecute ? "On\n" : "Off\n");
  os << indent << "Progress: " << this->Progress << "\n";
  if ( this->ProgressText )
    {
    os << indent << "Progress Text: " << this->ProgressText << "\n";
    }
  else
    {
    os << indent << "Progress Text: (None)\n";
    }

  os << indent << "ErrorCode: " << vtkErrorCode::GetStringFromErrorCode(this->ErrorCode) << endl;
}
<commit_msg>remove useless and bad code<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkProcessObject.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
#include "vtkProcessObject.h"

#include "vtkObjectFactory.h"
#include "vtkDataObject.h"
#include "vtkErrorCode.h"
#include "vtkCommand.h"

vtkCxxRevisionMacro(vtkProcessObject, "1.37");

// Instantiate object with no start, end, or progress methods.
vtkProcessObject::vtkProcessObject()
{
  this->AbortExecute = 0;
  this->Progress = 0.0;
  this->ProgressText = NULL;
  this->NumberOfInputs = 0;
  this->NumberOfRequiredInputs = 0;
  this->Inputs = NULL;
  this->SortedInputs = NULL;
  this->SortedInputs2 = NULL;
  this->ErrorCode = 0;
}

// Destructor for the vtkProcessObject class
vtkProcessObject::~vtkProcessObject()
{
  int idx;

  for (idx = 0; idx < this->NumberOfInputs; ++idx)
    {
    if (this->Inputs[idx])
      {
      this->Inputs[idx]->RemoveConsumer(this);
      this->Inputs[idx]->UnRegister(this);
      this->Inputs[idx] = NULL;
      }
    }
  if (this->Inputs)
    {
    delete [] this->Inputs;
    this->Inputs = NULL;
    this->NumberOfInputs = 0;
    }
  if (this->SortedInputs)
    {
    delete [] this->SortedInputs;
    this->SortedInputs = NULL;
    }
  if (this->SortedInputs2)
    {
    delete [] this->SortedInputs2;
    this->SortedInputs2 = NULL;
    }
  delete [] this->ProgressText;
  this->ProgressText = NULL;
}

typedef vtkDataObject *vtkDataObjectPointer;
//----------------------------------------------------------------------------
// Called by constructor to set up input array.
void vtkProcessObject::SetNumberOfInputs(int num)
{
  int idx;
  vtkDataObjectPointer *inputs;

  // in case nothing has changed.
  if (num == this->NumberOfInputs)
    {
    return;
    }

  // Allocate new arrays.
  inputs = new vtkDataObjectPointer[num];

  // Initialize with NULLs.
  for (idx = 0; idx < num; ++idx)
    {
    inputs[idx] = NULL;
    }

  // Copy old inputs
  for (idx = 0; idx < num && idx < this->NumberOfInputs; ++idx)
    {
    inputs[idx] = this->Inputs[idx];
    }

  // delete the previous arrays
  delete [] this->Inputs;
  this->Inputs = NULL;
  this->NumberOfInputs = 0;

  delete [] this->SortedInputs;
  this->SortedInputs = NULL;

  delete [] this->SortedInputs2;
  this->SortedInputs2 = NULL;

  // Set the new arrays
  this->Inputs = inputs;
  this->SortedInputs = new vtkDataObjectPointer[num];
  this->SortedInputs2 = new vtkDataObjectPointer[num];

  this->NumberOfInputs = num;
  this->Modified();
}

//----------------------------------------------------------------------------
// Adds an input to the first null position in the input list.
// Expands the list memory if necessary
void vtkProcessObject::AddInput(vtkDataObject *input)
{
  int idx;

  if (input)
    {
    input->AddConsumer(this);
    input->Register(this);
    }
  this->Modified();

  for (idx = 0; idx < this->NumberOfInputs; ++idx)
    {
    if (this->Inputs[idx] == NULL)
      {
      this->Inputs[idx] = input;
      return;
      }
    }

  this->SetNumberOfInputs(this->NumberOfInputs + 1);
  this->Inputs[this->NumberOfInputs - 1] = input;
}

//----------------------------------------------------------------------------
// Adds an input to the first null position in the input list.
// Expands the list memory if necessary
void vtkProcessObject::RemoveInput(vtkDataObject *input)
{
  int idx, loc;

  if (!input)
    {
    return;
    }

  // find the input in the list of inputs
  loc = -1;
  for (idx = 0; idx < this->NumberOfInputs; ++idx)
    {
    if (this->Inputs[idx] == input)
      {
      loc = idx;
      }
    }
  if (loc == -1)
    {
    vtkDebugMacro("tried to remove an input that was not in the list");
    return;
    }

  this->Inputs[loc]->RemoveConsumer(this);
  this->Inputs[loc]->UnRegister(this);
  this->Inputs[loc] = NULL;

  // if that was the last input, then shrink the list
  if (loc == this->NumberOfInputs - 1)
    {
    this->SetNumberOfInputs(this->NumberOfInputs - 1);
    }

  this->Modified();
}

//----------------------------------------------------------------------------
// Adds an input to the first null position in the input list.
// Expands the list memory if necessary
void vtkProcessObject::SqueezeInputArray()
{
  int idx, loc;

  // move NULL entries to the end
  for (idx = 0; idx < this->NumberOfInputs; ++idx)
    {
    if (this->Inputs[idx] == NULL)
      {
      for (loc = idx+1; loc < this->NumberOfInputs; loc++)
        {
        this->Inputs[loc-1] = this->Inputs[loc];
        }
      this->Inputs[this->NumberOfInputs -1] = NULL;
      }
    }

  // adjust the size of the array
  loc = -1;
  for (idx = 0; idx < this->NumberOfInputs; ++idx)
    {
    if (loc == -1 && this->Inputs[idx] == NULL)
      {
      loc = idx;
      }
    }
  if (loc > 0)
    {
    this->SetNumberOfInputs(loc);
    }
}

//----------------------------------------------------------------------------
// Set an Input of this filter.
void vtkProcessObject::SetNthInput(int idx, vtkDataObject *input)
{
  if (idx < 0)
    {
    vtkErrorMacro(<< "SetNthInput: " << idx << ", cannot set input. ");
    return;
    }
  // Expand array if necessary.
  if (idx >= this->NumberOfInputs)
    {
    this->SetNumberOfInputs(idx + 1);
    }

  // does this change anything?
  if (input == this->Inputs[idx])
    {
    return;
    }

  if (this->Inputs[idx])
    {
    this->Inputs[idx]->RemoveConsumer(this);
    this->Inputs[idx]->UnRegister(this);
    this->Inputs[idx] = NULL;
    }

  if (input)
    {
    input->AddConsumer(this);
    input->Register(this);
    }

  this->Inputs[idx] = input;
  this->Modified();
}

// Update the progress of the process object. If a ProgressMethod exists,
// executes it. Then set the Progress ivar to amount. The parameter amount
// should range between (0,1).
void vtkProcessObject::UpdateProgress(double amount)
{
  this->Progress = amount;
  this->InvokeEvent(vtkCommand::ProgressEvent,(void *)&amount);
}

void vtkProcessObject::RemoveAllInputs()
{
  if ( this->Inputs )
    {
    for (int idx = 0; idx < this->NumberOfInputs; ++idx)
      {
      if ( this->Inputs[idx] )
        {
        this->Inputs[idx]->UnRegister(this);
        this->Inputs[idx] = NULL;
        }
      }
    delete [] this->Inputs;
    this->Inputs = NULL;
    this->NumberOfInputs = 0;
    this->Modified();
    }
}

void vtkProcessObject::SortInputsByLocality()
{
  int i1, i2;
  int l1, l2;
  // length starts at 1 and doubles every pass.
  int length;
  vtkDataObject **tmp;

  // Copy inputs over to sorted array.
  memcpy(this->SortedInputs, this->Inputs,
         this->NumberOfInputs * sizeof(void*));

  length = 1;
  while (length < this->NumberOfInputs)
    {
    i1 = 0;
    while (i1 < this->NumberOfInputs)
      {
      l1 = length;
      i2 = i1 + l1;
      if (i2 > this->NumberOfInputs)
        { // Piece one has all the remaining entries.
        l1 = this->NumberOfInputs - i1;
        i2 = this->NumberOfInputs;
        l2 = 0;
        }
      else
        { // l2 is the smaller of the remainder or the current length.
        l2 = this->NumberOfInputs - i2;
        if (l2 > length)
          {
          l2 = length;
          }
        }
      this->SortMerge(this->SortedInputs+i1, l1,
                      this->SortedInputs+i2, l2,
                      this->SortedInputs2+i1);
      i1 = i2 + l2;
      }
    // swap the two arrays
    tmp = this->SortedInputs;
    this->SortedInputs = this->SortedInputs2;
    this->SortedInputs2 = tmp;
    length *= 2;
    }
}

void vtkProcessObject::SortMerge(vtkDataObject **a1, int l1,
                                 vtkDataObject **a2, int l2,
                                 vtkDataObject **results)
{
  while (l1 > 0 || l2 > 0)
    {
    // When the second list is empty, finish the first.
    if (l2 == 0)
      {
      *results++ = *a1++;
      --l1;
      }
    // When the first list is empty, finish the second.
    else if (l1 == 0 || *a1 == NULL)
      {
      *results++ = *a2++;
      --l2;
      }
    // Handle NULL pointers (put them at the end).
    else if (*a2 == NULL)
      {
      *results++ = *a1++;
      --l1;
      }
    else if (*a1 == NULL)
      {
      *results++ = *a2++;
      --l2;
      }
    // Sort by locality.
    else if ((*a1)->GetLocality() < (*a2)->GetLocality())
      {
      *results++ = *a1++;
      --l1;
      }
    else
      {
      *results++ = *a2++;
      --l2;
      }
    }
}

void vtkProcessObject::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os,indent);

  os << indent << "Number Of Required Inputs: "
     << this->NumberOfRequiredInputs << endl;

  if ( this->NumberOfInputs)
    {
    int idx;
    for (idx = 0; idx < this->NumberOfInputs; ++idx)
      {
      os << indent << "Input " << idx << ": (" << this->Inputs[idx] << ")\n";
      }
    }
  else
    {
    os << indent <<"No Inputs\n";
    }

  os << indent << "AbortExecute: " << (this->AbortExecute ? "On\n" : "Off\n");
  os << indent << "Progress: " << this->Progress << "\n";
  if ( this->ProgressText )
    {
    os << indent << "Progress Text: " << this->ProgressText << "\n";
    }
  else
    {
    os << indent << "Progress Text: (None)\n";
    }

  os << indent << "ErrorCode: " << vtkErrorCode::GetStringFromErrorCode(this->ErrorCode) << endl;
}
<|endoftext|>


<commit_before>/*
	This file is part of cpp-ethereum.

	cpp-ethereum is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	cpp-ethereum 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 General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with cpp-ethereum.  If not, see <http://www.gnu.org/licenses/>.
*/
/** @file ContractCallDataEncoder.cpp
 * @author Yann yann@ethdev.com
 * @date 2014
 * Ethereum IDE client.
 */

#include <QDebug>
#include <QMap>
#include <QStringList>
#include <libdevcore/CommonJS.h>
#include <libsolidity/AST.h>
#include "QVariableDeclaration.h"
#include "QVariableDefinition.h"
#include "ContractCallDataEncoder.h"
using namespace dev;
using namespace dev::solidity;
using namespace dev::mix;

bytes ContractCallDataEncoder::encodedData()
{
	return m_encodedData;
}

void ContractCallDataEncoder::encode(int _functionIndex)
{
	bytes i = jsToBytes(std::to_string(_functionIndex));
	m_encodedData.insert(m_encodedData.end(), i.begin(), i.end());
}

void ContractCallDataEncoder::encode(QVariableDeclaration* _dec, bool _value)
{
	return encode(_dec, QString(formatBool(_value)));
}

void ContractCallDataEncoder::encode(QVariableDeclaration* _dec, QString _value)
{
	int padding = this->padding(_dec->type());
	bytes data = padded(jsToBytes(_value.toStdString()), padding);
	m_encodedData.insert(m_encodedData.end(), data.begin(), data.end());
}

void ContractCallDataEncoder::encode(QVariableDeclaration* _dec, u256 _value)
{
	int padding = this->padding(_dec->type());
	std::ostringstream s;
	s << std::hex << "0x" << _value;
	bytes data = padded(jsToBytes(s.str()), padding);
	m_encodedData.insert(m_encodedData.end(), data.begin(), data.end());
	encodedData();
}

QList<QVariableDefinition*> ContractCallDataEncoder::decode(QList<QVariableDeclaration*> _returnParameters, bytes _value)
{
	QList<QVariableDefinition*> r;
	std::string returnValue = toJS(_value);
	returnValue = returnValue.substr(2, returnValue.length() - 1);
	for (int k = 0; k <_returnParameters.length(); k++)
	{
		QVariableDeclaration* dec = (QVariableDeclaration*)_returnParameters.at(k);
		int padding = this->padding(dec->type());
		std::string rawParam = returnValue.substr(0, padding * 2);
		r.append(new QVariableDefinition(dec, convertToReadable(unpadded(rawParam), dec)));
		returnValue = returnValue.substr(rawParam.length(), returnValue.length() - 1);
	}
	return r;
}

int ContractCallDataEncoder::padding(QString type)
{
	// TODO : to be improved (load types automatically from solidity library).
	if (type.indexOf("uint") != -1)
		return integerPadding(type.remove("uint").toInt());
	else if (type.indexOf("int") != -1)
		return integerPadding(type.remove("int").toInt());
	else if (type.indexOf("bool") != -1)
		return 1;
	else if ((type.indexOf("address") != -1))
		return 20;
	else
		return 0;
}

int ContractCallDataEncoder::integerPadding(int bitValue)
{
	return bitValue / 8;
}

QString ContractCallDataEncoder::formatBool(bool _value)
{
	return (_value ? "1" : "0");
}

QString ContractCallDataEncoder::convertToReadable(std::string _v, QVariableDeclaration* _dec)
{
	if (_dec->type().indexOf("int") != -1)
		return convertToInt(_v);
	else if (_dec->type().indexOf("bool") != -1)
		return convertToBool(_v);
	else
		return QString::fromStdString(_v);
}

QString ContractCallDataEncoder::convertToBool(std::string _v)
{
	return _v == "1" ? "true" : "false";
}

QString ContractCallDataEncoder::convertToInt(std::string _v)
{
	//TO DO to be improve to manage all int, uint size (128, 256, ...) in ethereum QML types task #612.
	int x = std::stol(_v, nullptr, 16);
	std::stringstream ss;
	ss << std::dec << x;
	return QString::fromStdString(ss.str());
}
<commit_msg> - Rollback previous change on toCompactBigEndian, unpadded(bytes _b).  - Change content of padded(bytes _b, unsigned _l).  - Add function unpadLeft.<commit_after>/*
	This file is part of cpp-ethereum.

	cpp-ethereum is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	cpp-ethereum 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 General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with cpp-ethereum.  If not, see <http://www.gnu.org/licenses/>.
*/
/** @file ContractCallDataEncoder.cpp
 * @author Yann yann@ethdev.com
 * @date 2014
 * Ethereum IDE client.
 */

#include <QDebug>
#include <QMap>
#include <QStringList>
#include <libdevcore/CommonJS.h>
#include <libsolidity/AST.h>
#include "QVariableDeclaration.h"
#include "QVariableDefinition.h"
#include "ContractCallDataEncoder.h"
using namespace dev;
using namespace dev::solidity;
using namespace dev::mix;

bytes ContractCallDataEncoder::encodedData()
{
	return m_encodedData;
}

void ContractCallDataEncoder::encode(int _functionIndex)
{
	bytes i = jsToBytes(std::to_string(_functionIndex));
	m_encodedData.insert(m_encodedData.end(), i.begin(), i.end());
}

void ContractCallDataEncoder::encode(QVariableDeclaration* _dec, bool _value)
{
	return encode(_dec, QString(formatBool(_value)));
}

void ContractCallDataEncoder::encode(QVariableDeclaration* _dec, QString _value)
{
	int padding = this->padding(_dec->type());
	bytes data = padded(jsToBytes(_value.toStdString()), padding);
	m_encodedData.insert(m_encodedData.end(), data.begin(), data.end());
}

void ContractCallDataEncoder::encode(QVariableDeclaration* _dec, u256 _value)
{
	int padding = this->padding(_dec->type());
	std::ostringstream s;
	s << std::hex << "0x" << _value;
	bytes data = padded(jsToBytes(s.str()), padding);
	m_encodedData.insert(m_encodedData.end(), data.begin(), data.end());
	encodedData();
}

QList<QVariableDefinition*> ContractCallDataEncoder::decode(QList<QVariableDeclaration*> _returnParameters, bytes _value)
{
	QList<QVariableDefinition*> r;
	std::string returnValue = toJS(_value);
	returnValue = returnValue.substr(2, returnValue.length() - 1);
	for (int k = 0; k <_returnParameters.length(); k++)
	{
		QVariableDeclaration* dec = (QVariableDeclaration*)_returnParameters.at(k);
		int padding = this->padding(dec->type());
		std::string rawParam = returnValue.substr(0, padding * 2);
		r.append(new QVariableDefinition(dec, convertToReadable(unpadLeft(rawParam), dec)));
		returnValue = returnValue.substr(rawParam.length(), returnValue.length() - 1);
	}
	return r;
}

int ContractCallDataEncoder::padding(QString type)
{
	// TODO : to be improved (load types automatically from solidity library).
	if (type.indexOf("uint") != -1)
		return integerPadding(type.remove("uint").toInt());
	else if (type.indexOf("int") != -1)
		return integerPadding(type.remove("int").toInt());
	else if (type.indexOf("bool") != -1)
		return 1;
	else if ((type.indexOf("address") != -1))
		return 20;
	else
		return 0;
}

int ContractCallDataEncoder::integerPadding(int bitValue)
{
	return bitValue / 8;
}

QString ContractCallDataEncoder::formatBool(bool _value)
{
	return (_value ? "1" : "0");
}

QString ContractCallDataEncoder::convertToReadable(std::string _v, QVariableDeclaration* _dec)
{
	if (_dec->type().indexOf("int") != -1)
		return convertToInt(_v);
	else if (_dec->type().indexOf("bool") != -1)
		return convertToBool(_v);
	else
		return QString::fromStdString(_v);
}

QString ContractCallDataEncoder::convertToBool(std::string _v)
{
	return _v == "1" ? "true" : "false";
}

QString ContractCallDataEncoder::convertToInt(std::string _v)
{
	//TO DO to be improve to manage all int, uint size (128, 256, ...) in ethereum QML types task #612.
	int x = std::stol(_v, nullptr, 16);
	std::stringstream ss;
	ss << std::dec << x;
	return QString::fromStdString(ss.str());
}
<|endoftext|>


<commit_before>#include "cell.h"
#include "liste.h"

using namespace std;

int main(int argc, char** argv)
{
	Liste L;
	Cell a(1);
	Cell b(2);
	Cell c(3);

	L.setSuivant(L.getPremier(), &a);
	L.setSuivant(&a, &b);
	L.setSuivant(&b, &c);
	L.affiche();

	//Probleme dans le destructeur arrivé à delete p;

	return 0;
}
<commit_msg>Suppression<commit_after><|endoftext|>


<commit_before>f94546e1-ad5b-11e7-becd-ac87a332f658<commit_msg>more fixes<commit_after>f9b88291-ad5b-11e7-8d04-ac87a332f658<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include <fstream>

#include "main.h"
#include "bond_angle.cpp"

using namespace std;
/**
 * @mainpage The Gaussian Optimization Analytical Tool (GOAT)
 *
 * Welcome to the Gaussian Optimization Analytical Tool (GOAT) documentation site!
 * Users may find relevant info related to this program, a program designed to provide
 * structural analyses of biomolecules successfully optimized using Gaussian software.
 *
 * @short   Main program
 * @file    main.cpp
 * @author  Kate Charbonnet, Hannah Lozano, and Thomas Summers
 * @param   none
 * @return  0 on success
 *
 * The purpose of this program is to provide preliminary structural information on biomolecules
 * optimized using Gaussian computational chemistry software.  Structural and chemical properties
 * identified include: element identification, bond length, bond order, central angles, and torsional
 * angles.  Input of the file to be analyzed will result in an output file listing all the structural
 * information of the biomolecule.
 */

int main(int argc, char* argv[]) {
    ifstream inputfile;
    ofstream logfile;
    ifstream bond_angle;
    unsigned int count_line = 0;
    string line;
    string header1 = "Optimized Parameters";
    string header2 = "Standard orientation:";
    string print(string);

    //Check that input file was directed into the command line
    if (argc < 2) {
        cout << "Error: Inputfile not specified in command line\n";
        return 1;
    }

    //Open the input file and check that it opened
    inputfile.open(argv[1]);
    if (!inputfile.is_open()) {
        cout << "Error: Unable to open the input file.";
        return 2;
    }

    //Generate a log file and check that it opened
    logfile.open("log.txt");
    if (!logfile.is_open()) {
        cout << "Error: Unable to open the logfile.";
        return 3;
    } else {
        logfile << "Logfile for Gaussian Optimization Analytical Tool\n";
    }

    //Search the input file for the first keywords
    while (getline(inputfile, line)) {
        count_line++;
        if (line.find(header1, 0) != string::npos) {
            cout << "Found: " << header1 << " at position " << count_line << endl;
            logfile << "Found: " << header1 << " at position " << count_line << endl;
            if (line.find(header2, 0) != string::npos) {
                cout << "Found: " << header2 << " at position " << count_line << endl;
	        logfile << "Found: " << header2 << "at position " << count_line << endl;
            }
	    else {
                cout << "Unable to find " << header2 << endl;
	        logfile << "Unable to find " << header2 << endl;
	        return 4;
            }
            }
    }
    inputfile.close();
    cout << "Search Complete";
    logfile << "Search Complete" << endl;
    logfile.close();
    return 0;

    //Open the file bond_angle.cpp and check that it opened
    bond_angle.open("bond_angle.cpp");
    if (!bond_angle.is_open()) {
        cout << "Error: Unable to open bond_angle file.";
        return 1;
    }
    //Close the file bond_angle.cpp
    bond_angle.close();
    cout << "Bond angle calculation complete.";
    return 0;
}
<commit_msg>added comment that will be a base file when it compiles<commit_after>#include <iostream>
#include <string>
#include <fstream>

#include "main.h"
#include "bond_angle.cpp"
// #include "bond_length.cpp"

using namespace std;
/**
 * @mainpage The Gaussian Optimization Analytical Tool (GOAT)
 *
 * Welcome to the Gaussian Optimization Analytical Tool (GOAT) documentation site!
 * Users may find relevant info related to this program, a program designed to provide
 * structural analyses of biomolecules successfully optimized using Gaussian software.
 *
 * @short   Main program
 * @file    main.cpp
 * @author  Kate Charbonnet, Hannah Lozano, and Thomas Summers
 * @param   none
 * @return  0 on success
 *
 * The purpose of this program is to provide preliminary structural information on biomolecules
 * optimized using Gaussian computational chemistry software.  Structural and chemical properties
 * identified include: element identification, bond length, bond order, central angles, and torsional
 * angles.  Input of the file to be analyzed will result in an output file listing all the structural
 * information of the biomolecule.
 */

int main(int argc, char* argv[]) {
    ifstream inputfile;
    ofstream logfile;
    ifstream bond_angle;
    unsigned int count_line = 0;
    string line;
    string header1 = "Optimized Parameters";
    string header2 = "Standard orientation:";
    string print(string);

    //Check that input file was directed into the command line
    if (argc < 2) {
        cout << "Error: Inputfile not specified in command line\n";
        return 1;
    }

    //Open the input file and check that it opened
    inputfile.open(argv[1]);
    if (!inputfile.is_open()) {
        cout << "Error: Unable to open the input file.";
        return 2;
    }

    //Generate a log file and check that it opened
    logfile.open("log.txt");
    if (!logfile.is_open()) {
        cout << "Error: Unable to open the logfile.";
        return 3;
    } else {
        logfile << "Logfile for Gaussian Optimization Analytical Tool\n";
    }

    //Search the input file for the first keywords
    while (getline(inputfile, line)) {
        count_line++;
        if (line.find(header1, 0) != string::npos) {
            cout << "Found: " << header1 << " at position " << count_line << endl;
            logfile << "Found: " << header1 << " at position " << count_line << endl;
            if (line.find(header2, 0) != string::npos) {
                cout << "Found: " << header2 << " at position " << count_line << endl;
	        logfile << "Found: " << header2 << "at position " << count_line << endl;
            }
	    else {
                cout << "Unable to find " << header2 << endl;
	        logfile << "Unable to find " << header2 << endl;
	        return 4;
            }
            }
    }
    inputfile.close();
    cout << "Search Complete";
    logfile << "Search Complete" << endl;
    logfile.close();
    return 0;

    //Open the file bond_angle.cpp and check that it opened
    bond_angle.open("bond_angle.cpp");
    if (!bond_angle.is_open()) {
        cout << "Error: Unable to open bond_angle file.";
        return 1;
    }
    //Close the file bond_angle.cpp
    bond_angle.close();
    cout << "Bond angle calculation complete.";
    return 0;
}
<|endoftext|>


<commit_before>97ff8e0c-ad5a-11e7-bf59-ac87a332f658<commit_msg>I'm done<commit_after>988e51e6-ad5a-11e7-9ee6-ac87a332f658<|endoftext|>


<commit_before>f26871e3-ad58-11e7-ad24-ac87a332f658<commit_msg>Deal with it<commit_after>f2c919b8-ad58-11e7-a5cb-ac87a332f658<|endoftext|>


<commit_before>ac04271c-4b02-11e5-adf8-28cfe9171a43<commit_msg>more fixes<commit_after>ac10cbca-4b02-11e5-901f-28cfe9171a43<|endoftext|>


<commit_before>#include <iostream>
#include <exception>

#ifdef __APPLE__
# include <OpenGL/OpenGL.h>
# include <GLUT/glut.h>
#else
# include <GL/glut.h>
#endif

using namespace std;

float angle = 0;
float blue = .65;

class esc_except : public exception {
    virtual const char* what() const throw() {
        return "ESC key pressed";
    }
} escape;

void handle_keypress(unsigned char key, int x, int y) {
    switch (key) {
        case 27: // ESC
            throw escape;
    }
}

void init_render() {
    glEnable(GL_DEPTH_TEST);
    glEnable(GL_COLOR_MATERIAL);
    glClearColor(.14, .18, .2, 1);
    glEnable(GL_LIGHTING); //Enable lighting
    glEnable(GL_LIGHT0); //Enable light #0
    glEnable(GL_LIGHT1); //Enable light #1
    glEnable(GL_NORMALIZE); //Automatically normalize normals
    glShadeModel(GL_SMOOTH); //Enable smooth shading
}

void handle_resize(int w, int h) {
    glViewport(0, 0, w, h);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(
        45,                    // camera angle
        double(w) / double(h), // width-to-height ratio
        1, 200                 // near and far z clipping coordinates
    );
}

void draw_scene() {

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    glTranslatef(0, 0, -5);

    // ambient light
    GLfloat ambient_color[] = {.2, .2, .2, 1};
    glLightModelfv(GL_LIGHT_MODEL_AMBIENT, ambient_color);

    // positioned light
    GLfloat light_color0[] = {1, .5, .5, 1};
    GLfloat light_pos0[] = {0, 1, 0, 1};
    glLightfv(GL_LIGHT0, GL_DIFFUSE, light_color0);
    glLightfv(GL_LIGHT0, GL_POSITION, light_pos0);

    // Trapezoid
    glPushMatrix();
    glTranslatef(0, -1, 0);
    glRotatef(angle, 0, 0, 1);
    glBegin(GL_QUADS);

        glColor3f(0.5f, 0.0f, 1-blue);
        glVertex3f(-0.7f, -0.5f, 0.0f);
        glColor3f(0.0f, 0.9f, 0.0f);
        glVertex3f(0.7f, -0.5f, 0.0f);
        glColor3f(1.0f, 0.0f, 0.0f);
        glVertex3f(0.4f, 0.5f, 0.0f);
        glColor3f(0.0f, 0.65f, blue);
        glVertex3f(-0.4f, 0.5f, 0.0f);

    glEnd();
    glPopMatrix();

    // Pentagon
    glPushMatrix();
    glTranslatef(1, 1, 0);
    glRotatef(angle, 0, 1, 0);
    glScalef(.5, .5, .5);
    glBegin(GL_TRIANGLES);

        glVertex3f(-0.5f, -0.5f, 0.0f);
        glVertex3f(0.5f, -0.5f, 0.0f);
        glVertex3f(-0.5f, 0.0f, 0.0f);

        glVertex3f(-0.5f, 0.0f, 0.0f);
        glVertex3f(0.5f, -0.5f, 0.0f);
        glVertex3f(0.5f, 0.0f, 0.0f);

        glVertex3f(-0.5f, 0.0f, 0.0f);
        glVertex3f(0.5f, 0.0f, 0.0f);
        glVertex3f(0.0f, 0.5f, 0.0f);

    glEnd();
    glPopMatrix();

    // Triangle
    glPushMatrix();
    glTranslatef(-1, 1, 0);
    glRotatef(angle, 1, 2, 3);
    glBegin(GL_TRIANGLES);

        glNormal3f(1.f, 0.f, 1.f);
        glVertex3f(0.5f, -0.5f, 0.0f);
        glNormal3f(0.f, 1.f, 1.f);
        glVertex3f(0.0f, 0.5f, 0.0f);
        glNormal3f(-1.0f, 0.0f, 1.0f);
        glVertex3f(-0.5f, -0.5f, 0.0f);

    glEnd();
    glPopMatrix();

    glutSwapBuffers();

}

void update(int value) {

    angle += 2;
    if (angle >= 180) angle -= 360;

    blue += .005;
    if (blue >= 1) blue -= 1;

    glutPostRedisplay();
    glutTimerFunc(25, update, 0);

}

int main(int argc, char** argv) {

    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
    glutInitWindowSize(400, 400);

    glutCreateWindow("OpenWAR");
    init_render();

    glutDisplayFunc(draw_scene);
    glutKeyboardFunc(handle_keypress);
    glutReshapeFunc(handle_resize);
    glutTimerFunc(25, update, 0);

    try {
        glutMainLoop();
    }
    catch (esc_except& e) {
        cout << "Bye." << endl;
    }

    return 0;

}
<commit_msg>now keys are a namespace<commit_after>#include <iostream>
#include <exception>

#ifdef __APPLE__
# include <OpenGL/OpenGL.h>
# include <GLUT/glut.h>
#else
# include <GL/glut.h>
#endif

namespace Key {
    const int ESC = 27;
}

using namespace std;

float angle = 0;
float blue = .65;

class esc_except : public exception {
    virtual const char* what() const throw() {
        return "ESC key pressed";
    }
} escape;

void handle_keypress(unsigned char key, int x, int y) {
    switch (key) {
        case Key::ESC:
            throw escape;
    }
}

void init_render() {
    glEnable(GL_DEPTH_TEST);
    glEnable(GL_COLOR_MATERIAL);
    glClearColor(.14, .18, .2, 1);
    glEnable(GL_LIGHTING); //Enable lighting
    glEnable(GL_LIGHT0); //Enable light #0
    glEnable(GL_LIGHT1); //Enable light #1
    glEnable(GL_NORMALIZE); //Automatically normalize normals
    glShadeModel(GL_SMOOTH); //Enable smooth shading
}

void handle_resize(int w, int h) {
    glViewport(0, 0, w, h);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(
        45,                    // camera angle
        double(w) / double(h), // width-to-height ratio
        1, 200                 // near and far z clipping coordinates
    );
}

void draw_scene() {

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    glTranslatef(0, 0, -5);

    // ambient light
    GLfloat ambient_color[] = {.2, .2, .2, 1};
    glLightModelfv(GL_LIGHT_MODEL_AMBIENT, ambient_color);

    // positioned light
    GLfloat light_color0[] = {1, .5, .5, 1};
    GLfloat light_pos0[] = {0, 1, 0, 1};
    glLightfv(GL_LIGHT0, GL_DIFFUSE, light_color0);
    glLightfv(GL_LIGHT0, GL_POSITION, light_pos0);

    // Trapezoid
    glPushMatrix();
    glTranslatef(0, -1, 0);
    glRotatef(angle, 0, 0, 1);
    glBegin(GL_QUADS);

        glColor3f(0.5f, 0.0f, 1-blue);
        glVertex3f(-0.7f, -0.5f, 0.0f);
        glColor3f(0.0f, 0.9f, 0.0f);
        glVertex3f(0.7f, -0.5f, 0.0f);
        glColor3f(1.0f, 0.0f, 0.0f);
        glVertex3f(0.4f, 0.5f, 0.0f);
        glColor3f(0.0f, 0.65f, blue);
        glVertex3f(-0.4f, 0.5f, 0.0f);

    glEnd();
    glPopMatrix();

    // Pentagon
    glPushMatrix();
    glTranslatef(1, 1, 0);
    glRotatef(angle, 0, 1, 0);
    glScalef(.5, .5, .5);
    glBegin(GL_TRIANGLES);

        glVertex3f(-0.5f, -0.5f, 0.0f);
        glVertex3f(0.5f, -0.5f, 0.0f);
        glVertex3f(-0.5f, 0.0f, 0.0f);

        glVertex3f(-0.5f, 0.0f, 0.0f);
        glVertex3f(0.5f, -0.5f, 0.0f);
        glVertex3f(0.5f, 0.0f, 0.0f);

        glVertex3f(-0.5f, 0.0f, 0.0f);
        glVertex3f(0.5f, 0.0f, 0.0f);
        glVertex3f(0.0f, 0.5f, 0.0f);

    glEnd();
    glPopMatrix();

    // Triangle
    glPushMatrix();
    glTranslatef(-1, 1, 0);
    glRotatef(angle, 1, 2, 3);
    glBegin(GL_TRIANGLES);

        glNormal3f(1.f, 0.f, 1.f);
        glVertex3f(0.5f, -0.5f, 0.0f);
        glNormal3f(0.f, 1.f, 1.f);
        glVertex3f(0.0f, 0.5f, 0.0f);
        glNormal3f(-1.0f, 0.0f, 1.0f);
        glVertex3f(-0.5f, -0.5f, 0.0f);

    glEnd();
    glPopMatrix();

    glutSwapBuffers();

}

void update(int value) {

    angle += 2;
    if (angle >= 180) angle -= 360;

    blue += .005;
    if (blue >= 1) blue -= 1;

    glutPostRedisplay();
    glutTimerFunc(25, update, 0);

}

int main(int argc, char** argv) {

    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
    glutInitWindowSize(400, 400);

    glutCreateWindow("OpenWAR");
    init_render();

    glutDisplayFunc(draw_scene);
    glutKeyboardFunc(handle_keypress);
    glutReshapeFunc(handle_resize);
    glutTimerFunc(25, update, 0);

    try {
        glutMainLoop();
    }
    catch (esc_except& e) {
        cout << "Bye." << endl;
    }

    return 0;

}
<|endoftext|>


<commit_before>/*
     Copyright (C) 2014 Muller Romain

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program 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 General Public License for more details.

    You should have received a copy of the GNU General Public License along
    with this program; if not, write to the Free Software Foundation, Inc.,
    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

*/

#include <QtWidgets/QtWidgets>
#include <QtWidgets/QFileDialog>
#include <QtGui/QImage>

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    QDialog *win = new QDialog;

    QString ImgI = QFileDialog::getOpenFileName(win, "Choisir l'image à convertire", QStandardPaths::writableLocation(QStandardPaths::DesktopLocation), "Images (*.png *.jpg *.jpeg)");

    if(ImgI.isEmpty() || ImgI.isNull())
    {
        QMessageBox::critical(win, "Fichier non trouver !", "Impossible de trouver le fichier !");
        exit(EXIT_FAILURE);
    }

    QString ImgO = QFileDialog::getSaveFileName(win, "Choisir l'emplacement de sauvegarde", ImgI, "Images (*.png *.jpg *.jpeg)");

    if(ImgO.isEmpty() || ImgO.isNull())
    {
        QMessageBox::critical(win, "Fichier non trouver !", "Impossible de trouver le fichier !");
        exit(EXIT_FAILURE);
    }

    QImage tmpImg(ImgI);

    for(int x(0); x < tmpImg.width(); x++)
    {
        for(int y(0); y < tmpImg.height(); y++)
        {
            QRgb rgb = tmpImg.pixel(x, y);

            if(rgb > 0xFFC8C8C8)
            {
                tmpImg.setPixel(x, y, 0xFFFFFF);
            }
        }
    }

    tmpImg.save(ImgO);

    QMessageBox::information(win, "Yeah !", "Fini !");

    exit(EXIT_SUCCESS);

    return app.exec();
}
<commit_msg>Code more readable<commit_after>/*
     Copyright (C) 2014 Muller Romain

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program 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 General Public License for more details.

    You should have received a copy of the GNU General Public License along
    with this program; if not, write to the Free Software Foundation, Inc.,
    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

*/

#include <QtWidgets/QtWidgets>
#include <QtWidgets/QFileDialog>
#include <QtGui/QImage>

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    QDialog *win = new QDialog;

    QString ImgI = QFileDialog::getOpenFileName(
        win,
        "Choisir l'image à convertire",
        QStandardPaths::writableLocation(QStandardPaths::DesktopLocation),
        "Images (*.png *.jpg *.jpeg)"
    );

    if(ImgI.isEmpty() || ImgI.isNull())
    {
        QMessageBox::critical(win, "Fichier non trouver !", "Impossible de trouver le fichier !");
        exit(EXIT_FAILURE);
    }

    QString ImgO = QFileDialog::getSaveFileName(
        win,
        "Choisir l'emplacement de sauvegarde",
        ImgI,
        "Images (*.png *.jpg *.jpeg)"
    );

    if(ImgO.isEmpty() || ImgO.isNull())
    {
        QMessageBox::critical(win, "Fichier non trouver !", "Impossible de trouver le fichier !");
        exit(EXIT_FAILURE);
    }

    QImage tmpImg(ImgI);

    for(int x(0); x < tmpImg.width(); x++)
    {
        for(int y(0); y < tmpImg.height(); y++)
        {
            QRgb rgb = tmpImg.pixel(x, y);

            if(rgb > 0xFFC8C8C8)
            {
                tmpImg.setPixel(x, y, 0xFFFFFF);
            }
        }
    }

    tmpImg.save(ImgO);

    QMessageBox::information(win, "Yeah !", "Fini !");

    exit(EXIT_SUCCESS);

    return app.exec();
}
<|endoftext|>


<commit_before>b89282b0-4b02-11e5-98f6-28cfe9171a43<commit_msg>oh my, I hate charles<commit_after>b89d55a1-4b02-11e5-8f6e-28cfe9171a43<|endoftext|>


<commit_before>
#include <SFML/Graphics.hpp>

int main()
{
    sf::RenderWindow * main_window = new sf::RenderWindow(sf::VideoMode(800, 600, 32), "grinch");
    main_window->UseVerticalSync(true);

    while (main_window->IsOpened()) {
        sf::Event event;
        while (main_window->GetEvent(event)) {
            switch (event.Type) {
                case sf::Event::Closed:
                    main_window->Close();
                    break;
                case sf::Event::Resized:
                    glViewport(0, 0, event.Size.Width, event.Size.Height);
                    break;
                case sf::Event::KeyPressed:
                    // only check for closing here
                    if (event.Key.Code == sf::Key::Escape || (event.Key.Alt && event.Key.Code == sf::Key::F4))
                        main_window->Close();
                    break;
            }
        }

        main_window->Clear();

        main_window->Draw(sf::Shape::Line(10, 10, 710, 100, 15, sf::Color::Red));
        main_window->Draw(sf::Shape::Circle(200, 200, 100, sf::Color::Yellow, 10, sf::Color::Blue));
        main_window->Draw(sf::Shape::Rectangle(350, 200, 600, 350, sf::Color::Green));

        main_window->Display();
    }
    return 0;
}

<commit_msg>reacting to keyboard input<commit_after>
#include <SFML/Graphics.hpp>

static sf::RenderWindow * main_window;

void resized(const sf::Event::SizeEvent & size)
{
    sf::View * default_view = &main_window->GetDefaultView();
    default_view->SetHalfSize(size.Width / 2, size.Height / 2);
}

int main()
{
    main_window = new sf::RenderWindow(sf::VideoMode(800, 600, 32), "grinch");
    main_window->UseVerticalSync(true);

    while (main_window->IsOpened()) {
        sf::Event event;
        while (main_window->GetEvent(event)) {
            switch (event.Type) {
                case sf::Event::Closed:
                    main_window->Close();
                    break;
                case sf::Event::Resized:
                    resized(event.Size);
                    break;
                case sf::Event::KeyPressed:
                    // only check for closing here
                    if (event.Key.Code == sf::Key::Escape || (event.Key.Alt && event.Key.Code == sf::Key::F4))
                        main_window->Close();
                    break;
            }
        }

        const sf::Input * input = &main_window->GetInput();
        if (input->IsKeyDown(sf::Key::Up)) main_window->GetDefaultView().Move(0, -5);
        if (input->IsKeyDown(sf::Key::Left)) main_window->GetDefaultView().Move(-5, 0);
        if (input->IsKeyDown(sf::Key::Down)) main_window->GetDefaultView().Move(0, 5);
        if (input->IsKeyDown(sf::Key::Right)) main_window->GetDefaultView().Move(5, 0);

        if (input->IsKeyDown(sf::Key::Comma)) main_window->GetDefaultView().Zoom(0.9f);
        if (input->IsKeyDown(sf::Key::Period)) main_window->GetDefaultView().Zoom(1.0f / 0.9f);

        main_window->Clear();

        main_window->Draw(sf::Shape::Line(10, 10, 710, 100, 15, sf::Color::Red));
        main_window->Draw(sf::Shape::Circle(200, 200, 100, sf::Color::Yellow, 10, sf::Color::Blue));
        main_window->Draw(sf::Shape::Rectangle(350, 200, 600, 350, sf::Color::Green));

        main_window->Display();
    }
    return 0;
}

<|endoftext|>


<commit_before>#include "lib/sparsepp.h"
using spp::sparse_hash_map;

#include "optionsParser.hpp"
#include "hash.hpp"
#include "degenerate.hpp"
#include "node.hpp"
#include "mutual_information.hpp"
#include "fisher_test.hpp"
#include "graph_simplification.hpp"
#include "meme_format.hpp"

#include <utility>
using std::pair;

#include <chrono>

int main (int argc, char **argv) {

    auto start_chrono_parsing_options = std::chrono::high_resolution_clock::now();

    InputParser input(argc, argv);

    /* Parsing filename */

    const string &positive_filename = input.getCmdOption("-pf");
    if (positive_filename.empty()){
        cerr << "You did not input the positive sequence file, try adding \"-pf path/to/positive\" to the end of your command line" << endl;
        exit(EXIT_FAILURE);
    }

    const string &negative_filename = input.getCmdOption("-nf");
    if (negative_filename.empty()){
        cerr << "You did not input the negative sequence file, try adding \"-nf path/to/negative\" to the end of your command line" << endl;
        exit(EXIT_FAILURE);
    }

    /* Parsing kmere's size */

    const string &length_string = input.getCmdOption("-l");
    if (length_string.empty()){
        cerr << "Please input a motif length putting \"-l length\" to the end of your command line" << endl;
        exit(EXIT_FAILURE);
    }

    int signed_l;
    try {
      signed_l = stoi(length_string);
    } catch (std::invalid_argument& e) {
        cerr << "The motif length you input (" << length_string << ") could not be converted to an int." << endl;
        exit(EXIT_FAILURE);
    } catch (std::out_of_range& e) {
        cerr << "The motif length you input (" << length_string << ") is too big !" << endl;
        cerr << "Note that most of the k-mer will be unique when the size is >= 15" << endl;
        exit(EXIT_FAILURE);
    }
    if (signed_l < 2) {
        cerr << "The motif length must be greater than 1 !" << endl;
        exit(EXIT_FAILURE);
    }

    unsigned int l = signed_l;
    unsigned int d = l;

    if(input.cmdOptionExists("-d")) {

        const string &degeneration_level = input.getCmdOption("-d");
        int signed_d;
        if (degeneration_level.empty()) {
            cerr << "You specified the option -d (limit degeneration) but did not input a value." << endl;
            cerr << "Option usage : append \"-d X\" to the end of your command line." << endl;
            cerr << "Description : Limits the degeneration to at most X positions per motif. Please note that X cannot be greater than l." << endl;
            exit(EXIT_FAILURE);
        }
        else {
            try {
                signed_d = stoi(degeneration_level);
            } catch (std::invalid_argument &e) {
                cerr << "The degeneration limit you entered (" << degeneration_level << ") could not be converted to an int." << endl;
                exit(EXIT_FAILURE);
            } catch (std::out_of_range &e) {
                cerr << "The degeneration limit you entered (" << degeneration_level << ") is way too big !" << endl;
                cerr << "Please note that at most l positions can be degenerated (l being the motif size you chose)." << endl;
                exit(EXIT_FAILURE);
            }
            if (signed_d < 0 || signed_d > signed_l) {
                cerr << "The degeneration limit must be positive, and <= l ! (l being the motif size you chose)" << endl;
                exit(EXIT_FAILURE);
            }
            d = signed_d;
        }
    }

    unsigned int p = 0;
    sparse_hash_map<char, unsigned int> neg_nuc_count{
        {'A', 0},
        {'C', 0},
        {'G', 0},
        {'T', 0}
    };

    string meme_filename = input.getCmdOption("-o");

    if(input.cmdOptionExists("-p")) {
        const string &position = input.getCmdOption("-p");
        int signed_p;
        if (position.empty()) {
            cerr << "You specified the option -p (count only motif that end at a certain pos) but did not input a value." << endl;
            cerr << "Option usage : append \"-p X\" to the end of your command line." << endl;
            cerr << "Description : count only motif that end at pos X in the sequence." << endl;
            cerr << "Please note that the counting is made from the end (ie. -p 0 will only count the last motif of each sequence)." << endl;
            exit(EXIT_FAILURE);
        }
        else {
            try {
                signed_p = stoi(position);
            } catch (std::invalid_argument &e) {
                cerr << "The position you entered (" << position << ") could not be converted to an int." << endl;
                exit(EXIT_FAILURE);
            } catch (std::out_of_range &e) {
                cerr << "The position you entered (" << position << ") is too big !" << endl;
                cerr << "If you believe you should be able to count a motif this far please consider creating an issue." << endl;
                exit(EXIT_FAILURE);
            }
            if (signed_p < 0) {
                cerr << "The degeneration limit must be positive !" << endl;
                exit(EXIT_FAILURE);
            }
            p = signed_p;
        }
    } else {
        if (meme_filename.empty()){
            std::clog << "warning : you did not input a meme output file. \"dinamo_results.meme\" will be created/overriden as default output." << endl;
            meme_filename = "dinamo_results.meme";
        }
    }

    bool rc = !input.cmdOptionExists("-p");

    if(input.cmdOptionExists("-p") && input.cmdOptionExists("-norc")) {
        const string &norc_str = input.getCmdOption("-norc");
        if (!norc_str.empty()) {
            std::cerr << "warning : you provided an argument (" << norc_str << ") to the -norc option but this option doesn't require one." << endl;
        }
        rc = false;
    }

    auto end_chrono_parsing_options = std::chrono::high_resolution_clock::now();
    std::chrono::duration<double> parsing_options_time = end_chrono_parsing_options - start_chrono_parsing_options;
    std::clog << "Parsed options in : " << parsing_options_time.count() << " seconds\n";

    //vector of pointers to hash_map
    vector<sparse_hash_map<string, pair<int, Node *>> *> hash_map_holder(d+1);

    //0_degree_motifs_hash_map
    hash_map_holder[0] = new sparse_hash_map<string, pair<int, Node *>>();

    unsigned int global_motif_count_positive;
    unsigned int global_motif_count_negative;

    //counting k-mers

    auto start_chrono_counting = std::chrono::high_resolution_clock::now();
    std::clog << "======== Counting ========" << endl << endl;

    std::clog << "\tBeginning to read positive file..." << endl;
    if(input.cmdOptionExists("-p"))
         global_motif_count_positive = fill_hash_map_from_pos(*hash_map_holder[0], positive_filename, l, p, true, rc);
    else global_motif_count_positive = fill_hash_map         (*hash_map_holder[0], positive_filename, l,    true, rc, neg_nuc_count);
    std::clog << "\tPositive file read." << endl;

    std::clog << "\tBeginning to read negative file..." << endl;
    if(input.cmdOptionExists("-p"))
         global_motif_count_negative = fill_hash_map_from_pos(*hash_map_holder[0], negative_filename, l, p, false, rc);
    else global_motif_count_negative = fill_hash_map         (*hash_map_holder[0], negative_filename, l,    false, rc, neg_nuc_count);
    std::clog << "\tNegative file read." << endl;

    auto end_chrono_counting = std::chrono::high_resolution_clock::now();
    std::chrono::duration<double> counting_time = end_chrono_counting - start_chrono_counting;
    std::clog << "Counting done in : " << counting_time.count() << " seconds" << endl;

    auto start_chrono_degeneration = std::chrono::high_resolution_clock::now();
    std::clog << endl << "======== Degeneration ========" << endl << endl;

    std::clog << "Before : Total motif count before degeneration" << endl;
    std::clog << "After  : Total motif count after degeneration" << endl;
    std::clog << "\t\t\tBefore\t\tAfter\t\tRatio" << endl;
    unsigned int total_motif_created = hash_map_holder[0]->size();

    for (unsigned int i=0; i < d; i++) {

        double count_before_deg = total_motif_created;
        std::clog << "\tLevel " << i+1 << "\t\t" << total_motif_created << "\t\t";

        hash_map_holder[i+1] = new sparse_hash_map<string, pair<int, Node *>>();
        degenerate(*(hash_map_holder[i]), *(hash_map_holder[i+1]), l, rc);

        total_motif_created += hash_map_holder[i+1]->size();
        std::clog << total_motif_created << "\t\t" << total_motif_created / count_before_deg << endl;
    }

    auto end_chrono_degeneration = std::chrono::high_resolution_clock::now();
    std::chrono::duration<double> degeneration_time = end_chrono_degeneration - start_chrono_degeneration;
    std::clog << "Degeneration done in : " << degeneration_time.count() << " seconds\n";

    auto start_chrono_simplification = std::chrono::high_resolution_clock::now();
    std::clog << endl << "======== Simplification ========" << endl << endl;

    std::clog << "\tGenerating MIs..." << endl;
    //TODO get the number of nodes to define the vector as an array
    std::vector<pair<const string, pair<int, Node *> > *> mi_sorted_hash_map_entries;
    std::vector<pair<const string, pair<int, Node *> > *> pvalue_sorted_hash_map_entries;

    for (auto const &hash_map_reference : hash_map_holder) {
        for (auto &hash_map_entry_ref : *hash_map_reference ) {
            mi_sorted_hash_map_entries.push_back(&hash_map_entry_ref);
            hash_map_entry_ref.second.second->calculate_mi(global_motif_count_positive, global_motif_count_negative);
        }
    }

    std::clog << "\tDone generating MIs." << endl << endl;

    std::clog << "\tSorting entries by MI..." << endl << endl;
    std::sort(  mi_sorted_hash_map_entries.begin(),
                mi_sorted_hash_map_entries.end(),
                [] (const auto entry_one, const auto entry_two) {
                    return entry_one->second.second->get_mi() > entry_two->second.second->get_mi();
                }
             );

    std::clog << "\tSimplificating graph..." << endl;

    graph_simplification(mi_sorted_hash_map_entries, input.cmdOptionExists("-p"));

    std::clog << "\tSimplification done !" << endl << endl;

    std::clog << "\tGenerating pvalue of the remaining entries..." << endl;
    unsigned int m = 0;
    for (auto &entry : mi_sorted_hash_map_entries) {
        if (entry->second.second->get_state() == validated) {
            entry->second.second->calculate_pvalue(global_motif_count_positive, global_motif_count_negative);
            pvalue_sorted_hash_map_entries.push_back(entry);
            m++;
        }
    }
    std::clog << "\tDone generating pvalues." << endl << endl;

    std::clog << "\tSorting the remaining entries by pvalue..." << endl;
    std::sort(  pvalue_sorted_hash_map_entries.begin(),
                pvalue_sorted_hash_map_entries.end(),
                [] (const auto entry_one, const auto entry_two) {
                    return entry_one->second.second->get_pvalue() < entry_two->second.second->get_pvalue();
                }
             );

    auto end_chrono_simplification = std::chrono::high_resolution_clock::now();
    std::chrono::duration<double> simplification_time = end_chrono_simplification - start_chrono_simplification;
    std::clog << "Simplification made in : " << simplification_time.count() << " seconds\n";

    auto start_chrono_holm_test = std::chrono::high_resolution_clock::now();

    std::clog << endl << "======== Holm-Bonferroni ========" << endl << endl;

    std::clog << "\tApplying Holm-Bonferroni method to determine independance of observed values in both files" << endl;

    mi_sorted_hash_map_entries.clear();

    unsigned int k = 0;
    double alpha = 0.05;
    while (pvalue_sorted_hash_map_entries[k]->second.second->get_pvalue()
           <= (alpha / ((double)(m + 1 - k)))
          ) {
        mi_sorted_hash_map_entries.push_back(pvalue_sorted_hash_map_entries[k]);
        k++;
    }

    std::sort(  mi_sorted_hash_map_entries.begin(),
                mi_sorted_hash_map_entries.end(),
                [] (const auto entry_one, const auto entry_two) {
                    return entry_one->second.second->get_mi() > entry_two->second.second->get_mi();
                }
             );

    auto end_chrono_holm_test = std::chrono::high_resolution_clock::now();
    std::chrono::duration<double> holm_test_time = end_chrono_holm_test - start_chrono_holm_test;
    std::clog << "Holm method performed in : " << holm_test_time.count() << " seconds\n";

    std::clog << endl << "======== Results ========" << endl << endl;
    for (auto &entry : mi_sorted_hash_map_entries) {
        std::cout << entry->first << "\t" << entry->second.second->get_mi() << endl;
    }

    if (!input.cmdOptionExists("-p"))
        create_meme_file(mi_sorted_hash_map_entries, *hash_map_holder[0], neg_nuc_count, l, meme_filename);

    // std::clog << endl << "======== Cleaning ========" << endl << endl;
    //
    // for (auto const &hash_map_ptr_reference : hash_map_holder) {
    //     for (auto const &hash_map_value : *hash_map_ptr_reference ) {
    //         delete(hash_map_value.second.second);
    //     }
    //     delete(hash_map_ptr_reference);
    // }
}
<commit_msg>[FEATURE] Removed reverse complementaries from the list of valid motifs, right after graph simplification<commit_after>#include "lib/sparsepp.h"
using spp::sparse_hash_map;

#include "optionsParser.hpp"
#include "hash.hpp"
#include "degenerate.hpp"
#include "node.hpp"
#include "mutual_information.hpp"
#include "fisher_test.hpp"
#include "graph_simplification.hpp"
#include "meme_format.hpp"

#include <utility>
using std::pair;

#include <chrono>

int main (int argc, char **argv) {

    auto start_chrono_parsing_options = std::chrono::high_resolution_clock::now();

    InputParser input(argc, argv);

    /* Parsing filename */

    const string &positive_filename = input.getCmdOption("-pf");
    if (positive_filename.empty()){
        cerr << "You did not input the positive sequence file, try adding \"-pf path/to/positive\" to the end of your command line" << endl;
        exit(EXIT_FAILURE);
    }

    const string &negative_filename = input.getCmdOption("-nf");
    if (negative_filename.empty()){
        cerr << "You did not input the negative sequence file, try adding \"-nf path/to/negative\" to the end of your command line" << endl;
        exit(EXIT_FAILURE);
    }

    /* Parsing kmere's size */

    const string &length_string = input.getCmdOption("-l");
    if (length_string.empty()){
        cerr << "Please input a motif length putting \"-l length\" to the end of your command line" << endl;
        exit(EXIT_FAILURE);
    }

    int signed_l;
    try {
      signed_l = stoi(length_string);
    } catch (std::invalid_argument& e) {
        cerr << "The motif length you input (" << length_string << ") could not be converted to an int." << endl;
        exit(EXIT_FAILURE);
    } catch (std::out_of_range& e) {
        cerr << "The motif length you input (" << length_string << ") is too big !" << endl;
        cerr << "Note that most of the k-mer will be unique when the size is >= 15" << endl;
        exit(EXIT_FAILURE);
    }
    if (signed_l < 2) {
        cerr << "The motif length must be greater than 1 !" << endl;
        exit(EXIT_FAILURE);
    }

    unsigned int l = signed_l;
    unsigned int d = l;

    if(input.cmdOptionExists("-d")) {

        const string &degeneration_level = input.getCmdOption("-d");
        int signed_d;
        if (degeneration_level.empty()) {
            cerr << "You specified the option -d (limit degeneration) but did not input a value." << endl;
            cerr << "Option usage : append \"-d X\" to the end of your command line." << endl;
            cerr << "Description : Limits the degeneration to at most X positions per motif. Please note that X cannot be greater than l." << endl;
            exit(EXIT_FAILURE);
        }
        else {
            try {
                signed_d = stoi(degeneration_level);
            } catch (std::invalid_argument &e) {
                cerr << "The degeneration limit you entered (" << degeneration_level << ") could not be converted to an int." << endl;
                exit(EXIT_FAILURE);
            } catch (std::out_of_range &e) {
                cerr << "The degeneration limit you entered (" << degeneration_level << ") is way too big !" << endl;
                cerr << "Please note that at most l positions can be degenerated (l being the motif size you chose)." << endl;
                exit(EXIT_FAILURE);
            }
            if (signed_d < 0 || signed_d > signed_l) {
                cerr << "The degeneration limit must be positive, and <= l ! (l being the motif size you chose)" << endl;
                exit(EXIT_FAILURE);
            }
            d = signed_d;
        }
    }

    unsigned int p = 0;
    sparse_hash_map<char, unsigned int> neg_nuc_count{
        {'A', 0},
        {'C', 0},
        {'G', 0},
        {'T', 0}
    };

    string meme_filename = input.getCmdOption("-o");

    if(input.cmdOptionExists("-p")) {
        const string &position = input.getCmdOption("-p");
        int signed_p;
        if (position.empty()) {
            cerr << "You specified the option -p (count only motif that end at a certain pos) but did not input a value." << endl;
            cerr << "Option usage : append \"-p X\" to the end of your command line." << endl;
            cerr << "Description : count only motif that end at pos X in the sequence." << endl;
            cerr << "Please note that the counting is made from the end (ie. -p 0 will only count the last motif of each sequence)." << endl;
            exit(EXIT_FAILURE);
        }
        else {
            try {
                signed_p = stoi(position);
            } catch (std::invalid_argument &e) {
                cerr << "The position you entered (" << position << ") could not be converted to an int." << endl;
                exit(EXIT_FAILURE);
            } catch (std::out_of_range &e) {
                cerr << "The position you entered (" << position << ") is too big !" << endl;
                cerr << "If you believe you should be able to count a motif this far please consider creating an issue." << endl;
                exit(EXIT_FAILURE);
            }
            if (signed_p < 0) {
                cerr << "The degeneration limit must be positive !" << endl;
                exit(EXIT_FAILURE);
            }
            p = signed_p;
        }
    } else {
        if (meme_filename.empty()){
            std::clog << "warning : you did not input a meme output file. \"dinamo_results.meme\" will be created/overriden as default output." << endl;
            meme_filename = "dinamo_results.meme";
        }
    }

    bool rc = !input.cmdOptionExists("-p");

    if(input.cmdOptionExists("-p") && input.cmdOptionExists("-norc")) {
        const string &norc_str = input.getCmdOption("-norc");
        if (!norc_str.empty()) {
            std::cerr << "warning : you provided an argument (" << norc_str << ") to the -norc option but this option doesn't require one." << endl;
        }
        rc = false;
    }

    auto end_chrono_parsing_options = std::chrono::high_resolution_clock::now();
    std::chrono::duration<double> parsing_options_time = end_chrono_parsing_options - start_chrono_parsing_options;
    std::clog << "Parsed options in : " << parsing_options_time.count() << " seconds\n";

    //vector of pointers to hash_map
    vector<sparse_hash_map<string, pair<int, Node *>> *> hash_map_holder(d+1);

    //0_degree_motifs_hash_map
    hash_map_holder[0] = new sparse_hash_map<string, pair<int, Node *>>();

    unsigned int global_motif_count_positive;
    unsigned int global_motif_count_negative;

    //counting k-mers

    auto start_chrono_counting = std::chrono::high_resolution_clock::now();
    std::clog << "======== Counting ========" << endl << endl;

    std::clog << "\tBeginning to read positive file..." << endl;
    if(input.cmdOptionExists("-p"))
         global_motif_count_positive = fill_hash_map_from_pos(*hash_map_holder[0], positive_filename, l, p, true, rc);
    else global_motif_count_positive = fill_hash_map         (*hash_map_holder[0], positive_filename, l,    true, rc, neg_nuc_count);
    std::clog << "\tPositive file read." << endl;

    std::clog << "\tBeginning to read negative file..." << endl;
    if(input.cmdOptionExists("-p"))
         global_motif_count_negative = fill_hash_map_from_pos(*hash_map_holder[0], negative_filename, l, p, false, rc);
    else global_motif_count_negative = fill_hash_map         (*hash_map_holder[0], negative_filename, l,    false, rc, neg_nuc_count);
    std::clog << "\tNegative file read." << endl;

    auto end_chrono_counting = std::chrono::high_resolution_clock::now();
    std::chrono::duration<double> counting_time = end_chrono_counting - start_chrono_counting;
    std::clog << "Counting done in : " << counting_time.count() << " seconds" << endl;

    auto start_chrono_degeneration = std::chrono::high_resolution_clock::now();
    std::clog << endl << "======== Degeneration ========" << endl << endl;

    std::clog << "Before : Total motif count before degeneration" << endl;
    std::clog << "After  : Total motif count after degeneration" << endl;
    std::clog << "\t\t\tBefore\t\tAfter\t\tRatio" << endl;
    unsigned int total_motif_created = hash_map_holder[0]->size();

    for (unsigned int i=0; i < d; i++) {

        double count_before_deg = total_motif_created;
        std::clog << "\tLevel " << i+1 << "\t\t" << total_motif_created << "\t\t";

        hash_map_holder[i+1] = new sparse_hash_map<string, pair<int, Node *>>();
        degenerate(*(hash_map_holder[i]), *(hash_map_holder[i+1]), l, rc);

        total_motif_created += hash_map_holder[i+1]->size();
        std::clog << total_motif_created << "\t\t" << total_motif_created / count_before_deg << endl;
    }

    auto end_chrono_degeneration = std::chrono::high_resolution_clock::now();
    std::chrono::duration<double> degeneration_time = end_chrono_degeneration - start_chrono_degeneration;
    std::clog << "Degeneration done in : " << degeneration_time.count() << " seconds\n";

    auto start_chrono_simplification = std::chrono::high_resolution_clock::now();
    std::clog << endl << "======== Simplification ========" << endl << endl;

    std::clog << "\tGenerating MIs..." << endl;
    //TODO get the number of nodes to define the vector as an array
    std::vector<pair<const string, pair<int, Node *> > *> mi_sorted_hash_map_entries;
    std::vector<pair<const string, pair<int, Node *> > *> pvalue_sorted_hash_map_entries;

    for (auto const &hash_map_reference : hash_map_holder) {
        for (auto &hash_map_entry_ref : *hash_map_reference ) {
            mi_sorted_hash_map_entries.push_back(&hash_map_entry_ref);
            hash_map_entry_ref.second.second->calculate_mi(global_motif_count_positive, global_motif_count_negative);
        }
    }

    std::clog << "\tDone generating MIs." << endl << endl;

    std::clog << "\tSorting entries by MI..." << endl << endl;
    std::sort(  mi_sorted_hash_map_entries.begin(),
                mi_sorted_hash_map_entries.end(),
                [] (const auto entry_one, const auto entry_two) {
                    return entry_one->second.second->get_mi() > entry_two->second.second->get_mi();
                }
             );

    std::clog << "\tSimplificating graph..." << endl;

    graph_simplification(mi_sorted_hash_map_entries, input.cmdOptionExists("-p"));

    std::clog << "\tSimplification done !" << endl << endl;

    std::clog << "\tGenerating pvalue of the remaining entries..." << endl;
    unsigned int m = 0;
    for (auto &entry : mi_sorted_hash_map_entries) {
        if (entry->second.second->get_state() == validated) {
            entry->second.second->suppress();
            entry->second.second->calculate_pvalue(global_motif_count_positive, global_motif_count_negative);
            pvalue_sorted_hash_map_entries.push_back(entry);
            m++;
        }
    }
    std::clog << "\tDone generating pvalues." << endl << endl;

    std::clog << "\tSorting the remaining entries by pvalue..." << endl;
    std::sort(  pvalue_sorted_hash_map_entries.begin(),
                pvalue_sorted_hash_map_entries.end(),
                [] (const auto entry_one, const auto entry_two) {
                    return entry_one->second.second->get_pvalue() < entry_two->second.second->get_pvalue();
                }
             );

    auto end_chrono_simplification = std::chrono::high_resolution_clock::now();
    std::chrono::duration<double> simplification_time = end_chrono_simplification - start_chrono_simplification;
    std::clog << "Simplification made in : " << simplification_time.count() << " seconds\n";

    auto start_chrono_holm_test = std::chrono::high_resolution_clock::now();

    std::clog << endl << "======== Holm-Bonferroni ========" << endl << endl;

    std::clog << "\tApplying Holm-Bonferroni method to determine independance of observed values in both files" << endl;

    mi_sorted_hash_map_entries.clear();

    unsigned int k = 0;
    double alpha = 0.05;
    while (pvalue_sorted_hash_map_entries[k]->second.second->get_pvalue()
           <= (alpha / ((double)(m + 1 - k)))
          ) {
        mi_sorted_hash_map_entries.push_back(pvalue_sorted_hash_map_entries[k]);
        k++;
    }

    std::sort(  mi_sorted_hash_map_entries.begin(),
                mi_sorted_hash_map_entries.end(),
                [] (const auto entry_one, const auto entry_two) {
                    return entry_one->second.second->get_mi() > entry_two->second.second->get_mi();
                }
             );

    auto end_chrono_holm_test = std::chrono::high_resolution_clock::now();
    std::chrono::duration<double> holm_test_time = end_chrono_holm_test - start_chrono_holm_test;
    std::clog << "Holm method performed in : " << holm_test_time.count() << " seconds\n";

    std::clog << endl << "======== Results ========" << endl << endl;
    for (auto &entry : mi_sorted_hash_map_entries) {
        std::cout << entry->first << "\t" << entry->second.second->get_mi() << endl;
    }

    if (!input.cmdOptionExists("-p"))
        create_meme_file(mi_sorted_hash_map_entries, *hash_map_holder[0], neg_nuc_count, l, meme_filename);

    // std::clog << endl << "======== Cleaning ========" << endl << endl;
    //
    // for (auto const &hash_map_ptr_reference : hash_map_holder) {
    //     for (auto const &hash_map_value : *hash_map_ptr_reference ) {
    //         delete(hash_map_value.second.second);
    //     }
    //     delete(hash_map_ptr_reference);
    // }
}
<|endoftext|>