• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C++ Value类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C++中Value的典型用法代码示例。如果您正苦于以下问题:C++ Value类的具体用法?C++ Value怎么用?C++ Value使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了Value类的18个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C++代码示例。

示例1: allocValue

Value* Builder::getConstantV256(V256 c) {
    Value* value = allocValue(TYPE_V256);
    value->setConstantV256(c);
    return value;
}
开发者ID:garyttierney,项目名称:nucleus,代码行数:5,代码来源:builder.cpp


示例2: parseSpell

	void parseSpell(Game& game, const Value& elem)
	{
		auto level = game.Resources().getLevel(getStringKey(elem, "level"));
		if (level == nullptr)
		{
			return;
		}
		std::string id;
		auto spell = parseSpellHelper(game, *level, elem, id);
		if (spell == nullptr)
		{
			return;
		}

		spell->Id(id);

		if (elem.HasMember("name") == true)
		{
			spell->Name(getStringVal(elem["name"]));
		}
		if (elem.HasMember("type") == true)
		{
			spell->SpellType(getStringVal(elem["type"]));
		}

		if (elem.HasMember("properties") == true)
		{
			const auto& props = elem["properties"];
			if (props.IsObject() == true)
			{
				for (auto it = props.MemberBegin(); it != props.MemberEnd(); ++it)
				{
					if (it->name.GetStringLength() > 0)
					{
						auto name = getStringViewVal(it->name);
						auto nameHash = str2int16(name);
						level->setPropertyName(nameHash, name);
						spell->setIntByHash(nameHash,
							getMinMaxIntVal<LevelObjValue>(it->value));
					}
				}
			}
		}

		if (elem.HasMember("descriptions") == true)
		{
			const auto& descriptions = elem["descriptions"];
			if (descriptions.IsObject() == true)
			{
				parseDescriptionValue(*spell, *level, descriptions);
			}
			else if (descriptions.IsArray() == true)
			{
				for (const auto& val : descriptions)
				{
					parseDescriptionValue(*spell, *level, val);
				}
			}
		}

		if (elem.HasMember("formulas") == true)
		{
			const auto& formulas = elem["formulas"];
			if (formulas.IsObject() == true)
			{
				for (auto it = formulas.MemberBegin(); it != formulas.MemberEnd(); ++it)
				{
					auto nameHash = str2int16(getStringViewVal(it->name));
					if (nameHash != str2int16(""))
					{
						spell->setFormula(nameHash, getStringVal(it->value));
					}
				}
			}
		}

		level->addClass(id, std::move(spell));
	}
开发者ID:dgengin,项目名称:DGEngine,代码行数:78,代码来源:ParseSpell.cpp


示例3: assert

Value * CallGen::generateCode(const Generater& generater)
{
	auto* m = generater.module;
	auto func = generater.func;
	auto& builder = generater.builder();

	if (!llvmFunction) {
		if (pointerGen) { // 函数指针
			Value* v = pointerGen->generate(generater);
			auto *x=dyn_cast<PointerType>(v->getType());

			if (x->getElementType()->isPointerTy()) {
				// 函数是作为指针保存的
				Type* t = PointerType::get(pointerGen->type, 0);
				// v = builder.CreateBitOrPointerCast(v, t);
				llvmFunction = builder.CreateLoad(v);
			} else {
				llvmFunction = v;
			}
		} else {
			assert(function);
			llvmFunction = function->generateCode(m, builder.getContext());
			funcType = function->func->getFunctionType();
		}
	}

	if(function)
		function->generateBody(m, builder.getContext());

	auto iter = funcType->param_begin();
	auto end = funcType->param_end();
	std::vector< llvm::Value* > a;
	if (object)
		putBack(builder, a, object->generate(generater), iter, end);
	for (auto *i : params) {
		Value* v = i->generate(generater);
		// 如果是基本类型
		if (i->type->isIntegerTy() || i->type->isFloatingPointTy()) {
			if (v->getType()->isPointerTy())
				v = builder.CreateLoad(v);
			putBack(builder, a, v, iter, end);
		} else if (i->type->isArrayTy()) {
			putBack(builder, a, v, iter, end);
			// 写入大小
			auto sz = i->type->getArrayNumElements();
			auto* s = ConstantInt::get(func->getContext(), APInt(32, sz));
			putBack(builder, a, s, iter, end);
		} else {
			putBack(builder, a, v, iter, end);
		}
	}

	std::clog << "Call func " << llvmFunction->getName().str() << std::endl;
	
	Value* v= builder.CreateCall(funcType, llvmFunction, a);

	// 添加一个强制转换,避免某些 c 函数返回的类型不一致
	if (type->isStructTy()) {
		Type* ty = llvm::PointerType::get(type, 0);
		return builder.CreateBitOrPointerCast(v, ty);
	}
	return v;
}
开发者ID:jadedrip,项目名称:silang,代码行数:63,代码来源:CallGen.cpp


示例4: AddMember

void JSONValue::AddBool(bool value)
{
    Value jsonValue;
    jsonValue.SetBool(value);
    AddMember(jsonValue);
}
开发者ID:AGreatFish,项目名称:Urho3D,代码行数:6,代码来源:JSONValue.cpp


示例5: exe_ctx

ValueObjectSP
ABISysV_mips64::GetReturnValueObjectImpl (Thread &thread, ClangASTType &return_clang_type) const
{
    ValueObjectSP return_valobj_sp;
    Value value;

    ExecutionContext exe_ctx (thread.shared_from_this());
    if (exe_ctx.GetTargetPtr() == NULL || exe_ctx.GetProcessPtr() == NULL)
        return return_valobj_sp;

    value.SetClangType(return_clang_type);

    RegisterContext *reg_ctx = thread.GetRegisterContext().get();
    if (!reg_ctx)
        return return_valobj_sp;

    const size_t byte_size = return_clang_type.GetByteSize(nullptr);
    const uint32_t type_flags = return_clang_type.GetTypeInfo (NULL);

    if (type_flags & eTypeIsScalar)
    {
        value.SetValueType(Value::eValueTypeScalar);

        bool success = false;
        if (type_flags & eTypeIsInteger)
        {
            // Extract the register context so we can read arguments from registers
            // In MIPS register "r2" (v0) holds the integer function return values

            uint64_t raw_value = reg_ctx->ReadRegisterAsUnsigned(reg_ctx->GetRegisterInfoByName("r2", 0), 0);

            const bool is_signed = (type_flags & eTypeIsSigned) != 0;
            switch (byte_size)
            {
                default:
                    break;

                case sizeof(uint64_t):
                    if (is_signed)
                        value.GetScalar() = (int64_t)(raw_value);
                    else
                        value.GetScalar() = (uint64_t)(raw_value);
                    success = true;
                    break;

                case sizeof(uint32_t):
                    if (is_signed)
                        value.GetScalar() = (int32_t)(raw_value & UINT32_MAX);
                    else
                        value.GetScalar() = (uint32_t)(raw_value & UINT32_MAX);
                    success = true;
                    break;

                case sizeof(uint16_t):
                    if (is_signed)
                        value.GetScalar() = (int16_t)(raw_value & UINT16_MAX);
                    else
                        value.GetScalar() = (uint16_t)(raw_value & UINT16_MAX);
                    success = true;
                    break;

                case sizeof(uint8_t):
                    if (is_signed)
                        value.GetScalar() = (int8_t)(raw_value & UINT8_MAX);
                    else
                        value.GetScalar() = (uint8_t)(raw_value & UINT8_MAX);
                    success = true;
                    break;
            }
        }

        if (success)
        return_valobj_sp = ValueObjectConstResult::Create (thread.GetStackFrameAtIndex(0).get(),
                                                           value,
                                                           ConstString(""));
    }
    else if (type_flags & eTypeIsPointer)
    {
        value.SetValueType(Value::eValueTypeScalar);
        uint64_t raw_value = reg_ctx->ReadRegisterAsUnsigned(reg_ctx->GetRegisterInfoByName("r2", 0), 0);
        value.GetScalar() = (uint64_t)(raw_value);

        return_valobj_sp = ValueObjectConstResult::Create (thread.GetStackFrameAtIndex(0).get(),
                                                           value,
                                                           ConstString(""));
    }
    else if (type_flags & eTypeIsVector)
    {
        // TODO: Handle vector types
    }
    return return_valobj_sp;
}
开发者ID:CTSRD-CHERI,项目名称:lldb,代码行数:92,代码来源:ABISysV_mips64.cpp


示例6: visitCmpInst

bool CallAnalyzer::visitCmpInst(CmpInst &I) {
  Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
  // First try to handle simplified comparisons.
  if (!isa<Constant>(LHS))
    if (Constant *SimpleLHS = SimplifiedValues.lookup(LHS))
      LHS = SimpleLHS;
  if (!isa<Constant>(RHS))
    if (Constant *SimpleRHS = SimplifiedValues.lookup(RHS))
      RHS = SimpleRHS;
  if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
    if (Constant *CRHS = dyn_cast<Constant>(RHS))
      if (Constant *C = ConstantExpr::getCompare(I.getPredicate(), CLHS, CRHS)) {
        SimplifiedValues[&I] = C;
        return true;
      }
  }

  if (I.getOpcode() == Instruction::FCmp)
    return false;

  // Otherwise look for a comparison between constant offset pointers with
  // a common base.
  Value *LHSBase, *RHSBase;
  APInt LHSOffset, RHSOffset;
  llvm::tie(LHSBase, LHSOffset) = ConstantOffsetPtrs.lookup(LHS);
  if (LHSBase) {
    llvm::tie(RHSBase, RHSOffset) = ConstantOffsetPtrs.lookup(RHS);
    if (RHSBase && LHSBase == RHSBase) {
      // We have common bases, fold the icmp to a constant based on the
      // offsets.
      Constant *CLHS = ConstantInt::get(LHS->getContext(), LHSOffset);
      Constant *CRHS = ConstantInt::get(RHS->getContext(), RHSOffset);
      if (Constant *C = ConstantExpr::getICmp(I.getPredicate(), CLHS, CRHS)) {
        SimplifiedValues[&I] = C;
        ++NumConstantPtrCmps;
        return true;
      }
    }
  }

  // If the comparison is an equality comparison with null, we can simplify it
  // for any alloca-derived argument.
  if (I.isEquality() && isa<ConstantPointerNull>(I.getOperand(1)))
    if (isAllocaDerivedArg(I.getOperand(0))) {
      // We can actually predict the result of comparisons between an
      // alloca-derived value and null. Note that this fires regardless of
      // SROA firing.
      bool IsNotEqual = I.getPredicate() == CmpInst::ICMP_NE;
      SimplifiedValues[&I] = IsNotEqual ? ConstantInt::getTrue(I.getType())
                                        : ConstantInt::getFalse(I.getType());
      return true;
    }

  // Finally check for SROA candidates in comparisons.
  Value *SROAArg;
  DenseMap<Value *, int>::iterator CostIt;
  if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt)) {
    if (isa<ConstantPointerNull>(I.getOperand(1))) {
      accumulateSROACost(CostIt, InlineConstants::InstrCost);
      return true;
    }

    disableSROA(CostIt);
  }

  return false;
}
开发者ID:adevress,项目名称:root-1,代码行数:67,代码来源:InlineCost.cpp


示例7: main

int main(int argc, char *argv[])
{
    // usual stuff...
    Network yarp;
    if (!yarp.checkNetwork())
    {
        printf("YARP is not available!\n");
        return 1;
    }

    ResourceFinder rf;
    rf.configure(argc,argv);

    string name=rf.check("name",Value("tuner")).asString();
    string robot=rf.check("robot",Value("icub")).asString();
    string part=rf.check("part",Value("right_arm")).asString();
    int joint=rf.check("joint",Value(11)).asInt();
    double encoder=rf.check("encoder",Value(2.43)).asDouble();

    Property pOptions;
    pOptions.put("device","remote_controlboard");
    pOptions.put("remote","/"+robot+"/"+part);
    pOptions.put("local","/"+name+"/"+part);
    PolyDriver driver(pOptions);
    if (!driver.isValid())
    {
        printf("Part \"%s\" is not ready!\n",string("/"+robot+"/"+part).c_str());
        return 1;
    }

    // ##### Preamble
    // The objective is to tune online a P controller that will make 
    // the joint move complying with some given bandwidth specification.
    //
    // The plant is to be identified using an Extended-Kalman-Filter (EKF)
    // under the assumption that the adopted model obeys to the following
    // tansfer function which gives out the position when fed with voltage:
    //
    // K / (s*(1 + tau*s))
    //
    // You might have realized that we disregard the electrical dynamics in
    // favour of the slower mechanical one represented by the time constant tau.
    //
    // ##### Additional notes on the control design
    // The low-level layer provides the user with a PID controller. However, the
    // I part is not specifically required for such control task since by virtue
    // of the internal model principle the steady-state error can be already 
    // compensated thanks to the presence of the integrator in the plant. On the
    // other hand, this principle holds only for linear systems and indeed,
    // nonlinear effects - such as the stiction - make the final behavior deviate
    // from this baseline, eventually requiring the integral part. Nonetheless,
    // if stiction is compensated separately, I is again not strictly needed.
    // 
    // Finally, a few words about the D part. In order to include D within the design,
    // the derivative part must be implemented according to the standard which states
    // that D = Kd*s / (1 + tau_d*s).
    //
    // In the following a short example will guide you through the steps required
    // to identify the plant, validate the retrieved model and then design the
    // P controller that meets the user specifications. Stiction identification is
    // carried out as well.

    // First thing to do is to prepare configuration options
    // which are to be given in the form:
    //
    // [general]
    // joint ...
    // port  ...
    // [plant_estimation]
    // Ts    ...
    // ...
    // [stiction_estimation]
    // ...
    Property pGeneral;
    pGeneral.put("joint",joint);
    // the "port" option allows opening up a yarp port which
    // will stream out useful information while identifying
    // and validating the system
    pGeneral.put("port","/"+name+"/info:o");
    string sGeneral="(general ";
    sGeneral+=pGeneral.toString();
    sGeneral+=')';

    Bottle bGeneral,bPlantEstimation,bStictionEstimation;
    bGeneral.fromString(sGeneral);
    // here follow the parameters for the EKF along with the
    // initial values for tau and K
    bPlantEstimation.fromString("(plant_estimation (Ts 0.01) (Q 1.0) (R 1.0) (P0 100000.0) (tau 1.0) (K 1.0) (max_pwm 800.0))");
    bStictionEstimation.fromString("(stiction_estimation (Ts 0.01) (T 2.0) (vel_thres 5.0) (e_thres 1.0) (gamma (10.0 10.0)) (stiction (0.0 0.0)))");

    // compose the overall configuration
    Bottle bConf=bGeneral;
    bConf.append(bPlantEstimation);
    bConf.append(bStictionEstimation);
    pOptions.fromString(bConf.toString());

    OnlineCompensatorDesign designer;
    if (!designer.configure(driver,pOptions))
    {
        printf("Configuration failed!\n");
//.........这里部分代码省略.........
开发者ID:robotology,项目名称:icub-tutorials,代码行数:101,代码来源:main.cpp


示例8: i18n

void ValidityDialog::OkPressed()
{
    const KLocale* locale = m_selection->activeSheet()->map()->calculationSettings()->locale();
    const ValueParser *const parser = m_selection->activeSheet()->map()->parser();
    Validity validity;
    if (chooseType->currentIndex() == 1) {
        bool ok;
        val_min->text().toDouble(&ok);
        if (! ok) {
            KMessageBox::error(this , i18n("This is not a valid value."), i18n("Error"));
            val_min->setText("");
            return;
        }
        val_max->text().toDouble(&ok);
        if (! ok && choose->currentIndex() >= 5 && choose->currentIndex() < 7) {
            KMessageBox::error(this , i18n("This is not a valid value."), i18n("Error"));
            val_max->setText("");
            return;
        }
    } else if (chooseType->currentIndex() == 2 || chooseType->currentIndex() == 6) {
        bool ok;
        val_min->text().toInt(&ok);
        if (! ok) {
            KMessageBox::error(this , i18n("This is not a valid value."), i18n("Error"));
            val_min->setText("");
            return;
        }
        val_max->text().toInt(&ok);
        if (! ok && choose->currentIndex() >= 5 && choose->currentIndex() < 7) {
            KMessageBox::error(this , i18n("This is not a valid value."), i18n("Error"));
            val_max->setText("");
            return;
        }
    } else  if (chooseType->currentIndex() == 5) {
        if (!locale->readTime(val_min->text()).isValid()) {
            KMessageBox::error(this , i18n("This is not a valid time."), i18n("Error"));
            val_min->setText("");
            return;
        }
        if (!locale->readTime(val_max->text()).isValid() && choose->currentIndex()  >= 5) {
            KMessageBox::error(this , i18n("This is not a valid time."), i18n("Error"));
            val_max->setText("");
            return;
        }
    } else  if (chooseType->currentIndex() == 4) {
        if (!locale->readDate(val_min->text()).isValid()) {
            KMessageBox::error(this , i18n("This is not a valid date."), i18n("Error"));
            val_min->setText("");
            return;
        }
        if (!locale->readDate(val_max->text()).isValid() && choose->currentIndex()  >= 5) {
            KMessageBox::error(this , i18n("This is not a valid date."), i18n("Error"));
            val_max->setText("");
            return;
        }
    } else if (chooseType->currentIndex() == 7) {
        //Nothing
    }

    if (chooseType->currentIndex() == 0) {//no validity
        validity.setRestriction(Validity::None);
        validity.setAction(Validity::Stop);
        validity.setCondition(Conditional::Equal);
        validity.setMessage(message->toPlainText());
        validity.setTitle(title->text());
        validity.setMinimumValue(Value());
        validity.setMaximumValue(Value());
    } else {
        validity.setRestriction(chooseType->itemData(chooseType->currentIndex()).value<Validity::Restriction>());
        validity.setAction(chooseAction->itemData(chooseAction->currentIndex()).value<Validity::Action>());
        validity.setCondition(choose->itemData(choose->currentIndex()).value<Conditional::Type>());
        validity.setMessage(message->toPlainText());
        validity.setTitle(title->text());
        validity.setMinimumValue(Value());
        validity.setMaximumValue(Value());

        if (chooseType->currentIndex() == 1) {
            if (choose->currentIndex()  < 5) {
                validity.setMinimumValue(Value(val_min->text().toDouble()));
            } else {
                validity.setMinimumValue(Value(qMin(val_min->text().toDouble(), val_max->text().toDouble())));
                validity.setMaximumValue(Value(qMax(val_max->text().toDouble(), val_min->text().toDouble())));
            }
        } else if (chooseType->currentIndex() == 2 || chooseType->currentIndex() == 6) {
            if (choose->currentIndex()  < 5) {
                validity.setMinimumValue(Value(val_min->text().toInt()));
            } else {
                validity.setMinimumValue(Value(qMin(val_min->text().toInt(), val_max->text().toInt())));
                validity.setMaximumValue(Value(qMax(val_max->text().toInt(), val_min->text().toInt())));
            }
        } else  if (chooseType->currentIndex() == 4) {
            const Value minValue = parser->tryParseDate(val_min->text());
            const Value maxValue = parser->tryParseDate(val_max->text());
            if (choose->currentIndex()  < 5) {
                validity.setMinimumValue(minValue);
            } else {
                if (minValue.less(maxValue)) {
                    validity.setMinimumValue(minValue);
                    validity.setMaximumValue(maxValue);
                } else {
//.........这里部分代码省略.........
开发者ID:crayonink,项目名称:calligra-2,代码行数:101,代码来源:ValidityDialog.cpp


示例9: Exception

static JSBool
Exception(JSContext *cx, uintN argc, Value *vp)
{
    JSString *message, *filename;
    JSStackFrame *fp;

    /*
     * ECMA ed. 3, 15.11.1 requires Error, etc., to construct even when
     * called as functions, without operator new.  But as we do not give
     * each constructor a distinct JSClass, whose .name member is used by
     * NewNativeClassInstance to find the class prototype, we must get the
     * class prototype ourselves.
     */
    JSObject &callee = vp[0].toObject();
    Value protov;
    if (!callee.getProperty(cx, ATOM_TO_JSID(cx->runtime->atomState.classPrototypeAtom), &protov))
        return JS_FALSE;

    if (!protov.isObject()) {
        JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_BAD_PROTOTYPE, "Error");
        return JS_FALSE;
    }

    JSObject *errProto = &protov.toObject();
    JSObject *obj = NewNativeClassInstance(cx, &js_ErrorClass, errProto, errProto->getParent());
    if (!obj)
        return JS_FALSE;

    /*
     * If it's a new object of class Exception, then null out the private
     * data so that the finalizer doesn't attempt to free it.
     */
    if (obj->getClass() == &js_ErrorClass)
        obj->setPrivate(NULL);

    /* Set the 'message' property. */
    Value *argv = vp + 2;
    if (argc != 0) {
        message = js_ValueToString(cx, argv[0]);
        if (!message)
            return JS_FALSE;
        argv[0].setString(message);
    } else {
        message = cx->runtime->emptyString;
    }

    /* Set the 'fileName' property. */
    if (argc > 1) {
        filename = js_ValueToString(cx, argv[1]);
        if (!filename)
            return JS_FALSE;
        argv[1].setString(filename);
        fp = NULL;
    } else {
        fp = js_GetScriptedCaller(cx, NULL);
        if (fp) {
            filename = FilenameToString(cx, fp->script()->filename);
            if (!filename)
                return JS_FALSE;
        } else {
            filename = cx->runtime->emptyString;
        }
    }

    /* Set the 'lineNumber' property. */
    uint32_t lineno;
    if (argc > 2) {
        if (!ValueToECMAUint32(cx, argv[2], &lineno))
            return JS_FALSE;
    } else {
        if (!fp)
            fp = js_GetScriptedCaller(cx, NULL);
        lineno = (fp && fp->pc(cx)) ? js_FramePCToLineNumber(cx, fp) : 0;
    }

    if (obj->getClass() == &js_ErrorClass &&
        !InitExnPrivate(cx, obj, message, filename, lineno, NULL)) {
        return JS_FALSE;
    }

    vp->setObject(*obj);
    return JS_TRUE;
}
开发者ID:sahlberg,项目名称:timberwolf,代码行数:83,代码来源:jsexn.cpp


示例10: errs

void ComputeSSO::PrintTainted(std::set<GraphNode*> tainted)
{
    //  errs()<<"\n\n Tainted Nodes: "<<tainted.size();


    for(set<GraphNode*>::iterator taintNode = tainted.begin();taintNode != tainted.end();++taintNode)
    {
        //errs()<<"\n Node Label : "<<(*taintNode)->getLabel();
        // errs()<<"--";
        if(isa<MemNode>(*taintNode))
        {
            // errs()<<"\n is mem node";
            //string nodeLab = (*taintNode)->getLabel();
           // string str = "sub_42BC4";
          //  std::size_t found = nodeLab.find(str);
            // if (found!=std::string::npos || 1)
            {

                MemNode * memNew = dyn_cast<MemNode>(*taintNode);
                Value * val = memNew->defLocation.second;
                std::set<Value*> aliases = memNew->getAliases();

                if(val)
                {
                    errs()<<"\n Sink Node Tainted : "<<(*taintNode)->getLabel();
                    if(isa<Instruction>(val))
                    {
                        Instruction * inst = dyn_cast<Instruction>(val);
                        string funcName = inst->getParent()->getParent()->getName();
                        errs()<<"\n Function: "<<funcName;
                    }
                    val->dump();
                }
                if(aliases.size()>0)
                    errs()<<"\n Sink Node Tainted : "<<(*taintNode)->getLabel();
                for(set<Value*>::iterator alVal = aliases.begin(); alVal != aliases.end();++alVal)
                {
                    if(isa<Instruction>(*alVal))
                    {
                        Instruction * inst = dyn_cast<Instruction>(*alVal);
                        string funcName = inst->getParent()->getParent()->getName();
                        errs()<<"\n Function: "<<funcName;
                    }
                    (*alVal)->dump();
                }
            }

        }
        if(isa<VarNode>(*taintNode))
        {
            VarNode * varNew = dyn_cast<VarNode>(*taintNode);
            Value * val = varNew->getValue(); //->defLocation.second;
            if(val)
            {
                errs()<<"\n Sink Node Tainted : "<<(*taintNode)->getLabel();
                if(isa<Instruction>(val))
                {
                    Instruction * inst = dyn_cast<Instruction>(val);
                    string funcName = inst->getParent()->getParent()->getName();
                    errs()<<"\n Function: "<<funcName;
                }
                val->dump();
            }
        }
        //if
    }
}
开发者ID:jamella,项目名称:TaintFlowAnalysis,代码行数:67,代码来源:computesso.cpp


示例11: MemoryLocation

/// processByValArgument - This is called on every byval argument in call sites.
bool MemCpyOpt::processByValArgument(CallSite CS, unsigned ArgNo) {
  const DataLayout &DL = CS.getCaller()->getParent()->getDataLayout();
  // Find out what feeds this byval argument.
  Value *ByValArg = CS.getArgument(ArgNo);
  Type *ByValTy = cast<PointerType>(ByValArg->getType())->getElementType();
  uint64_t ByValSize = DL.getTypeAllocSize(ByValTy);
  MemDepResult DepInfo = MD->getPointerDependencyFrom(
      MemoryLocation(ByValArg, ByValSize), true, CS.getInstruction(),
      CS.getInstruction()->getParent());
  if (!DepInfo.isClobber())
    return false;

  // If the byval argument isn't fed by a memcpy, ignore it.  If it is fed by
  // a memcpy, see if we can byval from the source of the memcpy instead of the
  // result.
  MemCpyInst *MDep = dyn_cast<MemCpyInst>(DepInfo.getInst());
  if (!MDep || MDep->isVolatile() ||
      ByValArg->stripPointerCasts() != MDep->getDest())
    return false;

  // The length of the memcpy must be larger or equal to the size of the byval.
  ConstantInt *C1 = dyn_cast<ConstantInt>(MDep->getLength());
  if (!C1 || C1->getValue().getZExtValue() < ByValSize)
    return false;

  // Get the alignment of the byval.  If the call doesn't specify the alignment,
  // then it is some target specific value that we can't know.
  unsigned ByValAlign = CS.getParamAlignment(ArgNo+1);
  if (ByValAlign == 0) return false;

  // If it is greater than the memcpy, then we check to see if we can force the
  // source of the memcpy to the alignment we need.  If we fail, we bail out.
  AssumptionCache &AC =
      getAnalysis<AssumptionCacheTracker>().getAssumptionCache(
          *CS->getParent()->getParent());
  DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
  if (MDep->getAlignment() < ByValAlign &&
      getOrEnforceKnownAlignment(MDep->getSource(), ByValAlign, DL,
                                 CS.getInstruction(), &AC, &DT) < ByValAlign)
    return false;

  // Verify that the copied-from memory doesn't change in between the memcpy and
  // the byval call.
  //    memcpy(a <- b)
  //    *b = 42;
  //    foo(*a)
  // It would be invalid to transform the second memcpy into foo(*b).
  //
  // NOTE: This is conservative, it will stop on any read from the source loc,
  // not just the defining memcpy.
  MemDepResult SourceDep =
      MD->getPointerDependencyFrom(MemoryLocation::getForSource(MDep), false,
                                   CS.getInstruction(), MDep->getParent());
  if (!SourceDep.isClobber() || SourceDep.getInst() != MDep)
    return false;

  Value *TmpCast = MDep->getSource();
  if (MDep->getSource()->getType() != ByValArg->getType())
    TmpCast = new BitCastInst(MDep->getSource(), ByValArg->getType(),
                              "tmpcast", CS.getInstruction());

  DEBUG(dbgs() << "MemCpyOpt: Forwarding memcpy to byval:\n"
               << "  " << *MDep << "\n"
               << "  " << *CS.getInstruction() << "\n");

  // Otherwise we're good!  Update the byval argument.
  CS.setArgument(ArgNo, TmpCast);
  ++NumMemCpyInstr;
  return true;
}
开发者ID:EdwardBetts,项目名称:expert-disco,代码行数:71,代码来源:MemCpyOptimizer.cpp


示例12: CS

/// performCallSlotOptzn - takes a memcpy and a call that it depends on,
/// and checks for the possibility of a call slot optimization by having
/// the call write its result directly into the destination of the memcpy.
bool MemCpyOpt::performCallSlotOptzn(Instruction *cpy,
                                     Value *cpyDest, Value *cpySrc,
                                     uint64_t cpyLen, unsigned cpyAlign,
                                     CallInst *C) {
  // The general transformation to keep in mind is
  //
  //   call @func(..., src, ...)
  //   memcpy(dest, src, ...)
  //
  // ->
  //
  //   memcpy(dest, src, ...)
  //   call @func(..., dest, ...)
  //
  // Since moving the memcpy is technically awkward, we additionally check that
  // src only holds uninitialized values at the moment of the call, meaning that
  // the memcpy can be discarded rather than moved.

  // Deliberately get the source and destination with bitcasts stripped away,
  // because we'll need to do type comparisons based on the underlying type.
  CallSite CS(C);

  // Require that src be an alloca.  This simplifies the reasoning considerably.
  AllocaInst *srcAlloca = dyn_cast<AllocaInst>(cpySrc);
  if (!srcAlloca)
    return false;

  ConstantInt *srcArraySize = dyn_cast<ConstantInt>(srcAlloca->getArraySize());
  if (!srcArraySize)
    return false;

  const DataLayout &DL = cpy->getModule()->getDataLayout();
  uint64_t srcSize = DL.getTypeAllocSize(srcAlloca->getAllocatedType()) *
                     srcArraySize->getZExtValue();

  if (cpyLen < srcSize)
    return false;

  // Check that accessing the first srcSize bytes of dest will not cause a
  // trap.  Otherwise the transform is invalid since it might cause a trap
  // to occur earlier than it otherwise would.
  if (AllocaInst *A = dyn_cast<AllocaInst>(cpyDest)) {
    // The destination is an alloca.  Check it is larger than srcSize.
    ConstantInt *destArraySize = dyn_cast<ConstantInt>(A->getArraySize());
    if (!destArraySize)
      return false;

    uint64_t destSize = DL.getTypeAllocSize(A->getAllocatedType()) *
                        destArraySize->getZExtValue();

    if (destSize < srcSize)
      return false;
  } else if (Argument *A = dyn_cast<Argument>(cpyDest)) {
    if (A->getDereferenceableBytes() < srcSize) {
      // If the destination is an sret parameter then only accesses that are
      // outside of the returned struct type can trap.
      if (!A->hasStructRetAttr())
        return false;

      Type *StructTy = cast<PointerType>(A->getType())->getElementType();
      if (!StructTy->isSized()) {
        // The call may never return and hence the copy-instruction may never
        // be executed, and therefore it's not safe to say "the destination
        // has at least <cpyLen> bytes, as implied by the copy-instruction",
        return false;
      }

      uint64_t destSize = DL.getTypeAllocSize(StructTy);
      if (destSize < srcSize)
        return false;
    }
  } else {
    return false;
  }

  // Check that dest points to memory that is at least as aligned as src.
  unsigned srcAlign = srcAlloca->getAlignment();
  if (!srcAlign)
    srcAlign = DL.getABITypeAlignment(srcAlloca->getAllocatedType());
  bool isDestSufficientlyAligned = srcAlign <= cpyAlign;
  // If dest is not aligned enough and we can't increase its alignment then
  // bail out.
  if (!isDestSufficientlyAligned && !isa<AllocaInst>(cpyDest))
    return false;

  // Check that src is not accessed except via the call and the memcpy.  This
  // guarantees that it holds only undefined values when passed in (so the final
  // memcpy can be dropped), that it is not read or written between the call and
  // the memcpy, and that writing beyond the end of it is undefined.
  SmallVector<User*, 8> srcUseList(srcAlloca->user_begin(),
                                   srcAlloca->user_end());
  while (!srcUseList.empty()) {
    User *U = srcUseList.pop_back_val();

    if (isa<BitCastInst>(U) || isa<AddrSpaceCastInst>(U)) {
      for (User *UU : U->users())
        srcUseList.push_back(UU);
//.........这里部分代码省略.........
开发者ID:EdwardBetts,项目名称:expert-disco,代码行数:101,代码来源:MemCpyOptimizer.cpp


示例13: parseSpellHelper

	std::unique_ptr<Spell> parseSpellHelper(const Game& game,
		const Level& level, const Value& elem, std::string& id)
	{
		if (isValidString(elem, "id") == false)
		{
			return nullptr;
		}
		id = std::string(elem["id"].GetString());
		if (isValidId(id) == false)
		{
			return nullptr;
		}
		if (level.hasClass(id) == true)
		{
			return nullptr;
		}

		std::unique_ptr<Spell> spell;

		if (isValidString(elem, "fromId") == true)
		{
			std::string fromId(elem["fromId"].GetString());
			if (fromId != id)
			{
				auto obj = level.getClass<Spell>(fromId);
				if (obj == nullptr)
				{
					return nullptr;
				}
				spell = std::make_unique<Spell>(*obj);
			}
		}

		auto texturePack1 = game.Resources().getTexturePack(
			getStringKey(elem, "texturePack1"));
		auto texturePack2 = game.Resources().getTexturePack(
			getStringKey(elem, "texturePack2"));

		auto textureIndex1 = (size_t)getUIntKey(elem, "textureIndex1");
		auto textureIndex2 = (size_t)getUIntKey(elem, "textureIndex2");

		if (spell == nullptr)
		{
			if (texturePack1 != nullptr &&
				texturePack2 != nullptr)
			{
				spell = std::make_unique<Spell>(
					texturePack1, texturePack2, textureIndex1, textureIndex2);
			}
		}
		else
		{
			if (texturePack1 != nullptr)
			{
				spell->setTexturePack1(texturePack1);
			}
			if (texturePack2 != nullptr)
			{
				spell->setTexturePack2(texturePack2);
			}
			if (elem.HasMember("textureIndex1") == true)
			{
				spell->setTextureIndex1(textureIndex1);
			}
			if (elem.HasMember("textureIndex2") == true)
			{
				spell->setTextureIndex2(textureIndex2);
			}
		}
		return spell;
	}
开发者ID:dgengin,项目名称:DGEngine,代码行数:71,代码来源:ParseSpell.cpp


示例14: script

void
StackFrame::initFromBailout(JSContext *cx, SnapshotIterator &iter)
{
    AutoAssertNoGC nogc;
    uint32_t exprStackSlots = iter.slots() - script()->nfixed;

#ifdef TRACK_SNAPSHOTS
    iter.spewBailingFrom();
#endif
    IonSpew(IonSpew_Bailouts, " expr stack slots %u, is function frame %u",
            exprStackSlots, isFunctionFrame());

    if (iter.bailoutKind() == Bailout_ArgumentCheck) {
        // Temporary hack -- skip the (unused) scopeChain, because it could be
        // bogus (we can fail before the scope chain slot is set). Strip the
        // hasScopeChain flag and we'll check this later to run prologue().
        iter.skip();
        flags_ &= ~StackFrame::HAS_SCOPECHAIN;
    } else {
        Value v = iter.read();
        if (v.isObject()) {
            scopeChain_ = &v.toObject();
            flags_ |= StackFrame::HAS_SCOPECHAIN;
            if (isFunctionFrame() && fun()->isHeavyweight())
                flags_ |= StackFrame::HAS_CALL_OBJ;
        } else {
            JS_ASSERT(v.isUndefined());
        }
    }

    // Assume that all new stack frames have had their entry flag set if
    // profiling has been turned on. This will be corrected if necessary
    // elsewhere.
    if (cx->runtime->spsProfiler.enabled())
        setPushedSPSFrame();

    if (isFunctionFrame()) {
        Value thisv = iter.read();
        formals()[-1] = thisv;

        // The new |this| must have already been constructed prior to an Ion
        // constructor running.
        if (isConstructing())
            JS_ASSERT(!thisv.isPrimitive());

        JS_ASSERT(iter.slots() >= CountArgSlots(fun()));
        IonSpew(IonSpew_Bailouts, " frame slots %u, nargs %u, nfixed %u",
                iter.slots(), fun()->nargs, script()->nfixed);

        for (uint32_t i = 0; i < fun()->nargs; i++) {
            Value arg = iter.read();
            formals()[i] = arg;
        }
    }
    exprStackSlots -= CountArgSlots(maybeFun());

    for (uint32_t i = 0; i < script()->nfixed; i++) {
        Value slot = iter.read();
        slots()[i] = slot;
    }

    IonSpew(IonSpew_Bailouts, " pushing %u expression stack slots", exprStackSlots);
    FrameRegs &regs = cx->regs();
    for (uint32_t i = 0; i < exprStackSlots; i++) {
        Value v;

        // If coming from an invalidation bailout, and this is the topmost
        // value, and a value override has been specified, don't read from the
        // iterator. Otherwise, we risk using a garbage value.
        if (!iter.moreFrames() && i == exprStackSlots - 1 && cx->runtime->hasIonReturnOverride())
            v = iter.skip();
        else
            v = iter.read();

        *regs.sp++ = v;
    }
    unsigned pcOff = iter.pcOffset();
    regs.pc = script()->code + pcOff;

    if (iter.resumeAfter())
        regs.pc = GetNextPc(regs.pc);

    IonSpew(IonSpew_Bailouts, " new PC is offset %u within script %p (line %d)",
            pcOff, (void *)script(), PCToLineNumber(script(), regs.pc));
    JS_ASSERT(exprStackSlots == js_ReconstructStackDepth(cx, script(), regs.pc));
}
开发者ID:lofter2011,项目名称:Icefox,代码行数:86,代码来源:Bailouts.cpp


示例15: XmlExecuteMultiCall

static void XmlExecuteMultiCall(MethodManager* manager, Value &params, Value &result)
{
    log_debug("ExecuteMultiCall: params= " << params);

    result.SetSize(params.Size());
    for (int i=0; i<(int)params.Size(); i++)
    {
        Value singleParams;
        singleParams.Assign(params[i]);
        log_debug("Execute index " << i << ": params= " << singleParams);
        if (!singleParams.IsMap() ||
            !singleParams.HasMember("methodName") ||
            !singleParams["methodName"].IsString() ||
            !singleParams.HasMember("params"))
            XmlGenerateFaultValue(AnyRpcErrorInvalidRequest, "Invalid request", result[i]);
        else
        {
            Value singleResult;
            Value methodName = singleParams["methodName"];
            try
            {
                if (manager->ExecuteMethod(methodName.GetString(),singleParams["params"],singleResult))
                {
                    if (singleResult.IsInvalid())
                        singleResult = "";
                    result[i][0] = singleResult;
                }
                else
                    XmlGenerateFaultValue(AnyRpcErrorMethodNotFound, "Method not found", result[i] );
            }
            catch (const AnyRpcException& fault)
            {
                XmlGenerateFaultValue(fault.GetCode(), fault.GetMessage(), result[i]);
            }
        }
    }
    log_debug("ExecuteMultiCall: result= " << result);
}
开发者ID:JanPlitzkow,项目名称:anyrpc,代码行数:38,代码来源:xmlserver.cpp


示例16: CallRPC

Object CallRPC(const string& strMethod, const Array& params)
{
    if (mapArgs["-rpcuser"] == "" && mapArgs["-rpcpassword"] == "")
        throw runtime_error(strprintf(
            _("You must set rpcpassword=<password> in the configuration file:\n%s\n"
              "If the file does not exist, create it with owner-readable-only file permissions."),
                GetConfigFile().string().c_str()));

    // Connect to localhost
    bool fUseSSL = GetBoolArg("-rpcssl", false);
    asio::io_service io_service;
    ssl::context context(io_service, ssl::context::sslv23);
    context.set_options(ssl::context::no_sslv2 | ssl::context::no_sslv3);
    asio::ssl::stream<asio::ip::tcp::socket> sslStream(io_service, context);
    SSLIOStreamDevice<asio::ip::tcp> d(sslStream, fUseSSL);
    iostreams::stream< SSLIOStreamDevice<asio::ip::tcp> > stream(d);

    bool fWait = GetBoolArg("-rpcwait", false); // -rpcwait means try until server has started
    do {
        bool fConnected = d.connect(GetArg("-rpcconnect", "127.0.0.1"), GetArg("-rpcport", itostr(Params().RPCPort())));
        if (fConnected) break;
        if (fWait)
            MilliSleep(1000);
        else
            throw runtime_error("couldn't connect to server");
    } while (fWait);

    // HTTP basic authentication
    string strUserPass64 = EncodeBase64(mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"]);
    map<string, string> mapRequestHeaders;
    mapRequestHeaders["Authorization"] = string("Basic ") + strUserPass64;

    // Send request
    string strRequest = JSONRPCRequest(strMethod, params, 1);
    string strPost = HTTPPost(strRequest, mapRequestHeaders);
    stream << strPost << std::flush;

    // Receive HTTP reply status
    int nProto = 0;
    int nStatus = ReadHTTPStatus(stream, nProto);

    // Receive HTTP reply message headers and body
    map<string, string> mapHeaders;
    string strReply;
    ReadHTTPMessage(stream, mapHeaders, strReply, nProto);

    if (nStatus == HTTP_UNAUTHORIZED)
        throw runtime_error("incorrect rpcuser or rpcpassword (authorization failed)");
    else if (nStatus >= 400 && nStatus != HTTP 

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C++ ValueAnimationInfo类代码示例发布时间:2022-05-31
下一篇:
C++ Validity类代码示例发布时间:2022-05-31
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap