<commit_before>// Author: Junyang

#define DEBUG_TYPE "dyn-aa"

#include <cstdio>
#include <fstream>

#include "llvm/Pass.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/ADT/Statistic.h"

#include "rcs/IDAssigner.h"

#include "dyn-aa/LogCounter.h"
#include "dyn-aa/TraceSlicer.h"

using namespace std;
using namespace llvm;
using namespace rcs;
using namespace dyn_aa;

static cl::opt<unsigned> FirstPointerRecordID(
    "pt1",
    cl::desc("RecordID of the first pointer"));

static cl::opt<unsigned> SecondPointerRecordID(
    "pt2",
    cl::desc("RecordID of the second pointer"));

static RegisterPass<TraceSlicer> X("slice-trace",
                                   "Slice trace of two input pointers",
                                   false, // Is CFG Only?
                                   true); // Is Analysis?

char TraceSlicer::ID = 0;

bool TraceSlicer::runOnModule(Module &M) {
  LogCounter LC;
  LC.processLog();
  CurrentRecordID = LC.getNumLogRecords();

  CurrentState[0].StartRecordID = FirstPointerRecordID;
  CurrentState[1].StartRecordID = SecondPointerRecordID;

  processLog(true);

  return false;
}

void TraceSlicer::getAnalysisUsage(AnalysisUsage &AU) const {
  AU.setPreservesAll();
  AU.addRequired<IDAssigner>();
}

void TraceSlicer::printTrace(raw_ostream &O,
                             pair<unsigned, unsigned> TraceRecord,
                             int PointerLabel) const {
  unsigned RecordID = TraceRecord.first;
  unsigned ValueID = TraceRecord.second;
  IDAssigner &IDA = getAnalysis<IDAssigner>();
  Value *V = IDA.getValue(ValueID);
  O << RecordID << "\t";
  O << "ptr" << PointerLabel + 1 << "\t";
  O << ValueID << "\t";
  DynAAUtils::PrintValue(O, V);
//  if (Argument *A = dyn_cast<Argument>(V)) {
//    O << " (argNo " << A->getArgNo() << ")";
//  }
  O << "\n";
}

void TraceSlicer::print(raw_ostream &O, const Module *M) const {
  O << "RecID\tPtr\tValueID\tFunc:  Inst/Arg\n\n";
  for (int PointerLabel = 0; PointerLabel < 2; ++PointerLabel) {
    O << "ptr" << PointerLabel + 1 << ": \n";
    for (int i = CurrentState[PointerLabel].Trace.size() - 1; i >= 0; --i) {
      printTrace(O, CurrentState[PointerLabel].Trace[i], PointerLabel);
    }
    O << "\n";
  }

  O << "Merged: \n";
  int Index[2];
  Index[0] = CurrentState[0].Trace.size() - 1;
  Index[1] = CurrentState[1].Trace.size() - 1;
  while (true) {
    unsigned Min;
    int PointerLabel = -1;
    for (int i = 0; i < 2; ++i) {
      if (Index[i] >= 0 &&
          (PointerLabel == -1 || CurrentState[i].Trace[Index[i]].first < Min)) {
        Min = CurrentState[i].Trace[Index[i]].first;
        PointerLabel = i;
      }
    }
    if (PointerLabel != -1) {
      printTrace(O,
                 CurrentState[PointerLabel].Trace[Index[PointerLabel]],
                 PointerLabel);
      Index[PointerLabel]--;
    } else
      break;
  }
}

bool TraceSlicer::isLive(int PointerLabel) {
  if (CurrentState[PointerLabel].StartRecordID < CurrentRecordID ||
      CurrentState[PointerLabel].End) {
    return false;
  }
  return true;
}

void TraceSlicer::processAddrTakenDecl(const AddrTakenDeclLogRecord &Record) {
  CurrentRecordID--;
  for (int PointerLabel = 0; PointerLabel < 2; ++PointerLabel) {
    // Starting record must be a TopLevelPointTo record
    assert(CurrentState[PointerLabel].StartRecordID != CurrentRecordID);
  }
}

void TraceSlicer::processTopLevelPointTo(
    const TopLevelPointToLogRecord &Record) {
  CurrentRecordID--;
  int NumContainingSlices = 0;
  IDAssigner &IDA = getAnalysis<IDAssigner>();
  for (int PointerLabel = 0; PointerLabel < 2; ++PointerLabel) {
    if (CurrentState[PointerLabel].StartRecordID == CurrentRecordID) {
      Value *V = IDA.getValue(Record.PointerValueID);
      assert(V->getType()->isPointerTy());
      CurrentState[PointerLabel].ValueID = Record.PointerValueID;
    }
    if (isLive(PointerLabel)) {
      if (CurrentState[PointerLabel].Action != TopLevelPointTo) {
        continue;
      }

      if (!CurrentState[PointerLabel].ValueIDCandidates.empty()) {
        // For select and PHI, find current ID according to Address and
        // ValueIDCandidates.
        // If two variables of select have the same value, we follow the one
        // occurs latter, this is just a temporary method.
        if (Record.PointeeAddress == CurrentState[PointerLabel].Address &&
            CurrentState[PointerLabel].ValueIDCandidates.count(
              Record.PointerValueID)) {
          CurrentState[PointerLabel].ValueIDCandidates.clear();
          CurrentState[PointerLabel].ValueID = Record.PointerValueID;

          NumContainingSlices++;
          CurrentState[PointerLabel].Trace.push_back(pair<unsigned, unsigned>(
            CurrentRecordID, CurrentState[PointerLabel].ValueID));
          trackSourcePointer(CurrentState[PointerLabel], Record);
        }
      } else {
        if (Record.PointerValueID == CurrentState[PointerLabel].ValueID) {
          NumContainingSlices++;
          CurrentState[PointerLabel].Trace.push_back(pair<unsigned, unsigned>(
            CurrentRecordID, CurrentState[PointerLabel].ValueID));
          trackSourcePointer(CurrentState[PointerLabel], Record);
        }
      }
    }
  }
  // If two sliced traces meet, we stop tracking
  if (NumContainingSlices == 2) {
    CurrentState[0].End = true;
    CurrentState[1].End = true;
  }
}

void TraceSlicer::trackSourcePointer(TraceState &TS,
                                    const TopLevelPointToLogRecord &Record) {
  IDAssigner &IDA = getAnalysis<IDAssigner>();
  Value *V = IDA.getValue(TS.ValueID);
  if (LoadInst *LI = dyn_cast<LoadInst>(V)) {
    TS.Address = Record.LoadedFrom;
    TS.Action = AddrTakenPointTo;
  } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(V)) {
    TS.ValueID = IDA.getValueID(GEPI->getPointerOperand());
  } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(V)) {
    TS.ValueID = IDA.getValueID(BCI->getOperand(0));
  } else if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
    TS.ValueIDCandidates.insert(IDA.getValueID(SI->getTrueValue()));
    TS.ValueIDCandidates.insert(IDA.getValueID(SI->getFalseValue()));
    TS.Address = Record.PointeeAddress;
  } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
    unsigned NumIncomingValues = PN->getNumIncomingValues();
    for (unsigned VI = 0; VI != NumIncomingValues; ++VI) {
      TS.ValueIDCandidates.insert(IDA.getValueID(PN->getIncomingValue(VI)));
    }
    TS.Address = Record.PointeeAddress;
  } else if (Argument *A = dyn_cast<Argument>(V)) {
    TS.Action = CallInstruction;
    TS.ArgNo = A->getArgNo();
    // errs() << "(argument of @" << A->getParent()->getName() << ")\n";
  } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
    TS.Action = ReturnInstruction;
    // errs() << "(call @" << CI->getCalledFunction()->getName() << ")\n";
  } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
    TS.Action = ReturnInstruction;
    // errs() << "(call @" << II->getCalledFunction()->getName() << ")\n";
  } else if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
    TS.End = true;
  } else if (isa<GlobalValue>(V)) {
    TS.End = true;
  } else {
    errs() << "Unknown instruction \'" << *V << "\'\n";
    TS.End = true;
  }
}

void TraceSlicer::processAddrTakenPointTo(
    const AddrTakenPointToLogRecord &Record) {
  CurrentRecordID--;
  int NumContainingSlices = 0;
  IDAssigner &IDA = getAnalysis<IDAssigner>();
  Instruction *I = IDA.getInstruction(Record.InstructionID);
  assert(isa<StoreInst>(I));

  for (int PointerLabel = 0; PointerLabel < 2; ++PointerLabel) {
    // Starting record must be a TopLevelPointTo record
    assert(CurrentState[PointerLabel].StartRecordID != CurrentRecordID);
    if (isLive(PointerLabel)) {
      if (CurrentState[PointerLabel].Action != AddrTakenPointTo) {
        continue;
      }
      if (Record.PointerAddress == CurrentState[PointerLabel].Address) {
        NumContainingSlices++;
        CurrentState[PointerLabel].Trace.push_back(pair<unsigned, unsigned>(
          CurrentRecordID, IDA.getValueID(I)));
        CurrentState[PointerLabel].Action = TopLevelPointTo;
        StoreInst *SI = dyn_cast<StoreInst>(I);
        CurrentState[PointerLabel].ValueID =
          IDA.getValueID(SI->getValueOperand());
      }
    }
  }
  // If two sliced traces meet, we stop tracking
  if (NumContainingSlices == 2) {
    CurrentState[0].End = true;
    CurrentState[1].End = true;
  }
}

void TraceSlicer::processCallInstruction(
    const CallInstructionLogRecord &Record) {
  CurrentRecordID--;
  int NumContainingSlices = 0;
  IDAssigner &IDA = getAnalysis<IDAssigner>();
  Instruction *I = IDA.getInstruction(Record.InstructionID);
  CallSite CS(I);
  assert(CS);

  for (int PointerLabel = 0; PointerLabel < 2; ++PointerLabel) {
    // Starting record must be a TopLevelPointTo record
    assert(CurrentState[PointerLabel].StartRecordID != CurrentRecordID);
    if (isLive(PointerLabel)) {
      if (CurrentState[PointerLabel].Action == ReturnInstruction) {
        // this callee is an external function, the trace ends
        CurrentState[PointerLabel].End = true;
        continue;
      }
      if (CurrentState[PointerLabel].Action != CallInstruction) {
        continue;
      }

      NumContainingSlices++;
      CurrentState[PointerLabel].Trace.push_back(pair<unsigned, unsigned>(
        CurrentRecordID, IDA.getValueID(I)));
      CurrentState[PointerLabel].Action = TopLevelPointTo;
      CurrentState[PointerLabel].ValueID =
        IDA.getValueID(CS.getArgument(CurrentState[PointerLabel].ArgNo));
    }
  }
  // If two sliced traces meet, we stop tracking
  if (NumContainingSlices == 2) {
    CurrentState[0].End = true;
    CurrentState[1].End = true;
  }
}

void TraceSlicer::processReturnInstruction(
    const ReturnInstructionLogRecord &Record) {
  CurrentRecordID--;
  int NumContainingSlices = 0;
  IDAssigner &IDA = getAnalysis<IDAssigner>();
  Instruction *I = IDA.getInstruction(Record.InstructionID);
  assert(isa<ReturnInst>(I) || isa<ResumeInst>(I));

  for (int PointerLabel = 0; PointerLabel < 2; ++PointerLabel) {
    // Starting record must be a TopLevelPointTo record
    assert(CurrentState[PointerLabel].StartRecordID != CurrentRecordID);
    if (isLive(PointerLabel)) {
      if (CurrentState[PointerLabel].Action != ReturnInstruction) {
        continue;
      }

      NumContainingSlices++;
      CurrentState[PointerLabel].Trace.push_back(pair<unsigned, unsigned>(
        CurrentRecordID, IDA.getValueID(I)));
      CurrentState[PointerLabel].Action = TopLevelPointTo;
      if (ReturnInst *RI = dyn_cast<ReturnInst>(I)) {
        CurrentState[PointerLabel].ValueID = IDA.getValueID(RI->getReturnValue());
      } else if (ResumeInst *RI = dyn_cast<ResumeInst>(I)) {
        assert(false);
        // CurrentState[PointerLabel].ValueID = IDA.getValueID(RI->getValue());
      } else {
        assert(false);
      }
    }
  }
  // If two sliced traces meet, we stop tracking
  if (NumContainingSlices == 2) {
    CurrentState[0].End = true;
    CurrentState[1].End = true;
  }
}
<commit_msg>Warnings fixed.<commit_after>// Author: Junyang

#define DEBUG_TYPE "dyn-aa"

#include <cstdio>
#include <fstream>

#include "llvm/Pass.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/ADT/Statistic.h"

#include "rcs/IDAssigner.h"

#include "dyn-aa/LogCounter.h"
#include "dyn-aa/TraceSlicer.h"

using namespace std;
using namespace llvm;
using namespace rcs;
using namespace dyn_aa;

static cl::opt<unsigned> FirstPointerRecordID(
    "pt1",
    cl::desc("RecordID of the first pointer"));

static cl::opt<unsigned> SecondPointerRecordID(
    "pt2",
    cl::desc("RecordID of the second pointer"));

static RegisterPass<TraceSlicer> X("slice-trace",
                                   "Slice trace of two input pointers",
                                   false, // Is CFG Only?
                                   true); // Is Analysis?

char TraceSlicer::ID = 0;

bool TraceSlicer::runOnModule(Module &M) {
  LogCounter LC;
  LC.processLog();
  CurrentRecordID = LC.getNumLogRecords();

  CurrentState[0].StartRecordID = FirstPointerRecordID;
  CurrentState[1].StartRecordID = SecondPointerRecordID;

  processLog(true);

  return false;
}

void TraceSlicer::getAnalysisUsage(AnalysisUsage &AU) const {
  AU.setPreservesAll();
  AU.addRequired<IDAssigner>();
}

void TraceSlicer::printTrace(raw_ostream &O,
                             pair<unsigned, unsigned> TraceRecord,
                             int PointerLabel) const {
  unsigned RecordID = TraceRecord.first;
  unsigned ValueID = TraceRecord.second;
  IDAssigner &IDA = getAnalysis<IDAssigner>();
  Value *V = IDA.getValue(ValueID);
  O << RecordID << "\t";
  O << "ptr" << PointerLabel + 1 << "\t";
  O << ValueID << "\t";
  DynAAUtils::PrintValue(O, V);
//  if (Argument *A = dyn_cast<Argument>(V)) {
//    O << " (argNo " << A->getArgNo() << ")";
//  }
  O << "\n";
}

void TraceSlicer::print(raw_ostream &O, const Module *M) const {
  O << "RecID\tPtr\tValueID\tFunc:  Inst/Arg\n\n";
  for (int PointerLabel = 0; PointerLabel < 2; ++PointerLabel) {
    O << "ptr" << PointerLabel + 1 << ": \n";
    for (int i = CurrentState[PointerLabel].Trace.size() - 1; i >= 0; --i) {
      printTrace(O, CurrentState[PointerLabel].Trace[i], PointerLabel);
    }
    O << "\n";
  }

  O << "Merged: \n";
  int Index[2];
  Index[0] = CurrentState[0].Trace.size() - 1;
  Index[1] = CurrentState[1].Trace.size() - 1;
  while (true) {
    unsigned Min;
    int PointerLabel = -1;
    for (int i = 0; i < 2; ++i) {
      if (Index[i] >= 0 &&
          (PointerLabel == -1 || CurrentState[i].Trace[Index[i]].first < Min)) {
        Min = CurrentState[i].Trace[Index[i]].first;
        PointerLabel = i;
      }
    }
    if (PointerLabel != -1) {
      printTrace(O,
                 CurrentState[PointerLabel].Trace[Index[PointerLabel]],
                 PointerLabel);
      Index[PointerLabel]--;
    } else
      break;
  }
}

bool TraceSlicer::isLive(int PointerLabel) {
  if (CurrentState[PointerLabel].StartRecordID < CurrentRecordID ||
      CurrentState[PointerLabel].End) {
    return false;
  }
  return true;
}

void TraceSlicer::processAddrTakenDecl(const AddrTakenDeclLogRecord &Record) {
  CurrentRecordID--;
  for (int PointerLabel = 0; PointerLabel < 2; ++PointerLabel) {
    // Starting record must be a TopLevelPointTo record
    assert(CurrentState[PointerLabel].StartRecordID != CurrentRecordID);
  }
}

void TraceSlicer::processTopLevelPointTo(
    const TopLevelPointToLogRecord &Record) {
  CurrentRecordID--;
  int NumContainingSlices = 0;
  IDAssigner &IDA = getAnalysis<IDAssigner>();
  for (int PointerLabel = 0; PointerLabel < 2; ++PointerLabel) {
    if (CurrentState[PointerLabel].StartRecordID == CurrentRecordID) {
      Value *V = IDA.getValue(Record.PointerValueID);
      assert(V->getType()->isPointerTy());
      CurrentState[PointerLabel].ValueID = Record.PointerValueID;
    }
    if (isLive(PointerLabel)) {
      if (CurrentState[PointerLabel].Action != TopLevelPointTo) {
        continue;
      }

      if (!CurrentState[PointerLabel].ValueIDCandidates.empty()) {
        // For select and PHI, find current ID according to Address and
        // ValueIDCandidates.
        // If two variables of select have the same value, we follow the one
        // occurs latter, this is just a temporary method.
        if (Record.PointeeAddress == CurrentState[PointerLabel].Address &&
            CurrentState[PointerLabel].ValueIDCandidates.count(
              Record.PointerValueID)) {
          CurrentState[PointerLabel].ValueIDCandidates.clear();
          CurrentState[PointerLabel].ValueID = Record.PointerValueID;

          NumContainingSlices++;
          CurrentState[PointerLabel].Trace.push_back(pair<unsigned, unsigned>(
            CurrentRecordID, CurrentState[PointerLabel].ValueID));
          trackSourcePointer(CurrentState[PointerLabel], Record);
        }
      } else {
        if (Record.PointerValueID == CurrentState[PointerLabel].ValueID) {
          NumContainingSlices++;
          CurrentState[PointerLabel].Trace.push_back(pair<unsigned, unsigned>(
            CurrentRecordID, CurrentState[PointerLabel].ValueID));
          trackSourcePointer(CurrentState[PointerLabel], Record);
        }
      }
    }
  }
  // If two sliced traces meet, we stop tracking
  if (NumContainingSlices == 2) {
    CurrentState[0].End = true;
    CurrentState[1].End = true;
  }
}

void TraceSlicer::trackSourcePointer(TraceState &TS,
                                    const TopLevelPointToLogRecord &Record) {
  IDAssigner &IDA = getAnalysis<IDAssigner>();
  Value *V = IDA.getValue(TS.ValueID);
  if (isa<LoadInst>(V)) {
    TS.Address = Record.LoadedFrom;
    TS.Action = AddrTakenPointTo;
  } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(V)) {
    TS.ValueID = IDA.getValueID(GEPI->getPointerOperand());
  } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(V)) {
    TS.ValueID = IDA.getValueID(BCI->getOperand(0));
  } else if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
    TS.ValueIDCandidates.insert(IDA.getValueID(SI->getTrueValue()));
    TS.ValueIDCandidates.insert(IDA.getValueID(SI->getFalseValue()));
    TS.Address = Record.PointeeAddress;
  } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
    unsigned NumIncomingValues = PN->getNumIncomingValues();
    for (unsigned VI = 0; VI != NumIncomingValues; ++VI) {
      TS.ValueIDCandidates.insert(IDA.getValueID(PN->getIncomingValue(VI)));
    }
    TS.Address = Record.PointeeAddress;
  } else if (Argument *A = dyn_cast<Argument>(V)) {
    TS.Action = CallInstruction;
    TS.ArgNo = A->getArgNo();
    // errs() << "(argument of @" << A->getParent()->getName() << ")\n";
  } else if (isa<CallInst>(V) || isa<InvokeInst>(V)) {
    TS.Action = ReturnInstruction;
  } else if (isa<AllocaInst>(V)) {
    TS.End = true;
  } else if (isa<GlobalValue>(V)) {
    TS.End = true;
  } else {
    errs() << "Unknown instruction \'" << *V << "\'\n";
    TS.End = true;
  }
}

void TraceSlicer::processAddrTakenPointTo(
    const AddrTakenPointToLogRecord &Record) {
  CurrentRecordID--;
  int NumContainingSlices = 0;
  IDAssigner &IDA = getAnalysis<IDAssigner>();
  Instruction *I = IDA.getInstruction(Record.InstructionID);
  assert(isa<StoreInst>(I));

  for (int PointerLabel = 0; PointerLabel < 2; ++PointerLabel) {
    // Starting record must be a TopLevelPointTo record
    assert(CurrentState[PointerLabel].StartRecordID != CurrentRecordID);
    if (isLive(PointerLabel)) {
      if (CurrentState[PointerLabel].Action != AddrTakenPointTo) {
        continue;
      }
      if (Record.PointerAddress == CurrentState[PointerLabel].Address) {
        NumContainingSlices++;
        CurrentState[PointerLabel].Trace.push_back(pair<unsigned, unsigned>(
          CurrentRecordID, IDA.getValueID(I)));
        CurrentState[PointerLabel].Action = TopLevelPointTo;
        StoreInst *SI = dyn_cast<StoreInst>(I);
        CurrentState[PointerLabel].ValueID =
          IDA.getValueID(SI->getValueOperand());
      }
    }
  }
  // If two sliced traces meet, we stop tracking
  if (NumContainingSlices == 2) {
    CurrentState[0].End = true;
    CurrentState[1].End = true;
  }
}

void TraceSlicer::processCallInstruction(
    const CallInstructionLogRecord &Record) {
  CurrentRecordID--;
  int NumContainingSlices = 0;
  IDAssigner &IDA = getAnalysis<IDAssigner>();
  Instruction *I = IDA.getInstruction(Record.InstructionID);
  CallSite CS(I);
  assert(CS);

  for (int PointerLabel = 0; PointerLabel < 2; ++PointerLabel) {
    // Starting record must be a TopLevelPointTo record
    assert(CurrentState[PointerLabel].StartRecordID != CurrentRecordID);
    if (isLive(PointerLabel)) {
      if (CurrentState[PointerLabel].Action == ReturnInstruction) {
        // this callee is an external function, the trace ends
        CurrentState[PointerLabel].End = true;
        continue;
      }
      if (CurrentState[PointerLabel].Action != CallInstruction) {
        continue;
      }

      NumContainingSlices++;
      CurrentState[PointerLabel].Trace.push_back(pair<unsigned, unsigned>(
        CurrentRecordID, IDA.getValueID(I)));
      CurrentState[PointerLabel].Action = TopLevelPointTo;
      CurrentState[PointerLabel].ValueID =
        IDA.getValueID(CS.getArgument(CurrentState[PointerLabel].ArgNo));
    }
  }
  // If two sliced traces meet, we stop tracking
  if (NumContainingSlices == 2) {
    CurrentState[0].End = true;
    CurrentState[1].End = true;
  }
}

void TraceSlicer::processReturnInstruction(
    const ReturnInstructionLogRecord &Record) {
  CurrentRecordID--;
  int NumContainingSlices = 0;
  IDAssigner &IDA = getAnalysis<IDAssigner>();
  Instruction *I = IDA.getInstruction(Record.InstructionID);
  assert(isa<ReturnInst>(I) || isa<ResumeInst>(I));

  for (int PointerLabel = 0; PointerLabel < 2; ++PointerLabel) {
    // Starting record must be a TopLevelPointTo record
    assert(CurrentState[PointerLabel].StartRecordID != CurrentRecordID);
    if (isLive(PointerLabel)) {
      if (CurrentState[PointerLabel].Action != ReturnInstruction) {
        continue;
      }

      NumContainingSlices++;
      CurrentState[PointerLabel].Trace.push_back(pair<unsigned, unsigned>(
        CurrentRecordID, IDA.getValueID(I)));
      CurrentState[PointerLabel].Action = TopLevelPointTo;
      if (ReturnInst *RI = dyn_cast<ReturnInst>(I)) {
        CurrentState[PointerLabel].ValueID =
          IDA.getValueID(RI->getReturnValue());
      } else if (isa<ResumeInst>(I)) {
        assert(false);
      } else {
        assert(false);
      }
    }
  }
  // If two sliced traces meet, we stop tracking
  if (NumContainingSlices == 2) {
    CurrentState[0].End = true;
    CurrentState[1].End = true;
  }
}
<|endoftext|>


<commit_before>//===-- OptimizeExts.cpp - Optimize sign / zero extension instrs -----===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This pass performs optimization of sign / zero extension instructions. It
// may be extended to handle other instructions of similar property.
//
// On some targets, some instructions, e.g. X86 sign / zero extension, may
// leave the source value in the lower part of the result. This pass will
// replace (some) uses of the pre-extension value with uses of the sub-register
// of the results.
//
//===----------------------------------------------------------------------===//

#define DEBUG_TYPE "ext-opt"
#include "llvm/CodeGen/Passes.h"
#include "llvm/CodeGen/MachineDominators.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/Target/TargetInstrInfo.h"
#include "llvm/Target/TargetRegisterInfo.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/Statistic.h"
using namespace llvm;

static cl::opt<bool> Aggressive("aggressive-ext-opt", cl::Hidden,
                                cl::desc("Aggressive extension optimization"));

STATISTIC(NumReuse, "Number of extension results reused");

namespace {
  class OptimizeExts : public MachineFunctionPass {
    const TargetMachine   *TM;
    const TargetInstrInfo *TII;
    MachineRegisterInfo *MRI;
    MachineDominatorTree *DT;   // Machine dominator tree

  public:
    static char ID; // Pass identification
    OptimizeExts() : MachineFunctionPass(&ID) {}

    virtual bool runOnMachineFunction(MachineFunction &MF);

    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
      AU.setPreservesCFG();
      MachineFunctionPass::getAnalysisUsage(AU);
      if (Aggressive) {
        AU.addRequired<MachineDominatorTree>();
        AU.addPreserved<MachineDominatorTree>();
      }
    }

  private:
    bool OptimizeInstr(MachineInstr *MI, MachineBasicBlock *MBB,
                       SmallPtrSet<MachineInstr*, 8> &LocalMIs);
  };
}

char OptimizeExts::ID = 0;
INITIALIZE_PASS(OptimizeExts, "opt-exts",
                "Optimize sign / zero extensions", false, false);

FunctionPass *llvm::createOptimizeExtsPass() { return new OptimizeExts(); }

/// OptimizeInstr - If instruction is a copy-like instruction, i.e. it reads
/// a single register and writes a single register and it does not modify
/// the source, and if the source value is preserved as a sub-register of
/// the result, then replace all reachable uses of the source with the subreg
/// of the result.
/// Do not generate an EXTRACT that is used only in a debug use, as this
/// changes the code.  Since this code does not currently share EXTRACTs, just
/// ignore all debug uses.
bool OptimizeExts::OptimizeInstr(MachineInstr *MI, MachineBasicBlock *MBB,
                                 SmallPtrSet<MachineInstr*, 8> &LocalMIs) {
  bool Changed = false;
  LocalMIs.insert(MI);

  unsigned SrcReg, DstReg, SubIdx;
  if (TII->isCoalescableExtInstr(*MI, SrcReg, DstReg, SubIdx)) {
    if (TargetRegisterInfo::isPhysicalRegister(DstReg) ||
        TargetRegisterInfo::isPhysicalRegister(SrcReg))
      return false;

    MachineRegisterInfo::use_nodbg_iterator UI = MRI->use_nodbg_begin(SrcReg);
    if (++UI == MRI->use_nodbg_end())
      // No other uses.
      return false;

    // Ok, the source has other uses. See if we can replace the other uses
    // with use of the result of the extension.
    SmallPtrSet<MachineBasicBlock*, 4> ReachedBBs;
    UI = MRI->use_nodbg_begin(DstReg);
    for (MachineRegisterInfo::use_nodbg_iterator UE = MRI->use_nodbg_end();
         UI != UE; ++UI)
      ReachedBBs.insert(UI->getParent());

    bool ExtendLife = true;
    // Uses that are in the same BB of uses of the result of the instruction.
    SmallVector<MachineOperand*, 8> Uses;
    // Uses that the result of the instruction can reach.
    SmallVector<MachineOperand*, 8> ExtendedUses;

    UI = MRI->use_nodbg_begin(SrcReg);
    for (MachineRegisterInfo::use_nodbg_iterator UE = MRI->use_nodbg_end();
         UI != UE; ++UI) {
      MachineOperand &UseMO = UI.getOperand();
      MachineInstr *UseMI = &*UI;
      if (UseMI == MI)
        continue;
      if (UseMI->isPHI()) {
        ExtendLife = false;
        continue;
      }

      // It's an error to translate this:
      //
      //    %reg1025 = <sext> %reg1024
      //     ...
      //    %reg1026 = SUBREG_TO_REG 0, %reg1024, 4
      //
      // into this:
      //
      //    %reg1025 = <sext> %reg1024
      //     ...
      //    %reg1027 = COPY %reg1025:4
      //    %reg1026 = SUBREG_TO_REG 0, %reg1027, 4
      //
      // The problem here is that SUBREG_TO_REG is there to assert that an
      // implicit zext occurs. It doesn't insert a zext instruction. If we allow
      // the COPY here, it will give us the value after the <sext>,
      // not the original value of %reg1024 before <sext>.
      if (UseMI->getOpcode() == TargetOpcode::SUBREG_TO_REG)
        continue;

      MachineBasicBlock *UseMBB = UseMI->getParent();
      if (UseMBB == MBB) {
        // Local uses that come after the extension.
        if (!LocalMIs.count(UseMI))
          Uses.push_back(&UseMO);
      } else if (ReachedBBs.count(UseMBB))
        // Non-local uses where the result of extension is used. Always
        // replace these unless it's a PHI.
        Uses.push_back(&UseMO);
      else if (Aggressive && DT->dominates(MBB, UseMBB))
        // We may want to extend live range of the extension result in order
        // to replace these uses.
        ExtendedUses.push_back(&UseMO);
      else {
        // Both will be live out of the def MBB anyway. Don't extend live
        // range of the extension result.
        ExtendLife = false;
        break;
      }
    }

    if (ExtendLife && !ExtendedUses.empty())
      // Ok, we'll extend the liveness of the extension result.
      std::copy(ExtendedUses.begin(), ExtendedUses.end(),
                std::back_inserter(Uses));

    // Now replace all uses.
    if (!Uses.empty()) {
      SmallPtrSet<MachineBasicBlock*, 4> PHIBBs;
      // Look for PHI uses of the extended result, we don't want to extend the
      // liveness of a PHI input. It breaks all kinds of assumptions down
      // stream. A PHI use is expected to be the kill of its source values.
      UI = MRI->use_nodbg_begin(DstReg);
      for (MachineRegisterInfo::use_nodbg_iterator UE = MRI->use_nodbg_end();
           UI != UE; ++UI)
        if (UI->isPHI())
          PHIBBs.insert(UI->getParent());

      const TargetRegisterClass *RC = MRI->getRegClass(SrcReg);
      for (unsigned i = 0, e = Uses.size(); i != e; ++i) {
        MachineOperand *UseMO = Uses[i];
        MachineInstr *UseMI = UseMO->getParent();
        MachineBasicBlock *UseMBB = UseMI->getParent();
        if (PHIBBs.count(UseMBB))
          continue;
        unsigned NewVR = MRI->createVirtualRegister(RC);
        BuildMI(*UseMBB, UseMI, UseMI->getDebugLoc(),
                TII->get(TargetOpcode::COPY), NewVR)
          .addReg(DstReg, 0, SubIdx);
        UseMO->setReg(NewVR);
        ++NumReuse;
        Changed = true;
      }
    }
  }

  return Changed;
}

bool OptimizeExts::runOnMachineFunction(MachineFunction &MF) {
  TM = &MF.getTarget();
  TII = TM->getInstrInfo();
  MRI = &MF.getRegInfo();
  DT = Aggressive ? &getAnalysis<MachineDominatorTree>() : 0;

  bool Changed = false;

  SmallPtrSet<MachineInstr*, 8> LocalMIs;
  for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
    MachineBasicBlock *MBB = &*I;
    LocalMIs.clear();
    for (MachineBasicBlock::iterator MII = I->begin(), ME = I->end(); MII != ME;
         ++MII) {
      MachineInstr *MI = &*MII;
      Changed |= OptimizeInstr(MI, MBB, LocalMIs);
    }
  }

  return Changed;
}
<commit_msg>Early exit and reduce indentation. No functionality change.<commit_after>//===-- OptimizeExts.cpp - Optimize sign / zero extension instrs -----===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This pass performs optimization of sign / zero extension instructions. It
// may be extended to handle other instructions of similar property.
//
// On some targets, some instructions, e.g. X86 sign / zero extension, may
// leave the source value in the lower part of the result. This pass will
// replace (some) uses of the pre-extension value with uses of the sub-register
// of the results.
//
//===----------------------------------------------------------------------===//

#define DEBUG_TYPE "ext-opt"
#include "llvm/CodeGen/Passes.h"
#include "llvm/CodeGen/MachineDominators.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/Target/TargetInstrInfo.h"
#include "llvm/Target/TargetRegisterInfo.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/Statistic.h"
using namespace llvm;

static cl::opt<bool> Aggressive("aggressive-ext-opt", cl::Hidden,
                                cl::desc("Aggressive extension optimization"));

STATISTIC(NumReuse, "Number of extension results reused");

namespace {
  class OptimizeExts : public MachineFunctionPass {
    const TargetMachine   *TM;
    const TargetInstrInfo *TII;
    MachineRegisterInfo *MRI;
    MachineDominatorTree *DT;   // Machine dominator tree

  public:
    static char ID; // Pass identification
    OptimizeExts() : MachineFunctionPass(&ID) {}

    virtual bool runOnMachineFunction(MachineFunction &MF);

    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
      AU.setPreservesCFG();
      MachineFunctionPass::getAnalysisUsage(AU);
      if (Aggressive) {
        AU.addRequired<MachineDominatorTree>();
        AU.addPreserved<MachineDominatorTree>();
      }
    }

  private:
    bool OptimizeInstr(MachineInstr *MI, MachineBasicBlock *MBB,
                       SmallPtrSet<MachineInstr*, 8> &LocalMIs);
  };
}

char OptimizeExts::ID = 0;
INITIALIZE_PASS(OptimizeExts, "opt-exts",
                "Optimize sign / zero extensions", false, false);

FunctionPass *llvm::createOptimizeExtsPass() { return new OptimizeExts(); }

/// OptimizeInstr - If instruction is a copy-like instruction, i.e. it reads
/// a single register and writes a single register and it does not modify
/// the source, and if the source value is preserved as a sub-register of
/// the result, then replace all reachable uses of the source with the subreg
/// of the result.
/// Do not generate an EXTRACT that is used only in a debug use, as this
/// changes the code.  Since this code does not currently share EXTRACTs, just
/// ignore all debug uses.
bool OptimizeExts::OptimizeInstr(MachineInstr *MI, MachineBasicBlock *MBB,
                                 SmallPtrSet<MachineInstr*, 8> &LocalMIs) {
  LocalMIs.insert(MI);

  unsigned SrcReg, DstReg, SubIdx;
  if (!TII->isCoalescableExtInstr(*MI, SrcReg, DstReg, SubIdx))
    return false;

  if (TargetRegisterInfo::isPhysicalRegister(DstReg) ||
      TargetRegisterInfo::isPhysicalRegister(SrcReg))
    return false;

  MachineRegisterInfo::use_nodbg_iterator UI = MRI->use_nodbg_begin(SrcReg);
  if (++UI == MRI->use_nodbg_end())
    // No other uses.
    return false;

  // Ok, the source has other uses. See if we can replace the other uses
  // with use of the result of the extension.
  SmallPtrSet<MachineBasicBlock*, 4> ReachedBBs;
  UI = MRI->use_nodbg_begin(DstReg);
  for (MachineRegisterInfo::use_nodbg_iterator UE = MRI->use_nodbg_end();
       UI != UE; ++UI)
    ReachedBBs.insert(UI->getParent());

  bool ExtendLife = true;
  // Uses that are in the same BB of uses of the result of the instruction.
  SmallVector<MachineOperand*, 8> Uses;
  // Uses that the result of the instruction can reach.
  SmallVector<MachineOperand*, 8> ExtendedUses;

  UI = MRI->use_nodbg_begin(SrcReg);
  for (MachineRegisterInfo::use_nodbg_iterator UE = MRI->use_nodbg_end();
       UI != UE; ++UI) {
    MachineOperand &UseMO = UI.getOperand();
    MachineInstr *UseMI = &*UI;
    if (UseMI == MI)
      continue;
    if (UseMI->isPHI()) {
      ExtendLife = false;
      continue;
    }

    // It's an error to translate this:
    //
    //    %reg1025 = <sext> %reg1024
    //     ...
    //    %reg1026 = SUBREG_TO_REG 0, %reg1024, 4
    //
    // into this:
    //
    //    %reg1025 = <sext> %reg1024
    //     ...
    //    %reg1027 = COPY %reg1025:4
    //    %reg1026 = SUBREG_TO_REG 0, %reg1027, 4
    //
    // The problem here is that SUBREG_TO_REG is there to assert that an
    // implicit zext occurs. It doesn't insert a zext instruction. If we allow
    // the COPY here, it will give us the value after the <sext>, not the
    // original value of %reg1024 before <sext>.
    if (UseMI->getOpcode() == TargetOpcode::SUBREG_TO_REG)
      continue;

    MachineBasicBlock *UseMBB = UseMI->getParent();
    if (UseMBB == MBB) {
      // Local uses that come after the extension.
      if (!LocalMIs.count(UseMI))
        Uses.push_back(&UseMO);
    } else if (ReachedBBs.count(UseMBB))
      // Non-local uses where the result of extension is used. Always replace
      // these unless it's a PHI.
      Uses.push_back(&UseMO);
    else if (Aggressive && DT->dominates(MBB, UseMBB))
      // We may want to extend live range of the extension result in order to
      // replace these uses.
      ExtendedUses.push_back(&UseMO);
    else {
      // Both will be live out of the def MBB anyway. Don't extend live range of
      // the extension result.
      ExtendLife = false;
      break;
    }
  }

  if (ExtendLife && !ExtendedUses.empty())
    // Ok, we'll extend the liveness of the extension result.
    std::copy(ExtendedUses.begin(), ExtendedUses.end(),
              std::back_inserter(Uses));

  // Now replace all uses.
  bool Changed = false;
  if (!Uses.empty()) {
    SmallPtrSet<MachineBasicBlock*, 4> PHIBBs;
    // Look for PHI uses of the extended result, we don't want to extend the
    // liveness of a PHI input. It breaks all kinds of assumptions down
    // stream. A PHI use is expected to be the kill of its source values.
    UI = MRI->use_nodbg_begin(DstReg);
    for (MachineRegisterInfo::use_nodbg_iterator UE = MRI->use_nodbg_end();
         UI != UE; ++UI)
      if (UI->isPHI())
        PHIBBs.insert(UI->getParent());

    const TargetRegisterClass *RC = MRI->getRegClass(SrcReg);
    for (unsigned i = 0, e = Uses.size(); i != e; ++i) {
      MachineOperand *UseMO = Uses[i];
      MachineInstr *UseMI = UseMO->getParent();
      MachineBasicBlock *UseMBB = UseMI->getParent();
      if (PHIBBs.count(UseMBB))
        continue;
      unsigned NewVR = MRI->createVirtualRegister(RC);
      BuildMI(*UseMBB, UseMI, UseMI->getDebugLoc(),
              TII->get(TargetOpcode::COPY), NewVR)
        .addReg(DstReg, 0, SubIdx);
      UseMO->setReg(NewVR);
      ++NumReuse;
      Changed = true;
    }
  }

  return Changed;
}

bool OptimizeExts::runOnMachineFunction(MachineFunction &MF) {
  TM = &MF.getTarget();
  TII = TM->getInstrInfo();
  MRI = &MF.getRegInfo();
  DT = Aggressive ? &getAnalysis<MachineDominatorTree>() : 0;

  bool Changed = false;

  SmallPtrSet<MachineInstr*, 8> LocalMIs;
  for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
    MachineBasicBlock *MBB = &*I;
    LocalMIs.clear();
    for (MachineBasicBlock::iterator MII = I->begin(), ME = I->end(); MII != ME;
         ++MII) {
      MachineInstr *MI = &*MII;
      Changed |= OptimizeInstr(MI, MBB, LocalMIs);
    }
  }

  return Changed;
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <folly/portability/GFlags.h>
#include <folly/portability/GTest.h>

#include <thrift/lib/cpp2/async/RocketClientChannel.h>
#include <thrift/lib/cpp2/server/Cpp2Worker.h>
#include <thrift/lib/cpp2/transport/core/testutil/MockCallback.h>
#include <thrift/lib/cpp2/transport/core/testutil/TransportCompatibilityTest.h>
#include <thrift/lib/cpp2/transport/rocket/server/RocketServerConnection.h>
#include <thrift/lib/cpp2/transport/rocket/server/ThriftRocketServerHandler.h>
#include <thrift/lib/cpp2/transport/rsocket/server/RSRoutingHandler.h>

DECLARE_int32(num_client_connections);
DECLARE_string(transport); // ConnectionManager depends on this flag.

namespace apache {
namespace thrift {

using namespace testutil::testservice;
using namespace apache::thrift::transport;

class RSCompatibilityTest
    : public testing::Test,
      public testing::WithParamInterface<bool /* useRocketClient */> {
 public:
  RSCompatibilityTest() {
    FLAGS_transport = "rocket";

    compatibilityTest_ = std::make_unique<TransportCompatibilityTest>();
    compatibilityTest_->addRoutingHandler(
        std::make_unique<apache::thrift::RSRoutingHandler>());
    compatibilityTest_->startServer();
  }

 protected:
  std::unique_ptr<TransportCompatibilityTest> compatibilityTest_;
};

TEST_F(RSCompatibilityTest, RequestResponse_Simple) {
  compatibilityTest_->TestRequestResponse_Simple();
}

TEST_F(RSCompatibilityTest, RequestResponse_Sync) {
  compatibilityTest_->TestRequestResponse_Sync();
}

TEST_F(RSCompatibilityTest, RequestResponse_Destruction) {
  compatibilityTest_->TestRequestResponse_Destruction();
}

TEST_F(RSCompatibilityTest, RequestResponse_MultipleClients) {
  compatibilityTest_->TestRequestResponse_MultipleClients();
}

TEST_F(RSCompatibilityTest, RequestResponse_ExpectedException) {
  compatibilityTest_->TestRequestResponse_ExpectedException();
}

TEST_F(RSCompatibilityTest, RequestResponse_UnexpectedException) {
  compatibilityTest_->TestRequestResponse_UnexpectedException();
}

// Warning: This test may be flaky due to use of timeouts.
TEST_F(RSCompatibilityTest, RequestResponse_Timeout) {
  compatibilityTest_->TestRequestResponse_Timeout();
}

TEST_F(RSCompatibilityTest, DefaultTimeoutValueTest) {
  compatibilityTest_->connectToServer([](auto client) {
    // Opts with no timeout value
    RpcOptions opts;

    // Ok to sleep for 100msec
    auto cb = std::make_unique<MockCallback>(false, false);
    client->sleep(opts, std::move(cb), 100);

    /* Sleep to give time for all callbacks to be completed */
    /* sleep override */
    std::this_thread::sleep_for(std::chrono::milliseconds(200));

    auto* channel = dynamic_cast<ClientChannel*>(client->getChannel());
    EXPECT_TRUE(channel);
    channel->getEventBase()->runInEventBaseThreadAndWait([&]() {
      channel->setTimeout(1); // 1ms
    });

    // Now it should timeout
    cb = std::make_unique<MockCallback>(false, true);
    client->sleep(opts, std::move(cb), 100);

    /* Sleep to give time for all callbacks to be completed */
    /* sleep override */
    std::this_thread::sleep_for(std::chrono::milliseconds(200));
  });
}

TEST_F(RSCompatibilityTest, RequestResponse_Header) {
  compatibilityTest_->TestRequestResponse_Header();
}

TEST_F(RSCompatibilityTest, RequestResponse_Header_Load) {
  compatibilityTest_->TestRequestResponse_Header_Load();
}

TEST_F(RSCompatibilityTest, RequestResponse_Header_ExpectedException) {
  compatibilityTest_->TestRequestResponse_Header_ExpectedException();
}

TEST_F(RSCompatibilityTest, RequestResponse_Header_UnexpectedException) {
  compatibilityTest_->TestRequestResponse_Header_UnexpectedException();
}

TEST_F(RSCompatibilityTest, RequestResponse_Saturation) {
  compatibilityTest_->connectToServer([this](auto client) {
    EXPECT_CALL(*compatibilityTest_->handler_.get(), add_(3)).Times(2);
    // note that no EXPECT_CALL for add_(5)
    auto* channel = dynamic_cast<RocketClientChannel*>(client->getChannel());
    ASSERT_NE(nullptr, channel);

    channel->getEventBase()->runInEventBaseThreadAndWait(
        [&]() { channel->setMaxPendingRequests(0u); });
    EXPECT_THROW(client->future_add(5).get(), TTransportException);

    channel->getEventBase()->runInEventBaseThreadAndWait(
        [&]() { channel->setMaxPendingRequests(1u); });

    EXPECT_EQ(3, client->future_add(3).get());
    EXPECT_EQ(6, client->future_add(3).get());
  });
}

TEST_F(RSCompatibilityTest, RequestResponse_Connection_CloseNow) {
  compatibilityTest_->TestRequestResponse_Connection_CloseNow();
}

TEST_F(RSCompatibilityTest, RequestResponse_ServerQueueTimeout) {
  compatibilityTest_->TestRequestResponse_ServerQueueTimeout();
}

TEST_F(RSCompatibilityTest, RequestResponse_ResponseSizeTooBig) {
  compatibilityTest_->TestRequestResponse_ResponseSizeTooBig();
}

TEST_F(RSCompatibilityTest, RequestResponse_Checksumming) {
  compatibilityTest_->TestRequestResponse_Checksumming();
}

TEST_F(RSCompatibilityTest, RequestResponse_CompressRequest) {
  compatibilityTest_->connectToServer([this](auto client) {
    EXPECT_CALL(*compatibilityTest_->handler_.get(), hello_(testing::_));
    auto* channel = dynamic_cast<RocketClientChannel*>(client->getChannel());
    ASSERT_NE(nullptr, channel);

    // set the channel to compress requests
    channel->setNegotiatedCompressionAlgorithm(CompressionAlgorithm::ZSTD);
    channel->setAutoCompressSizeLimit(0);

    std::string name("snoopy");
    auto result =
        client->future_hello(RpcOptions().setEnableChecksum(true), name).get();
    EXPECT_EQ("Hello, snoopy", result);
  });
}

TEST_F(RSCompatibilityTest, Oneway_Simple) {
  compatibilityTest_->TestOneway_Simple();
}

TEST_F(RSCompatibilityTest, Oneway_WithDelay) {
  compatibilityTest_->TestOneway_WithDelay();
}

TEST_F(RSCompatibilityTest, Oneway_Saturation) {
  compatibilityTest_->connectToServer([this](auto client) {
    EXPECT_CALL(*compatibilityTest_->handler_.get(), addAfterDelay_(100, 5));
    EXPECT_CALL(*compatibilityTest_->handler_.get(), addAfterDelay_(50, 5));

    if (auto* channel =
            dynamic_cast<RocketClientChannel*>(client->getChannel())) {
      channel->getEventBase()->runInEventBaseThreadAndWait(
          [&]() { channel->setMaxPendingRequests(0u); });
      EXPECT_THROW(
          client->future_addAfterDelay(0, 5).get(), TTransportException);

      // the first call is not completed as the connection was saturated
      channel->getEventBase()->runInEventBaseThreadAndWait(
          [&]() { channel->setMaxPendingRequests(1u); });
    } else {
      FAIL() << "Test run with unexpected channel type";
    }

    // Client should be able to issue both of these functions as
    // SINGLE_REQUEST_NO_RESPONSE doesn't need to wait for server response
    client->future_addAfterDelay(100, 5).get();
    client->future_addAfterDelay(50, 5).get(); // TODO: H2 fails in this call.
  });
}

TEST_F(RSCompatibilityTest, Oneway_UnexpectedException) {
  compatibilityTest_->TestOneway_UnexpectedException();
}

TEST_F(RSCompatibilityTest, Oneway_Connection_CloseNow) {
  compatibilityTest_->TestOneway_Connection_CloseNow();
}

TEST_F(RSCompatibilityTest, Oneway_ServerQueueTimeout) {
  compatibilityTest_->TestOneway_ServerQueueTimeout();
}

TEST_F(RSCompatibilityTest, Oneway_Checksumming) {
  compatibilityTest_->TestOneway_Checksumming();
}

TEST_F(RSCompatibilityTest, RequestContextIsPreserved) {
  compatibilityTest_->TestRequestContextIsPreserved();
}

TEST_F(RSCompatibilityTest, BadPayload) {
  compatibilityTest_->TestBadPayload();
}

TEST_F(RSCompatibilityTest, EvbSwitch) {
  compatibilityTest_->TestEvbSwitch();
}

TEST_F(RSCompatibilityTest, EvbSwitch_Failure) {
  compatibilityTest_->TestEvbSwitch_Failure();
}

TEST_F(RSCompatibilityTest, CloseCallback) {
  compatibilityTest_->TestCloseCallback();
}

TEST_F(RSCompatibilityTest, ConnectionStats) {
  compatibilityTest_->TestConnectionStats();
}

TEST_F(RSCompatibilityTest, ObserverSendReceiveRequests) {
  compatibilityTest_->TestObserverSendReceiveRequests();
}

TEST_F(RSCompatibilityTest, ConnectionContext) {
  compatibilityTest_->TestConnectionContext();
}

TEST_F(RSCompatibilityTest, ClientIdentityHook) {
  compatibilityTest_->TestClientIdentityHook();
}

/**
 * This is a test class with customized RoutingHandler. The main purpose is to
 * set compression on the server-side and test the behavior.
 */
class RSCompatibilityTest2 : public testing::Test {
  class TestRoutingHandler : public RSRoutingHandler {
   public:
    TestRoutingHandler() = default;
    TestRoutingHandler(const TestRoutingHandler&) = delete;
    TestRoutingHandler& operator=(const TestRoutingHandler&) = delete;
    void handleConnection(
        wangle::ConnectionManager* connectionManager,
        folly::AsyncTransportWrapper::UniquePtr sock,
        folly::SocketAddress const* address,
        wangle::TransportInfo const& /*tinfo*/,
        std::shared_ptr<Cpp2Worker> worker) override {
      auto sockPtr = sock.get();

      auto* const server = worker->getServer();
      auto* const connection = new rocket::RocketServerConnection(
          std::move(sock),
          std::make_shared<rocket::ThriftRocketServerHandler>(
              worker, *address, sockPtr, setupFrameHandlers),
          server->getStreamExpireTime());
      connection->setNegotiatedCompressionAlgorithm(CompressionAlgorithm::ZSTD);
      connection->setMinCompressBytes(server->getMinCompressBytes());
      connectionManager->addConnection(connection);

      if (auto* observer = server->getObserver()) {
        observer->connAccepted();
        observer->activeConnections(
            connectionManager->getNumConnections() *
            server->getNumIOWorkerThreads());
      }
    }

   private:
    std::vector<std::unique_ptr<rocket::SetupFrameHandler>> setupFrameHandlers;
  };

 public:
  RSCompatibilityTest2() {
    FLAGS_transport = "rocket";

    compatibilityTest_ = std::make_unique<TransportCompatibilityTest>();
    compatibilityTest_->addRoutingHandler(
        std::make_unique<TestRoutingHandler>());
    compatibilityTest_->startServer();
  }

 protected:
  std::unique_ptr<TransportCompatibilityTest> compatibilityTest_;
};

TEST_F(RSCompatibilityTest2, RequestResponse_CompressRequestResponse) {
  compatibilityTest_->connectToServer([this](auto client) {
    EXPECT_CALL(*compatibilityTest_->handler_.get(), hello_(testing::_));
    auto* channel = dynamic_cast<RocketClientChannel*>(client->getChannel());
    ASSERT_NE(nullptr, channel);

    // set the channel to compress requests
    channel->setNegotiatedCompressionAlgorithm(CompressionAlgorithm::ZSTD);
    channel->setAutoCompressSizeLimit(0);

    std::string name("snoopy");
    auto result =
        client->future_hello(RpcOptions().setEnableChecksum(true), name).get();
    EXPECT_EQ("Hello, snoopy", result);
  });
}

} // namespace thrift
} // namespace apache
<commit_msg>clean up unused bool for rocket tests<commit_after>/*
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <folly/portability/GFlags.h>
#include <folly/portability/GTest.h>

#include <thrift/lib/cpp2/async/RocketClientChannel.h>
#include <thrift/lib/cpp2/server/Cpp2Worker.h>
#include <thrift/lib/cpp2/transport/core/testutil/MockCallback.h>
#include <thrift/lib/cpp2/transport/core/testutil/TransportCompatibilityTest.h>
#include <thrift/lib/cpp2/transport/rocket/server/RocketServerConnection.h>
#include <thrift/lib/cpp2/transport/rocket/server/ThriftRocketServerHandler.h>
#include <thrift/lib/cpp2/transport/rsocket/server/RSRoutingHandler.h>

DECLARE_int32(num_client_connections);
DECLARE_string(transport); // ConnectionManager depends on this flag.

namespace apache {
namespace thrift {

using namespace testutil::testservice;
using namespace apache::thrift::transport;

class RSCompatibilityTest : public testing::Test {
 public:
  RSCompatibilityTest() {
    FLAGS_transport = "rocket";

    compatibilityTest_ = std::make_unique<TransportCompatibilityTest>();
    compatibilityTest_->addRoutingHandler(
        std::make_unique<apache::thrift::RSRoutingHandler>());
    compatibilityTest_->startServer();
  }

 protected:
  std::unique_ptr<TransportCompatibilityTest> compatibilityTest_;
};

TEST_F(RSCompatibilityTest, RequestResponse_Simple) {
  compatibilityTest_->TestRequestResponse_Simple();
}

TEST_F(RSCompatibilityTest, RequestResponse_Sync) {
  compatibilityTest_->TestRequestResponse_Sync();
}

TEST_F(RSCompatibilityTest, RequestResponse_Destruction) {
  compatibilityTest_->TestRequestResponse_Destruction();
}

TEST_F(RSCompatibilityTest, RequestResponse_MultipleClients) {
  compatibilityTest_->TestRequestResponse_MultipleClients();
}

TEST_F(RSCompatibilityTest, RequestResponse_ExpectedException) {
  compatibilityTest_->TestRequestResponse_ExpectedException();
}

TEST_F(RSCompatibilityTest, RequestResponse_UnexpectedException) {
  compatibilityTest_->TestRequestResponse_UnexpectedException();
}

// Warning: This test may be flaky due to use of timeouts.
TEST_F(RSCompatibilityTest, RequestResponse_Timeout) {
  compatibilityTest_->TestRequestResponse_Timeout();
}

TEST_F(RSCompatibilityTest, DefaultTimeoutValueTest) {
  compatibilityTest_->connectToServer([](auto client) {
    // Opts with no timeout value
    RpcOptions opts;

    // Ok to sleep for 100msec
    auto cb = std::make_unique<MockCallback>(false, false);
    client->sleep(opts, std::move(cb), 100);

    /* Sleep to give time for all callbacks to be completed */
    /* sleep override */
    std::this_thread::sleep_for(std::chrono::milliseconds(200));

    auto* channel = dynamic_cast<ClientChannel*>(client->getChannel());
    EXPECT_TRUE(channel);
    channel->getEventBase()->runInEventBaseThreadAndWait([&]() {
      channel->setTimeout(1); // 1ms
    });

    // Now it should timeout
    cb = std::make_unique<MockCallback>(false, true);
    client->sleep(opts, std::move(cb), 100);

    /* Sleep to give time for all callbacks to be completed */
    /* sleep override */
    std::this_thread::sleep_for(std::chrono::milliseconds(200));
  });
}

TEST_F(RSCompatibilityTest, RequestResponse_Header) {
  compatibilityTest_->TestRequestResponse_Header();
}

TEST_F(RSCompatibilityTest, RequestResponse_Header_Load) {
  compatibilityTest_->TestRequestResponse_Header_Load();
}

TEST_F(RSCompatibilityTest, RequestResponse_Header_ExpectedException) {
  compatibilityTest_->TestRequestResponse_Header_ExpectedException();
}

TEST_F(RSCompatibilityTest, RequestResponse_Header_UnexpectedException) {
  compatibilityTest_->TestRequestResponse_Header_UnexpectedException();
}

TEST_F(RSCompatibilityTest, RequestResponse_Saturation) {
  compatibilityTest_->connectToServer([this](auto client) {
    EXPECT_CALL(*compatibilityTest_->handler_.get(), add_(3)).Times(2);
    // note that no EXPECT_CALL for add_(5)
    auto* channel = dynamic_cast<RocketClientChannel*>(client->getChannel());
    ASSERT_NE(nullptr, channel);

    channel->getEventBase()->runInEventBaseThreadAndWait(
        [&]() { channel->setMaxPendingRequests(0u); });
    EXPECT_THROW(client->future_add(5).get(), TTransportException);

    channel->getEventBase()->runInEventBaseThreadAndWait(
        [&]() { channel->setMaxPendingRequests(1u); });

    EXPECT_EQ(3, client->future_add(3).get());
    EXPECT_EQ(6, client->future_add(3).get());
  });
}

TEST_F(RSCompatibilityTest, RequestResponse_Connection_CloseNow) {
  compatibilityTest_->TestRequestResponse_Connection_CloseNow();
}

TEST_F(RSCompatibilityTest, RequestResponse_ServerQueueTimeout) {
  compatibilityTest_->TestRequestResponse_ServerQueueTimeout();
}

TEST_F(RSCompatibilityTest, RequestResponse_ResponseSizeTooBig) {
  compatibilityTest_->TestRequestResponse_ResponseSizeTooBig();
}

TEST_F(RSCompatibilityTest, RequestResponse_Checksumming) {
  compatibilityTest_->TestRequestResponse_Checksumming();
}

TEST_F(RSCompatibilityTest, RequestResponse_CompressRequest) {
  compatibilityTest_->connectToServer([this](auto client) {
    EXPECT_CALL(*compatibilityTest_->handler_.get(), hello_(testing::_));
    auto* channel = dynamic_cast<RocketClientChannel*>(client->getChannel());
    ASSERT_NE(nullptr, channel);

    // set the channel to compress requests
    channel->setNegotiatedCompressionAlgorithm(CompressionAlgorithm::ZSTD);
    channel->setAutoCompressSizeLimit(0);

    std::string name("snoopy");
    auto result =
        client->future_hello(RpcOptions().setEnableChecksum(true), name).get();
    EXPECT_EQ("Hello, snoopy", result);
  });
}

TEST_F(RSCompatibilityTest, Oneway_Simple) {
  compatibilityTest_->TestOneway_Simple();
}

TEST_F(RSCompatibilityTest, Oneway_WithDelay) {
  compatibilityTest_->TestOneway_WithDelay();
}

TEST_F(RSCompatibilityTest, Oneway_Saturation) {
  compatibilityTest_->connectToServer([this](auto client) {
    EXPECT_CALL(*compatibilityTest_->handler_.get(), addAfterDelay_(100, 5));
    EXPECT_CALL(*compatibilityTest_->handler_.get(), addAfterDelay_(50, 5));

    if (auto* channel =
            dynamic_cast<RocketClientChannel*>(client->getChannel())) {
      channel->getEventBase()->runInEventBaseThreadAndWait(
          [&]() { channel->setMaxPendingRequests(0u); });
      EXPECT_THROW(
          client->future_addAfterDelay(0, 5).get(), TTransportException);

      // the first call is not completed as the connection was saturated
      channel->getEventBase()->runInEventBaseThreadAndWait(
          [&]() { channel->setMaxPendingRequests(1u); });
    } else {
      FAIL() << "Test run with unexpected channel type";
    }

    // Client should be able to issue both of these functions as
    // SINGLE_REQUEST_NO_RESPONSE doesn't need to wait for server response
    client->future_addAfterDelay(100, 5).get();
    client->future_addAfterDelay(50, 5).get(); // TODO: H2 fails in this call.
  });
}

TEST_F(RSCompatibilityTest, Oneway_UnexpectedException) {
  compatibilityTest_->TestOneway_UnexpectedException();
}

TEST_F(RSCompatibilityTest, Oneway_Connection_CloseNow) {
  compatibilityTest_->TestOneway_Connection_CloseNow();
}

TEST_F(RSCompatibilityTest, Oneway_ServerQueueTimeout) {
  compatibilityTest_->TestOneway_ServerQueueTimeout();
}

TEST_F(RSCompatibilityTest, Oneway_Checksumming) {
  compatibilityTest_->TestOneway_Checksumming();
}

TEST_F(RSCompatibilityTest, RequestContextIsPreserved) {
  compatibilityTest_->TestRequestContextIsPreserved();
}

TEST_F(RSCompatibilityTest, BadPayload) {
  compatibilityTest_->TestBadPayload();
}

TEST_F(RSCompatibilityTest, EvbSwitch) {
  compatibilityTest_->TestEvbSwitch();
}

TEST_F(RSCompatibilityTest, EvbSwitch_Failure) {
  compatibilityTest_->TestEvbSwitch_Failure();
}

TEST_F(RSCompatibilityTest, CloseCallback) {
  compatibilityTest_->TestCloseCallback();
}

TEST_F(RSCompatibilityTest, ConnectionStats) {
  compatibilityTest_->TestConnectionStats();
}

TEST_F(RSCompatibilityTest, ObserverSendReceiveRequests) {
  compatibilityTest_->TestObserverSendReceiveRequests();
}

TEST_F(RSCompatibilityTest, ConnectionContext) {
  compatibilityTest_->TestConnectionContext();
}

TEST_F(RSCompatibilityTest, ClientIdentityHook) {
  compatibilityTest_->TestClientIdentityHook();
}

/**
 * This is a test class with customized RoutingHandler. The main purpose is to
 * set compression on the server-side and test the behavior.
 */
class RSCompatibilityTest2 : public testing::Test {
  class TestRoutingHandler : public RSRoutingHandler {
   public:
    TestRoutingHandler() = default;
    TestRoutingHandler(const TestRoutingHandler&) = delete;
    TestRoutingHandler& operator=(const TestRoutingHandler&) = delete;
    void handleConnection(
        wangle::ConnectionManager* connectionManager,
        folly::AsyncTransportWrapper::UniquePtr sock,
        folly::SocketAddress const* address,
        wangle::TransportInfo const& /*tinfo*/,
        std::shared_ptr<Cpp2Worker> worker) override {
      auto sockPtr = sock.get();

      auto* const server = worker->getServer();
      auto* const connection = new rocket::RocketServerConnection(
          std::move(sock),
          std::make_shared<rocket::ThriftRocketServerHandler>(
              worker, *address, sockPtr, setupFrameHandlers),
          server->getStreamExpireTime());
      connection->setNegotiatedCompressionAlgorithm(CompressionAlgorithm::ZSTD);
      connection->setMinCompressBytes(server->getMinCompressBytes());
      connectionManager->addConnection(connection);

      if (auto* observer = server->getObserver()) {
        observer->connAccepted();
        observer->activeConnections(
            connectionManager->getNumConnections() *
            server->getNumIOWorkerThreads());
      }
    }

   private:
    std::vector<std::unique_ptr<rocket::SetupFrameHandler>> setupFrameHandlers;
  };

 public:
  RSCompatibilityTest2() {
    FLAGS_transport = "rocket";

    compatibilityTest_ = std::make_unique<TransportCompatibilityTest>();
    compatibilityTest_->addRoutingHandler(
        std::make_unique<TestRoutingHandler>());
    compatibilityTest_->startServer();
  }

 protected:
  std::unique_ptr<TransportCompatibilityTest> compatibilityTest_;
};

TEST_F(RSCompatibilityTest2, RequestResponse_CompressRequestResponse) {
  compatibilityTest_->connectToServer([this](auto client) {
    EXPECT_CALL(*compatibilityTest_->handler_.get(), hello_(testing::_));
    auto* channel = dynamic_cast<RocketClientChannel*>(client->getChannel());
    ASSERT_NE(nullptr, channel);

    // set the channel to compress requests
    channel->setNegotiatedCompressionAlgorithm(CompressionAlgorithm::ZSTD);
    channel->setAutoCompressSizeLimit(0);

    std::string name("snoopy");
    auto result =
        client->future_hello(RpcOptions().setEnableChecksum(true), name).get();
    EXPECT_EQ("Hello, snoopy", result);
  });
}

} // namespace thrift
} // namespace apache
<|endoftext|>


<commit_before>// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.

// Simple test for a fuzzer: find interesting value of array index.
#include <assert.h>
#include <cstdint>
#include <cstring>
#include <cstddef>
#include <iostream>

static volatile int Sink;
const int kArraySize = 1234567;
int array[kArraySize];

extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) {
  if (Size < 8) return 0;
  size_t a = 0;
  memcpy(&a, Data, 8);
  Sink = array[a % (kArraySize + 1)];
  return 0;
}

<commit_msg>[libFuzzer] Update Load test to work on 32 bits.<commit_after>// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.

// Simple test for a fuzzer: find interesting value of array index.
#include <assert.h>
#include <cstdint>
#include <cstring>
#include <cstddef>
#include <iostream>

static volatile int Sink;
const int kArraySize = 1234567;
int array[kArraySize];

extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) {
  if (Size < 8) return 0;
  uint64_t a = 0;
  memcpy(&a, Data, 8);
  Sink = array[a % (kArraySize + 1)];
  return 0;
}

<|endoftext|>


<commit_before>#include "DeferredRenderer.hpp"
#include "scene/lights/Light.hpp"
#include "scene/Sky.hpp"
#include "system/System.hpp"
#include "graphics/GLUtilities.hpp"

DeferredRenderer::DeferredRenderer(const glm::vec2 & resolution, ShadowMode mode, bool ssao) :
	_applySSAO(ssao), _shadowMode(mode) {

	const uint renderWidth	  = uint(resolution[0]);
	const uint renderHeight	  = uint(resolution[1]);

	// G-buffer setup.
	const Descriptor albedoDesc			= {Layout::RGBA16F, Filter::NEAREST_NEAREST, Wrap::CLAMP};
	const Descriptor normalDesc			= {Layout::RGB16F, Filter::NEAREST_NEAREST, Wrap::CLAMP};
	const Descriptor effectsDesc		= {Layout::RGB8, Filter::NEAREST_NEAREST, Wrap::CLAMP};
	const Descriptor depthDesc			= {Layout::DEPTH_COMPONENT32F, Filter::NEAREST_NEAREST, Wrap::CLAMP};
	const Descriptor desc = {Layout::RGB16F, Filter::LINEAR_LINEAR, Wrap::CLAMP};

	const std::vector<Descriptor> descs = {albedoDesc, normalDesc, effectsDesc, depthDesc};
	_gbuffer							= std::unique_ptr<Framebuffer>(new Framebuffer(renderWidth, renderHeight, descs, false, "G-buffer"));
	_ssaoPass							= std::unique_ptr<SSAO>(new SSAO(renderWidth, renderHeight, 2, 0.5f));
	_lightBuffer						= std::unique_ptr<Framebuffer>(new Framebuffer(renderWidth, renderHeight, desc, false, "Deferred lighting"));
	_preferredFormat.push_back(desc);
	_needsDepth = false;

	_skyboxProgram		= Resources::manager().getProgram("skybox_gbuffer", "skybox_infinity", "skybox_gbuffer");
	_bgProgram			= Resources::manager().getProgram("background_gbuffer", "background_infinity", "background_gbuffer");
	_atmoProgram		= Resources::manager().getProgram("atmosphere_gbuffer", "background_infinity", "atmosphere_gbuffer");
	_parallaxProgram	= Resources::manager().getProgram("object_parallax_gbuffer");
	_objectProgram		= Resources::manager().getProgram("object_gbuffer");
	_emissiveProgram	= Resources::manager().getProgram("object_emissive_gbuffer");

	// Lighting passes.
	_ambientScreen = std::unique_ptr<AmbientQuad>(new AmbientQuad(_gbuffer->texture(0), _gbuffer->texture(1),
		_gbuffer->texture(2), _gbuffer->depthBuffer(), _ssaoPass->texture()));
	_lightRenderer = std::unique_ptr<DeferredLight>(new DeferredLight(_gbuffer->texture(0), _gbuffer->texture(1), _gbuffer->depthBuffer(), _gbuffer->texture(2)));
	checkGLError();
}

void DeferredRenderer::setScene(const std::shared_ptr<Scene> & scene) {
	// Do not accept a null scene.
	if(!scene) {
		return;
	}
	_scene = scene;
	_culler.reset(new Culler(_scene->objects));
	checkGLError();
}

void DeferredRenderer::renderScene(const glm::mat4 & view, const glm::mat4 & proj, const glm::vec3 & pos) {
	GLUtilities::setDepthState(true, TestFunction::LESS, true);

	// Bind the full scene framebuffer.
	_gbuffer->bind();
	// Set screen viewport
	_gbuffer->setViewport();
	// Clear the depth buffer (we know we will draw everywhere, no need to clear color).
	GLUtilities::clearDepth(1.0f);

	// Request list of visible objects from culler.
	const auto & visibles = _culler->cullAndSort(view, proj, pos);

	// Scene objects.
	for(const long & objectId : visibles) {
		// Once we get a -1, there is no other object to render.
		if(objectId == -1){
			break;
		}
		const Object & object = _scene->objects[objectId];

		// Combine the three matrices.
		const glm::mat4 MV  = view * object.model();
		const glm::mat4 MVP = proj * MV;
		// Compute the normal matrix
		const glm::mat3 normalMatrix = glm::transpose(glm::inverse(glm::mat3(MV)));

		// Select the program (and shaders).
		switch(object.type()) {
			case Object::Parallax:
				_parallaxProgram->use();
				// Upload the MVP matrix.
				_parallaxProgram->uniform("mvp", MVP);
				// Upload the projection matrix.
				_parallaxProgram->uniform("p", proj);
				// Upload the MV matrix.
				_parallaxProgram->uniform("mv", MV);
				// Upload the normal matrix.
				_parallaxProgram->uniform("normalMatrix", normalMatrix);
				break;
			case Object::Regular:
				_objectProgram->use();
				// Upload the MVP matrix.
				_objectProgram->uniform("mvp", MVP);
				// Upload the normal matrix.
				_objectProgram->uniform("normalMatrix", normalMatrix);
				_objectProgram->uniform("hasUV", object.useTexCoords());
				break;
			case Object::Emissive:
				_emissiveProgram->use();
				// Upload the MVP matrix.
				_emissiveProgram->uniform("mvp", MVP);
				// Are UV available. Note: we might want to decouple UV use from their existence.
				_emissiveProgram->uniform("hasUV", object.useTexCoords());
				break;
			default:
				break;
		}

		// Backface culling state.
		if(object.twoSided()) {
			GLUtilities::setCullState(false);
		}

		// Bind the textures.
		GLUtilities::bindTextures(object.textures());
		GLUtilities::drawMesh(*object.mesh());
		// Restore state.
		GLUtilities::setCullState(true);
	}

	renderBackground(view, proj, pos);

	GLUtilities::setDepthState(false);
}

void DeferredRenderer::renderBackground(const glm::mat4 & view, const glm::mat4 & proj, const glm::vec3 & pos){
	// Background.
	// No need to write the skybox depth to the framebuffer.
	// Accept a depth of 1.0 (far plane).
	GLUtilities::setDepthState(true, TestFunction::LEQUAL, false);
	const Object * background	= _scene->background.get();
	const Scene::Background mode = _scene->backgroundMode;

	if(mode == Scene::Background::SKYBOX) {
		// Skybox.
		const glm::mat4 backgroundMVP = proj * view * background->model();
		// Draw background.
		_skyboxProgram->use();
		// Upload the MVP matrix.
		_skyboxProgram->uniform("mvp", backgroundMVP);
		GLUtilities::bindTextures(background->textures());
		GLUtilities::drawMesh(*background->mesh());

	} else if(mode == Scene::Background::ATMOSPHERE) {
		// Atmosphere screen quad.
		_atmoProgram->use();
		// Revert the model to clip matrix, removing the translation part.
		const glm::mat4 worldToClipNoT = proj * glm::mat4(glm::mat3(view));
		const glm::mat4 clipToWorldNoT = glm::inverse(worldToClipNoT);
		const glm::vec3 & sunDir	   = dynamic_cast<const Sky *>(background)->direction();
		// Send and draw.
		_atmoProgram->uniform("clipToWorld", clipToWorldNoT);
		_atmoProgram->uniform("viewPos", pos);
		_atmoProgram->uniform("lightDirection", sunDir);
		GLUtilities::bindTextures(background->textures());
		GLUtilities::drawMesh(*background->mesh());

	} else {
		// Background color or 2D image.
		_bgProgram->use();
		if(mode == Scene::Background::IMAGE) {
			_bgProgram->uniform("useTexture", 1);
			GLUtilities::bindTextures(background->textures());
		} else {
			_bgProgram->uniform("useTexture", 0);
			_bgProgram->uniform("bgColor", _scene->backgroundColor);
		}
		GLUtilities::drawMesh(*background->mesh());
	}
	GLUtilities::setDepthState(true, TestFunction::LESS, true);
}

void DeferredRenderer::draw(const Camera & camera, Framebuffer & framebuffer, size_t layer) {

	const glm::mat4 & view = camera.view();
	const glm::mat4 & proj = camera.projection();
	const glm::vec3 & pos = camera.position();

	// --- Scene pass -------
	renderScene(view, proj, pos);

	// --- SSAO pass
	if(_applySSAO) {
		_ssaoPass->process(proj, _gbuffer->depthBuffer(), _gbuffer->texture(int(TextureType::Normal)));
	} else {
		_ssaoPass->clear();
	}

	// --- Gbuffer composition pass
	_lightRenderer->updateCameraInfos(view, proj);
	_lightRenderer->updateShadowMapInfos(_shadowMode, 0.002f);
	_lightBuffer->bind();
	_lightBuffer->setViewport();
	_ambientScreen->draw(view, proj, _scene->environment);
	GLUtilities::setBlendState(true, BlendEquation::ADD, BlendFunction::ONE, BlendFunction::ONE);
	for(auto & light : _scene->lights) {
		light->draw(*_lightRenderer);
	}
	GLUtilities::setBlendState(false);
	// Copy to the final framebuffer.
	GLUtilities::blit(*_lightBuffer, framebuffer, 0, layer, Filter::NEAREST);

}

void DeferredRenderer::resize(unsigned int width, unsigned int height) {
	// Resize the framebuffers.
	_gbuffer->resize(glm::vec2(width, height));
	_lightBuffer->resize(glm::vec2(width, height));
	_ssaoPass->resize(width, height);
	checkGLError();

}

void DeferredRenderer::interface(){
	ImGui::Checkbox("Freeze culling", &_freezeFrustum);
	ImGui::Combo("Shadow technique", reinterpret_cast<int*>(&_shadowMode), "None\0Basic\0Variance\0\0");
	ImGui::Checkbox("SSAO", &_applySSAO);
	if(_applySSAO) {
		ImGui::SameLine();
		ImGui::Combo("Blur quality", reinterpret_cast<int*>(&_ssaoPass->quality()), "Low\0Medium\0High\0\0");
		ImGui::InputFloat("Radius", &_ssaoPass->radius(), 0.5f);
	}
}

const Framebuffer * DeferredRenderer::sceneDepth() const {
	return _gbuffer.get();
}

const Texture * DeferredRenderer::sceneNormal() const {
	return _gbuffer->texture(1);
}
<commit_msg>DeferredRenderer: add missing culler interface.<commit_after>#include "DeferredRenderer.hpp"
#include "scene/lights/Light.hpp"
#include "scene/Sky.hpp"
#include "system/System.hpp"
#include "graphics/GLUtilities.hpp"

DeferredRenderer::DeferredRenderer(const glm::vec2 & resolution, ShadowMode mode, bool ssao) :
	_applySSAO(ssao), _shadowMode(mode) {

	const uint renderWidth	  = uint(resolution[0]);
	const uint renderHeight	  = uint(resolution[1]);

	// G-buffer setup.
	const Descriptor albedoDesc			= {Layout::RGBA16F, Filter::NEAREST_NEAREST, Wrap::CLAMP};
	const Descriptor normalDesc			= {Layout::RGB16F, Filter::NEAREST_NEAREST, Wrap::CLAMP};
	const Descriptor effectsDesc		= {Layout::RGB8, Filter::NEAREST_NEAREST, Wrap::CLAMP};
	const Descriptor depthDesc			= {Layout::DEPTH_COMPONENT32F, Filter::NEAREST_NEAREST, Wrap::CLAMP};
	const Descriptor desc = {Layout::RGB16F, Filter::LINEAR_LINEAR, Wrap::CLAMP};

	const std::vector<Descriptor> descs = {albedoDesc, normalDesc, effectsDesc, depthDesc};
	_gbuffer							= std::unique_ptr<Framebuffer>(new Framebuffer(renderWidth, renderHeight, descs, false, "G-buffer"));
	_ssaoPass							= std::unique_ptr<SSAO>(new SSAO(renderWidth, renderHeight, 2, 0.5f));
	_lightBuffer						= std::unique_ptr<Framebuffer>(new Framebuffer(renderWidth, renderHeight, desc, false, "Deferred lighting"));
	_preferredFormat.push_back(desc);
	_needsDepth = false;

	_skyboxProgram		= Resources::manager().getProgram("skybox_gbuffer", "skybox_infinity", "skybox_gbuffer");
	_bgProgram			= Resources::manager().getProgram("background_gbuffer", "background_infinity", "background_gbuffer");
	_atmoProgram		= Resources::manager().getProgram("atmosphere_gbuffer", "background_infinity", "atmosphere_gbuffer");
	_parallaxProgram	= Resources::manager().getProgram("object_parallax_gbuffer");
	_objectProgram		= Resources::manager().getProgram("object_gbuffer");
	_emissiveProgram	= Resources::manager().getProgram("object_emissive_gbuffer");

	// Lighting passes.
	_ambientScreen = std::unique_ptr<AmbientQuad>(new AmbientQuad(_gbuffer->texture(0), _gbuffer->texture(1),
		_gbuffer->texture(2), _gbuffer->depthBuffer(), _ssaoPass->texture()));
	_lightRenderer = std::unique_ptr<DeferredLight>(new DeferredLight(_gbuffer->texture(0), _gbuffer->texture(1), _gbuffer->depthBuffer(), _gbuffer->texture(2)));
	checkGLError();
}

void DeferredRenderer::setScene(const std::shared_ptr<Scene> & scene) {
	// Do not accept a null scene.
	if(!scene) {
		return;
	}
	_scene = scene;
	_culler.reset(new Culler(_scene->objects));
	checkGLError();
}

void DeferredRenderer::renderScene(const glm::mat4 & view, const glm::mat4 & proj, const glm::vec3 & pos) {
	GLUtilities::setDepthState(true, TestFunction::LESS, true);

	// Bind the full scene framebuffer.
	_gbuffer->bind();
	// Set screen viewport
	_gbuffer->setViewport();
	// Clear the depth buffer (we know we will draw everywhere, no need to clear color).
	GLUtilities::clearDepth(1.0f);

	// Request list of visible objects from culler.
	const auto & visibles = _culler->cullAndSort(view, proj, pos);

	// Scene objects.
	for(const long & objectId : visibles) {
		// Once we get a -1, there is no other object to render.
		if(objectId == -1){
			break;
		}
		const Object & object = _scene->objects[objectId];

		// Combine the three matrices.
		const glm::mat4 MV  = view * object.model();
		const glm::mat4 MVP = proj * MV;
		// Compute the normal matrix
		const glm::mat3 normalMatrix = glm::transpose(glm::inverse(glm::mat3(MV)));

		// Select the program (and shaders).
		switch(object.type()) {
			case Object::Parallax:
				_parallaxProgram->use();
				// Upload the MVP matrix.
				_parallaxProgram->uniform("mvp", MVP);
				// Upload the projection matrix.
				_parallaxProgram->uniform("p", proj);
				// Upload the MV matrix.
				_parallaxProgram->uniform("mv", MV);
				// Upload the normal matrix.
				_parallaxProgram->uniform("normalMatrix", normalMatrix);
				break;
			case Object::Regular:
				_objectProgram->use();
				// Upload the MVP matrix.
				_objectProgram->uniform("mvp", MVP);
				// Upload the normal matrix.
				_objectProgram->uniform("normalMatrix", normalMatrix);
				_objectProgram->uniform("hasUV", object.useTexCoords());
				break;
			case Object::Emissive:
				_emissiveProgram->use();
				// Upload the MVP matrix.
				_emissiveProgram->uniform("mvp", MVP);
				// Are UV available. Note: we might want to decouple UV use from their existence.
				_emissiveProgram->uniform("hasUV", object.useTexCoords());
				break;
			default:
				break;
		}

		// Backface culling state.
		if(object.twoSided()) {
			GLUtilities::setCullState(false);
		}

		// Bind the textures.
		GLUtilities::bindTextures(object.textures());
		GLUtilities::drawMesh(*object.mesh());
		// Restore state.
		GLUtilities::setCullState(true);
	}

	renderBackground(view, proj, pos);

	GLUtilities::setDepthState(false);
}

void DeferredRenderer::renderBackground(const glm::mat4 & view, const glm::mat4 & proj, const glm::vec3 & pos){
	// Background.
	// No need to write the skybox depth to the framebuffer.
	// Accept a depth of 1.0 (far plane).
	GLUtilities::setDepthState(true, TestFunction::LEQUAL, false);
	const Object * background	= _scene->background.get();
	const Scene::Background mode = _scene->backgroundMode;

	if(mode == Scene::Background::SKYBOX) {
		// Skybox.
		const glm::mat4 backgroundMVP = proj * view * background->model();
		// Draw background.
		_skyboxProgram->use();
		// Upload the MVP matrix.
		_skyboxProgram->uniform("mvp", backgroundMVP);
		GLUtilities::bindTextures(background->textures());
		GLUtilities::drawMesh(*background->mesh());

	} else if(mode == Scene::Background::ATMOSPHERE) {
		// Atmosphere screen quad.
		_atmoProgram->use();
		// Revert the model to clip matrix, removing the translation part.
		const glm::mat4 worldToClipNoT = proj * glm::mat4(glm::mat3(view));
		const glm::mat4 clipToWorldNoT = glm::inverse(worldToClipNoT);
		const glm::vec3 & sunDir	   = dynamic_cast<const Sky *>(background)->direction();
		// Send and draw.
		_atmoProgram->uniform("clipToWorld", clipToWorldNoT);
		_atmoProgram->uniform("viewPos", pos);
		_atmoProgram->uniform("lightDirection", sunDir);
		GLUtilities::bindTextures(background->textures());
		GLUtilities::drawMesh(*background->mesh());

	} else {
		// Background color or 2D image.
		_bgProgram->use();
		if(mode == Scene::Background::IMAGE) {
			_bgProgram->uniform("useTexture", 1);
			GLUtilities::bindTextures(background->textures());
		} else {
			_bgProgram->uniform("useTexture", 0);
			_bgProgram->uniform("bgColor", _scene->backgroundColor);
		}
		GLUtilities::drawMesh(*background->mesh());
	}
	GLUtilities::setDepthState(true, TestFunction::LESS, true);
}

void DeferredRenderer::draw(const Camera & camera, Framebuffer & framebuffer, size_t layer) {

	const glm::mat4 & view = camera.view();
	const glm::mat4 & proj = camera.projection();
	const glm::vec3 & pos = camera.position();

	// --- Scene pass -------
	renderScene(view, proj, pos);

	// --- SSAO pass
	if(_applySSAO) {
		_ssaoPass->process(proj, _gbuffer->depthBuffer(), _gbuffer->texture(int(TextureType::Normal)));
	} else {
		_ssaoPass->clear();
	}

	// --- Gbuffer composition pass
	_lightRenderer->updateCameraInfos(view, proj);
	_lightRenderer->updateShadowMapInfos(_shadowMode, 0.002f);
	_lightBuffer->bind();
	_lightBuffer->setViewport();
	_ambientScreen->draw(view, proj, _scene->environment);
	GLUtilities::setBlendState(true, BlendEquation::ADD, BlendFunction::ONE, BlendFunction::ONE);
	for(auto & light : _scene->lights) {
		light->draw(*_lightRenderer);
	}
	GLUtilities::setBlendState(false);
	// Copy to the final framebuffer.
	GLUtilities::blit(*_lightBuffer, framebuffer, 0, layer, Filter::NEAREST);

}

void DeferredRenderer::resize(unsigned int width, unsigned int height) {
	// Resize the framebuffers.
	_gbuffer->resize(glm::vec2(width, height));
	_lightBuffer->resize(glm::vec2(width, height));
	_ssaoPass->resize(width, height);
	checkGLError();

}

void DeferredRenderer::interface(){

	ImGui::Combo("Shadow technique", reinterpret_cast<int*>(&_shadowMode), "None\0Basic\0Variance\0\0");
	ImGui::Checkbox("SSAO", &_applySSAO);
	if(_applySSAO) {
		ImGui::SameLine();
		ImGui::Combo("Blur quality", reinterpret_cast<int*>(&_ssaoPass->quality()), "Low\0Medium\0High\0\0");
		ImGui::InputFloat("Radius", &_ssaoPass->radius(), 0.5f);
	}
	if(_culler){
		_culler->interface();
	}

}

const Framebuffer * DeferredRenderer::sceneDepth() const {
	return _gbuffer.get();
}

const Texture * DeferredRenderer::sceneNormal() const {
	return _gbuffer->texture(1);
}
<|endoftext|>


<commit_before>//===--- MemoryBuffer.cpp - Memory Buffer implementation ------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
//  This file implements the MemoryBuffer interface.
//
//===----------------------------------------------------------------------===//

#include "llvm/Support/MemoryBuffer.h"
#include "llvm/ADT/OwningPtr.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/System/Path.h"
#include "llvm/System/Process.h"
#include "llvm/System/Program.h"
#include <cassert>
#include <cstdio>
#include <cstring>
#include <cerrno>
#include <sys/types.h>
#include <sys/stat.h>
#if !defined(_MSC_VER) && !defined(__MINGW32__)
#include <unistd.h>
#include <sys/uio.h>
#else
#include <io.h>
#endif
#include <fcntl.h>
using namespace llvm;

//===----------------------------------------------------------------------===//
// MemoryBuffer implementation itself.
//===----------------------------------------------------------------------===//

MemoryBuffer::~MemoryBuffer() {
  if (MustDeleteBuffer)
    free((void*)BufferStart);
}

/// initCopyOf - Initialize this source buffer with a copy of the specified
/// memory range.  We make the copy so that we can null terminate it
/// successfully.
void MemoryBuffer::initCopyOf(const char *BufStart, const char *BufEnd) {
  size_t Size = BufEnd-BufStart;
  BufferStart = (char *)malloc((Size+1) * sizeof(char));
  BufferEnd = BufferStart+Size;
  memcpy(const_cast<char*>(BufferStart), BufStart, Size);
  *const_cast<char*>(BufferEnd) = 0;   // Null terminate buffer.
  MustDeleteBuffer = true;
}

/// init - Initialize this MemoryBuffer as a reference to externally allocated
/// memory, memory that we know is already null terminated.
void MemoryBuffer::init(const char *BufStart, const char *BufEnd) {
  assert(BufEnd[0] == 0 && "Buffer is not null terminated!");
  BufferStart = BufStart;
  BufferEnd = BufEnd;
  MustDeleteBuffer = false;
}

//===----------------------------------------------------------------------===//
// MemoryBufferMem implementation.
//===----------------------------------------------------------------------===//

namespace {
class MemoryBufferMem : public MemoryBuffer {
  std::string FileID;
public:
  MemoryBufferMem(const char *Start, const char *End, StringRef FID,
                  bool Copy = false)
  : FileID(FID) {
    if (!Copy)
      init(Start, End);
    else
      initCopyOf(Start, End);
  }

  virtual const char *getBufferIdentifier() const {
    return FileID.c_str();
  }
};
}

/// getMemBuffer - Open the specified memory range as a MemoryBuffer.  Note
/// that EndPtr[0] must be a null byte and be accessible!
MemoryBuffer *MemoryBuffer::getMemBuffer(const char *StartPtr,
                                         const char *EndPtr,
                                         const char *BufferName) {
  return new MemoryBufferMem(StartPtr, EndPtr, BufferName);
}

/// getMemBufferCopy - Open the specified memory range as a MemoryBuffer,
/// copying the contents and taking ownership of it.  This has no requirements
/// on EndPtr[0].
MemoryBuffer *MemoryBuffer::getMemBufferCopy(const char *StartPtr,
                                             const char *EndPtr,
                                             const char *BufferName) {
  return new MemoryBufferMem(StartPtr, EndPtr, BufferName, true);
}

/// getNewUninitMemBuffer - Allocate a new MemoryBuffer of the specified size
/// that is completely initialized to zeros.  Note that the caller should
/// initialize the memory allocated by this method.  The memory is owned by
/// the MemoryBuffer object.
MemoryBuffer *MemoryBuffer::getNewUninitMemBuffer(size_t Size,
                                                  StringRef BufferName) {
  char *Buf = (char *)malloc((Size+1) * sizeof(char));
  if (!Buf) return 0;
  Buf[Size] = 0;
  MemoryBufferMem *SB = new MemoryBufferMem(Buf, Buf+Size, BufferName);
  // The memory for this buffer is owned by the MemoryBuffer.
  SB->MustDeleteBuffer = true;
  return SB;
}

/// getNewMemBuffer - Allocate a new MemoryBuffer of the specified size that
/// is completely initialized to zeros.  Note that the caller should
/// initialize the memory allocated by this method.  The memory is owned by
/// the MemoryBuffer object.
MemoryBuffer *MemoryBuffer::getNewMemBuffer(size_t Size,
                                            const char *BufferName) {
  MemoryBuffer *SB = getNewUninitMemBuffer(Size, BufferName);
  if (!SB) return 0;
  memset(const_cast<char*>(SB->getBufferStart()), 0, Size+1);
  return SB;
}

/// getFileOrSTDIN - Open the specified file as a MemoryBuffer, or open stdin
/// if the Filename is "-".  If an error occurs, this returns null and fills
/// in *ErrStr with a reason.  If stdin is empty, this API (unlike getSTDIN)
/// returns an empty buffer.
MemoryBuffer *MemoryBuffer::getFileOrSTDIN(StringRef Filename,
                                           std::string *ErrStr,
                                           int64_t FileSize) {
  if (Filename == "-")
    return getSTDIN();
  return getFile(Filename, ErrStr, FileSize);
}

//===----------------------------------------------------------------------===//
// MemoryBuffer::getFile implementation.
//===----------------------------------------------------------------------===//

namespace {
/// MemoryBufferMMapFile - This represents a file that was mapped in with the
/// sys::Path::MapInFilePages method.  When destroyed, it calls the
/// sys::Path::UnMapFilePages method.
class MemoryBufferMMapFile : public MemoryBuffer {
  std::string Filename;
public:
  MemoryBufferMMapFile(StringRef filename, const char *Pages, uint64_t Size)
    : Filename(filename) {
    init(Pages, Pages+Size);
  }

  virtual const char *getBufferIdentifier() const {
    return Filename.c_str();
  }

  ~MemoryBufferMMapFile() {
    sys::Path::UnMapFilePages(getBufferStart(), getBufferSize());
  }
};
}

MemoryBuffer *MemoryBuffer::getFile(StringRef Filename, std::string *ErrStr,
                                    int64_t FileSize) {
  int OpenFlags = 0;
#ifdef O_BINARY
  OpenFlags |= O_BINARY;  // Open input file in binary mode on win32.
#endif
  int FD = ::open(Filename.str().c_str(), O_RDONLY|OpenFlags);
  if (FD == -1) {
    if (ErrStr) *ErrStr = strerror(errno);
    return 0;
  }

  // If we don't know the file size, use fstat to find out.  fstat on an open
  // file descriptor is cheaper than stat on a random path.
  if (FileSize == -1) {
    struct stat FileInfo;
    // TODO: This should use fstat64 when available.
    if (fstat(FD, &FileInfo) == -1) {
      if (ErrStr) *ErrStr = strerror(errno);
      ::close(FD);
      return 0;
    }
    FileSize = FileInfo.st_size;
  }

  // If the file is large, try to use mmap to read it in.  We don't use mmap
  // for small files, because this can severely fragment our address space. Also
  // don't try to map files that are exactly a multiple of the system page size,
  // as the file would not have the required null terminator.
  //
  // FIXME: Can we just mmap an extra page in the latter case?
  if (FileSize >= 4096*4 &&
      (FileSize & (sys::Process::GetPageSize()-1)) != 0) {
    if (const char *Pages = sys::Path::MapInFilePages(FD, FileSize)) {
      // Close the file descriptor, now that the whole file is in memory.
      ::close(FD);
      return new MemoryBufferMMapFile(Filename, Pages, FileSize);
    }
  }

  MemoryBuffer *Buf = MemoryBuffer::getNewUninitMemBuffer(FileSize, Filename);
  if (!Buf) {
    // Failed to create a buffer.
    if (ErrStr) *ErrStr = "could not allocate buffer";
    ::close(FD);
    return 0;
  }

  OwningPtr<MemoryBuffer> SB(Buf);
  char *BufPtr = const_cast<char*>(SB->getBufferStart());

  size_t BytesLeft = FileSize;
  while (BytesLeft) {
    ssize_t NumRead = ::read(FD, BufPtr, BytesLeft);
    if (NumRead > 0) {
      BytesLeft -= NumRead;
      BufPtr += NumRead;
    } else if (NumRead == -1 && errno == EINTR) {
      // try again
    } else {
      // error reading.
      if (ErrStr) *ErrStr = strerror(errno);
      close(FD);
      return 0;
    }
  }
  close(FD);

  return SB.take();
}

//===----------------------------------------------------------------------===//
// MemoryBuffer::getSTDIN implementation.
//===----------------------------------------------------------------------===//

namespace {
class STDINBufferFile : public MemoryBuffer {
public:
  virtual const char *getBufferIdentifier() const {
    return "<stdin>";
  }
};
}

MemoryBuffer *MemoryBuffer::getSTDIN() {
  char Buffer[4096*4];

  std::vector<char> FileData;

  // Read in all of the data from stdin, we cannot mmap stdin.
  //
  // FIXME: That isn't necessarily true, we should try to mmap stdin and
  // fallback if it fails.
  sys::Program::ChangeStdinToBinary();
  size_t ReadBytes;
  do {
    ReadBytes = fread(Buffer, sizeof(char), sizeof(Buffer), stdin);
    FileData.insert(FileData.end(), Buffer, Buffer+ReadBytes);
  } while (ReadBytes == sizeof(Buffer));

  FileData.push_back(0); // &FileData[Size] is invalid. So is &*FileData.end().
  size_t Size = FileData.size();
  MemoryBuffer *B = new STDINBufferFile();
  B->initCopyOf(&FileData[0], &FileData[Size-1]);
  return B;
}
<commit_msg>sizeof(char) is always 1.<commit_after>//===--- MemoryBuffer.cpp - Memory Buffer implementation ------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
//  This file implements the MemoryBuffer interface.
//
//===----------------------------------------------------------------------===//

#include "llvm/Support/MemoryBuffer.h"
#include "llvm/ADT/OwningPtr.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/System/Path.h"
#include "llvm/System/Process.h"
#include "llvm/System/Program.h"
#include <cassert>
#include <cstdio>
#include <cstring>
#include <cerrno>
#include <sys/types.h>
#include <sys/stat.h>
#if !defined(_MSC_VER) && !defined(__MINGW32__)
#include <unistd.h>
#include <sys/uio.h>
#else
#include <io.h>
#endif
#include <fcntl.h>
using namespace llvm;

//===----------------------------------------------------------------------===//
// MemoryBuffer implementation itself.
//===----------------------------------------------------------------------===//

MemoryBuffer::~MemoryBuffer() {
  if (MustDeleteBuffer)
    free((void*)BufferStart);
}

/// initCopyOf - Initialize this source buffer with a copy of the specified
/// memory range.  We make the copy so that we can null terminate it
/// successfully.
void MemoryBuffer::initCopyOf(const char *BufStart, const char *BufEnd) {
  size_t Size = BufEnd-BufStart;
  BufferStart = (char *)malloc(Size+1);
  BufferEnd = BufferStart+Size;
  memcpy(const_cast<char*>(BufferStart), BufStart, Size);
  *const_cast<char*>(BufferEnd) = 0;   // Null terminate buffer.
  MustDeleteBuffer = true;
}

/// init - Initialize this MemoryBuffer as a reference to externally allocated
/// memory, memory that we know is already null terminated.
void MemoryBuffer::init(const char *BufStart, const char *BufEnd) {
  assert(BufEnd[0] == 0 && "Buffer is not null terminated!");
  BufferStart = BufStart;
  BufferEnd = BufEnd;
  MustDeleteBuffer = false;
}

//===----------------------------------------------------------------------===//
// MemoryBufferMem implementation.
//===----------------------------------------------------------------------===//

namespace {
class MemoryBufferMem : public MemoryBuffer {
  std::string FileID;
public:
  MemoryBufferMem(const char *Start, const char *End, StringRef FID,
                  bool Copy = false)
  : FileID(FID) {
    if (!Copy)
      init(Start, End);
    else
      initCopyOf(Start, End);
  }

  virtual const char *getBufferIdentifier() const {
    return FileID.c_str();
  }
};
}

/// getMemBuffer - Open the specified memory range as a MemoryBuffer.  Note
/// that EndPtr[0] must be a null byte and be accessible!
MemoryBuffer *MemoryBuffer::getMemBuffer(const char *StartPtr,
                                         const char *EndPtr,
                                         const char *BufferName) {
  return new MemoryBufferMem(StartPtr, EndPtr, BufferName);
}

/// getMemBufferCopy - Open the specified memory range as a MemoryBuffer,
/// copying the contents and taking ownership of it.  This has no requirements
/// on EndPtr[0].
MemoryBuffer *MemoryBuffer::getMemBufferCopy(const char *StartPtr,
                                             const char *EndPtr,
                                             const char *BufferName) {
  return new MemoryBufferMem(StartPtr, EndPtr, BufferName, true);
}

/// getNewUninitMemBuffer - Allocate a new MemoryBuffer of the specified size
/// that is completely initialized to zeros.  Note that the caller should
/// initialize the memory allocated by this method.  The memory is owned by
/// the MemoryBuffer object.
MemoryBuffer *MemoryBuffer::getNewUninitMemBuffer(size_t Size,
                                                  StringRef BufferName) {
  char *Buf = (char *)malloc(Size+1);
  if (!Buf) return 0;
  Buf[Size] = 0;
  MemoryBufferMem *SB = new MemoryBufferMem(Buf, Buf+Size, BufferName);
  // The memory for this buffer is owned by the MemoryBuffer.
  SB->MustDeleteBuffer = true;
  return SB;
}

/// getNewMemBuffer - Allocate a new MemoryBuffer of the specified size that
/// is completely initialized to zeros.  Note that the caller should
/// initialize the memory allocated by this method.  The memory is owned by
/// the MemoryBuffer object.
MemoryBuffer *MemoryBuffer::getNewMemBuffer(size_t Size,
                                            const char *BufferName) {
  MemoryBuffer *SB = getNewUninitMemBuffer(Size, BufferName);
  if (!SB) return 0;
  memset(const_cast<char*>(SB->getBufferStart()), 0, Size+1);
  return SB;
}

/// getFileOrSTDIN - Open the specified file as a MemoryBuffer, or open stdin
/// if the Filename is "-".  If an error occurs, this returns null and fills
/// in *ErrStr with a reason.  If stdin is empty, this API (unlike getSTDIN)
/// returns an empty buffer.
MemoryBuffer *MemoryBuffer::getFileOrSTDIN(StringRef Filename,
                                           std::string *ErrStr,
                                           int64_t FileSize) {
  if (Filename == "-")
    return getSTDIN();
  return getFile(Filename, ErrStr, FileSize);
}

//===----------------------------------------------------------------------===//
// MemoryBuffer::getFile implementation.
//===----------------------------------------------------------------------===//

namespace {
/// MemoryBufferMMapFile - This represents a file that was mapped in with the
/// sys::Path::MapInFilePages method.  When destroyed, it calls the
/// sys::Path::UnMapFilePages method.
class MemoryBufferMMapFile : public MemoryBuffer {
  std::string Filename;
public:
  MemoryBufferMMapFile(StringRef filename, const char *Pages, uint64_t Size)
    : Filename(filename) {
    init(Pages, Pages+Size);
  }

  virtual const char *getBufferIdentifier() const {
    return Filename.c_str();
  }

  ~MemoryBufferMMapFile() {
    sys::Path::UnMapFilePages(getBufferStart(), getBufferSize());
  }
};
}

MemoryBuffer *MemoryBuffer::getFile(StringRef Filename, std::string *ErrStr,
                                    int64_t FileSize) {
  int OpenFlags = 0;
#ifdef O_BINARY
  OpenFlags |= O_BINARY;  // Open input file in binary mode on win32.
#endif
  int FD = ::open(Filename.str().c_str(), O_RDONLY|OpenFlags);
  if (FD == -1) {
    if (ErrStr) *ErrStr = strerror(errno);
    return 0;
  }

  // If we don't know the file size, use fstat to find out.  fstat on an open
  // file descriptor is cheaper than stat on a random path.
  if (FileSize == -1) {
    struct stat FileInfo;
    // TODO: This should use fstat64 when available.
    if (fstat(FD, &FileInfo) == -1) {
      if (ErrStr) *ErrStr = strerror(errno);
      ::close(FD);
      return 0;
    }
    FileSize = FileInfo.st_size;
  }

  // If the file is large, try to use mmap to read it in.  We don't use mmap
  // for small files, because this can severely fragment our address space. Also
  // don't try to map files that are exactly a multiple of the system page size,
  // as the file would not have the required null terminator.
  //
  // FIXME: Can we just mmap an extra page in the latter case?
  if (FileSize >= 4096*4 &&
      (FileSize & (sys::Process::GetPageSize()-1)) != 0) {
    if (const char *Pages = sys::Path::MapInFilePages(FD, FileSize)) {
      // Close the file descriptor, now that the whole file is in memory.
      ::close(FD);
      return new MemoryBufferMMapFile(Filename, Pages, FileSize);
    }
  }

  MemoryBuffer *Buf = MemoryBuffer::getNewUninitMemBuffer(FileSize, Filename);
  if (!Buf) {
    // Failed to create a buffer.
    if (ErrStr) *ErrStr = "could not allocate buffer";
    ::close(FD);
    return 0;
  }

  OwningPtr<MemoryBuffer> SB(Buf);
  char *BufPtr = const_cast<char*>(SB->getBufferStart());

  size_t BytesLeft = FileSize;
  while (BytesLeft) {
    ssize_t NumRead = ::read(FD, BufPtr, BytesLeft);
    if (NumRead > 0) {
      BytesLeft -= NumRead;
      BufPtr += NumRead;
    } else if (NumRead == -1 && errno == EINTR) {
      // try again
    } else {
      // error reading.
      if (ErrStr) *ErrStr = strerror(errno);
      close(FD);
      return 0;
    }
  }
  close(FD);

  return SB.take();
}

//===----------------------------------------------------------------------===//
// MemoryBuffer::getSTDIN implementation.
//===----------------------------------------------------------------------===//

namespace {
class STDINBufferFile : public MemoryBuffer {
public:
  virtual const char *getBufferIdentifier() const {
    return "<stdin>";
  }
};
}

MemoryBuffer *MemoryBuffer::getSTDIN() {
  char Buffer[4096*4];

  std::vector<char> FileData;

  // Read in all of the data from stdin, we cannot mmap stdin.
  //
  // FIXME: That isn't necessarily true, we should try to mmap stdin and
  // fallback if it fails.
  sys::Program::ChangeStdinToBinary();
  size_t ReadBytes;
  do {
    ReadBytes = fread(Buffer, sizeof(char), sizeof(Buffer), stdin);
    FileData.insert(FileData.end(), Buffer, Buffer+ReadBytes);
  } while (ReadBytes == sizeof(Buffer));

  FileData.push_back(0); // &FileData[Size] is invalid. So is &*FileData.end().
  size_t Size = FileData.size();
  MemoryBuffer *B = new STDINBufferFile();
  B->initCopyOf(&FileData[0], &FileData[Size-1]);
  return B;
}
<|endoftext|>