예제 #1
0
/// parseMetadata - Parse metadata from the module
void LTOModule::parseMetadata() {
  raw_string_ostream OS(LinkerOpts);

  // Linker Options
  if (Metadata *Val = getModule().getModuleFlag("Linker Options")) {
    MDNode *LinkerOptions = cast<MDNode>(Val);
    for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
      MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
      for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
        MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
        OS << " " << MDOption->getString();
      }
    }
  }

  // Globals
  Mangler Mang;
  for (const NameAndAttributes &Sym : _symbols) {
    if (!Sym.symbol)
      continue;
    _target->getObjFileLowering()->emitLinkerFlagsForGlobal(OS, Sym.symbol,
                                                            Mang);
  }

  // Add other interesting metadata here.
}
예제 #2
0
파일: IRParser.cpp 프로젝트: orcc/jade
MoC* IRParser::parseMoC(Module* module){
    NamedMDNode* mocKeyMD =  module->getNamedMetadata(IRConstant::KEY_MOC);

    if (mocKeyMD == NULL) {
        return new DPNMoC(actor);
    }

    //Parse MoC type
    MDNode* node = mocKeyMD->getOperand(0);
    MDString* name = cast<MDString>(node->getOperand(0));
    StringRef nameStr = name->getString();

    if (nameStr == "SDF"){
        return parseCSDF(cast<MDNode>(node->getOperand(1)));
    }else if(nameStr == "CSDF"){
        return parseCSDF(cast<MDNode>(node->getOperand(1)));
    }else if(nameStr == "QuasiStatic"){
        return parseQSDF(node);
    }else if(nameStr == "KPN"){
        return new KPNMoC(actor);
    }else if(nameStr == "DPN"){
        return new DPNMoC(actor);
    }

    cerr << "Unsupported type of MoC" << endl;
    exit(1);
}
예제 #3
0
// Remove existing unroll metadata and add unroll disable metadata to
// indicate the loop has already been unrolled.  This prevents a loop
// from being unrolled more than is directed by a pragma if the loop
// unrolling pass is run more than once (which it generally is).
static void SetLoopAlreadyUnrolled(Loop *L) {
  MDNode *LoopID = L->getLoopID();
  if (!LoopID) return;

  // First remove any existing loop unrolling metadata.
  SmallVector<Metadata *, 4> MDs;
  // Reserve first location for self reference to the LoopID metadata node.
  MDs.push_back(nullptr);
  for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
    bool IsUnrollMetadata = false;
    MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
    if (MD) {
      const MDString *S = dyn_cast<MDString>(MD->getOperand(0));
      IsUnrollMetadata = S && S->getString().startswith("llvm.loop.unroll.");
    }
    if (!IsUnrollMetadata)
      MDs.push_back(LoopID->getOperand(i));
  }

  // Add unroll(disable) metadata to disable future unrolling.
  LLVMContext &Context = L->getHeader()->getContext();
  SmallVector<Metadata *, 1> DisableOperands;
  DisableOperands.push_back(MDString::get(Context, "llvm.loop.unroll.disable"));
  MDNode *DisableNode = MDNode::get(Context, DisableOperands);
  MDs.push_back(DisableNode);

  MDNode *NewLoopID = MDNode::get(Context, MDs);
  // Set operand 0 to refer to the loop id itself.
  NewLoopID->replaceOperandWith(0, NewLoopID);
  L->setLoopID(NewLoopID);
}
예제 #4
0
MDNode *MDNode::getMostGenericTBAA(MDNode *A, MDNode *B) {
  if (!A || !B)
    return NULL;

  if (A == B)
    return A;

  SmallVector<MDNode *, 4> PathA;
  MDNode *T = A;
  while (T) {
    PathA.push_back(T);
    T = T->getNumOperands() >= 2 ? cast_or_null<MDNode>(T->getOperand(1)) : 0;
  }

  SmallVector<MDNode *, 4> PathB;
  T = B;
  while (T) {
    PathB.push_back(T);
    T = T->getNumOperands() >= 2 ? cast_or_null<MDNode>(T->getOperand(1)) : 0;
  }

  int IA = PathA.size() - 1;
  int IB = PathB.size() - 1;

  MDNode *Ret = 0;
  while (IA >= 0 && IB >=0) {
    if (PathA[IA] == PathB[IB])
      Ret = PathA[IA];
    else
      break;
    --IA;
    --IB;
  }
  return Ret;
}
예제 #5
0
파일: LoopUtils.cpp 프로젝트: theryee/llvm
/// \brief Find string metadata for loop
///
/// If it has a value (e.g. {"llvm.distribute", 1} return the value as an
/// operand or null otherwise.  If the string metadata is not found return
/// Optional's not-a-value.
Optional<const MDOperand *> llvm::findStringMetadataForLoop(Loop *TheLoop,
                                                            StringRef Name) {
  MDNode *LoopID = TheLoop->getLoopID();
  // Return none if LoopID is false.
  if (!LoopID)
    return None;

  // First operand should refer to the loop id itself.
  assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
  assert(LoopID->getOperand(0) == LoopID && "invalid loop id");

  // Iterate over LoopID operands and look for MDString Metadata
  for (unsigned i = 1, e = LoopID->getNumOperands(); i < e; ++i) {
    MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
    if (!MD)
      continue;
    MDString *S = dyn_cast<MDString>(MD->getOperand(0));
    if (!S)
      continue;
    // Return true if MDString holds expected MetaData.
    if (Name.equals(S->getString()))
      switch (MD->getNumOperands()) {
      case 1:
        return nullptr;
      case 2:
        return &MD->getOperand(1);
      default:
        llvm_unreachable("loop metadata has 0 or 1 operand");
      }
  }
  return None;
}
예제 #6
0
파일: IRParser.cpp 프로젝트: orcc/jade
map<string, Variable*>* IRParser::parseParameters(Module* module){
    map<string, Variable*>* parameters = new map<string, Variable*>();

    NamedMDNode* inputsMD =  module->getNamedMetadata(IRConstant::KEY_PARAMETERS);
    if (inputsMD != NULL){
        for (unsigned i = 0, e = inputsMD->getNumOperands(); i != e; ++i) {

            //Parse a parameter
            MDNode* parameterNode = cast<MDNode>(inputsMD->getOperand(i));
            MDNode* details = cast<MDNode>(parameterNode->getOperand(0));
            MDString* nameMD = cast<MDString>(details->getOperand(0));

            Type* type = parseType(cast<MDNode>(parameterNode->getOperand(1)));

            GlobalVariable* variable = cast<GlobalVariable>(parameterNode->getOperand(2));

            //Parse create parameter
            StateVar* parameter = new StateVar(type, nameMD->getString(), false, variable);

            parameters->insert(pair<string, Variable*>(nameMD->getString(), parameter));
        }

    }
    return parameters;
}
예제 #7
0
파일: IRParser.cpp 프로젝트: orcc/jade
ActionScheduler* IRParser::parseActionScheduler(Module* module){
    NamedMDNode* inputsMD =  module->getNamedMetadata(IRConstant::KEY_ACTION_SCHED);

    MDNode* actionSchedulerMD = cast<MDNode>(inputsMD->getOperand(0));
    list<Action*>* actions = new list<Action*>();
    FSM* fsm = NULL;

    //Get actions outside fsm if present
    Value* actionsValue = actionSchedulerMD->getOperand(0);

    if (actionsValue != NULL){
        MDNode* actionsNode =  cast<MDNode>(actionsValue);
        for (unsigned i = 0, e = actionsNode->getNumOperands(); i != e; ++i) {
            actions->push_back(getAction(cast<MDNode>(actionsNode->getOperand(i))));
        }
    }

    //Get fsm if present
    Value* fsmValue = actionSchedulerMD->getOperand(1);

    if (fsmValue != NULL){
        fsm = parseFSM(cast<MDNode>(fsmValue));
    }

    return new ActionScheduler(actions, fsm);
}
void TargetLoweringObjectFileCOFF::
emitModuleFlags(MCStreamer &Streamer,
                ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
                Mangler &Mang, const TargetMachine &TM) const {
  MDNode *LinkerOptions = nullptr;

  // Look for the "Linker Options" flag, since it's the only one we support.
  for (ArrayRef<Module::ModuleFlagEntry>::iterator
       i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
    const Module::ModuleFlagEntry &MFE = *i;
    StringRef Key = MFE.Key->getString();
    Metadata *Val = MFE.Val;
    if (Key == "Linker Options") {
      LinkerOptions = cast<MDNode>(Val);
      break;
    }
  }
  if (!LinkerOptions)
    return;

  // Emit the linker options to the linker .drectve section.  According to the
  // spec, this section is a space-separated string containing flags for linker.
  const MCSection *Sec = getDrectveSection();
  Streamer.SwitchSection(Sec);
  for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
    MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
    for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
      MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
      // Lead with a space for consistency with our dllexport implementation.
      std::string Directive(" ");
      Directive.append(MDOption->getString());
      Streamer.EmitBytes(Directive);
    }
  }
}
예제 #9
0
파일: LTOModule.cpp 프로젝트: SDkie/llvm
/// parseMetadata - Parse metadata from the module
void LTOModule::parseMetadata() {
  // Linker Options
  if (Metadata *Val = getModule().getModuleFlag("Linker Options")) {
    MDNode *LinkerOptions = cast<MDNode>(Val);
    for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
      MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
      for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
        MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
        // FIXME: Make StringSet::insert match Self-Associative Container
        // requirements, returning <iter,bool> rather than bool, and use that
        // here.
        StringRef Op =
            _linkeropt_strings.insert(MDOption->getString()).first->first();
        StringRef DepLibName = _target->getSubtargetImpl()
                                   ->getTargetLowering()
                                   ->getObjFileLowering()
                                   .getDepLibFromLinkerOpt(Op);
        if (!DepLibName.empty())
          _deplibs.push_back(DepLibName.data());
        else if (!Op.empty())
          _linkeropts.push_back(Op.data());
      }
    }
  }

  // Add other interesting metadata here.
}
예제 #10
0
파일: GCOVProfiling.cpp 프로젝트: cyw3/llvm
std::string GCOVProfiler::mangleName(const DICompileUnit *CU,
                                     const char *NewStem) {
  if (NamedMDNode *GCov = M->getNamedMetadata("llvm.gcov")) {
    for (int i = 0, e = GCov->getNumOperands(); i != e; ++i) {
      MDNode *N = GCov->getOperand(i);
      if (N->getNumOperands() != 2) continue;
      MDString *GCovFile = dyn_cast<MDString>(N->getOperand(0));
      MDNode *CompileUnit = dyn_cast<MDNode>(N->getOperand(1));
      if (!GCovFile || !CompileUnit) continue;
      if (CompileUnit == CU) {
        SmallString<128> Filename = GCovFile->getString();
        sys::path::replace_extension(Filename, NewStem);
        return Filename.str();
      }
    }
  }

  SmallString<128> Filename = CU->getFilename();
  sys::path::replace_extension(Filename, NewStem);
  StringRef FName = sys::path::filename(Filename);
  SmallString<128> CurPath;
  if (sys::fs::current_path(CurPath)) return FName;
  sys::path::append(CurPath, FName);
  return CurPath.str();
}
예제 #11
0
MDNode *MDNode::getMostGenericTBAA(MDNode *A, MDNode *B) {
  if (!A || !B)
    return nullptr;

  if (A == B)
    return A;

  // For struct-path aware TBAA, we use the access type of the tag.
  bool StructPath = isStructPathTBAA(A) && isStructPathTBAA(B);
  if (StructPath) {
    A = cast_or_null<MDNode>(A->getOperand(1));
    if (!A) return nullptr;
    B = cast_or_null<MDNode>(B->getOperand(1));
    if (!B) return nullptr;
  }

  SmallSetVector<MDNode *, 4> PathA;
  MDNode *T = A;
  while (T) {
    if (PathA.count(T))
      report_fatal_error("Cycle found in TBAA metadata.");
    PathA.insert(T);
    T = T->getNumOperands() >= 2 ? cast_or_null<MDNode>(T->getOperand(1))
                                 : nullptr;
  }

  SmallSetVector<MDNode *, 4> PathB;
  T = B;
  while (T) {
    if (PathB.count(T))
      report_fatal_error("Cycle found in TBAA metadata.");
    PathB.insert(T);
    T = T->getNumOperands() >= 2 ? cast_or_null<MDNode>(T->getOperand(1))
                                 : nullptr;
  }

  int IA = PathA.size() - 1;
  int IB = PathB.size() - 1;

  MDNode *Ret = nullptr;
  while (IA >= 0 && IB >=0) {
    if (PathA[IA] == PathB[IB])
      Ret = PathA[IA];
    else
      break;
    --IA;
    --IB;
  }
  if (!StructPath)
    return Ret;

  if (!Ret)
    return nullptr;
  // We need to convert from a type node to a tag node.
  Type *Int64 = IntegerType::get(A->getContext(), 64);
  Metadata *Ops[3] = {Ret, Ret,
                      ConstantAsMetadata::get(ConstantInt::get(Int64, 0))};
  return MDNode::get(A->getContext(), Ops);
}
예제 #12
0
파일: LinkModules.cpp 프로젝트: groue/llvm
/// categorizeModuleFlagNodes -
bool ModuleLinker::
categorizeModuleFlagNodes(const NamedMDNode *ModFlags,
                          DenseMap<MDString*, MDNode*> &ErrorNode,
                          DenseMap<MDString*, MDNode*> &WarningNode,
                          DenseMap<MDString*, MDNode*> &OverrideNode,
                          DenseMap<MDString*,
                            SmallSetVector<MDNode*, 8> > &RequireNodes,
                          SmallSetVector<MDString*, 16> &SeenIDs) {
  bool HasErr = false;

  for (unsigned I = 0, E = ModFlags->getNumOperands(); I != E; ++I) {
    MDNode *Op = ModFlags->getOperand(I);
    assert(Op->getNumOperands() == 3 && "Invalid module flag metadata!");
    assert(isa<ConstantInt>(Op->getOperand(0)) &&
           "Module flag's first operand must be an integer!");
    assert(isa<MDString>(Op->getOperand(1)) &&
           "Module flag's second operand must be an MDString!");

    ConstantInt *Behavior = cast<ConstantInt>(Op->getOperand(0));
    MDString *ID = cast<MDString>(Op->getOperand(1));
    Value *Val = Op->getOperand(2);
    switch (Behavior->getZExtValue()) {
    default:
      assert(false && "Invalid behavior in module flag metadata!");
      break;
    case Module::Error: {
      MDNode *&ErrNode = ErrorNode[ID];
      if (!ErrNode) ErrNode = Op;
      if (ErrNode->getOperand(2) != Val)
        HasErr = emitError("linking module flags '" + ID->getString() +
                           "': IDs have conflicting values");
      break;
    }
    case Module::Warning: {
      MDNode *&WarnNode = WarningNode[ID];
      if (!WarnNode) WarnNode = Op;
      if (WarnNode->getOperand(2) != Val)
        errs() << "WARNING: linking module flags '" << ID->getString()
               << "': IDs have conflicting values";
      break;
    }
    case Module::Require:  RequireNodes[ID].insert(Op);     break;
    case Module::Override: {
      MDNode *&OvrNode = OverrideNode[ID];
      if (!OvrNode) OvrNode = Op;
      if (OvrNode->getOperand(2) != Val)
        HasErr = emitError("linking module flags '" + ID->getString() +
                           "': IDs have conflicting override values");
      break;
    }
    }

    SeenIDs.insert(ID);
  }

  return HasErr;
}
예제 #13
0
  void
  SpecializationTable::initialize(Module* m)
  {
    assert(this->module == NULL);
    this->module = m;
#ifdef RECORD_IN_METADATA
    // Parse the module metadata to populate the table
    NamedMDNode* specs = m->getNamedMetadata("previrt::specializations");
    if (specs == NULL)
    return;

    errs() << "Specialization Count: " << specs->getNumOperands() << "\n";

    for (unsigned int i = 0; i < specs->getNumOperands(); ++i) {
      MDNode* funNode = specs->getOperand(i);
      if (funNode == NULL) {
        continue;
      }
      assert (funNode->getNumOperands() > 2);
      MDString* prinName = dyn_cast_or_null<MDString>(funNode->getOperand(0));
      MDString* specName = dyn_cast_or_null<MDString>(funNode->getOperand(1));
      if (prinName == NULL || specName == NULL) {
        errs() << "must skip " << (prinName == NULL ? "?" : prinName->getString()) << "\n";
        continue;
      }
      Function* prin = m->getFunction(prinName->getString());
      Function* spec = m->getFunction(specName->getString());
      if (prin == NULL || spec == NULL) {
        errs() << "must skip " << (prin == NULL ? "?" : prin->getName()) << "\n";
        continue;
      }

      const unsigned int arg_count = prin->getArgumentList().size();
      if (funNode->getNumOperands() != 2 + arg_count) {
        continue;
      }

      SpecScheme scheme = new Value*[arg_count];
      for (unsigned int i = 0; i < arg_count; i++) {
        Value* opr = funNode->getOperand(2 + i);
        if (opr == NULL) {
          scheme[i] = NULL;
        } else {
          assert (dyn_cast<Constant>(opr) != NULL);
          scheme[i] = opr;
        }
      }

      this->addSpecialization(prin, scheme, spec, false);
      errs() << "recording specialization of '" << prin->getName() << "' to '" << spec->getName() << "'\n";
    }
#endif /* RECORD_IN_METADATA */
  }
예제 #14
0
MDNode *MDNode::getMostGenericTBAA(MDNode *A, MDNode *B) {
  if (!A || !B)
    return NULL;

  if (A == B)
    return A;

  // For struct-path aware TBAA, we use the access type of the tag.
  bool StructPath = isStructPathTBAA(A);
  if (StructPath) {
    A = cast_or_null<MDNode>(A->getOperand(1));
    if (!A) return 0;
    B = cast_or_null<MDNode>(B->getOperand(1));
    if (!B) return 0;
  }

  SmallVector<MDNode *, 4> PathA;
  MDNode *T = A;
  while (T) {
    PathA.push_back(T);
    T = T->getNumOperands() >= 2 ? cast_or_null<MDNode>(T->getOperand(1)) : 0;
  }

  SmallVector<MDNode *, 4> PathB;
  T = B;
  while (T) {
    PathB.push_back(T);
    T = T->getNumOperands() >= 2 ? cast_or_null<MDNode>(T->getOperand(1)) : 0;
  }

  int IA = PathA.size() - 1;
  int IB = PathB.size() - 1;

  MDNode *Ret = 0;
  while (IA >= 0 && IB >=0) {
    if (PathA[IA] == PathB[IB])
      Ret = PathA[IA];
    else
      break;
    --IA;
    --IB;
  }
  if (!StructPath)
    return Ret;

  if (!Ret)
    return 0;
  // We need to convert from a type node to a tag node.
  Type *Int64 = IntegerType::get(A->getContext(), 64);
  Value *Ops[3] = { Ret, Ret, ConstantInt::get(Int64, 0) };
  return MDNode::get(A->getContext(), Ops);
}
예제 #15
0
파일: IRParser.cpp 프로젝트: orcc/jade
Pattern* IRParser::parsePattern(map<std::string, Port*>* ports, Value* value){
    // No node for pattern
    if (value == NULL){
        return new Pattern();
    }

    MDNode* patternNode = cast<MDNode>(value);

    // Parse pattern property
    map<Port*, ConstantInt*>* numTokens = parserNumTokens(ports, patternNode->getOperand(0));
    map<Port*, Variable*>* varMap = parserVarMap(ports, patternNode->getOperand(1));

    return new Pattern(numTokens, varMap);
}
예제 #16
0
파일: Module.cpp 프로젝트: mapu/llvm
/// getModuleFlagsMetadata - Returns the module flags in the provided vector.
void Module::
getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> &Flags) const {
  const NamedMDNode *ModFlags = getModuleFlagsMetadata();
  if (!ModFlags) return;

  for (unsigned i = 0, e = ModFlags->getNumOperands(); i != e; ++i) {
    MDNode *Flag = ModFlags->getOperand(i);
    ConstantInt *Behavior = cast<ConstantInt>(Flag->getOperand(0));
    MDString *Key = cast<MDString>(Flag->getOperand(1));
    Value *Val = Flag->getOperand(2);
    Flags.push_back(ModuleFlagEntry(ModFlagBehavior(Behavior->getZExtValue()),
                                    Key, Val));
  }
}
예제 #17
0
/// Remap the operands of an MDNode.
///
/// If \c Node is temporary, uniquing cycles are ignored.  If \c Node is
/// distinct, uniquing cycles are resolved as they're found.
///
/// \pre \c Node.isDistinct() or \c Node.isTemporary().
static bool remapOperands(MDNode &Node,
                          SmallVectorImpl<MDNode *> &DistinctWorklist,
                          ValueToValueMapTy &VM, RemapFlags Flags,
                          ValueMapTypeRemapper *TypeMapper,
                          ValueMaterializer *Materializer) {
  assert(!Node.isUniqued() && "Expected temporary or distinct node");
  const bool IsDistinct = Node.isDistinct();

  bool AnyChanged = false;
  for (unsigned I = 0, E = Node.getNumOperands(); I != E; ++I) {
    Metadata *Old = Node.getOperand(I);
    Metadata *New = mapMetadataOp(Old, DistinctWorklist, VM, Flags, TypeMapper,
                                  Materializer);
    if (Old != New) {
      AnyChanged = true;
      Node.replaceOperandWith(I, New);

      // Resolve uniquing cycles underneath distinct nodes on the fly so they
      // don't infect later operands.
      if (IsDistinct)
        resolveCycles(New);
    }
  }

  return AnyChanged;
}
예제 #18
0
파일: LoopInfo.cpp 프로젝트: happz/llvm
MDNode *llvm::findOptionMDForLoopID(MDNode *LoopID, StringRef Name) {
  // No loop metadata node, no loop properties.
  if (!LoopID)
    return nullptr;

  // First operand should refer to the metadata node itself, for legacy reasons.
  assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
  assert(LoopID->getOperand(0) == LoopID && "invalid loop id");

  // Iterate over the metdata node operands and look for MDString metadata.
  for (unsigned i = 1, e = LoopID->getNumOperands(); i < e; ++i) {
    MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
    if (!MD || MD->getNumOperands() < 1)
      continue;
    MDString *S = dyn_cast<MDString>(MD->getOperand(0));
    if (!S)
      continue;
    // Return the operand node if MDString holds expected metadata.
    if (Name.equals(S->getString()))
      return MD;
  }

  // Loop property not found.
  return nullptr;
}
예제 #19
0
파일: IRParser.cpp 프로젝트: orcc/jade
Action* IRParser::getAction(llvm::MDNode* node) {
    Value* idValue = node->getOperand(0);

    if (idValue == NULL){
        map<Function*, Action*>::iterator it;

        // Action has not tag, find it by its function name
        Function* function = getBodyFunction(node);
        it = untaggedActions.find(function);

        return it->second;
    }

    //Get identifiers of action tag
    map<std::string, Action*>::iterator it;
    ActionTag tag;
    MDNode* idNode = cast<MDNode>(idValue);

    for (unsigned i = 0, e = idNode->getNumOperands(); i != e; ++i){
        MDString* tagMD = cast<MDString>(idNode->getOperand(i));
        tag.add(tagMD->getString());
    }

    it = actions.find(tag.getIdentifier());

    return it->second;
}
예제 #20
0
파일: LoopInfo.cpp 프로젝트: bryant/llvm
MDNode *Loop::getLoopID() const {
  MDNode *LoopID = nullptr;
  if (isLoopSimplifyForm()) {
    LoopID = getLoopLatch()->getTerminator()->getMetadata(LLVMContext::MD_loop);
  } else {
    // Go through each predecessor of the loop header and check the
    // terminator for the metadata.
    BasicBlock *H = getHeader();
    for (BasicBlock *BB : this->blocks()) {
      TerminatorInst *TI = BB->getTerminator();
      MDNode *MD = nullptr;

      // Check if this terminator branches to the loop header.
      for (BasicBlock *Successor : TI->successors()) {
        if (Successor == H) {
          MD = TI->getMetadata(LLVMContext::MD_loop);
          break;
        }
      }
      if (!MD)
        return nullptr;

      if (!LoopID)
        LoopID = MD;
      else if (MD != LoopID)
        return nullptr;
    }
  }
  if (!LoopID || LoopID->getNumOperands() == 0 ||
      LoopID->getOperand(0) != LoopID)
    return nullptr;
  return LoopID;
}
예제 #21
0
void Instruction::swapProfMetadata() {
  MDNode *ProfileData = getMetadata(LLVMContext::MD_prof);
  if (!ProfileData || ProfileData->getNumOperands() != 3 ||
      !isa<MDString>(ProfileData->getOperand(0)))
    return;

  MDString *MDName = cast<MDString>(ProfileData->getOperand(0));
  if (MDName->getString() != "branch_weights")
    return;

  // The first operand is the name. Fetch them backwards and build a new one.
  Metadata *Ops[] = {ProfileData->getOperand(0), ProfileData->getOperand(2),
                     ProfileData->getOperand(1)};
  setMetadata(LLVMContext::MD_prof,
              MDNode::get(ProfileData->getContext(), Ops));
}
예제 #22
0
MDNode *Loop::getLoopID() const {
  MDNode *LoopID = nullptr;
  if (isLoopSimplifyForm()) {
    LoopID = getLoopLatch()->getTerminator()->getMetadata(LoopMDName);
  } else {
    // Go through each predecessor of the loop header and check the
    // terminator for the metadata.
    BasicBlock *H = getHeader();
    for (block_iterator I = block_begin(), IE = block_end(); I != IE; ++I) {
      TerminatorInst *TI = (*I)->getTerminator();
      MDNode *MD = nullptr;

      // Check if this terminator branches to the loop header.
      for (unsigned i = 0, ie = TI->getNumSuccessors(); i != ie; ++i) {
        if (TI->getSuccessor(i) == H) {
          MD = TI->getMetadata(LoopMDName);
          break;
        }
      }
      if (!MD)
        return nullptr;

      if (!LoopID)
        LoopID = MD;
      else if (MD != LoopID)
        return nullptr;
    }
  }
  if (!LoopID || LoopID->getNumOperands() == 0 ||
      LoopID->getOperand(0) != LoopID)
    return nullptr;
  return LoopID;
}
예제 #23
0
/// parseMetadata - Parse metadata from the module
void LTOModule::parseMetadata() {
  raw_string_ostream OS(LinkerOpts);

  // Linker Options
  if (NamedMDNode *LinkerOptions =
          getModule().getNamedMetadata("llvm.linker.options")) {
    for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
      MDNode *MDOptions = LinkerOptions->getOperand(i);
      for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
        MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
        OS << " " << MDOption->getString();
      }
    }
  }

  // Globals - we only need to do this for COFF.
  const Triple TT(_target->getTargetTriple());
  if (!TT.isOSBinFormatCOFF())
    return;
  Mangler M;
  for (const NameAndAttributes &Sym : _symbols) {
    if (!Sym.symbol)
      continue;
    emitLinkerFlagsForGlobalCOFF(OS, Sym.symbol, TT, M);
  }

  // Add other interesting metadata here.
}
// Propagate existing explicit probabilities from either profile data or
// 'expect' intrinsic processing.
bool BranchProbabilityAnalysis::calcMetadataWeights(BasicBlock *BB) {
  TerminatorInst *TI = BB->getTerminator();
  if (TI->getNumSuccessors() == 1)
    return false;
  if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI))
    return false;

  MDNode *WeightsNode = TI->getMetadata(LLVMContext::MD_prof);
  if (!WeightsNode)
    return false;

  // Ensure there are weights for all of the successors. Note that the first
  // operand to the metadata node is a name, not a weight.
  if (WeightsNode->getNumOperands() != TI->getNumSuccessors() + 1)
    return false;

  // Build up the final weights that will be used in a temporary buffer, but
  // don't add them until all weihts are present. Each weight value is clamped
  // to [1, getMaxWeightFor(BB)].
  uint32_t WeightLimit = getMaxWeightFor(BB);
  SmallVector<uint32_t, 2> Weights;
  Weights.reserve(TI->getNumSuccessors());
  for (unsigned i = 1, e = WeightsNode->getNumOperands(); i != e; ++i) {
    ConstantInt *Weight = dyn_cast<ConstantInt>(WeightsNode->getOperand(i));
    if (!Weight)
      return false;
    Weights.push_back(
      std::max<uint32_t>(1, Weight->getLimitedValue(WeightLimit)));
  }
  assert(Weights.size() == TI->getNumSuccessors() && "Checked above");
  for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
    BP->setEdgeWeight(BB, TI->getSuccessor(i), Weights[i]);

  return true;
}
void TargetLoweringObjectFileCOFF::
emitModuleFlags(MCStreamer &Streamer,
                ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
                Mangler &Mang, const TargetMachine &TM) const {
  MDNode *LinkerOptions = nullptr;

  // Look for the "Linker Options" flag, since it's the only one we support.
  for (ArrayRef<Module::ModuleFlagEntry>::iterator
       i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
    const Module::ModuleFlagEntry &MFE = *i;
    StringRef Key = MFE.Key->getString();
    Value *Val = MFE.Val;
    if (Key == "Linker Options") {
      LinkerOptions = cast<MDNode>(Val);
      break;
    }
  }
  if (!LinkerOptions)
    return;

  // Emit the linker options to the linker .drectve section.  According to the
  // spec, this section is a space-separated string containing flags for linker.
  const MCSection *Sec = getDrectveSection();
  Streamer.SwitchSection(Sec);
  for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
    MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
    for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
      MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
      StringRef Op = MDOption->getString();
      // Lead with a space for consistency with our dllexport implementation.
      std::string Escaped(" ");
      if (Op.find(" ") != StringRef::npos) {
        // The PE-COFF spec says args with spaces must be quoted.  It doesn't say
        // how to escape quotes, but it probably uses this algorithm:
        // http://msdn.microsoft.com/en-us/library/17w5ykft(v=vs.85).aspx
        // FIXME: Reuse escaping code from Support/Windows/Program.inc
        Escaped.push_back('\"');
        Escaped.append(Op);
        Escaped.push_back('\"');
      } else {
        Escaped.append(Op);
      }
      Streamer.EmitBytes(Escaped);
    }
  }
}
예제 #26
0
unsigned IDManager::getInstructionID(const Instruction *I) const {
	MDNode *Node = I->getMetadata("ins_id");
	if (!Node)
		return INVALID_ID;
	assert(Node->getNumOperands() == 1);
	ConstantInt *CI = dyn_cast<ConstantInt>(Node->getOperand(0));
	assert(CI);
	return CI->getZExtValue();
}
예제 #27
0
void ScopAnnotator::annotateLoopLatch(BranchInst *B, Loop *L,
                                      bool IsParallel) const {
  if (!IsParallel)
    return;

  assert(!ParallelLoops.empty() && "Expected a parallel loop to annotate");
  MDNode *Ids = ParallelLoops.back();
  MDNode *Id = cast<MDNode>(Ids->getOperand(Ids->getNumOperands() - 1));
  B->setMetadata("llvm.loop", Id);
}
예제 #28
0
/// getModuleFlagsMetadata - Returns the module flags in the provided vector.
void Module::
getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> &Flags) const {
  const NamedMDNode *ModFlags = getModuleFlagsMetadata();
  if (!ModFlags) return;

  for (unsigned i = 0, e = ModFlags->getNumOperands(); i != e; ++i) {
    MDNode *Flag = ModFlags->getOperand(i);
    if (Flag->getNumOperands() >= 3 && isa<ConstantInt>(Flag->getOperand(0)) &&
        isa<MDString>(Flag->getOperand(1))) {
      // Check the operands of the MDNode before accessing the operands.
      // The verifier will actually catch these failures.
      ConstantInt *Behavior = cast<ConstantInt>(Flag->getOperand(0));
      MDString *Key = cast<MDString>(Flag->getOperand(1));
      Value *Val = Flag->getOperand(2);
      Flags.push_back(ModuleFlagEntry(ModFlagBehavior(Behavior->getZExtValue()),
                                      Key, Val));
    }
  }
}
예제 #29
0
void MDNodeMapper::remapOperands(MDNode &N, OperandMapper mapOperand) {
  assert(!N.isUniqued() && "Expected distinct or temporary nodes");
  for (unsigned I = 0, E = N.getNumOperands(); I != E; ++I) {
    Metadata *Old = N.getOperand(I);
    Metadata *New = mapOperand(Old);

    if (Old != New)
      N.replaceOperandWith(I, New);
  }
}
예제 #30
0
std::string GCOVProfiler::mangleName(DICompileUnit CU, std::string NewStem) {
  if (NamedMDNode *GCov = M->getNamedMetadata("llvm.gcov")) {
    for (int i = 0, e = GCov->getNumOperands(); i != e; ++i) {
      MDNode *N = GCov->getOperand(i);
      if (N->getNumOperands() != 2) continue;
      MDString *GCovFile = dyn_cast<MDString>(N->getOperand(0));
      MDNode *CompileUnit = dyn_cast<MDNode>(N->getOperand(1));
      if (!GCovFile || !CompileUnit) continue;
      if (CompileUnit == CU) {
        SmallString<128> Filename = GCovFile->getString();
        sys::path::replace_extension(Filename, NewStem);
        return Filename.str();
      }
    }
  }

  SmallString<128> Filename = CU.getFilename();
  sys::path::replace_extension(Filename, NewStem);
  return sys::path::filename(Filename.str());
}