<commit_before>#include <osg/Group>
#include <osg/Notify>
#include <osg/Geometry>
#include <osg/ArgumentParser>
#include <osg/ApplicationUsage>
#include <osg/Texture2D>
#include <osg/Geode>
#include <osg/PagedLOD>

#include <osgDB/Registry>
#include <osgDB/ReadFile>
#include <osgDB/WriteFile>

#include <osgUtil/Optimizer>

#include <iostream>
#include <sstream>

class WriteOutPagedLODSubgraphsVistor : public osg::NodeVisitor
{
public:
    WriteOutPagedLODSubgraphsVistor():
        osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN)
    {
    }

    virtual void apply(osg::PagedLOD& plod)
    {

        // go through all the named children and write them out to disk.
        for(unsigned int i=0;i<plod.getNumChildren();++i)
        {
            osg::Node* child = plod.getChild(i);
            std::string filename = plod.getFileName(i);
            if (!filename.empty())
            {
                osg::notify(osg::NOTICE)<<"Writing out "<<filename<<std::endl;
                osgDB::writeNodeFile(*child,filename);
            }
        }

        traverse(plod);
    }
};

class ConvertToPageLODVistor : public osg::NodeVisitor
{
public:
    ConvertToPageLODVistor(const std::string& basename, const std::string& extension):
        osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN),
        _basename(basename),
        _extension(extension)
    {
    }

    virtual ~ConvertToPageLODVistor()
    {
    }

    virtual void apply(osg::LOD& lod)
    {
        _lodSet.insert(&lod);

        traverse(lod);
    }

    virtual void apply(osg::PagedLOD& plod)
    {
        // do thing, but want to avoid call LOD.
        traverse(plod);
    }

    void convert()
    {
        unsigned int lodNum = 0;
        for(LODSet::iterator itr = _lodSet.begin();
            itr != _lodSet.end();
            ++itr, ++lodNum)
        {
            osg::ref_ptr<osg::LOD> lod = const_cast<osg::LOD*>(itr->get());

            if (lod->getNumParents()==0)
            {
                osg::notify(osg::NOTICE)<<"Warning can't operator on root node."<<std::endl;
                break;
            }

            osg::notify(osg::NOTICE)<<"Converting LOD to PagedLOD"<<std::endl;

            osg::PagedLOD* plod = new osg::PagedLOD;

            const osg::LOD::RangeList& originalRangeList = lod->getRangeList();
            typedef std::map< osg::LOD::MinMaxPair , unsigned int > MinMaxPairMap;
            MinMaxPairMap rangeMap;
            unsigned int pos = 0;
            for(osg::LOD::RangeList::const_iterator ritr = originalRangeList.begin();
                ritr != originalRangeList.end();
                ++ritr, ++pos)
            {
                rangeMap[*ritr] = pos;
            }

            pos = 0;
            for(MinMaxPairMap::reverse_iterator mitr = rangeMap.rbegin();
                mitr != rangeMap.rend();
                ++mitr, ++pos)
            {
                if (pos==0)
                {
                    plod->addChild(lod->getChild(mitr->second), mitr->first.first, mitr->first.second);
                   osg::notify(osg::NOTICE)<<"  adding staight child"<<std::endl;
                }
                else
                {
                    std::string filename = _basename;
                    std::ostringstream os;
                    os << _basename << "_"<<lodNum<<"_"<<pos<<_extension;

                    plod->addChild(lod->getChild(mitr->second), mitr->first.first, mitr->first.second, os.str());
                   osg::notify(osg::NOTICE)<<"  adding tiled subgraph"<<os.str()<<std::endl;
                }
            }

            osg::Node::ParentList parents = lod->getParents();
            for(osg::Node::ParentList::iterator pitr=parents.begin();
                pitr!=parents.end();
                ++pitr)
            {
                (*pitr)->replaceChild(lod.get(),plod);
            }

            plod->setCenter(plod->getBound().center());
            plod->setCenter(plod->getBound().center());

        }
    }

    typedef std::set< osg::ref_ptr<osg::LOD> >  LODSet;
    LODSet _lodSet;
    std::string _basename;
    std::string _extension;

};

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

    // use an ArgumentParser object to manage the program arguments.
    osg::ArgumentParser arguments(&argc,argv);

    // set up the usage document, in case we need to print out how to use this program.
    arguments.getApplicationUsage()->setApplicationName(arguments.getApplicationName());
    arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" creates a hierachy of files for paging which can be later loaded by viewers.");
    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...");
    arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");

    // if user request help write it out to cout.
    if (arguments.read("-h") || arguments.read("--help"))
    {
        arguments.getApplicationUsage()->write(std::cout);
        return 1;
    }

    // any option left unread are converted into errors to write out later.
    arguments.reportRemainingOptionsAsUnrecognized();

    // report any errors if they have occured when parsing the program aguments.
    if (arguments.errors())
    {
        arguments.writeErrorMessages(std::cout);
        return 1;
    }

//     if (arguments.argc()<=1)
//     {
//         arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION);
//         return 1;
//     }

    osg::ref_ptr<osg::Node> model = osgDB::readNodeFiles(arguments);

    if (!model)
    {
        osg::notify(osg::NOTICE)<<"No model loaded."<<std::endl;
        return 1;
    }

    ConvertToPageLODVistor converter("tile",".ive");
    model->accept(converter);
    converter.convert();

    if (model.valid())
    {
        osgDB::writeNodeFile(*model,"tile.ive");

        WriteOutPagedLODSubgraphsVistor woplsv;
        model->accept(woplsv);
    }

    return 0;
}
<commit_msg>Updates<commit_after>#include <osg/Group>
#include <osg/Notify>
#include <osg/Geometry>
#include <osg/ArgumentParser>
#include <osg/ApplicationUsage>
#include <osg/Texture2D>
#include <osg/Geode>
#include <osg/PagedLOD>

#include <osgDB/Registry>
#include <osgDB/ReadFile>
#include <osgDB/WriteFile>
#include <osgDB/FileNameUtils>

#include <osgUtil/Optimizer>

#include <iostream>
#include <sstream>

class NameVistor : public osg::NodeVisitor
{
public:
    NameVistor():
        osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN),
        _count(0)
    {
    }

    virtual void apply(osg::Node& node)
    {
        std::ostringstream os;
        os << node.className() << "_"<<_count++;

        node.setName(os.str());

        traverse(node);
    }

    unsigned int _count;
};

class CheckVisitor : public osg::NodeVisitor
{
public:
    CheckVisitor():
        osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN)
    {
    }

    virtual void apply(osg::PagedLOD& plod)
    {
        std::cout<<"PagedLOD "<<plod.getName()<<"  numRanges = "<< plod.getNumRanges()<<"  numFiles = "<<plod.getNumFileNames()<<std::endl;
        for(unsigned int i=0;i<plod.getNumFileNames();++i)
        {
            std::cout<<"  files = '"<<plod.getFileName(i)<<"'"<<std::endl;
        }
    }
};

class WriteOutPagedLODSubgraphsVistor : public osg::NodeVisitor
{
public:
    WriteOutPagedLODSubgraphsVistor():
        osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN)
    {
    }

    virtual void apply(osg::PagedLOD& plod)
    {

        // go through all the named children and write them out to disk.
        for(unsigned int i=0;i<plod.getNumChildren();++i)
        {
            osg::Node* child = plod.getChild(i);
            std::string filename = plod.getFileName(i);
            if (!filename.empty())
            {
                osg::notify(osg::NOTICE)<<"Writing out "<<filename<<std::endl;
                osgDB::writeNodeFile(*child,filename);
            }
        }

        traverse(plod);
    }
};

class ConvertToPageLODVistor : public osg::NodeVisitor
{
public:
    ConvertToPageLODVistor(const std::string& basename, const std::string& extension, bool makeAllChildrenPaged):
        osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN),
        _basename(basename),
        _extension(extension),
        _makeAllChildrenPaged(makeAllChildrenPaged)
    {
    }

    virtual ~ConvertToPageLODVistor()
    {
    }

    virtual void apply(osg::LOD& lod)
    {
        _lodSet.insert(&lod);

        traverse(lod);
    }

    virtual void apply(osg::PagedLOD& plod)
    {
        // do thing, but want to avoid call LOD.
        traverse(plod);
    }

    void convert()
    {
        unsigned int lodNum = 0;
        for(LODSet::iterator itr = _lodSet.begin();
            itr != _lodSet.end();
            ++itr, ++lodNum)
        {
            osg::ref_ptr<osg::LOD> lod = const_cast<osg::LOD*>(itr->get());

            if (lod->getNumParents()==0)
            {
                osg::notify(osg::NOTICE)<<"Warning can't operator on root node."<<std::endl;
                break;
            }

            if (!_makeAllChildrenPaged && lod->getNumRanges()<2)
            {
                osg::notify(osg::NOTICE)<<"Leaving LOD with one child as is."<<std::endl;
                break;
            }

            osg::notify(osg::NOTICE)<<"Converting LOD to PagedLOD."<<std::endl;

            osg::PagedLOD* plod = new osg::PagedLOD;

            const osg::LOD::RangeList& originalRangeList = lod->getRangeList();
            typedef std::multimap< osg::LOD::MinMaxPair , unsigned int > MinMaxPairMap;
            MinMaxPairMap rangeMap;
            unsigned int pos = 0;
            for(osg::LOD::RangeList::const_iterator ritr = originalRangeList.begin();
                ritr != originalRangeList.end();
                ++ritr, ++pos)
            {
                rangeMap.insert(std::multimap< osg::LOD::MinMaxPair , unsigned int >::value_type(*ritr, pos));
            }

            pos = 0;
            for(MinMaxPairMap::reverse_iterator mitr = rangeMap.rbegin();
                mitr != rangeMap.rend();
                ++mitr, ++pos)
            {
                if (pos==0 && !_makeAllChildrenPaged)
                {
                    plod->addChild(lod->getChild(mitr->second), mitr->first.first, mitr->first.second);
                }
                else
                {
                    std::string filename = _basename;
                    std::ostringstream os;
                    os << _basename << "_"<<lodNum<<"_"<<pos<<_extension;

                    plod->addChild(lod->getChild(mitr->second), mitr->first.first, mitr->first.second, os.str());
                }
            }

            osg::Node::ParentList parents = lod->getParents();
            for(osg::Node::ParentList::iterator pitr=parents.begin();
                pitr!=parents.end();
                ++pitr)
            {
                (*pitr)->replaceChild(lod.get(),plod);
            }

            plod->setCenter(plod->getBound().center());

        }
    }

    typedef std::set< osg::ref_ptr<osg::LOD> >  LODSet;
    LODSet _lodSet;
    std::string _basename;
    std::string _extension;
    bool _makeAllChildrenPaged;
};

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

    // use an ArgumentParser object to manage the program arguments.
    osg::ArgumentParser arguments(&argc,argv);

    // set up the usage document, in case we need to print out how to use this program.
    arguments.getApplicationUsage()->setApplicationName(arguments.getApplicationName());
    arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" creates a hierachy of files for paging which can be later loaded by viewers.");
    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...");
    arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
    arguments.getApplicationUsage()->addCommandLineOption("-o","set the output file (defaults to output.ive)");
    arguments.getApplicationUsage()->addCommandLineOption("--makeAllChildrenPaged","Force all children of LOD to be written out as external PagedLOD children");

    // if user request help write it out to cout.
    if (arguments.read("-h") || arguments.read("--help"))
    {
        arguments.getApplicationUsage()->write(std::cout);
        return 1;
    }

    std::string outputfile("output.ive");
    while (arguments.read("-o",outputfile)) {}

    bool makeAllChildrenPaged = false;
    while (arguments.read("--makeAllChildrenPaged")) { makeAllChildrenPaged = true; }

    // any option left unread are converted into errors to write out later.
    arguments.reportRemainingOptionsAsUnrecognized();

    // report any errors if they have occured when parsing the program aguments.
    if (arguments.errors())
    {
        arguments.writeErrorMessages(std::cout);
        return 1;
    }

//     if (arguments.argc()<=1)
//     {
//         arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION);
//         return 1;
//     }

    osg::ref_ptr<osg::Node> model = osgDB::readNodeFiles(arguments);

    if (!model)
    {
        osg::notify(osg::NOTICE)<<"No model loaded."<<std::endl;
        return 1;
    }

    std::string basename( osgDB::getNameLessExtension(outputfile) );
    std::string ext = '.'+ osgDB::getFileExtension(outputfile);

    ConvertToPageLODVistor converter(basename,ext, makeAllChildrenPaged);
    model->accept(converter);
    converter.convert();

    NameVistor nameNodes;
    model->accept(nameNodes);

    //CheckVisitor checkNodes;
    //model->accept(checkNodes);

    if (model.valid())
    {
        osgDB::writeNodeFile(*model,outputfile);

        WriteOutPagedLODSubgraphsVistor woplsv;
        model->accept(woplsv);
    }

    return 0;
}
<|endoftext|>


<commit_before>//===-- MipsTargetInfo.cpp - Mips Target Implementation -------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "Mips.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/TargetRegistry.h"
using namespace llvm;

Target &llvm::getTheMipsTarget() {
  static Target TheMipsTarget;
  return TheMipsTarget;
}
Target &llvm::getTheMipselTarget() {
  static Target TheMipselTarget;
  return TheMipselTarget;
}
Target &llvm::getTheMips64Target() {
  static Target TheMips64Target;
  return TheMips64Target;
}
Target &llvm::getTheMips64elTarget() {
  static Target TheMips64elTarget;
  return TheMips64elTarget;
}

extern "C" void LLVMInitializeMipsTargetInfo() {
  RegisterTarget<Triple::mips,
                 /*HasJIT=*/true>
      X(getTheMipsTarget(), "mips", "Mips", "Mips");

  RegisterTarget<Triple::mipsel,
                 /*HasJIT=*/true>
      Y(getTheMipselTarget(), "mipsel", "Mipsel", "Mips");

  RegisterTarget<Triple::mips64,
                 /*HasJIT=*/true>
      A(getTheMips64Target(), "mips64", "Mips64 [experimental]", "Mips");

  RegisterTarget<Triple::mips64el,
                 /*HasJIT=*/true>
      B(getTheMips64elTarget(), "mips64el", "Mips64el [experimental]", "Mips");
}
<commit_msg>[mips] Remove obsoleted "experimental" tag from MIPS 64-bit targets. NFC<commit_after>//===-- MipsTargetInfo.cpp - Mips Target Implementation -------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "Mips.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/TargetRegistry.h"
using namespace llvm;

Target &llvm::getTheMipsTarget() {
  static Target TheMipsTarget;
  return TheMipsTarget;
}
Target &llvm::getTheMipselTarget() {
  static Target TheMipselTarget;
  return TheMipselTarget;
}
Target &llvm::getTheMips64Target() {
  static Target TheMips64Target;
  return TheMips64Target;
}
Target &llvm::getTheMips64elTarget() {
  static Target TheMips64elTarget;
  return TheMips64elTarget;
}

extern "C" void LLVMInitializeMipsTargetInfo() {
  RegisterTarget<Triple::mips,
                 /*HasJIT=*/true>
      X(getTheMipsTarget(), "mips", "Mips", "Mips");

  RegisterTarget<Triple::mipsel,
                 /*HasJIT=*/true>
      Y(getTheMipselTarget(), "mipsel", "Mipsel", "Mips");

  RegisterTarget<Triple::mips64,
                 /*HasJIT=*/true>
      A(getTheMips64Target(), "mips64", "Mips64", "Mips");

  RegisterTarget<Triple::mips64el,
                 /*HasJIT=*/true>
      B(getTheMips64elTarget(), "mips64el", "Mips64el", "Mips");
}
<|endoftext|>


<commit_before>//===-- VPlanHCFGBuilder.cpp ----------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
/// \file
/// This file implements the construction of a VPlan-based Hierarchical CFG
/// (H-CFG) for an incoming IR. This construction comprises the following
/// components and steps:
//
/// 1. PlainCFGBuilder class: builds a plain VPBasicBlock-based CFG that
/// faithfully represents the CFG in the incoming IR. A VPRegionBlock (Top
/// Region) is created to enclose and serve as parent of all the VPBasicBlocks
/// in the plain CFG.
/// NOTE: At this point, there is a direct correspondence between all the
/// VPBasicBlocks created for the initial plain CFG and the incoming
/// BasicBlocks. However, this might change in the future.
///
//===----------------------------------------------------------------------===//

#include "VPlanHCFGBuilder.h"
#include "LoopVectorizationPlanner.h"
#include "llvm/Analysis/LoopIterator.h"

#define DEBUG_TYPE "loop-vectorize"

using namespace llvm;

// Class that is used to build the plain CFG for the incoming IR.
class PlainCFGBuilder {
private:
  // The outermost loop of the input loop nest considered for vectorization.
  Loop *TheLoop;

  // Loop Info analysis.
  LoopInfo *LI;

  // Vectorization plan that we are working on.
  VPlan &Plan;

  // Output Top Region.
  VPRegionBlock *TopRegion = nullptr;

  // Builder of the VPlan instruction-level representation.
  VPBuilder VPIRBuilder;

  // NOTE: The following maps are intentionally destroyed after the plain CFG
  // construction because subsequent VPlan-to-VPlan transformation may
  // invalidate them.
  // Map incoming BasicBlocks to their newly-created VPBasicBlocks.
  DenseMap<BasicBlock *, VPBasicBlock *> BB2VPBB;
  // Map incoming Value definitions to their newly-created VPValues.
  DenseMap<Value *, VPValue *> IRDef2VPValue;

  // Hold phi node's that need to be fixed once the plain CFG has been built.
  SmallVector<PHINode *, 8> PhisToFix;

  // Utility functions.
  void setVPBBPredsFromBB(VPBasicBlock *VPBB, BasicBlock *BB);
  void fixPhiNodes();
  VPBasicBlock *getOrCreateVPBB(BasicBlock *BB);
  bool isExternalDef(Value *Val);
  VPValue *getOrCreateVPOperand(Value *IRVal);
  void createVPInstructionsForVPBB(VPBasicBlock *VPBB, BasicBlock *BB);

public:
  PlainCFGBuilder(Loop *Lp, LoopInfo *LI, VPlan &P)
      : TheLoop(Lp), LI(LI), Plan(P) {}

  // Build the plain CFG and return its Top Region.
  VPRegionBlock *buildPlainCFG();
};

// Return true if \p Inst is an incoming Instruction to be ignored in the VPlan
// representation.
static bool isInstructionToIgnore(Instruction *Inst) {
  return isa<BranchInst>(Inst);
}

// Set predecessors of \p VPBB in the same order as they are in \p BB. \p VPBB
// must have no predecessors.
void PlainCFGBuilder::setVPBBPredsFromBB(VPBasicBlock *VPBB, BasicBlock *BB) {
  SmallVector<VPBlockBase *, 8> VPBBPreds;
  // Collect VPBB predecessors.
  for (BasicBlock *Pred : predecessors(BB))
    VPBBPreds.push_back(getOrCreateVPBB(Pred));

  VPBB->setPredecessors(VPBBPreds);
}

// Add operands to VPInstructions representing phi nodes from the input IR.
void PlainCFGBuilder::fixPhiNodes() {
  for (auto *Phi : PhisToFix) {
    assert(IRDef2VPValue.count(Phi) && "Missing VPInstruction for PHINode.");
    VPValue *VPVal = IRDef2VPValue[Phi];
    assert(isa<VPInstruction>(VPVal) && "Expected VPInstruction for phi node.");
    auto *VPPhi = cast<VPInstruction>(VPVal);
    assert(VPPhi->getNumOperands() == 0 &&
           "Expected VPInstruction with no operands.");

    for (Value *Op : Phi->operands())
      VPPhi->addOperand(getOrCreateVPOperand(Op));
  }
}

// Create a new empty VPBasicBlock for an incoming BasicBlock or retrieve an
// existing one if it was already created.
VPBasicBlock *PlainCFGBuilder::getOrCreateVPBB(BasicBlock *BB) {
  auto BlockIt = BB2VPBB.find(BB);
  if (BlockIt != BB2VPBB.end())
    // Retrieve existing VPBB.
    return BlockIt->second;

  // Create new VPBB.
  LLVM_DEBUG(dbgs() << "Creating VPBasicBlock for " << BB->getName() << "\n");
  VPBasicBlock *VPBB = new VPBasicBlock(BB->getName());
  BB2VPBB[BB] = VPBB;
  VPBB->setParent(TopRegion);
  return VPBB;
}

// Return true if \p Val is considered an external definition. An external
// definition is either:
// 1. A Value that is not an Instruction. This will be refined in the future.
// 2. An Instruction that is outside of the CFG snippet represented in VPlan,
// i.e., is not part of: a) the loop nest, b) outermost loop PH and, c)
// outermost loop exits.
bool PlainCFGBuilder::isExternalDef(Value *Val) {
  // All the Values that are not Instructions are considered external
  // definitions for now.
  Instruction *Inst = dyn_cast<Instruction>(Val);
  if (!Inst)
    return true;

  BasicBlock *InstParent = Inst->getParent();
  assert(InstParent && "Expected instruction parent.");

  // Check whether Instruction definition is in loop PH.
  BasicBlock *PH = TheLoop->getLoopPreheader();
  assert(PH && "Expected loop pre-header.");

  if (InstParent == PH)
    // Instruction definition is in outermost loop PH.
    return false;

  // Check whether Instruction definition is in the loop exit.
  BasicBlock *Exit = TheLoop->getUniqueExitBlock();
  assert(Exit && "Expected loop with single exit.");
  if (InstParent == Exit) {
    // Instruction definition is in outermost loop exit.
    return false;
  }

  // Check whether Instruction definition is in loop body.
  return !TheLoop->contains(Inst);
}

// Create a new VPValue or retrieve an existing one for the Instruction's
// operand \p IRVal. This function must only be used to create/retrieve VPValues
// for *Instruction's operands* and not to create regular VPInstruction's. For
// the latter, please, look at 'createVPInstructionsForVPBB'.
VPValue *PlainCFGBuilder::getOrCreateVPOperand(Value *IRVal) {
  auto VPValIt = IRDef2VPValue.find(IRVal);
  if (VPValIt != IRDef2VPValue.end())
    // Operand has an associated VPInstruction or VPValue that was previously
    // created.
    return VPValIt->second;

  // Operand doesn't have a previously created VPInstruction/VPValue. This
  // means that operand is:
  //   A) a definition external to VPlan,
  //   B) any other Value without specific representation in VPlan.
  // For now, we use VPValue to represent A and B and classify both as external
  // definitions. We may introduce specific VPValue subclasses for them in the
  // future.
  assert(isExternalDef(IRVal) && "Expected external definition as operand.");

  // A and B: Create VPValue and add it to the pool of external definitions and
  // to the Value->VPValue map.
  VPValue *NewVPVal = new VPValue(IRVal);
  Plan.addExternalDef(NewVPVal);
  IRDef2VPValue[IRVal] = NewVPVal;
  return NewVPVal;
}

// Create new VPInstructions in a VPBasicBlock, given its BasicBlock
// counterpart. This function must be invoked in RPO so that the operands of a
// VPInstruction in \p BB have been visited before (except for Phi nodes).
void PlainCFGBuilder::createVPInstructionsForVPBB(VPBasicBlock *VPBB,
                                                  BasicBlock *BB) {
  VPIRBuilder.setInsertPoint(VPBB);
  for (Instruction &InstRef : *BB) {
    Instruction *Inst = &InstRef;
    if (isInstructionToIgnore(Inst))
      continue;

    // There should't be any VPValue for Inst at this point. Otherwise, we
    // visited Inst when we shouldn't, breaking the RPO traversal order.
    assert(!IRDef2VPValue.count(Inst) &&
           "Instruction shouldn't have been visited.");

    VPInstruction *NewVPInst;
    if (PHINode *Phi = dyn_cast<PHINode>(Inst)) {
      // Phi node's operands may have not been visited at this point. We create
      // an empty VPInstruction that we will fix once the whole plain CFG has
      // been built.
      NewVPInst = cast<VPInstruction>(VPIRBuilder.createNaryOp(
          Inst->getOpcode(), {} /*No operands*/, Inst));
      PhisToFix.push_back(Phi);
    } else {
      // Translate LLVM-IR operands into VPValue operands and set them in the
      // new VPInstruction.
      SmallVector<VPValue *, 4> VPOperands;
      for (Value *Op : Inst->operands())
        VPOperands.push_back(getOrCreateVPOperand(Op));

      // Build VPInstruction for any arbitraty Instruction without specific
      // representation in VPlan.
      NewVPInst = cast<VPInstruction>(
          VPIRBuilder.createNaryOp(Inst->getOpcode(), VPOperands, Inst));
    }

    IRDef2VPValue[Inst] = NewVPInst;
  }
}

// Main interface to build the plain CFG.
VPRegionBlock *PlainCFGBuilder::buildPlainCFG() {
  // 1. Create the Top Region. It will be the parent of all VPBBs.
  TopRegion = new VPRegionBlock("TopRegion", false /*isReplicator*/);

  // 2. Scan the body of the loop in a topological order to visit each basic
  // block after having visited its predecessor basic blocks. Create a VPBB for
  // each BB and link it to its successor and predecessor VPBBs. Note that
  // predecessors must be set in the same order as they are in the incomming IR.
  // Otherwise, there might be problems with existing phi nodes and algorithm
  // based on predecessors traversal.

  // Loop PH needs to be explicitly visited since it's not taken into account by
  // LoopBlocksDFS.
  BasicBlock *PreheaderBB = TheLoop->getLoopPreheader();
  assert((PreheaderBB->getTerminator()->getNumSuccessors() == 1) &&
         "Unexpected loop preheader");
  VPBasicBlock *PreheaderVPBB = getOrCreateVPBB(PreheaderBB);
  createVPInstructionsForVPBB(PreheaderVPBB, PreheaderBB);
  // Create empty VPBB for Loop H so that we can link PH->H.
  VPBlockBase *HeaderVPBB = getOrCreateVPBB(TheLoop->getHeader());
  // Preheader's predecessors will be set during the loop RPO traversal below.
  PreheaderVPBB->setOneSuccessor(HeaderVPBB);

  LoopBlocksRPO RPO(TheLoop);
  RPO.perform(LI);

  for (BasicBlock *BB : RPO) {
    // Create or retrieve the VPBasicBlock for this BB and create its
    // VPInstructions.
    VPBasicBlock *VPBB = getOrCreateVPBB(BB);
    createVPInstructionsForVPBB(VPBB, BB);

    // Set VPBB successors. We create empty VPBBs for successors if they don't
    // exist already. Recipes will be created when the successor is visited
    // during the RPO traversal.
    TerminatorInst *TI = BB->getTerminator();
    assert(TI && "Terminator expected.");
    unsigned NumSuccs = TI->getNumSuccessors();

    if (NumSuccs == 1) {
      VPBasicBlock *SuccVPBB = getOrCreateVPBB(TI->getSuccessor(0));
      assert(SuccVPBB && "VPBB Successor not found.");
      VPBB->setOneSuccessor(SuccVPBB);
    } else if (NumSuccs == 2) {
      VPBasicBlock *SuccVPBB0 = getOrCreateVPBB(TI->getSuccessor(0));
      assert(SuccVPBB0 && "Successor 0 not found.");
      VPBasicBlock *SuccVPBB1 = getOrCreateVPBB(TI->getSuccessor(1));
      assert(SuccVPBB1 && "Successor 1 not found.");
      VPBB->setTwoSuccessors(SuccVPBB0, SuccVPBB1);
    } else
      llvm_unreachable("Number of successors not supported.");

    // Set VPBB predecessors in the same order as they are in the incoming BB.
    setVPBBPredsFromBB(VPBB, BB);
  }

  // 3. Process outermost loop exit. We created an empty VPBB for the loop
  // single exit BB during the RPO traversal of the loop body but Instructions
  // weren't visited because it's not part of the the loop.
  BasicBlock *LoopExitBB = TheLoop->getUniqueExitBlock();
  assert(LoopExitBB && "Loops with multiple exits are not supported.");
  VPBasicBlock *LoopExitVPBB = BB2VPBB[LoopExitBB];
  createVPInstructionsForVPBB(LoopExitVPBB, LoopExitBB);
  // Loop exit was already set as successor of the loop exiting BB.
  // We only set its predecessor VPBB now.
  setVPBBPredsFromBB(LoopExitVPBB, LoopExitBB);

  // 4. The whole CFG has been built at this point so all the input Values must
  // have a VPlan couterpart. Fix VPlan phi nodes by adding their corresponding
  // VPlan operands.
  fixPhiNodes();

  // 5. Final Top Region setup. Set outermost loop pre-header and single exit as
  // Top Region entry and exit.
  TopRegion->setEntry(PreheaderVPBB);
  TopRegion->setExit(LoopExitVPBB);
  return TopRegion;
}

// Public interface to build a H-CFG.
void VPlanHCFGBuilder::buildHierarchicalCFG(VPlan &Plan) {
  // Build Top Region enclosing the plain CFG and set it as VPlan entry.
  PlainCFGBuilder PCFGBuilder(TheLoop, LI, Plan);
  VPRegionBlock *TopRegion = PCFGBuilder.buildPlainCFG();
  Plan.setEntry(TopRegion);
  LLVM_DEBUG(Plan.setName("HCFGBuilder: Plain CFG\n"); dbgs() << Plan);

  Verifier.verifyHierarchicalCFG(TopRegion);
}
<commit_msg>[NFC][VPlan] Wrap PlainCFGBuilder with an anonymous namespace.<commit_after>//===-- VPlanHCFGBuilder.cpp ----------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
/// \file
/// This file implements the construction of a VPlan-based Hierarchical CFG
/// (H-CFG) for an incoming IR. This construction comprises the following
/// components and steps:
//
/// 1. PlainCFGBuilder class: builds a plain VPBasicBlock-based CFG that
/// faithfully represents the CFG in the incoming IR. A VPRegionBlock (Top
/// Region) is created to enclose and serve as parent of all the VPBasicBlocks
/// in the plain CFG.
/// NOTE: At this point, there is a direct correspondence between all the
/// VPBasicBlocks created for the initial plain CFG and the incoming
/// BasicBlocks. However, this might change in the future.
///
//===----------------------------------------------------------------------===//

#include "VPlanHCFGBuilder.h"
#include "LoopVectorizationPlanner.h"
#include "llvm/Analysis/LoopIterator.h"

#define DEBUG_TYPE "loop-vectorize"

using namespace llvm;

namespace {
// Class that is used to build the plain CFG for the incoming IR.
class PlainCFGBuilder {
private:
  // The outermost loop of the input loop nest considered for vectorization.
  Loop *TheLoop;

  // Loop Info analysis.
  LoopInfo *LI;

  // Vectorization plan that we are working on.
  VPlan &Plan;

  // Output Top Region.
  VPRegionBlock *TopRegion = nullptr;

  // Builder of the VPlan instruction-level representation.
  VPBuilder VPIRBuilder;

  // NOTE: The following maps are intentionally destroyed after the plain CFG
  // construction because subsequent VPlan-to-VPlan transformation may
  // invalidate them.
  // Map incoming BasicBlocks to their newly-created VPBasicBlocks.
  DenseMap<BasicBlock *, VPBasicBlock *> BB2VPBB;
  // Map incoming Value definitions to their newly-created VPValues.
  DenseMap<Value *, VPValue *> IRDef2VPValue;

  // Hold phi node's that need to be fixed once the plain CFG has been built.
  SmallVector<PHINode *, 8> PhisToFix;

  // Utility functions.
  void setVPBBPredsFromBB(VPBasicBlock *VPBB, BasicBlock *BB);
  void fixPhiNodes();
  VPBasicBlock *getOrCreateVPBB(BasicBlock *BB);
  bool isExternalDef(Value *Val);
  VPValue *getOrCreateVPOperand(Value *IRVal);
  void createVPInstructionsForVPBB(VPBasicBlock *VPBB, BasicBlock *BB);

public:
  PlainCFGBuilder(Loop *Lp, LoopInfo *LI, VPlan &P)
      : TheLoop(Lp), LI(LI), Plan(P) {}

  // Build the plain CFG and return its Top Region.
  VPRegionBlock *buildPlainCFG();
};
} // anonymous namespace

// Return true if \p Inst is an incoming Instruction to be ignored in the VPlan
// representation.
static bool isInstructionToIgnore(Instruction *Inst) {
  return isa<BranchInst>(Inst);
}

// Set predecessors of \p VPBB in the same order as they are in \p BB. \p VPBB
// must have no predecessors.
void PlainCFGBuilder::setVPBBPredsFromBB(VPBasicBlock *VPBB, BasicBlock *BB) {
  SmallVector<VPBlockBase *, 8> VPBBPreds;
  // Collect VPBB predecessors.
  for (BasicBlock *Pred : predecessors(BB))
    VPBBPreds.push_back(getOrCreateVPBB(Pred));

  VPBB->setPredecessors(VPBBPreds);
}

// Add operands to VPInstructions representing phi nodes from the input IR.
void PlainCFGBuilder::fixPhiNodes() {
  for (auto *Phi : PhisToFix) {
    assert(IRDef2VPValue.count(Phi) && "Missing VPInstruction for PHINode.");
    VPValue *VPVal = IRDef2VPValue[Phi];
    assert(isa<VPInstruction>(VPVal) && "Expected VPInstruction for phi node.");
    auto *VPPhi = cast<VPInstruction>(VPVal);
    assert(VPPhi->getNumOperands() == 0 &&
           "Expected VPInstruction with no operands.");

    for (Value *Op : Phi->operands())
      VPPhi->addOperand(getOrCreateVPOperand(Op));
  }
}

// Create a new empty VPBasicBlock for an incoming BasicBlock or retrieve an
// existing one if it was already created.
VPBasicBlock *PlainCFGBuilder::getOrCreateVPBB(BasicBlock *BB) {
  auto BlockIt = BB2VPBB.find(BB);
  if (BlockIt != BB2VPBB.end())
    // Retrieve existing VPBB.
    return BlockIt->second;

  // Create new VPBB.
  LLVM_DEBUG(dbgs() << "Creating VPBasicBlock for " << BB->getName() << "\n");
  VPBasicBlock *VPBB = new VPBasicBlock(BB->getName());
  BB2VPBB[BB] = VPBB;
  VPBB->setParent(TopRegion);
  return VPBB;
}

// Return true if \p Val is considered an external definition. An external
// definition is either:
// 1. A Value that is not an Instruction. This will be refined in the future.
// 2. An Instruction that is outside of the CFG snippet represented in VPlan,
// i.e., is not part of: a) the loop nest, b) outermost loop PH and, c)
// outermost loop exits.
bool PlainCFGBuilder::isExternalDef(Value *Val) {
  // All the Values that are not Instructions are considered external
  // definitions for now.
  Instruction *Inst = dyn_cast<Instruction>(Val);
  if (!Inst)
    return true;

  BasicBlock *InstParent = Inst->getParent();
  assert(InstParent && "Expected instruction parent.");

  // Check whether Instruction definition is in loop PH.
  BasicBlock *PH = TheLoop->getLoopPreheader();
  assert(PH && "Expected loop pre-header.");

  if (InstParent == PH)
    // Instruction definition is in outermost loop PH.
    return false;

  // Check whether Instruction definition is in the loop exit.
  BasicBlock *Exit = TheLoop->getUniqueExitBlock();
  assert(Exit && "Expected loop with single exit.");
  if (InstParent == Exit) {
    // Instruction definition is in outermost loop exit.
    return false;
  }

  // Check whether Instruction definition is in loop body.
  return !TheLoop->contains(Inst);
}

// Create a new VPValue or retrieve an existing one for the Instruction's
// operand \p IRVal. This function must only be used to create/retrieve VPValues
// for *Instruction's operands* and not to create regular VPInstruction's. For
// the latter, please, look at 'createVPInstructionsForVPBB'.
VPValue *PlainCFGBuilder::getOrCreateVPOperand(Value *IRVal) {
  auto VPValIt = IRDef2VPValue.find(IRVal);
  if (VPValIt != IRDef2VPValue.end())
    // Operand has an associated VPInstruction or VPValue that was previously
    // created.
    return VPValIt->second;

  // Operand doesn't have a previously created VPInstruction/VPValue. This
  // means that operand is:
  //   A) a definition external to VPlan,
  //   B) any other Value without specific representation in VPlan.
  // For now, we use VPValue to represent A and B and classify both as external
  // definitions. We may introduce specific VPValue subclasses for them in the
  // future.
  assert(isExternalDef(IRVal) && "Expected external definition as operand.");

  // A and B: Create VPValue and add it to the pool of external definitions and
  // to the Value->VPValue map.
  VPValue *NewVPVal = new VPValue(IRVal);
  Plan.addExternalDef(NewVPVal);
  IRDef2VPValue[IRVal] = NewVPVal;
  return NewVPVal;
}

// Create new VPInstructions in a VPBasicBlock, given its BasicBlock
// counterpart. This function must be invoked in RPO so that the operands of a
// VPInstruction in \p BB have been visited before (except for Phi nodes).
void PlainCFGBuilder::createVPInstructionsForVPBB(VPBasicBlock *VPBB,
                                                  BasicBlock *BB) {
  VPIRBuilder.setInsertPoint(VPBB);
  for (Instruction &InstRef : *BB) {
    Instruction *Inst = &InstRef;
    if (isInstructionToIgnore(Inst))
      continue;

    // There should't be any VPValue for Inst at this point. Otherwise, we
    // visited Inst when we shouldn't, breaking the RPO traversal order.
    assert(!IRDef2VPValue.count(Inst) &&
           "Instruction shouldn't have been visited.");

    VPInstruction *NewVPInst;
    if (PHINode *Phi = dyn_cast<PHINode>(Inst)) {
      // Phi node's operands may have not been visited at this point. We create
      // an empty VPInstruction that we will fix once the whole plain CFG has
      // been built.
      NewVPInst = cast<VPInstruction>(VPIRBuilder.createNaryOp(
          Inst->getOpcode(), {} /*No operands*/, Inst));
      PhisToFix.push_back(Phi);
    } else {
      // Translate LLVM-IR operands into VPValue operands and set them in the
      // new VPInstruction.
      SmallVector<VPValue *, 4> VPOperands;
      for (Value *Op : Inst->operands())
        VPOperands.push_back(getOrCreateVPOperand(Op));

      // Build VPInstruction for any arbitraty Instruction without specific
      // representation in VPlan.
      NewVPInst = cast<VPInstruction>(
          VPIRBuilder.createNaryOp(Inst->getOpcode(), VPOperands, Inst));
    }

    IRDef2VPValue[Inst] = NewVPInst;
  }
}

// Main interface to build the plain CFG.
VPRegionBlock *PlainCFGBuilder::buildPlainCFG() {
  // 1. Create the Top Region. It will be the parent of all VPBBs.
  TopRegion = new VPRegionBlock("TopRegion", false /*isReplicator*/);

  // 2. Scan the body of the loop in a topological order to visit each basic
  // block after having visited its predecessor basic blocks. Create a VPBB for
  // each BB and link it to its successor and predecessor VPBBs. Note that
  // predecessors must be set in the same order as they are in the incomming IR.
  // Otherwise, there might be problems with existing phi nodes and algorithm
  // based on predecessors traversal.

  // Loop PH needs to be explicitly visited since it's not taken into account by
  // LoopBlocksDFS.
  BasicBlock *PreheaderBB = TheLoop->getLoopPreheader();
  assert((PreheaderBB->getTerminator()->getNumSuccessors() == 1) &&
         "Unexpected loop preheader");
  VPBasicBlock *PreheaderVPBB = getOrCreateVPBB(PreheaderBB);
  createVPInstructionsForVPBB(PreheaderVPBB, PreheaderBB);
  // Create empty VPBB for Loop H so that we can link PH->H.
  VPBlockBase *HeaderVPBB = getOrCreateVPBB(TheLoop->getHeader());
  // Preheader's predecessors will be set during the loop RPO traversal below.
  PreheaderVPBB->setOneSuccessor(HeaderVPBB);

  LoopBlocksRPO RPO(TheLoop);
  RPO.perform(LI);

  for (BasicBlock *BB : RPO) {
    // Create or retrieve the VPBasicBlock for this BB and create its
    // VPInstructions.
    VPBasicBlock *VPBB = getOrCreateVPBB(BB);
    createVPInstructionsForVPBB(VPBB, BB);

    // Set VPBB successors. We create empty VPBBs for successors if they don't
    // exist already. Recipes will be created when the successor is visited
    // during the RPO traversal.
    TerminatorInst *TI = BB->getTerminator();
    assert(TI && "Terminator expected.");
    unsigned NumSuccs = TI->getNumSuccessors();

    if (NumSuccs == 1) {
      VPBasicBlock *SuccVPBB = getOrCreateVPBB(TI->getSuccessor(0));
      assert(SuccVPBB && "VPBB Successor not found.");
      VPBB->setOneSuccessor(SuccVPBB);
    } else if (NumSuccs == 2) {
      VPBasicBlock *SuccVPBB0 = getOrCreateVPBB(TI->getSuccessor(0));
      assert(SuccVPBB0 && "Successor 0 not found.");
      VPBasicBlock *SuccVPBB1 = getOrCreateVPBB(TI->getSuccessor(1));
      assert(SuccVPBB1 && "Successor 1 not found.");
      VPBB->setTwoSuccessors(SuccVPBB0, SuccVPBB1);
    } else
      llvm_unreachable("Number of successors not supported.");

    // Set VPBB predecessors in the same order as they are in the incoming BB.
    setVPBBPredsFromBB(VPBB, BB);
  }

  // 3. Process outermost loop exit. We created an empty VPBB for the loop
  // single exit BB during the RPO traversal of the loop body but Instructions
  // weren't visited because it's not part of the the loop.
  BasicBlock *LoopExitBB = TheLoop->getUniqueExitBlock();
  assert(LoopExitBB && "Loops with multiple exits are not supported.");
  VPBasicBlock *LoopExitVPBB = BB2VPBB[LoopExitBB];
  createVPInstructionsForVPBB(LoopExitVPBB, LoopExitBB);
  // Loop exit was already set as successor of the loop exiting BB.
  // We only set its predecessor VPBB now.
  setVPBBPredsFromBB(LoopExitVPBB, LoopExitBB);

  // 4. The whole CFG has been built at this point so all the input Values must
  // have a VPlan couterpart. Fix VPlan phi nodes by adding their corresponding
  // VPlan operands.
  fixPhiNodes();

  // 5. Final Top Region setup. Set outermost loop pre-header and single exit as
  // Top Region entry and exit.
  TopRegion->setEntry(PreheaderVPBB);
  TopRegion->setExit(LoopExitVPBB);
  return TopRegion;
}

// Public interface to build a H-CFG.
void VPlanHCFGBuilder::buildHierarchicalCFG(VPlan &Plan) {
  // Build Top Region enclosing the plain CFG and set it as VPlan entry.
  PlainCFGBuilder PCFGBuilder(TheLoop, LI, Plan);
  VPRegionBlock *TopRegion = PCFGBuilder.buildPlainCFG();
  Plan.setEntry(TopRegion);
  LLVM_DEBUG(Plan.setName("HCFGBuilder: Plain CFG\n"); dbgs() << Plan);

  Verifier.verifyHierarchicalCFG(TopRegion);
}
<|endoftext|>


<commit_before><commit_msg>Yet another Ex28 commit<commit_after><|endoftext|>


<commit_before>/*
This file is part of Bohrium and copyright (c) 2012 the Bohrium
team <http://www.bh107.org>.

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

Bohrium 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 Lesser General Public License along with Bohrium.

If not, see <http://www.gnu.org/licenses/>.
*/
#include <bh.h>
#include <stdio.h>

using namespace std;

typedef vector<bh_instruction> ilist;
typedef ilist::iterator ilist_iter;

void filter(bh_ir &bhir)
{
    for(ilist_iter it = bhir.instr_list.begin();
        it!=bhir.instr_list.end();
        ++it) {
        bh_instruction& instr = *it;
        switch(instr.opcode) {
            case BH_ADD_REDUCE:
            case BH_MULTIPLY_REDUCE:
            case BH_MINIMUM_REDUCE:
            case BH_MAXIMUM_REDUCE:
            case BH_LOGICAL_AND_REDUCE:
            case BH_BITWISE_AND_REDUCE:
            case BH_LOGICAL_OR_REDUCE:
            case BH_BITWISE_OR_REDUCE:
            case BH_LOGICAL_XOR_REDUCE:
            case BH_BITWISE_XOR_REDUCE:
                printf("Reduction...");
                break;

            case BH_FREE:
                printf("Free...");
                break;

            case BH_DISCARD:
                printf("Discard...");
                break;

            default:
                printf("Something else.");
                break;
        }
    }
}
<commit_msg>filter-complete-reduction: First draft of the filter.<commit_after>/*
This file is part of Bohrium and copyright (c) 2012 the Bohrium
team <http://www.bh107.org>.

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

Bohrium 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 Lesser General Public License along with Bohrium.

If not, see <http://www.gnu.org/licenses/>.
*/
#include <bh.h>
#include <stdio.h>

using namespace std;

typedef vector<bh_instruction> ilist;
typedef ilist::iterator ilist_iter;

void rewrite_chain(vector<bh_instruction*>& links, bh_instruction* first, bh_instruction* last)
{
    // Rewrite the first reduction as a "COMPLETE" REDUCE.
    // Copy the meta-data of the SCALAR output from the last REDUCE
    first->operand[0] = last->operand[0];

    // Set the last reduction to NONE, it no longer needs execution.
    last->opcode = BH_NONE;

    // Set all the instructions "links" in the chain as BH_NONE
    // they no longer need execution.
    for(vector<bh_instruction*>::iterator rit=links.begin();
        rit!=links.end();
        ++rit) {
        bh_instruction& rinstr = **rit;
        rinstr.opcode = BH_NONE;
    }
}

void filter(bh_ir &bhir)
{
    bh_base* reduce_output = NULL;
    bh_opcode reduce_opcode = BH_NONE;
    bh_instruction* first;
    bh_instruction* last;

    vector<bh_instruction*> links;  // Instructions in the chain that are not,
                                    // the first and the last reduction.

    for(ilist_iter it = bhir.instr_list.begin();
        it!=bhir.instr_list.end();
        ++it) {
        bh_instruction& instr = *it;

        // Find the "first" reduction in a reduction chain.
        if ((reduce_output == NULL) and \
            (bh_opcode_is_reduction(instr.opcode))) {

            reduce_output = instr.operand[0].base;
            reduce_opcode = instr.opcode;

            first = &instr;

            printf("Beginning the chain...\n");

        // A potential continuation of the chain
        } else if ( (reduce_output != NULL) and \
                    (reduce_opcode == instr.opcode) and \
                    (reduce_output == instr.operand[1].base)) {

            bool other_use=false, gets_freed=false, gets_discarded=false;
            for(ilist_iter rit(it+1); rit!=bhir.instr_list.end(); ++rit) {
                bh_instruction& other_instr = *rit;
                switch(other_instr.opcode) {
                    case BH_FREE:
                        if (other_instr.operand[0].base == reduce_output) {
                            gets_freed = true;
                            links.push_back(&other_instr);
                        }
                        break;
                    case BH_DISCARD:
                        if (other_instr.operand[0].base == reduce_output) {
                            gets_discarded = true;

                            links.push_back(&other_instr);
                        }
                        break;
                    default:
                        for(int oidx=0; oidx<bh_operands(other_instr.opcode); ++oidx) {
                            if (bh_is_constant(&other_instr.operand[oidx])) {
                                continue;
                            }
                            if (other_instr.operand[oidx].base == reduce_output) {
                                other_use = true;
                            }
                        }
                        break;
                }
                // Can stop looking further if it gets used by something else
                // or if it gets freed and discarded.
                if (other_use or (gets_freed and gets_discarded)) {
                    break;
                }
            }

            bool is_continuation = gets_freed and gets_discarded and not other_use;
            bool is_scalar = (instr.operand[0].ndim == 1) and (instr.operand[0].shape[0] == 1);

            reduce_output = instr.operand[0].base;

            if (is_continuation and is_scalar) {            // End of the chain

                printf("Ending the chain and REWRITE as COMPLETE REDUCE\n");
                last = &instr;

                rewrite_chain(links, first, last);

            } else if (is_continuation and not is_scalar) { // Continuation
                printf("Continuing the chain...\n");
                links.push_back(&instr);
            } else {                                        // Break the chain.
                printf("Break the chain.\n");
            }

            if (not is_continuation or is_scalar) {         // Reset the search
                printf("Resetting search.\n");
                reduce_output = NULL;
                reduce_opcode = BH_NONE;
                links.clear();
            }

        // A break
        } else if (reduce_output != NULL) {
            reduce_output = NULL;
            reduce_opcode = BH_NONE;
            links.clear();
            printf("Breaking the chain...\n");
        }
    }
}
<|endoftext|>


<commit_before>#include "filefilteritems.h"
#include <qdebug.h>

namespace QmlProjectManager {

FileFilterBaseItem::FileFilterBaseItem(QObject *parent) :
        QmlProjectContentItem(parent),
        m_recursive(false)
{
    connect(&m_fsWatcher, SIGNAL(directoryChanged(QString)), this, SLOT(updateFileList()));
    connect(&m_fsWatcher, SIGNAL(fileChanged(QString)), this, SLOT(updateFileList()));
}

QString FileFilterBaseItem::directory() const
{
    return m_rootDir;
}

void FileFilterBaseItem::setDirectory(const QString &dirPath)
{
    if (m_rootDir == dirPath)
        return;
    m_rootDir = dirPath;
    emit directoryChanged();

    updateFileList();
}

void FileFilterBaseItem::setDefaultDirectory(const QString &dirPath)
{
    if (m_defaultDir == dirPath)
        return;
    m_defaultDir = dirPath;

    updateFileList();
}

QString FileFilterBaseItem::filter() const
{
    return m_filter;
}

void FileFilterBaseItem::setFilter(const QString &filter)
{
    if (filter == m_filter)
        return;
    m_filter = filter;
    m_regex.setPattern(m_filter);
    m_regex.setPatternSyntax(QRegExp::Wildcard);

    emit filterChanged();
    updateFileList();
}

bool FileFilterBaseItem::recursive() const
{
    return m_recursive;
}

void FileFilterBaseItem::setRecursive(bool recursive)
{
    if (recursive == m_recursive)
        return;
    m_recursive = recursive;
    updateFileList();
}

QStringList FileFilterBaseItem::files() const
{
    return m_files.toList();
}

QString FileFilterBaseItem::absoluteDir() const
{
    QString absoluteDir;
    if (QFileInfo(m_rootDir).isAbsolute()) {
        absoluteDir = m_rootDir;
    } else if (!m_defaultDir.isEmpty()) {
        absoluteDir = m_defaultDir + QLatin1Char('/') + m_rootDir;
    }

    return absoluteDir;
}

void FileFilterBaseItem::updateFileList()
{
    const QString projectDir = absoluteDir();
    if (projectDir.isEmpty())
        return;

    QSet<QString> dirsToBeWatched;
    const QSet<QString> newFiles = filesInSubTree(QDir(m_defaultDir), QDir(projectDir), &dirsToBeWatched);

    if (newFiles != m_files) {
        // update watched files
        const QSet<QString> unwatchFiles = QSet<QString>(m_files - newFiles);
        const QSet<QString> watchFiles = QSet<QString>(newFiles - m_files);
        if (!unwatchFiles.isEmpty())
            m_fsWatcher.removePaths(unwatchFiles.toList());
        if (!watchFiles.isEmpty())
            m_fsWatcher.addPaths(QSet<QString>(newFiles - m_files).toList());

        m_files = newFiles;

        emit filesChanged();
    }

    // update watched directories
    const QSet<QString> watchedDirectories = m_fsWatcher.directories().toSet();
    const QSet<QString> unwatchDirs = watchedDirectories - dirsToBeWatched;
    const QSet<QString> watchDirs = dirsToBeWatched - watchedDirectories;
    if (!unwatchDirs.isEmpty())
        m_fsWatcher.removePaths(unwatchDirs.toList());
    if (!watchDirs.isEmpty())
        m_fsWatcher.addPaths(watchDirs.toList());
}

QSet<QString> FileFilterBaseItem::filesInSubTree(const QDir &rootDir, const QDir &dir, QSet<QString> *parsedDirs)
{
    QSet<QString> fileSet;

    if (parsedDirs)
        parsedDirs->insert(dir.absolutePath());

    foreach (const QFileInfo &file, dir.entryInfoList(QDir::Files)) {
        if (m_regex.exactMatch(file.fileName())) {
            fileSet.insert(file.absoluteFilePath());
        }
    }

    if (m_recursive) {
        foreach (const QFileInfo &subDir, dir.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot)) {
            fileSet += filesInSubTree(rootDir, QDir(subDir.absoluteFilePath()));
        }
    }
    return fileSet;
}

QmlFileFilterItem::QmlFileFilterItem(QObject *parent)
    : FileFilterBaseItem(parent)
{
    setFilter(QLatin1String("*.qml"));
}

} // namespace QmlProjectManager

QML_DEFINE_TYPE(QmlProject,1,0,QmlFiles,QmlProjectManager::QmlFileFilterItem)
<commit_msg>Also watch sub-directories for changes<commit_after>#include "filefilteritems.h"
#include <qdebug.h>

namespace QmlProjectManager {

FileFilterBaseItem::FileFilterBaseItem(QObject *parent) :
        QmlProjectContentItem(parent),
        m_recursive(false)
{
    connect(&m_fsWatcher, SIGNAL(directoryChanged(QString)), this, SLOT(updateFileList()));
    connect(&m_fsWatcher, SIGNAL(fileChanged(QString)), this, SLOT(updateFileList()));
}

QString FileFilterBaseItem::directory() const
{
    return m_rootDir;
}

void FileFilterBaseItem::setDirectory(const QString &dirPath)
{
    if (m_rootDir == dirPath)
        return;
    m_rootDir = dirPath;
    emit directoryChanged();

    updateFileList();
}

void FileFilterBaseItem::setDefaultDirectory(const QString &dirPath)
{
    if (m_defaultDir == dirPath)
        return;
    m_defaultDir = dirPath;

    updateFileList();
}

QString FileFilterBaseItem::filter() const
{
    return m_filter;
}

void FileFilterBaseItem::setFilter(const QString &filter)
{
    if (filter == m_filter)
        return;
    m_filter = filter;
    m_regex.setPattern(m_filter);
    m_regex.setPatternSyntax(QRegExp::Wildcard);

    emit filterChanged();
    updateFileList();
}

bool FileFilterBaseItem::recursive() const
{
    return m_recursive;
}

void FileFilterBaseItem::setRecursive(bool recursive)
{
    if (recursive == m_recursive)
        return;
    m_recursive = recursive;
    updateFileList();
}

QStringList FileFilterBaseItem::files() const
{
    return m_files.toList();
}

QString FileFilterBaseItem::absoluteDir() const
{
    QString absoluteDir;
    if (QFileInfo(m_rootDir).isAbsolute()) {
        absoluteDir = m_rootDir;
    } else if (!m_defaultDir.isEmpty()) {
        absoluteDir = m_defaultDir + QLatin1Char('/') + m_rootDir;
    }

    return absoluteDir;
}

void FileFilterBaseItem::updateFileList()
{
    const QString projectDir = absoluteDir();
    if (projectDir.isEmpty())
        return;

    QSet<QString> dirsToBeWatched;
    const QSet<QString> newFiles = filesInSubTree(QDir(m_defaultDir), QDir(projectDir), &dirsToBeWatched);

    if (newFiles != m_files) {
        // update watched files
        const QSet<QString> unwatchFiles = QSet<QString>(m_files - newFiles);
        const QSet<QString> watchFiles = QSet<QString>(newFiles - m_files);
        if (!unwatchFiles.isEmpty())
            m_fsWatcher.removePaths(unwatchFiles.toList());
        if (!watchFiles.isEmpty())
            m_fsWatcher.addPaths(QSet<QString>(newFiles - m_files).toList());

        m_files = newFiles;

        emit filesChanged();
    }

    // update watched directories
    const QSet<QString> watchedDirectories = m_fsWatcher.directories().toSet();
    const QSet<QString> unwatchDirs = watchedDirectories - dirsToBeWatched;
    const QSet<QString> watchDirs = dirsToBeWatched - watchedDirectories;

    if (!unwatchDirs.isEmpty())
        m_fsWatcher.removePaths(unwatchDirs.toList());
    if (!watchDirs.isEmpty())
        m_fsWatcher.addPaths(watchDirs.toList());
}

QSet<QString> FileFilterBaseItem::filesInSubTree(const QDir &rootDir, const QDir &dir, QSet<QString> *parsedDirs)
{
    QSet<QString> fileSet;

    if (parsedDirs)
        parsedDirs->insert(dir.absolutePath());

    foreach (const QFileInfo &file, dir.entryInfoList(QDir::Files)) {
        if (m_regex.exactMatch(file.fileName())) {
            fileSet.insert(file.absoluteFilePath());
        }
    }

    if (m_recursive) {
        foreach (const QFileInfo &subDir, dir.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot)) {
            fileSet += filesInSubTree(rootDir, QDir(subDir.absoluteFilePath()), parsedDirs);
        }
    }
    return fileSet;
}

QmlFileFilterItem::QmlFileFilterItem(QObject *parent)
    : FileFilterBaseItem(parent)
{
    setFilter(QLatin1String("*.qml"));
}

} // namespace QmlProjectManager

QML_DEFINE_TYPE(QmlProject,1,0,QmlFiles,QmlProjectManager::QmlFileFilterItem)
<|endoftext|>


<commit_before>/*
 * This file is part of the AzerothCore Project. See AUTHORS file for Copyright information
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Affero General Public License as published by the
 * Free Software Foundation; either version 3 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 Affero General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program. If not, see <http://www.gnu.org/licenses/>.
 */

#include "ScriptMgr.h"
#include "ScriptedCreature.h"
#include "Spell.h"
#include "zulgurub.h"

/*
 * @todo
 * - Fix timers (research some more)
 */

enum Says
{
    SAY_VENOXIS_TRANSFORM           = 1,        // Let the coils of hate unfurl!
    SAY_VENOXIS_DEATH               = 2         // Ssserenity.. at lassst!
};

enum Spells
{
    // troll form
    SPELL_THRASH                    = 3391,
    SPELL_DISPEL_MAGIC              = 23859,
    SPELL_RENEW                     = 23895,
    SPELL_HOLY_NOVA                 = 23858,
    SPELL_HOLY_FIRE                 = 23860,
    SPELL_HOLY_WRATH                = 23979,
    // snake form
    SPELL_POISON_CLOUD              = 23861,
    SPELL_VENOM_SPIT                = 23862,

    SPELL_PARASITIC_SERPENT         = 23865,
    SPELL_SUMMON_PARASITIC_SERPENT  = 23866,
    SPELL_PARASITIC_SERPENT_TRIGGER = 23867,
    // used when swapping event-stages
    SPELL_VENOXIS_TRANSFORM         = 23849,    // 50% health - shapechange to cobra
    SPELL_FRENZY                    = 8269,      // 20% health - frenzy
    SPELL_POISON = 24097
};

enum Events
{
    // troll form
    EVENT_THRASH                    = 1,
    EVENT_DISPEL_MAGIC              = 2,
    EVENT_RENEW                     = 3,
    EVENT_HOLY_NOVA                 = 4,
    EVENT_HOLY_FIRE                 = 5,
    EVENT_HOLY_WRATH                = 6,
    // phase-changing
    EVENT_TRANSFORM                 = 7,
    // snake form events
    EVENT_POISON_CLOUD              = 8,
    EVENT_VENOM_SPIT                = 9,
    EVENT_PARASITIC_SERPENT         = 10,
    EVENT_FRENZY                    = 11,
    EVENT_POISON
};

enum Phases
{
    PHASE_ONE                       = 1,    // troll form
    PHASE_TWO                       = 2     // snake form
};

enum NPCs
{
    NPC_PARASITIC_SERPENT           = 14884,
    NPC_RAZZASHI_COBRA    = 11373,
    BOSS_VENOXIS          = 14507
};

class boss_venoxis : public CreatureScript
{
public:
    boss_venoxis() : CreatureScript("boss_venoxis") { }

    struct boss_venoxisAI : public BossAI
    {
        boss_venoxisAI(Creature* creature) : BossAI(creature, DATA_VENOXIS) { }

        void Reset() override
        {
            _Reset();
            // remove all spells and auras from previous attempts
            me->RemoveAllAuras();
            me->SetReactState(REACT_PASSIVE);
            // set some internally used variables to their defaults
            _inMeleeRange = 0;
            _transformed = false;
            _frenzied = false;
            events.SetPhase(PHASE_ONE);

            SpawnCobras();
        }

        void JustDied(Unit* /*killer*/) override
        {
            _JustDied();
            Talk(SAY_VENOXIS_DEATH);
            me->RemoveAllAuras();
        }

        void SpawnCobras()
        {
            me->SummonCreature(NPC_RAZZASHI_COBRA, -12021.20f, -1719.73f, 39.34f, 0.85f, TEMPSUMMON_CORPSE_DESPAWN);
            me->SummonCreature(NPC_RAZZASHI_COBRA, -12029.40f, -1714.54f, 39.36f, 0.68f, TEMPSUMMON_CORPSE_DESPAWN);
            me->SummonCreature(NPC_RAZZASHI_COBRA, -12036.79f, -1704.27f, 40.06f, 0.45f, TEMPSUMMON_CORPSE_DESPAWN);
            me->SummonCreature(NPC_RAZZASHI_COBRA, -12037.70f, -1694.20f, 39.35f, 0.27f, TEMPSUMMON_CORPSE_DESPAWN);
        }

        void SetCombatCombras()
        {
            std::list<Creature*> cobraList;
            me->GetCreatureListWithEntryInGrid(cobraList, NPC_RAZZASHI_COBRA, 50.0f);

            if (!cobraList.empty())
            {
                for (auto cobras : cobraList)
                {
                    cobras->SetInCombatWithZone();
                }
            }
        }

        void EnterCombat(Unit* /*who*/) override
        {
            _EnterCombat();
            me->SetReactState(REACT_AGGRESSIVE);
            // Always running events
            events.ScheduleEvent(EVENT_THRASH, 5000);
            // Phase one events (regular form)
            events.ScheduleEvent(EVENT_HOLY_NOVA, 5000, 0, PHASE_ONE);
            events.ScheduleEvent(EVENT_DISPEL_MAGIC, 35000, 0, PHASE_ONE);
            events.ScheduleEvent(EVENT_HOLY_FIRE, 10000, 0, PHASE_ONE);
            events.ScheduleEvent(EVENT_RENEW, 30000, 0, PHASE_ONE);
            events.ScheduleEvent(EVENT_HOLY_WRATH, 60000, 0, PHASE_ONE);

            events.SetPhase(PHASE_ONE);

            // Set zone in combat
            DoZoneInCombat();
            SetCombatCombras();
        }

        void DamageTaken(Unit*, uint32& /*damage*/, DamageEffectType, SpellSchoolMask) override
        {
            // check if venoxis is ready to transform
            if (!_transformed && !HealthAbovePct(50))
            {
                _transformed = true;
                // schedule the event that changes our phase
                events.ScheduleEvent(EVENT_TRANSFORM, 100);
            }
            // we're losing health, bad, go frenzy
            else if (!_frenzied && !HealthAbovePct(20))
            {
                _frenzied = true;
                events.ScheduleEvent(EVENT_FRENZY, 100);
            }
        }

        void UpdateAI(uint32 diff) override
        {
            if (!UpdateVictim())
                return;

            events.Update(diff);

            // return back to main code if we're still casting
            if (me->HasUnitState(UNIT_STATE_CASTING))
                return;

            while (uint32 eventId = events.ExecuteEvent())
            {
                switch (eventId)
                {
                    // thrash is available in all phases
                    case EVENT_THRASH:
                        DoCast(me, SPELL_THRASH, true);
                        events.ScheduleEvent(EVENT_THRASH, urand(10000, 20000));
                        break;

                    // troll form spells and Actions (first part)
                    case EVENT_DISPEL_MAGIC:
                        DoCast(me, SPELL_DISPEL_MAGIC);
                        events.ScheduleEvent(EVENT_DISPEL_MAGIC, urand(15000, 20000), 0, PHASE_ONE);
                        break;
                    case EVENT_RENEW:
                        DoCast(me, SPELL_RENEW);
                        events.ScheduleEvent(EVENT_RENEW, urand(25000, 30000), 0, PHASE_ONE);
                        break;
                    case EVENT_HOLY_NOVA:
                        _inMeleeRange = 0;

                        for (uint8 i = 0; i < 10; ++i)
                        {
                            if (Unit* target = SelectTarget(SelectTargetMethod::MaxThreat, i))
                                // check if target is within melee-distance
                                if (me->IsWithinMeleeRange(target))
                                    ++_inMeleeRange;
                        }

                        // trigger spellcast only if we have 3 or more targets to affect
                        if (_inMeleeRange >= 3)
                            DoCastVictim(SPELL_HOLY_NOVA);

                        events.ScheduleEvent(EVENT_HOLY_NOVA, urand(45000, 75000), 0, PHASE_ONE);
                        break;
                    case EVENT_HOLY_FIRE:
                        if (Unit* target = SelectTarget(SelectTargetMethod::Random))
                            DoCast(target, SPELL_HOLY_FIRE);
                        events.ScheduleEvent(EVENT_HOLY_FIRE, urand(45000, 60000), 0, PHASE_ONE);
                        break;
                    case EVENT_HOLY_WRATH:
                        if (Unit* target = SelectTarget(SelectTargetMethod::Random))
                            DoCast(target, SPELL_HOLY_WRATH);
                        events.ScheduleEvent(EVENT_HOLY_WRATH, urand(45000, 60000), 0, PHASE_ONE);
                        break;

                    //
                    // snake form spells and Actions
                    //

                    case EVENT_VENOM_SPIT:
                        if (Unit* target = SelectTarget(SelectTargetMethod::Random))
                            DoCast(target, SPELL_VENOM_SPIT);
                        events.ScheduleEvent(EVENT_VENOM_SPIT, urand(5000, 15000), 0, PHASE_TWO);
                        break;
                    case EVENT_POISON_CLOUD:
                        if (Unit* target = SelectTarget(SelectTargetMethod::Random))
                            DoCast(target, SPELL_POISON_CLOUD);
                        events.ScheduleEvent(EVENT_POISON_CLOUD, urand(15000, 20000), 0, PHASE_TWO);
                        break;
                    case EVENT_PARASITIC_SERPENT:
                        if (Unit* target = SelectTarget(SelectTargetMethod::Random))
                            DoCast(target, SPELL_SUMMON_PARASITIC_SERPENT);
                        events.ScheduleEvent(EVENT_PARASITIC_SERPENT, 15000, 0, PHASE_TWO);
                        break;
                    case EVENT_FRENZY:
                        // frenzy at 20% health
                        DoCast(me, SPELL_FRENZY, true);
                        break;

                    //
                    // shape and phase-changing
                    //

                    case EVENT_TRANSFORM:
                        // shapeshift at 50% health
                        DoCast(me, SPELL_VENOXIS_TRANSFORM);
                        Talk(SAY_VENOXIS_TRANSFORM);
                        DoResetThreat();

                        // phase two events (snakeform)
                        events.ScheduleEvent(EVENT_VENOM_SPIT, 5000, 0, PHASE_TWO);
                        events.ScheduleEvent(EVENT_POISON_CLOUD, 10000, 0, PHASE_TWO);
                        events.ScheduleEvent(EVENT_PARASITIC_SERPENT, 30000, 0, PHASE_TWO);

                        // transformed, start phase two
                        events.SetPhase(PHASE_TWO);

                        break;
                    default:
                        break;
                }
            }

            DoMeleeAttackIfReady();
        }

    private:
        uint8 _inMeleeRange;
        bool _transformed;
        bool _frenzied;
    };

    CreatureAI* GetAI(Creature* creature) const override
    {
        return GetZulGurubAI<boss_venoxisAI>(creature);
    }
};

class npc_razzashi_cobra_venoxis : public CreatureScript
{
public:
    npc_razzashi_cobra_venoxis() : CreatureScript("npc_razzashi_cobra_venoxis") {}

    struct npc_razzashi_cobra_venoxis_AI : public ScriptedAI
    {
        npc_razzashi_cobra_venoxis_AI(Creature* creature) : ScriptedAI(creature) {}

        EventMap events;

        void Reset()
        {
            events.Reset();
        }

        void EnterCombat(Unit*)
        {
            events.ScheduleEvent(EVENT_POISON, 8 * IN_MILLISECONDS);

            if (Creature* Venoxis = GetVenoxis())
            {
                Venoxis->SetInCombatWithZone();
            }
        }

        Creature* GetVenoxis()
        {
            return me->FindNearestCreature(BOSS_VENOXIS, 200.0f, true);
        }

        void UpdateAI(uint32 diff)
        {
            if (!UpdateVictim())
                return;

            events.Update(diff);

            if (me->HasUnitState(UNIT_STATE_CASTING))
                return;

            while (uint32 eventId = events.ExecuteEvent())
            {
                switch (eventId)
                {
                case EVENT_POISON:
                {
                    me->CastSpell(me->GetVictim(), SPELL_POISON);
                    events.ScheduleEvent(EVENT_POISON, 15 * IN_MILLISECONDS);
                    break;
                }
                }
            }

            DoMeleeAttackIfReady();
        }
    };

    CreatureAI* GetAI(Creature* creature) const override
    {
        return new npc_razzashi_cobra_venoxis_AI(creature);
    }
};

void AddSC_boss_venoxis()
{
    new boss_venoxis();
    new npc_razzashi_cobra_venoxis();
}
<commit_msg>fix(Scripts/ZulGurub): Venoxis - Holy wrath and Holy nova event (#12089)<commit_after>/*
 * This file is part of the AzerothCore Project. See AUTHORS file for Copyright information
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Affero General Public License as published by the
 * Free Software Foundation; either version 3 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 Affero General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program. If not, see <http://www.gnu.org/licenses/>.
 */

#include "ScriptMgr.h"
#include "ScriptedCreature.h"
#include "Spell.h"
#include "zulgurub.h"

/*
 * @todo
 * - Fix timers (research some more)
 */

enum Says
{
    SAY_VENOXIS_TRANSFORM           = 1,        // Let the coils of hate unfurl!
    SAY_VENOXIS_DEATH               = 2         // Ssserenity.. at lassst!
};

enum Spells
{
    // troll form
    SPELL_THRASH                    = 3391,
    SPELL_DISPEL_MAGIC              = 23859,
    SPELL_RENEW                     = 23895,
    SPELL_HOLY_NOVA                 = 23858,
    SPELL_HOLY_FIRE                 = 23860,
    SPELL_HOLY_WRATH                = 23979,
    // snake form
    SPELL_POISON_CLOUD              = 23861,
    SPELL_VENOM_SPIT                = 23862,

    SPELL_PARASITIC_SERPENT         = 23865,
    SPELL_SUMMON_PARASITIC_SERPENT  = 23866,
    SPELL_PARASITIC_SERPENT_TRIGGER = 23867,
    // used when swapping event-stages
    SPELL_VENOXIS_TRANSFORM         = 23849,    // 50% health - shapechange to cobra
    SPELL_FRENZY                    = 8269,      // 20% health - frenzy
    SPELL_POISON = 24097
};

enum Events
{
    // troll form
    EVENT_THRASH                    = 1,
    EVENT_DISPEL_MAGIC              = 2,
    EVENT_RENEW                     = 3,
    EVENT_HOLY_NOVA                 = 4,
    EVENT_HOLY_FIRE                 = 5,
    EVENT_HOLY_WRATH                = 6,
    // phase-changing
    EVENT_TRANSFORM                 = 7,
    // snake form events
    EVENT_POISON_CLOUD              = 8,
    EVENT_VENOM_SPIT                = 9,
    EVENT_PARASITIC_SERPENT         = 10,
    EVENT_FRENZY                    = 11,
    EVENT_POISON
};

enum Phases
{
    PHASE_ONE                       = 1,    // troll form
    PHASE_TWO                       = 2     // snake form
};

enum NPCs
{
    NPC_PARASITIC_SERPENT           = 14884,
    NPC_RAZZASHI_COBRA    = 11373,
    BOSS_VENOXIS          = 14507
};

class boss_venoxis : public CreatureScript
{
public:
    boss_venoxis() : CreatureScript("boss_venoxis") { }

    struct boss_venoxisAI : public BossAI
    {
        boss_venoxisAI(Creature* creature) : BossAI(creature, DATA_VENOXIS) { }

        void Reset() override
        {
            _Reset();
            // remove all spells and auras from previous attempts
            me->RemoveAllAuras();
            me->SetReactState(REACT_PASSIVE);
            // set some internally used variables to their defaults
            _inMeleeRange = 0;
            _transformed = false;
            _frenzied = false;
            events.SetPhase(PHASE_ONE);

            SpawnCobras();
        }

        void JustDied(Unit* /*killer*/) override
        {
            _JustDied();
            Talk(SAY_VENOXIS_DEATH);
            me->RemoveAllAuras();
        }

        void SpawnCobras()
        {
            me->SummonCreature(NPC_RAZZASHI_COBRA, -12021.20f, -1719.73f, 39.34f, 0.85f, TEMPSUMMON_CORPSE_DESPAWN);
            me->SummonCreature(NPC_RAZZASHI_COBRA, -12029.40f, -1714.54f, 39.36f, 0.68f, TEMPSUMMON_CORPSE_DESPAWN);
            me->SummonCreature(NPC_RAZZASHI_COBRA, -12036.79f, -1704.27f, 40.06f, 0.45f, TEMPSUMMON_CORPSE_DESPAWN);
            me->SummonCreature(NPC_RAZZASHI_COBRA, -12037.70f, -1694.20f, 39.35f, 0.27f, TEMPSUMMON_CORPSE_DESPAWN);
        }

        void SetCombatCombras()
        {
            std::list<Creature*> cobraList;
            me->GetCreatureListWithEntryInGrid(cobraList, NPC_RAZZASHI_COBRA, 50.0f);

            if (!cobraList.empty())
            {
                for (auto cobras : cobraList)
                {
                    cobras->SetInCombatWithZone();
                }
            }
        }

        void EnterCombat(Unit* /*who*/) override
        {
            _EnterCombat();
            me->SetReactState(REACT_AGGRESSIVE);
            // Always running events
            events.ScheduleEvent(EVENT_THRASH, 5000);
            // Phase one events (regular form)
            events.ScheduleEvent(EVENT_HOLY_NOVA, urand(5000, 15000), 0, PHASE_ONE);
            events.ScheduleEvent(EVENT_DISPEL_MAGIC, 35000, 0, PHASE_ONE);
            events.ScheduleEvent(EVENT_HOLY_FIRE, urand(10000,20000), 0, PHASE_ONE);
            events.ScheduleEvent(EVENT_RENEW, 30000, 0, PHASE_ONE);
            events.ScheduleEvent(EVENT_HOLY_WRATH, urand(15000, 25000), 0, PHASE_ONE);

            events.SetPhase(PHASE_ONE);

            // Set zone in combat
            DoZoneInCombat();
            SetCombatCombras();
        }

        void DamageTaken(Unit*, uint32& /*damage*/, DamageEffectType, SpellSchoolMask) override
        {
            // check if venoxis is ready to transform
            if (!_transformed && !HealthAbovePct(50))
            {
                _transformed = true;
                // schedule the event that changes our phase
                events.ScheduleEvent(EVENT_TRANSFORM, 100);
            }
            // we're losing health, bad, go frenzy
            else if (!_frenzied && !HealthAbovePct(20))
            {
                _frenzied = true;
                events.ScheduleEvent(EVENT_FRENZY, 100);
            }
        }

        void UpdateAI(uint32 diff) override
        {
            if (!UpdateVictim())
                return;

            events.Update(diff);

            // return back to main code if we're still casting
            if (me->HasUnitState(UNIT_STATE_CASTING))
                return;

            while (uint32 eventId = events.ExecuteEvent())
            {
                switch (eventId)
                {
                    // thrash is available in all phases
                    case EVENT_THRASH:
                        DoCast(me, SPELL_THRASH, true);
                        events.ScheduleEvent(EVENT_THRASH, urand(10000, 20000));
                        break;

                    // troll form spells and Actions (first part)
                    case EVENT_DISPEL_MAGIC:
                        DoCast(me, SPELL_DISPEL_MAGIC);
                        events.ScheduleEvent(EVENT_DISPEL_MAGIC, urand(15000, 20000), 0, PHASE_ONE);
                        break;
                    case EVENT_RENEW:
                        DoCast(me, SPELL_RENEW);
                        events.ScheduleEvent(EVENT_RENEW, urand(25000, 30000), 0, PHASE_ONE);
                        break;
                    case EVENT_HOLY_WRATH:
                        if (Unit* target = SelectTarget(SelectTargetMethod::MaxThreat))
                            DoCast(target, SPELL_HOLY_WRATH);
                        events.ScheduleEvent(EVENT_HOLY_WRATH, urand(12000, 22000), 0, PHASE_ONE);
                        break;
                    case EVENT_HOLY_FIRE:
                        if (Unit* target = SelectTarget(SelectTargetMethod::Random))
                            DoCast(target, SPELL_HOLY_FIRE);
                        events.ScheduleEvent(EVENT_HOLY_FIRE, urand(10000, 24000), 0, PHASE_ONE);
                        break;
                    case EVENT_HOLY_NOVA:
                        DoCastSelf(SPELL_HOLY_NOVA);
                        events.ScheduleEvent(EVENT_HOLY_NOVA, urand(10000, 24000), 0, PHASE_ONE);
                        break;

                    //
                    // snake form spells and Actions
                    //

                    case EVENT_VENOM_SPIT:
                        if (Unit* target = SelectTarget(SelectTargetMethod::Random))
                            DoCast(target, SPELL_VENOM_SPIT);
                        events.ScheduleEvent(EVENT_VENOM_SPIT, urand(5000, 15000), 0, PHASE_TWO);
                        break;
                    case EVENT_POISON_CLOUD:
                        if (Unit* target = SelectTarget(SelectTargetMethod::Random))
                            DoCast(target, SPELL_POISON_CLOUD);
                        events.ScheduleEvent(EVENT_POISON_CLOUD, urand(15000, 20000), 0, PHASE_TWO);
                        break;
                    case EVENT_PARASITIC_SERPENT:
                        if (Unit* target = SelectTarget(SelectTargetMethod::Random))
                            DoCast(target, SPELL_SUMMON_PARASITIC_SERPENT);
                        events.ScheduleEvent(EVENT_PARASITIC_SERPENT, 15000, 0, PHASE_TWO);
                        break;
                    case EVENT_FRENZY:
                        // frenzy at 20% health
                        DoCast(me, SPELL_FRENZY, true);
                        break;

                    //
                    // shape and phase-changing
                    //

                    case EVENT_TRANSFORM:
                        // shapeshift at 50% health
                        DoCast(me, SPELL_VENOXIS_TRANSFORM);
                        Talk(SAY_VENOXIS_TRANSFORM);
                        DoResetThreat();

                        // phase two events (snakeform)
                        events.ScheduleEvent(EVENT_VENOM_SPIT, 5000, 0, PHASE_TWO);
                        events.ScheduleEvent(EVENT_POISON_CLOUD, 10000, 0, PHASE_TWO);
                        events.ScheduleEvent(EVENT_PARASITIC_SERPENT, 30000, 0, PHASE_TWO);

                        // transformed, start phase two
                        events.SetPhase(PHASE_TWO);

                        break;
                    default:
                        break;
                }
            }

            DoMeleeAttackIfReady();
        }

    private:
        uint8 _inMeleeRange;
        bool _transformed;
        bool _frenzied;
    };

    CreatureAI* GetAI(Creature* creature) const override
    {
        return GetZulGurubAI<boss_venoxisAI>(creature);
    }
};

class npc_razzashi_cobra_venoxis : public CreatureScript
{
public:
    npc_razzashi_cobra_venoxis() : CreatureScript("npc_razzashi_cobra_venoxis") {}

    struct npc_razzashi_cobra_venoxis_AI : public ScriptedAI
    {
        npc_razzashi_cobra_venoxis_AI(Creature* creature) : ScriptedAI(creature) {}

        EventMap events;

        void Reset()
        {
            events.Reset();
        }

        void EnterCombat(Unit*)
        {
            events.ScheduleEvent(EVENT_POISON, 8 * IN_MILLISECONDS);

            if (Creature* Venoxis = GetVenoxis())
            {
                Venoxis->SetInCombatWithZone();
            }
        }

        Creature* GetVenoxis()
        {
            return me->FindNearestCreature(BOSS_VENOXIS, 200.0f, true);
        }

        void UpdateAI(uint32 diff)
        {
            if (!UpdateVictim())
                return;

            events.Update(diff);

            if (me->HasUnitState(UNIT_STATE_CASTING))
                return;

            while (uint32 eventId = events.ExecuteEvent())
            {
                switch (eventId)
                {
                case EVENT_POISON:
                {
                    me->CastSpell(me->GetVictim(), SPELL_POISON);
                    events.ScheduleEvent(EVENT_POISON, 15 * IN_MILLISECONDS);
                    break;
                }
                }
            }

            DoMeleeAttackIfReady();
        }
    };

    CreatureAI* GetAI(Creature* creature) const override
    {
        return new npc_razzashi_cobra_venoxis_AI(creature);
    }
};

void AddSC_boss_venoxis()
{
    new boss_venoxis();
    new npc_razzashi_cobra_venoxis();
}
<|endoftext|>