[midend]暂时仅用了魔数优化除法的手段

This commit is contained in:
rain2133
2025-08-19 08:56:51 +08:00
parent 839791e862
commit ad5f35c1a0
2 changed files with 21 additions and 19 deletions

View File

@@ -671,13 +671,13 @@ bool GlobalStrengthReductionContext::reduceDivision(BinaryInst *inst) {
} }
// x / c = x * magic_number (魔数乘法优化 - 使用libdivide算法) // x / c = x * magic_number (魔数乘法优化 - 使用libdivide算法)
if (isConstantInt(rhs, constVal) && constVal > 1 && constVal != (uint32_t)(-1)) { // if (isConstantInt(rhs, constVal) && constVal > 1 && constVal != (uint32_t)(-1)) {
// auto magicPair = computeMulhMagicNumbers(static_cast<int>(constVal)); // // auto magicPair = computeMulhMagicNumbers(static_cast<int>(constVal));
Value* magicResult = createMagicDivisionLibdivide(inst, static_cast<int>(constVal)); // Value* magicResult = createMagicDivisionLibdivide(inst, static_cast<int>(constVal));
replaceWithOptimized(inst, magicResult); // replaceWithOptimized(inst, magicResult);
divisionOptCount++; // divisionOptCount++;
return true; // return true;
} // }
return false; return false;
} }

View File

@@ -661,9 +661,9 @@ bool StrengthReductionContext::replaceOriginalInstruction(StrengthReductionCandi
case StrengthReductionCandidate::DIVIDE_CONST: { case StrengthReductionCandidate::DIVIDE_CONST: {
// 任意常数除法 // 任意常数除法
builder->setPosition(candidate->containingBlock, // builder->setPosition(candidate->containingBlock,
candidate->containingBlock->findInstIterator(candidate->originalInst)); // candidate->containingBlock->findInstIterator(candidate->originalInst));
replacementValue = generateConstantDivisionReplacement(candidate, builder); // replacementValue = generateConstantDivisionReplacement(candidate, builder);
break; break;
} }
@@ -683,17 +683,19 @@ bool StrengthReductionContext::replaceOriginalInstruction(StrengthReductionCandi
); );
// 检查原值是否为负数 // 检查原值是否为负数
Value* zero = ConstantInteger::get(0); Value* shift31condidata = builder->createBinaryInst(
Value* isNegative = builder->createICmpLTInst(candidate->inductionVar, zero); Instruction::Kind::kSra, candidate->inductionVar->getType(),
candidate->inductionVar, ConstantInteger::get(31)
);
// 如果为负数,需要调整结果 // 如果为负数,需要调整结果
Value* adjustment = ConstantInteger::get(candidate->multiplier); Value* adjustment = builder->createAndInst(shift31condidata, maskConstant);
Value* adjustedTemp = builder->createAddInst(temp, adjustment); Value* adjustedTemp = builder->createAddInst(candidate->inductionVar, adjustment);
Value* adjustedResult = builder->createBinaryInst(
// 使用条件分支来模拟select操作 Instruction::Kind::kAnd, candidate->inductionVar->getType(),
// 为简化起见,这里先用一个更复杂但可工作的方式 adjustedTemp, maskConstant
// 实际应该创建条件分支,但这里先简化处理 );
replacementValue = temp; // 简化版本,假设大多数情况下不是负数 replacementValue = adjustedResult;
} else { } else {
// 非负数的取模,直接使用位与 // 非负数的取模,直接使用位与
replacementValue = builder->createBinaryInst( replacementValue = builder->createBinaryInst(