Exemple #1
0
SDNode *VDAGToDAGISel::SelectMemAccess(SDNode *N) {
  MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
  MemOp[0] = cast<MemSDNode>(N)->getMemOperand();

  unsigned Opcode = VTM::VOpMemTrans;
  SmallVector<SDValue, 8> Ops;
  Ops.push_back(N->getOperand(1)); // Address
  Ops.push_back(N->getOperand(2)); // Data to store
  Ops.push_back(N->getOperand(3)); // write enable
  Ops.push_back(N->getOperand(4)); // byte enable
  if (unsigned AS = MemOp[0]->getPointerInfo().getAddrSpace()) {
    // Block RAM number.
    Ops.push_back(CurDAG->getTargetConstant(AS, MVT::i32));
    Opcode = VTM::VOpBRAMTrans;
  }
  Ops.push_back(SDValue()); //The dummy bit width operand
  Ops.push_back(CurDAG->getTargetConstant(0, MVT::i64)); //and trace number*
  Ops.push_back(N->getOperand(0));


  computeOperandsBitWidth(N, Ops.data(), Ops.size() -1 /*Skip the chain*/);
  SDNode *Ret = CurDAG->SelectNodeTo(N, Opcode, N->getVTList(),
                                     Ops.data(), Ops.size());

  cast<MachineSDNode>(Ret)->setMemRefs(MemOp, MemOp + 1);
  return Ret;
}
Exemple #2
0
void DebugIR::generateFilename(OwningPtr<int> &fd) {
  SmallVector<char, 16> PathVec;
  fd.reset(new int);
  sys::fs::createTemporaryFile("debug-ir", "ll", *fd, PathVec);
  StringRef Path(PathVec.data(), PathVec.size());
  Filename = sys::path::filename(Path);
  sys::path::remove_filename(PathVec);
  Directory = StringRef(PathVec.data(), PathVec.size());

  GeneratedPath = true;
}
Exemple #3
0
SDNode *VDAGToDAGISel::SelectSimpleNode(SDNode *N, unsigned Opc) {
  SmallVector<SDValue, 4> Ops;
  for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I)
    Ops.push_back(*I);

  Ops.push_back(SDValue());//The dummy bit width operand
  Ops.push_back(CurDAG->getTargetConstant(0, MVT::i64)); /*and trace number*/

  computeOperandsBitWidth(N, Ops.data(), Ops.size());

  return CurDAG->SelectNodeTo(N, Opc, N->getVTList(), Ops.data(), Ops.size());
}
Exemple #4
0
void DebugIR::generateFilename(OwningPtr<int> &fd) {
  StringRef FileModel("debug-ir-%s%s%s%s.ll");
  SmallVector<char, 16> PathVec;
  fd.reset(new int);
  sys::fs::unique_file(FileModel, *fd, PathVec);
  StringRef Path(PathVec.data(), PathVec.size());
  Filename = sys::path::filename(Path);
  sys::path::remove_filename(PathVec);
  Directory = StringRef(PathVec.data(), PathVec.size());

  GeneratedPath = true;
}
bool TempFile::init(const std::string &Ext) {
    SmallVector<char, 64> Vector;
    DEBUG(dbgs() << " - create-temp-file\n");
    if (auto EC = sys::fs::createTemporaryFile("uselistorder", Ext, Vector)) {
        errs() << "verify-uselistorder: error: " << EC.message() << "\n";
        return true;
    }
    assert(!Vector.empty());

    Filename.assign(Vector.data(), Vector.data() + Vector.size());
    Remover.setFile(Filename, !SaveTemps);
    if (SaveTemps)
        outs() << " - filename = " << Filename << "\n";
    return false;
}
Exemple #6
0
SDNode *VDAGToDAGISel::SelectInternalCall(SDNode *N) {
  SmallVector<SDValue, 8> Ops;

  for (unsigned I = 1, E = N->getNumOperands(); I != E; ++I)
    Ops.push_back(N->getOperand(I));
  Ops.push_back(SDValue()); // The bit width annotator.
  Ops.push_back(CurDAG->getTargetConstant(0, MVT::i64)); /*and trace number*/
  // And the chain.
  Ops.push_back(N->getOperand(0));

  computeOperandsBitWidth(N, Ops.data(), Ops.size() -1/*Skip the chain*/);

  return CurDAG->SelectNodeTo(N, VTM::VOpInternalCall, N->getVTList(),
                              Ops.data(), Ops.size());
}
void printMetadata(wxTextOutputStream & out, const llvm::Value* nodeVal,
    uint32_t maxDepth) {
  if (const MDString* ms = dyn_cast<MDString>(nodeVal)) {
    out << _("\"") << toWxStr(ms->getString()) << _("\"");
  } else if (const MDNode* m = dyn_cast<MDNode>(nodeVal)) {
    if (maxDepth > 0) {
      out << _("{");
      for (unsigned i = 0; i < m->getNumOperands(); ++i) {
        if (i != 0) {
          out << _(", ");
        }
        if (maxDepth == 1 && i > 3) {
          out << _("...");
          break;
        }

        printMetadata(out, m->getOperand(i), maxDepth - 1);
      }
      out << _("}");
    } else {
      out << _("{...}");
    }
  } else if (const GlobalVariable* gv = dyn_cast<GlobalVariable>(nodeVal)) {
    out << toWxStr(gv->getName());
  } else if (const Function* fn = dyn_cast<Function>(nodeVal)) {
    out << toWxStr(fn->getName());
  } else if (const ConstantInt* ci = dyn_cast<ConstantInt>(nodeVal)) {
    SmallVector<char, 16> intVal;
    ci->getValue().toString(intVal, 10, true);
    out << toWxStr(StringRef(intVal.data(), intVal.size()));
  } else {
    out << _("???");
  }
}
Exemple #8
0
std::string DebugIR::getPath() {
  SmallVector<char, 16> Path;
  sys::path::append(Path, Directory, Filename);
  Path.resize(Filename.size() + Directory.size() + 2);
  Path[Filename.size() + Directory.size() + 1] = '\0';
  return std::string(Path.data());
}
void RenameIndependentSubregs::distribute(const IntEqClasses &Classes,
    const SmallVectorImpl<SubRangeInfo> &SubRangeInfos,
    const SmallVectorImpl<LiveInterval*> &Intervals) const {
  unsigned NumClasses = Classes.getNumClasses();
  SmallVector<unsigned, 8> VNIMapping;
  SmallVector<LiveInterval::SubRange*, 8> SubRanges;
  BumpPtrAllocator &Allocator = LIS->getVNInfoAllocator();
  for (const SubRangeInfo &SRInfo : SubRangeInfos) {
    LiveInterval::SubRange &SR = *SRInfo.SR;
    unsigned NumValNos = SR.valnos.size();
    VNIMapping.clear();
    VNIMapping.reserve(NumValNos);
    SubRanges.clear();
    SubRanges.resize(NumClasses-1, nullptr);
    for (unsigned I = 0; I < NumValNos; ++I) {
      const VNInfo &VNI = *SR.valnos[I];
      unsigned LocalID = SRInfo.ConEQ.getEqClass(&VNI);
      unsigned ID = Classes[LocalID + SRInfo.Index];
      VNIMapping.push_back(ID);
      if (ID > 0 && SubRanges[ID-1] == nullptr)
        SubRanges[ID-1] = Intervals[ID]->createSubRange(Allocator, SR.LaneMask);
    }
    DistributeRange(SR, SubRanges.data(), VNIMapping);
  }
}
Exemple #10
0
int Compilation::performSingleCommand(const Job *Cmd) {
  assert(Cmd->getInputs().empty() &&
         "This can only be used to run a single command with no inputs");

  switch (Cmd->getCondition()) {
  case Job::Condition::CheckDependencies:
    return 0;
  case Job::Condition::RunWithoutCascading:
  case Job::Condition::Always:
  case Job::Condition::NewlyAdded:
    break;
  }

  if (!writeFilelistIfNecessary(Cmd, Diags))
    return 1;

  if (Level == OutputLevel::Verbose)
    Cmd->printCommandLine(llvm::errs());

  SmallVector<const char *, 128> Argv;
  Argv.push_back(Cmd->getExecutable());
  Argv.append(Cmd->getArguments().begin(), Cmd->getArguments().end());
  Argv.push_back(0);

  const char *ExecPath = Cmd->getExecutable();
  const char **argv = Argv.data();

  for (auto &envPair : Cmd->getExtraEnvironment())
    setenv(envPair.first, envPair.second, /*replacing=*/true);

  return ExecuteInPlace(ExecPath, argv);
}
AttrListPtr AttrListPtr::removeAttr(unsigned Idx, Attributes Attrs) const {
#ifndef NDEBUG
  // FIXME it is not obvious how this should work for alignment.
  // For now, say we can't pass in alignment, which no current use does.
  assert(!(Attrs & Attribute::Alignment) && "Attempt to exclude alignment!");
#endif
  if (AttrList == 0) return AttrListPtr();
  
  Attributes OldAttrs = getAttributes(Idx);
  Attributes NewAttrs = OldAttrs & ~Attrs;
  if (NewAttrs == OldAttrs)
    return *this;

  SmallVector<AttributeWithIndex, 8> NewAttrList;
  const SmallVector<AttributeWithIndex, 4> &OldAttrList = AttrList->Attrs;
  unsigned i = 0, e = OldAttrList.size();
  
  // Copy attributes for arguments before this one.
  for (; i != e && OldAttrList[i].Index < Idx; ++i)
    NewAttrList.push_back(OldAttrList[i]);
  
  // If there are attributes already at this index, merge them in.
  assert(OldAttrList[i].Index == Idx && "Attribute isn't set?");
  Attrs = OldAttrList[i].Attrs & ~Attrs;
  ++i;
  if (Attrs)  // If any attributes left for this parameter, add them.
    NewAttrList.push_back(AttributeWithIndex::get(Idx, Attrs));
  
  // Copy attributes for arguments after this one.
  NewAttrList.insert(NewAttrList.end(), 
                     OldAttrList.begin()+i, OldAttrList.end());
  
  return get(NewAttrList.data(), NewAttrList.size());
}
Exemple #12
0
int main(int argc_, const char *argv_[]) {
  // Print a stack trace if we signal out.
  sys::PrintStackTraceOnErrorSignal();
  PrettyStackTraceProgram X(argc_, argv_);

  SmallVector<const char *, 256> argv;
  SpecificBumpPtrAllocator<char> ArgAllocator;
  std::error_code EC = sys::Process::GetArgumentVector(
      argv, makeArrayRef(argv_, argc_), ArgAllocator);
  if (EC) {
    errs() << "error: couldn't get arguments: " << EC.message() << '\n';
    return 1;
  }

  llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.

  cl::ParseCommandLineOptions(argv.size(), argv.data(), "LLVM PDB Dumper\n");
  if (opts::Lines)
    opts::Compilands = true;

  if (opts::All) {
    opts::Compilands = true;
    opts::Symbols = true;
    opts::Globals = true;
    opts::Types = true;
    opts::Externals = true;
    opts::Lines = true;
  }

  // When adding filters for excluded compilands and types, we need to remember
  // that these are regexes.  So special characters such as * and \ need to be
  // escaped in the regex.  In the case of a literal \, this means it needs to
  // be escaped again in the C++.  So matching a single \ in the input requires
  // 4 \es in the C++.
  if (opts::ExcludeCompilerGenerated) {
    opts::ExcludeTypes.push_back("__vc_attributes");
    opts::ExcludeCompilands.push_back("\\* Linker \\*");
  }
  if (opts::ExcludeSystemLibraries) {
    opts::ExcludeCompilands.push_back(
        "f:\\\\binaries\\\\Intermediate\\\\vctools\\\\crt_bld");
    opts::ExcludeCompilands.push_back("f:\\\\dd\\\\vctools\\\\crt");
    opts::ExcludeCompilands.push_back("d:\\\\th.obj.x86fre\\\\minkernel");
  }

#if defined(HAVE_DIA_SDK)
  CoInitializeEx(nullptr, COINIT_MULTITHREADED);
#endif

  std::for_each(opts::InputFilenames.begin(), opts::InputFilenames.end(),
                dumpInput);

#if defined(HAVE_DIA_SDK)
  CoUninitialize();
#endif

  return 0;
}
Exemple #13
0
std::unique_ptr<Module>
llvm::splitCodeGen(std::unique_ptr<Module> M,
                   ArrayRef<llvm::raw_pwrite_stream *> OSs, StringRef CPU,
                   StringRef Features, const TargetOptions &Options,
                   Reloc::Model RM, CodeModel::Model CM, CodeGenOpt::Level OL,
                   TargetMachine::CodeGenFileType FileType,
                   bool PreserveLocals) {
  StringRef TripleStr = M->getTargetTriple();
  std::string ErrMsg;
  const Target *TheTarget = TargetRegistry::lookupTarget(TripleStr, ErrMsg);
  if (!TheTarget)
    report_fatal_error(Twine("Target not found: ") + ErrMsg);

  if (OSs.size() == 1) {
    codegen(M.get(), *OSs[0], TheTarget, CPU, Features, Options, RM, CM,
            OL, FileType);
    return M;
  }

  std::vector<thread> Threads;
  SplitModule(std::move(M), OSs.size(), [&](std::unique_ptr<Module> MPart) {
    // We want to clone the module in a new context to multi-thread the codegen.
    // We do it by serializing partition modules to bitcode (while still on the
    // main thread, in order to avoid data races) and spinning up new threads
    // which deserialize the partitions into separate contexts.
    // FIXME: Provide a more direct way to do this in LLVM.
    SmallVector<char, 0> BC;
    raw_svector_ostream BCOS(BC);
    WriteBitcodeToFile(MPart.get(), BCOS);

    llvm::raw_pwrite_stream *ThreadOS = OSs[Threads.size()];
    Threads.emplace_back(
        [TheTarget, CPU, Features, Options, RM, CM, OL, FileType,
         ThreadOS](const SmallVector<char, 0> &BC) {
          LLVMContext Ctx;
          ErrorOr<std::unique_ptr<Module>> MOrErr =
              parseBitcodeFile(MemoryBufferRef(StringRef(BC.data(), BC.size()),
                                               "<split-module>"),
                               Ctx);
          if (!MOrErr)
            report_fatal_error("Failed to read bitcode");
          std::unique_ptr<Module> MPartInCtx = std::move(MOrErr.get());

          codegen(MPartInCtx.get(), *ThreadOS, TheTarget, CPU, Features,
                  Options, RM, CM, OL, FileType);
        },
        // Pass BC using std::move to ensure that it get moved rather than
        // copied into the thread's context.
        std::move(BC));
  }, PreserveLocals);

  for (thread &T : Threads)
    T.join();

  return {};
}
Exemple #14
0
NamedMDNode *NamedMDNode::Create(const NamedMDNode *NMD, Module *M) {
  assert(NMD && "Invalid source NamedMDNode!");
  SmallVector<MDNode *, 4> Elems;
  Elems.reserve(NMD->getNumOperands());

  for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
    Elems.push_back(NMD->getOperand(i));
  return new NamedMDNode(NMD->getContext(), NMD->getName().data(),
                         Elems.data(), Elems.size(), M);
}
Exemple #15
0
/// GetOrCreateArray - Create an descriptor for an array of descriptors.
/// This implicitly uniques the arrays created.
DIArray DIFactory::GetOrCreateArray(DIDescriptor *Tys, unsigned NumTys) {
  SmallVector<Value*, 16> Elts;

  if (NumTys == 0)
    Elts.push_back(llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)));
  else
    for (unsigned i = 0; i != NumTys; ++i)
      Elts.push_back(Tys[i].getNode());

  return DIArray(MDNode::get(VMContext,Elts.data(), Elts.size()));
}
void ELFObjectWriter::writeSectionData(const MCAssembler &Asm, MCSection &Sec,
                                       const MCAsmLayout &Layout) {
  MCSectionELF &Section = static_cast<MCSectionELF &>(Sec);
  StringRef SectionName = Section.getSectionName();

  auto &MC = Asm.getContext();
  const auto &MAI = MC.getAsmInfo();

  // Compressing debug_frame requires handling alignment fragments which is
  // more work (possibly generalizing MCAssembler.cpp:writeFragment to allow
  // for writing to arbitrary buffers) for little benefit.
  bool CompressionEnabled =
      MAI->compressDebugSections() != DebugCompressionType::None;
  if (!CompressionEnabled || !SectionName.startswith(".debug_") ||
      SectionName == ".debug_frame") {
    Asm.writeSectionData(&Section, Layout);
    return;
  }

  assert((MAI->compressDebugSections() == DebugCompressionType::Z ||
          MAI->compressDebugSections() == DebugCompressionType::GNU) &&
         "expected zlib or zlib-gnu style compression");

  SmallVector<char, 128> UncompressedData;
  raw_svector_ostream VecOS(UncompressedData);
  raw_pwrite_stream &OldStream = getStream();
  setStream(VecOS);
  Asm.writeSectionData(&Section, Layout);
  setStream(OldStream);

  SmallVector<char, 128> CompressedContents;
  if (Error E = zlib::compress(
          StringRef(UncompressedData.data(), UncompressedData.size()),
          CompressedContents)) {
    consumeError(std::move(E));
    getStream() << UncompressedData;
    return;
  }

  bool ZlibStyle = MAI->compressDebugSections() == DebugCompressionType::Z;
  if (!maybeWriteCompression(UncompressedData.size(), CompressedContents,
                             ZlibStyle, Sec.getAlignment())) {
    getStream() << UncompressedData;
    return;
  }

  if (ZlibStyle)
    // Set the compressed flag. That is zlib style.
    Section.setFlags(Section.getFlags() | ELF::SHF_COMPRESSED);
  else
    // Add "z" prefix to section name. This is zlib-gnu style.
    MC.renameELFSection(&Section, (".z" + SectionName.drop_front(1)).str());
  getStream() << CompressedContents;
}
Exemple #17
0
Selector NSAPI::getOrInitSelector(ArrayRef<StringRef> Ids,
                                  Selector &Sel) const {
  if (Sel.isNull()) {
    SmallVector<IdentifierInfo *, 4> Idents;
    for (ArrayRef<StringRef>::const_iterator
           I = Ids.begin(), E = Ids.end(); I != E; ++I)
      Idents.push_back(&Ctx.Idents.get(*I));
    Sel = Ctx.Selectors.getSelector(Idents.size(), Idents.data());
  }
  return Sel;
}
Exemple #18
0
int Command::Execute(const StringRef **Redirects, std::string *ErrMsg,
                     bool *ExecutionFailed) const {
  SmallVector<const char*, 128> Argv;
  Argv.push_back(Executable);
  for (size_t i = 0, e = Arguments.size(); i != e; ++i)
    Argv.push_back(Arguments[i]);
  Argv.push_back(nullptr);

  return llvm::sys::ExecuteAndWait(Executable, Argv.data(), /*env*/ nullptr,
                                   Redirects, /*secondsToWait*/ 0,
                                   /*memoryLimit*/ 0, ErrMsg, ExecutionFailed);
}
Exemple #19
0
int Command::Execute(const StringRef **Redirects, std::string *ErrMsg,
                     bool *ExecutionFailed) const {
  SmallVector<const char*, 128> Argv;

  if (ResponseFile == nullptr) {
    Argv.push_back(Executable);
    Argv.append(Arguments.begin(), Arguments.end());
    Argv.push_back(nullptr);

    return llvm::sys::ExecuteAndWait(Executable, Argv.data(), /*env*/ nullptr,
                                     Redirects, /*secondsToWait*/ 0,
                                     /*memoryLimit*/ 0, ErrMsg,
                                     ExecutionFailed);
  }

  // We need to put arguments in a response file (command is too large)
  // Open stream to store the response file contents
  std::string RespContents;
  llvm::raw_string_ostream SS(RespContents);

  // Write file contents and build the Argv vector
  writeResponseFile(SS);
  buildArgvForResponseFile(Argv);
  Argv.push_back(nullptr);
  SS.flush();

  // Save the response file in the appropriate encoding
  if (std::error_code EC = writeFileWithEncoding(
          ResponseFile, RespContents, Creator.getResponseFileEncoding())) {
    if (ErrMsg)
      *ErrMsg = EC.message();
    if (ExecutionFailed)
      *ExecutionFailed = true;
    return -1;
  }

  return llvm::sys::ExecuteAndWait(Executable, Argv.data(), /*env*/ nullptr,
                                   Redirects, /*secondsToWait*/ 0,
                                   /*memoryLimit*/ 0, ErrMsg, ExecutionFailed);
}
void MatcherGen::EmitResultCode() {
  // Patterns that match nodes with (potentially multiple) chain inputs have to
  // merge them together into a token factor.  This informs the generated code
  // what all the chained nodes are.
  if (!MatchedChainNodes.empty())
    AddMatcher(new EmitMergeInputChainsMatcher
               (MatchedChainNodes.data(), MatchedChainNodes.size()));

  // Codegen the root of the result pattern, capturing the resulting values.
  SmallVector<unsigned, 8> Ops;
  EmitResultOperand(Pattern.getDstPattern(), Ops);

  // At this point, we have however many values the result pattern produces.
  // However, the input pattern might not need all of these.  If there are
  // excess values at the end (such as implicit defs of condition codes etc)
  // just lop them off.  This doesn't need to worry about glue or chains, just
  // explicit results.
  //
  unsigned NumSrcResults = Pattern.getSrcPattern()->getNumTypes();

  // If the pattern also has (implicit) results, count them as well.
  if (!Pattern.getDstRegs().empty()) {
    // If the root came from an implicit def in the instruction handling stuff,
    // don't re-add it.
    Record *HandledReg = 0;
    const TreePatternNode *DstPat = Pattern.getDstPattern();
    if (!DstPat->isLeaf() &&DstPat->getOperator()->isSubClassOf("Instruction")){
      const CodeGenTarget &CGT = CGP.getTargetInfo();
      CodeGenInstruction &II = CGT.getInstruction(DstPat->getOperator());

      if (II.HasOneImplicitDefWithKnownVT(CGT) != MVT::Other)
        HandledReg = II.ImplicitDefs[0];
    }

    for (unsigned i = 0; i != Pattern.getDstRegs().size(); ++i) {
      Record *Reg = Pattern.getDstRegs()[i];
      if (!Reg->isSubClassOf("Register") || Reg == HandledReg) continue;
      ++NumSrcResults;
    }
  }

  assert(Ops.size() >= NumSrcResults && "Didn't provide enough results");
  Ops.resize(NumSrcResults);

  // If the matched pattern covers nodes which define a glue result, emit a node
  // that tells the matcher about them so that it can update their results.
  if (!MatchedGlueResultNodes.empty())
    AddMatcher(new MarkGlueResultsMatcher(MatchedGlueResultNodes.data(),
                                          MatchedGlueResultNodes.size()));

  AddMatcher(new CompleteMatchMatcher(Ops.data(), Ops.size(), Pattern));
}
Exemple #21
0
Type ASTContext::GetBuiltinType(unsigned Id, GetBuiltinTypeError &Error,
                                unsigned *IntegerConstantArgs) const {
  const char *TypeStr = BuiltinInfo.GetTypeString(Id);
  SmallVector<Type, 8> ArgTypes;
  bool RequiresICE = false;
  Error = GE_None;
  Type ResType = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE,
                                   true);
  if (Error != GE_None)
    return Type();

  assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");

  while (TypeStr[0] && TypeStr[0] != '.') {
    Type Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
    if (Error != GE_None)
      return Type();

    // If this argument is required to be an IntegerConstantExpression and the
    // caller cares, fill in the bitmask we return.
    if (RequiresICE && IntegerConstantArgs)
      *IntegerConstantArgs |= 1 << ArgTypes.size();

    // Do array -> pointer decay.  The builtin should use the decayed type.
//		if (Ty->isArrayType())
//			Ty = getArrayDecayedType(Ty);
    ArgTypes.push_back(Ty);
  }

  assert((TypeStr[0] != '.' || TypeStr[1] == 0)
         && "'.' should only occur at end of builtin type list!");

  FunctionType::ExtInfo EI;
  if (BuiltinInfo.isNoReturn(Id))
    EI = EI.withNoReturn(true);

  bool Variadic = (TypeStr[0] == '.');

  // We really shouldn't be making a no-proto type here, especially in C++.
  if (ArgTypes.empty() && Variadic) {
    return getFunctionNoProtoType(ResType, EI);
  }

  FunctionProtoType::ExtProtoInfo EPI;
  EPI.ExtInfo = EI;
  EPI.Variadic = Variadic;

  return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
}
Exemple #22
0
void SwiftLookupTableWriter::writeExtensionContents(
       clang::Sema &sema,
       llvm::BitstreamWriter &stream) {
  // Populate the lookup table.
  SwiftLookupTable table(nullptr);
  PopulateTable(sema, table);

  SmallVector<uint64_t, 64> ScratchRecord;

  // First, gather the sorted list of base names.
  SmallVector<StringRef, 2> baseNames;
  for (const auto &entry : table.LookupTable)
    baseNames.push_back(entry.first);
  llvm::array_pod_sort(baseNames.begin(), baseNames.end());

  // Form the mapping from base names to entities with their context.
  {
    llvm::SmallString<4096> hashTableBlob;
    uint32_t tableOffset;
    {
      llvm::OnDiskChainedHashTableGenerator<BaseNameToEntitiesTableWriterInfo>
        generator;
      BaseNameToEntitiesTableWriterInfo info(table, Writer);
      for (auto baseName : baseNames)
        generator.insert(baseName, table.LookupTable[baseName], info);

      llvm::raw_svector_ostream blobStream(hashTableBlob);
      // Make sure that no bucket is at offset 0
      endian::Writer<little>(blobStream).write<uint32_t>(0);
      tableOffset = generator.Emit(blobStream, info);
    }

    BaseNameToEntitiesTableRecordLayout layout(stream);
    layout.emit(ScratchRecord, tableOffset, hashTableBlob);
  }

  // Write the categories, if there are any.
  if (!table.Categories.empty()) {
    SmallVector<clang::serialization::DeclID, 4> categoryIDs;
    for (auto category : table.Categories) {
      categoryIDs.push_back(Writer.getDeclID(category));
    }

    StringRef blob(reinterpret_cast<const char *>(categoryIDs.data()),
                   categoryIDs.size() * sizeof(clang::serialization::DeclID));
    CategoriesRecordLayout layout(stream);
    layout.emit(ScratchRecord, blob);
  }
}
void TextDiagnostic::emitFilename(StringRef Filename, const SourceManager &SM) {
  SmallVector<char, 128> AbsoluteFilename;
  if (DiagOpts->AbsolutePath) {
    const DirectoryEntry *Dir = SM.getFileManager().getDirectory(
        llvm::sys::path::parent_path(Filename));
    if (Dir) {
      StringRef DirName = SM.getFileManager().getCanonicalName(Dir);
      llvm::sys::path::append(AbsoluteFilename, DirName,
                              llvm::sys::path::filename(Filename));
      Filename = StringRef(AbsoluteFilename.data(), AbsoluteFilename.size());
    }
  }

  OS << Filename;
}
static void getInclusions(const SrcMgr::SLocEntry &(SourceManager::*Getter)(unsigned, bool*) const, unsigned n,
                          CXTranslationUnit TU, CXInclusionVisitor CB,
                          CXClientData clientData)
{
  ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
  SourceManager &SM = CXXUnit->getSourceManager();
  ASTContext &Ctx = CXXUnit->getASTContext();
  SmallVector<CXSourceLocation, 10> InclusionStack;
  const bool HasPreamble = SM.getPreambleFileID().isValid();

  for (unsigned i = 0 ; i < n ; ++i) {
    bool Invalid = false;
    const SrcMgr::SLocEntry &SL = (SM.*Getter)(i, &Invalid);

    if (!SL.isFile() || Invalid)
      continue;

    const SrcMgr::FileInfo &FI = SL.getFile();
    if (!FI.getContentCache()->OrigEntry)
      continue;

    // If this is the main file, and there is a preamble, skip this SLoc. The
    // inclusions of the preamble already showed it.
    SourceLocation L = FI.getIncludeLoc();
    if (HasPreamble && CXXUnit->isInMainFileID(L))
      continue;

    // Build the inclusion stack.
    InclusionStack.clear();
    while (L.isValid()) {
      PresumedLoc PLoc = SM.getPresumedLoc(L);
      InclusionStack.push_back(cxloc::translateSourceLocation(Ctx, L));
      L = PLoc.isValid()? PLoc.getIncludeLoc() : SourceLocation();
    }

    // If there is a preamble, the last entry is the "inclusion" of that
    // preamble into the main file, which has the bogus entry of main.c:1:1
    if (HasPreamble && !InclusionStack.empty())
      InclusionStack.pop_back();

    // Callback to the client.
    // FIXME: We should have a function to construct CXFiles.
    CB(static_cast<CXFile>(
         const_cast<FileEntry *>(FI.getContentCache()->OrigEntry)),
       InclusionStack.data(), InclusionStack.size(), clientData);
  }
}
Exemple #25
0
int main(int argc, char **argv) {
  cl::ParseCommandLineOptions(argc, argv, "Module concatenation");

  ExitOnError ExitOnErr("llvm-cat: ");
  LLVMContext Context;

  SmallVector<char, 0> Buffer;
  BitcodeWriter Writer(Buffer);
  if (BinaryCat) {
    for (const auto &InputFilename : InputFilenames) {
      std::unique_ptr<MemoryBuffer> MB = ExitOnErr(
          errorOrToExpected(MemoryBuffer::getFileOrSTDIN(InputFilename)));
      std::vector<BitcodeModule> Mods = ExitOnErr(getBitcodeModuleList(*MB));
      for (auto &BitcodeMod : Mods) {
        Buffer.insert(Buffer.end(), BitcodeMod.getBuffer().begin(),
                      BitcodeMod.getBuffer().end());
        Writer.copyStrtab(BitcodeMod.getStrtab());
      }
    }
  } else {
    // The string table does not own strings added to it, some of which are
    // owned by the modules; keep them alive until we write the string table.
    std::vector<std::unique_ptr<Module>> OwnedMods;
    for (const auto &InputFilename : InputFilenames) {
      SMDiagnostic Err;
      std::unique_ptr<Module> M = parseIRFile(InputFilename, Err, Context);
      if (!M) {
        Err.print(argv[0], errs());
        return 1;
      }
      Writer.writeModule(M.get());
      OwnedMods.push_back(std::move(M));
    }
    Writer.writeStrtab();
  }

  std::error_code EC;
  raw_fd_ostream OS(OutputFilename, EC, sys::fs::OpenFlags::F_None);
  if (EC) {
    errs() << argv[0] << ": cannot open " << OutputFilename << " for writing: "
           << EC.message();
    return 1;
  }

  OS.write(Buffer.data(), Buffer.size());
  return 0;
}
Exemple #26
0
//
// LLVMDisasmInstruction() disassembles a single instruction using the
// disassembler context specified in the parameter DC.  The bytes of the
// instruction are specified in the parameter Bytes, and contains at least
// BytesSize number of bytes.  The instruction is at the address specified by
// the PC parameter.  If a valid instruction can be disassembled its string is
// returned indirectly in OutString which whos size is specified in the
// parameter OutStringSize.  This function returns the number of bytes in the
// instruction or zero if there was no valid instruction.  If this function
// returns zero the caller will have to pick how many bytes they want to step
// over by printing a .byte, .long etc. to continue.
//
size_t LLVMDisasmInstruction(LLVMDisasmContextRef DCR, uint8_t *Bytes,
                             uint64_t BytesSize, uint64_t PC, char *OutString,
                             size_t OutStringSize){
  LLVMDisasmContext *DC = (LLVMDisasmContext *)DCR;
  // Wrap the pointer to the Bytes, BytesSize and PC in a MemoryObject.
  DisasmMemoryObject MemoryObject(Bytes, BytesSize, PC);

  uint64_t Size;
  MCInst Inst;
  const MCDisassembler *DisAsm = DC->getDisAsm();
  MCInstPrinter *IP = DC->getIP();
  MCDisassembler::DecodeStatus S;
  SmallVector<char, 64> InsnStr;
  raw_svector_ostream Annotations(InsnStr);
  S = DisAsm->getInstruction(Inst, Size, MemoryObject, PC,
                             /*REMOVE*/ nulls(), Annotations);
  switch (S) {
  case MCDisassembler::Fail:
  case MCDisassembler::SoftFail:
    // FIXME: Do something different for soft failure modes?
    return 0;

  case MCDisassembler::Success: {
    Annotations.flush();
    StringRef AnnotationsStr = Annotations.str();

    SmallVector<char, 64> InsnStr;
    raw_svector_ostream OS(InsnStr);
    formatted_raw_ostream FormattedOS(OS);
    IP->printInst(&Inst, FormattedOS, AnnotationsStr);

    if (DC->getOptions() & LLVMDisassembler_Option_PrintLatency)
      emitLatency(DC, Inst);

    emitComments(DC, FormattedOS);
    OS.flush();

    assert(OutStringSize != 0 && "Output buffer cannot be zero size");
    size_t OutputSize = std::min(OutStringSize-1, InsnStr.size());
    std::memcpy(OutString, InsnStr.data(), OutputSize);
    OutString[OutputSize] = '\0'; // Terminate string.

    return Size;
  }
  }
  llvm_unreachable("Invalid DecodeStatus!");
}
Exemple #27
0
int csabase::run(int argc_, const char **argv_)
{
    sys::PrintStackTraceOnErrorSignal();
    PrettyStackTraceProgram X(argc_, argv_);

    SmallVector<const char *, 1024> argv;
    SpecificBumpPtrAllocator<char>  ArgAllocator;
    StringSetSaver                  Saver;

    sys::Process::GetArgumentVector(argv,
                                    ArrayRef<const char *>(argv_, argc_),
                                    ArgAllocator);

    cl::ExpandResponseFiles(Saver, cl::TokenizeGNUCommandLine, argv);

    argv.insert(argv.begin() == argv.end() ? argv.begin() : argv.begin() + 1,
                "-xc++");

    llvm::InitializeNativeTarget();
    llvm::InitializeNativeTargetAsmParser();

    CompilerInstance                      Clang;
    TextDiagnosticBuffer                  DiagsBuffer;
    IntrusiveRefCntPtr<DiagnosticIDs>     DiagID(new DiagnosticIDs());
    IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions());

    DiagnosticsEngine Diags(DiagID, &*DiagOpts, &DiagsBuffer, false);

    bool Success = CompilerInvocation::CreateFromArgs(
        Clang.getInvocation(),
        argv.data() + 1,
        argv.data() + argv.size(),
        Diags);

    Clang.createDiagnostics();
    install_fatal_error_handler(LLVMErrorHandler, &Clang.getDiagnostics());
    DiagsBuffer.FlushDiagnostics(Clang.getDiagnostics());

    if (Success) {
        Success = ExecuteCompilerInvocation(&Clang);
    }

    remove_fatal_error_handler();
    llvm::llvm_shutdown();

    return !Success;
}
Exemple #28
0
void ObjCInterfaceDecl::mergeClassExtensionProtocolList(
                              ObjCProtocolDecl *const* ExtList, unsigned ExtNum,
                              ASTContext &C)
{
  if (data().ExternallyCompleted)
    LoadExternalDefinition();

  if (data().AllReferencedProtocols.empty() && 
      data().ReferencedProtocols.empty()) {
    data().AllReferencedProtocols.set(ExtList, ExtNum, C);
    return;
  }
  
  // Check for duplicate protocol in class's protocol list.
  // This is O(n*m). But it is extremely rare and number of protocols in
  // class or its extension are very few.
  SmallVector<ObjCProtocolDecl*, 8> ProtocolRefs;
  for (unsigned i = 0; i < ExtNum; i++) {
    bool protocolExists = false;
    ObjCProtocolDecl *ProtoInExtension = ExtList[i];
    for (all_protocol_iterator
          p = all_referenced_protocol_begin(),
          e = all_referenced_protocol_end(); p != e; ++p) {
      ObjCProtocolDecl *Proto = (*p);
      if (C.ProtocolCompatibleWithProtocol(ProtoInExtension, Proto)) {
        protocolExists = true;
        break;
      }      
    }
    // Do we want to warn on a protocol in extension class which
    // already exist in the class? Probably not.
    if (!protocolExists)
      ProtocolRefs.push_back(ProtoInExtension);
  }

  if (ProtocolRefs.empty())
    return;

  // Merge ProtocolRefs into class's protocol list;
  for (all_protocol_iterator p = all_referenced_protocol_begin(), 
        e = all_referenced_protocol_end(); p != e; ++p) {
    ProtocolRefs.push_back(*p);
  }

  data().AllReferencedProtocols.set(ProtocolRefs.data(), ProtocolRefs.size(),C);
}
Exemple #29
0
void EmitAssemblyHelper::setCommandLineOpts() {
  SmallVector<const char *, 16> BackendArgs;
  BackendArgs.push_back("clang"); // Fake program name.
  if (!CodeGenOpts.DebugPass.empty()) {
    BackendArgs.push_back("-debug-pass");
    BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
  }
  if (!CodeGenOpts.LimitFloatPrecision.empty()) {
    BackendArgs.push_back("-limit-float-precision");
    BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
  }
  for (const std::string &BackendOption : CodeGenOpts.BackendOptions)
    BackendArgs.push_back(BackendOption.c_str());
  BackendArgs.push_back(nullptr);
  llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
                                    BackendArgs.data());
}
int main(int argc_, const char *argv_[]) {
  // Print a stack trace if we signal out.
  sys::PrintStackTraceOnErrorSignal();
  PrettyStackTraceProgram X(argc_, argv_);

  SmallVector<const char *, 256> argv;
  llvm::SpecificBumpPtrAllocator<char> ArgAllocator;
  std::error_code EC = llvm::sys::Process::GetArgumentVector(
      argv, llvm::makeArrayRef(argv_, argc_), ArgAllocator);
  if (EC) {
    llvm::errs() << "error: couldn't get arguments: " << EC.message() << '\n';
    return 1;
  }

  llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.

  cl::ParseCommandLineOptions(argv.size(), argv.data(), "LLVM PDB Dumper\n");
  if (opts::All) {
    opts::Compilands = true;
    opts::Symbols = true;
    opts::Globals = true;
    opts::Types = true;
  }
  if (opts::ExcludeCompilerGenerated) {
    opts::ExcludeTypes.push_back("__vc_attributes");
    opts::ExcludeCompilands.push_back("* Linker *");
  }
  if (opts::ExcludeSystemLibraries) {
    opts::ExcludeCompilands.push_back(
        "f:\\binaries\\Intermediate\\vctools\\crt_bld");
  }

#if defined(HAVE_DIA_SDK)
  CoInitializeEx(nullptr, COINIT_MULTITHREADED);
#endif

  std::for_each(opts::InputFilenames.begin(), opts::InputFilenames.end(),
                dumpInput);

#if defined(HAVE_DIA_SDK)
  CoUninitialize();
#endif

  return 0;
}