#include "llvm/Transforms/IPO/IROutliner.h"
#include "llvm/Analysis/IRSimilarityIdentifier.h"
#include "llvm/Analysis/OptimizationRemarkEmitter.h"
#include "llvm/Analysis/TargetTransformInfo.h"
#include "llvm/IR/Attributes.h"
#include "llvm/IR/DIBuilder.h"
#include "llvm/IR/DebugInfo.h"
#include "llvm/IR/DebugInfoMetadata.h"
#include "llvm/IR/Dominators.h"
#include "llvm/IR/Mangler.h"
#include "llvm/IR/PassManager.h"
#include "llvm/InitializePasses.h"
#include "llvm/Pass.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Transforms/IPO.h"
#include <vector>
#define DEBUG_TYPE "iroutliner"
using namespace llvm;
using namespace IRSimilarity;
namespace llvm {
extern cl::opt<bool> DisableBranches;
extern cl::opt<bool> DisableIndirectCalls;
extern cl::opt<bool> DisableIntrinsics;
}
static cl::opt<bool> EnableLinkOnceODRIROutlining(
"enable-linkonceodr-ir-outlining", cl::Hidden,
cl::desc("Enable the IR outliner on linkonceodr functions"),
cl::init(false));
static cl::opt<bool> NoCostModel(
"ir-outlining-no-cost", cl::init(false), cl::ReallyHidden,
cl::desc("Debug option to outline greedily, without restriction that "
"calculated benefit outweighs cost"));
struct OutlinableGroup {
std::vector<OutlinableRegion *> Regions;
std::vector<Type *> ArgumentTypes;
FunctionType *OutlinedFunctionType = nullptr;
Function *OutlinedFunction = nullptr;
bool IgnoreGroup = false;
DenseMap<Value *, BasicBlock *> EndBBs;
DenseMap<Value *, BasicBlock *> PHIBlocks;
DenseSet<ArrayRef<unsigned>> OutputGVNCombinations;
bool InputTypesSet = false;
unsigned NumAggregateInputs = 0;
DenseMap<unsigned, unsigned> CanonicalNumberToAggArg;
unsigned BranchesToOutside = 0;
unsigned PHINodeGVNTracker = -3;
DenseMap<unsigned,
std::pair<std::pair<unsigned, unsigned>, SmallVector<unsigned, 2>>>
PHINodeGVNToGVNs;
DenseMap<hash_code, unsigned> GVNsToPHINodeGVN;
InstructionCost Benefit = 0;
InstructionCost Cost = 0;
Optional<unsigned> SwiftErrorArgument;
void findSameConstants(DenseSet<unsigned> &NotSame);
void collectGVNStoreSets(Module &M);
};
static void moveBBContents(BasicBlock &SourceBB, BasicBlock &TargetBB) {
for (Instruction &I : llvm::make_early_inc_range(SourceBB))
I.moveBefore(TargetBB, TargetBB.end());
}
static void getSortedConstantKeys(std::vector<Value *> &SortedKeys,
DenseMap<Value *, BasicBlock *> &Map) {
for (auto &VtoBB : Map)
SortedKeys.push_back(VtoBB.first);
stable_sort(SortedKeys, [](const Value *LHS, const Value *RHS) {
const ConstantInt *LHSC = dyn_cast<ConstantInt>(LHS);
const ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS);
assert(RHSC && "Not a constant integer in return value?");
assert(LHSC && "Not a constant integer in return value?");
return LHSC->getLimitedValue() < RHSC->getLimitedValue();
});
}
Value *OutlinableRegion::findCorrespondingValueIn(const OutlinableRegion &Other,
Value *V) {
Optional<unsigned> GVN = Candidate->getGVN(V);
assert(GVN && "No GVN for incoming value");
Optional<unsigned> CanonNum = Candidate->getCanonicalNum(*GVN);
Optional<unsigned> FirstGVN = Other.Candidate->fromCanonicalNum(*CanonNum);
Optional<Value *> FoundValueOpt = Other.Candidate->fromGVN(*FirstGVN);
return FoundValueOpt.value_or(nullptr);
}
BasicBlock *
OutlinableRegion::findCorrespondingBlockIn(const OutlinableRegion &Other,
BasicBlock *BB) {
Instruction *FirstNonPHI = BB->getFirstNonPHI();
assert(FirstNonPHI && "block is empty?");
Value *CorrespondingVal = findCorrespondingValueIn(Other, FirstNonPHI);
if (!CorrespondingVal)
return nullptr;
BasicBlock *CorrespondingBlock =
cast<Instruction>(CorrespondingVal)->getParent();
return CorrespondingBlock;
}
static void replaceTargetsFromPHINode(BasicBlock *PHIBlock, BasicBlock *Find,
BasicBlock *Replace,
DenseSet<BasicBlock *> &Included) {
for (PHINode &PN : PHIBlock->phis()) {
for (unsigned Idx = 0, PNEnd = PN.getNumIncomingValues(); Idx != PNEnd;
++Idx) {
BasicBlock *Incoming = PN.getIncomingBlock(Idx);
if (!Included.contains(Incoming))
continue;
BranchInst *BI = dyn_cast<BranchInst>(Incoming->getTerminator());
assert(BI && "Not a branch instruction?");
for (unsigned Succ = 0, End = BI->getNumSuccessors(); Succ != End;
Succ++) {
if (BI->getSuccessor(Succ) != Find)
continue;
BI->setSuccessor(Succ, Replace);
}
}
}
}
void OutlinableRegion::splitCandidate() {
assert(!CandidateSplit && "Candidate already split!");
Instruction *BackInst = Candidate->backInstruction();
Instruction *EndInst = nullptr;
if (!BackInst->isTerminator() ||
BackInst->getParent() != &BackInst->getFunction()->back()) {
EndInst = Candidate->end()->Inst;
assert(EndInst && "Expected an end instruction?");
}
if (!BackInst->isTerminator() &&
EndInst != BackInst->getNextNonDebugInstruction())
return;
Instruction *StartInst = (*Candidate->begin()).Inst;
assert(StartInst && "Expected a start instruction?");
StartBB = StartInst->getParent();
PrevBB = StartBB;
DenseSet<BasicBlock *> BBSet;
Candidate->getBasicBlocks(BBSet);
BasicBlock::iterator It = StartInst->getIterator();
EndBB = BackInst->getParent();
BasicBlock *IBlock;
BasicBlock *PHIPredBlock = nullptr;
bool EndBBTermAndBackInstDifferent = EndBB->getTerminator() != BackInst;
while (PHINode *PN = dyn_cast<PHINode>(&*It)) {
unsigned NumPredsOutsideRegion = 0;
for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
if (!BBSet.contains(PN->getIncomingBlock(i))) {
PHIPredBlock = PN->getIncomingBlock(i);
++NumPredsOutsideRegion;
continue;
}
IBlock = PN->getIncomingBlock(i);
if (IBlock == EndBB && EndBBTermAndBackInstDifferent) {
PHIPredBlock = PN->getIncomingBlock(i);
++NumPredsOutsideRegion;
}
}
if (NumPredsOutsideRegion > 1)
return;
It++;
}
if (isa<PHINode>(StartInst) && StartInst != &*StartBB->begin())
return;
if (isa<PHINode>(BackInst) &&
BackInst != &*std::prev(EndBB->getFirstInsertionPt()))
return;
std::string OriginalName = PrevBB->getName().str();
StartBB = PrevBB->splitBasicBlock(StartInst, OriginalName + "_to_outline");
PrevBB->replaceSuccessorsPhiUsesWith(PrevBB, StartBB);
if (PHIPredBlock)
PrevBB->replaceSuccessorsPhiUsesWith(PHIPredBlock, PrevBB);
CandidateSplit = true;
if (!BackInst->isTerminator()) {
EndBB = EndInst->getParent();
FollowBB = EndBB->splitBasicBlock(EndInst, OriginalName + "_after_outline");
EndBB->replaceSuccessorsPhiUsesWith(EndBB, FollowBB);
FollowBB->replaceSuccessorsPhiUsesWith(PrevBB, FollowBB);
} else {
EndBB = BackInst->getParent();
EndsInBranch = true;
FollowBB = nullptr;
}
BBSet.clear();
Candidate->getBasicBlocks(BBSet);
replaceTargetsFromPHINode(StartBB, PrevBB, StartBB, BBSet);
if (FollowBB)
replaceTargetsFromPHINode(FollowBB, EndBB, FollowBB, BBSet);
}
void OutlinableRegion::reattachCandidate() {
assert(CandidateSplit && "Candidate is not split!");
assert(StartBB != nullptr && "StartBB for Candidate is not defined!");
assert(PrevBB->getTerminator() && "Terminator removed from PrevBB!");
Instruction *StartInst = (*Candidate->begin()).Inst;
if (isa<PHINode>(StartInst) && !PrevBB->hasNPredecessors(0)) {
assert(!PrevBB->hasNPredecessorsOrMore(2) &&
"PrevBB has more than one predecessor. Should be 0 or 1.");
BasicBlock *BeforePrevBB = PrevBB->getSinglePredecessor();
PrevBB->replaceSuccessorsPhiUsesWith(PrevBB, BeforePrevBB);
}
PrevBB->getTerminator()->eraseFromParent();
if (!ExtractedFunction) {
DenseSet<BasicBlock *> BBSet;
Candidate->getBasicBlocks(BBSet);
replaceTargetsFromPHINode(StartBB, StartBB, PrevBB, BBSet);
if (!EndsInBranch)
replaceTargetsFromPHINode(FollowBB, FollowBB, EndBB, BBSet);
}
moveBBContents(*StartBB, *PrevBB);
BasicBlock *PlacementBB = PrevBB;
if (StartBB != EndBB)
PlacementBB = EndBB;
if (!EndsInBranch && PlacementBB->getUniqueSuccessor() != nullptr) {
assert(FollowBB != nullptr && "FollowBB for Candidate is not defined!");
assert(PlacementBB->getTerminator() && "Terminator removed from EndBB!");
PlacementBB->getTerminator()->eraseFromParent();
moveBBContents(*FollowBB, *PlacementBB);
PlacementBB->replaceSuccessorsPhiUsesWith(FollowBB, PlacementBB);
FollowBB->eraseFromParent();
}
PrevBB->replaceSuccessorsPhiUsesWith(StartBB, PrevBB);
StartBB->eraseFromParent();
StartBB = PrevBB;
EndBB = nullptr;
PrevBB = nullptr;
FollowBB = nullptr;
CandidateSplit = false;
}
static Optional<bool>
constantMatches(Value *V, unsigned GVN,
DenseMap<unsigned, Constant *> &GVNToConstant) {
Constant *CST = dyn_cast<Constant>(V);
if (!CST)
return None;
DenseMap<unsigned, Constant *>::iterator GVNToConstantIt;
bool Inserted;
std::tie(GVNToConstantIt, Inserted) =
GVNToConstant.insert(std::make_pair(GVN, CST));
if (Inserted || (GVNToConstantIt->second == CST))
return true;
return false;
}
InstructionCost OutlinableRegion::getBenefit(TargetTransformInfo &TTI) {
InstructionCost Benefit = 0;
for (IRInstructionData &ID : *Candidate) {
Instruction *I = ID.Inst;
switch (I->getOpcode()) {
case Instruction::FDiv:
case Instruction::FRem:
case Instruction::SDiv:
case Instruction::SRem:
case Instruction::UDiv:
case Instruction::URem:
Benefit += 1;
break;
default:
Benefit += TTI.getInstructionCost(I, TargetTransformInfo::TCK_CodeSize);
break;
}
}
return Benefit;
}
static Value *findOutputMapping(const DenseMap<Value *, Value *> OutputMappings,
Value *Input) {
DenseMap<Value *, Value *>::const_iterator OutputMapping =
OutputMappings.find(Input);
if (OutputMapping != OutputMappings.end())
return OutputMapping->second;
return Input;
}
static bool
collectRegionsConstants(OutlinableRegion &Region,
DenseMap<unsigned, Constant *> &GVNToConstant,
DenseSet<unsigned> &NotSame) {
bool ConstantsTheSame = true;
IRSimilarityCandidate &C = *Region.Candidate;
for (IRInstructionData &ID : C) {
for (Value *V : ID.OperVals) {
Optional<unsigned> GVNOpt = C.getGVN(V);
assert(GVNOpt && "Expected a GVN for operand?");
unsigned GVN = GVNOpt.value();
if (NotSame.contains(GVN)) {
if (isa<Constant>(V))
ConstantsTheSame = false;
continue;
}
Optional<bool> ConstantMatches = constantMatches(V, GVN, GVNToConstant);
if (ConstantMatches) {
if (ConstantMatches.value())
continue;
else
ConstantsTheSame = false;
}
if (GVNToConstant.find(GVN) != GVNToConstant.end())
ConstantsTheSame = false;
NotSame.insert(GVN);
}
}
return ConstantsTheSame;
}
void OutlinableGroup::findSameConstants(DenseSet<unsigned> &NotSame) {
DenseMap<unsigned, Constant *> GVNToConstant;
for (OutlinableRegion *Region : Regions)
collectRegionsConstants(*Region, GVNToConstant, NotSame);
}
void OutlinableGroup::collectGVNStoreSets(Module &M) {
for (OutlinableRegion *OS : Regions)
OutputGVNCombinations.insert(OS->GVNStores);
if (OutputGVNCombinations.size() > 1)
ArgumentTypes.push_back(Type::getInt32Ty(M.getContext()));
}
static DISubprogram *getSubprogramOrNull(OutlinableGroup &Group) {
for (OutlinableRegion *OS : Group.Regions)
if (Function *F = OS->Call->getFunction())
if (DISubprogram *SP = F->getSubprogram())
return SP;
return nullptr;
}
Function *IROutliner::createFunction(Module &M, OutlinableGroup &Group,
unsigned FunctionNameSuffix) {
assert(!Group.OutlinedFunction && "Function is already defined!");
Type *RetTy = Type::getVoidTy(M.getContext());
for (OutlinableRegion *R : Group.Regions) {
Type *ExtractedFuncType = R->ExtractedFunction->getReturnType();
if ((RetTy->isVoidTy() && !ExtractedFuncType->isVoidTy()) ||
(RetTy->isIntegerTy(1) && ExtractedFuncType->isIntegerTy(16)))
RetTy = ExtractedFuncType;
}
Group.OutlinedFunctionType = FunctionType::get(
RetTy, Group.ArgumentTypes, false);
Group.OutlinedFunction = Function::Create(
Group.OutlinedFunctionType, GlobalValue::InternalLinkage,
"outlined_ir_func_" + std::to_string(FunctionNameSuffix), M);
if (Group.SwiftErrorArgument)
Group.OutlinedFunction->addParamAttr(Group.SwiftErrorArgument.value(),
Attribute::SwiftError);
Group.OutlinedFunction->addFnAttr(Attribute::OptimizeForSize);
Group.OutlinedFunction->addFnAttr(Attribute::MinSize);
if (DISubprogram *SP = getSubprogramOrNull(Group)) {
Function *F = Group.OutlinedFunction;
DICompileUnit *CU = SP->getUnit();
DIBuilder DB(M, true, CU);
DIFile *Unit = SP->getFile();
Mangler Mg;
std::string Dummy;
llvm::raw_string_ostream MangledNameStream(Dummy);
Mg.getNameWithPrefix(MangledNameStream, F, false);
DISubprogram *OutlinedSP = DB.createFunction(
Unit , F->getName(), MangledNameStream.str(),
Unit ,
0 ,
DB.createSubroutineType(DB.getOrCreateTypeArray(None)),
0,
DINode::DIFlags::FlagArtificial ,
DISubprogram::SPFlagDefinition | DISubprogram::SPFlagOptimized);
DB.finalizeSubprogram(OutlinedSP);
F->setSubprogram(OutlinedSP);
DB.finalize();
}
return Group.OutlinedFunction;
}
static void moveFunctionData(Function &Old, Function &New,
DenseMap<Value *, BasicBlock *> &NewEnds) {
for (BasicBlock &CurrBB : llvm::make_early_inc_range(Old)) {
CurrBB.removeFromParent();
CurrBB.insertInto(&New);
Instruction *I = CurrBB.getTerminator();
if (ReturnInst *RI = dyn_cast<ReturnInst>(I))
NewEnds.insert(std::make_pair(RI->getReturnValue(), &CurrBB));
std::vector<Instruction *> DebugInsts;
for (Instruction &Val : CurrBB) {
if (!isa<CallInst>(&Val)) {
Val.setDebugLoc(DebugLoc());
auto updateLoopInfoLoc = [&New](Metadata *MD) -> Metadata * {
if (DISubprogram *SP = New.getSubprogram())
if (auto *Loc = dyn_cast_or_null<DILocation>(MD))
return DILocation::get(New.getContext(), Loc->getLine(),
Loc->getColumn(), SP, nullptr);
return MD;
};
updateLoopMetadataDebugLocations(Val, updateLoopInfoLoc);
continue;
}
CallInst *CI = cast<CallInst>(&Val);
if (isa<DbgInfoIntrinsic>(CI)) {
DebugInsts.push_back(&Val);
continue;
}
if (DISubprogram *SP = New.getSubprogram()) {
DILocation *DI = DILocation::get(New.getContext(), 0, 0, SP);
Val.setDebugLoc(DI);
}
}
for (Instruction *I : DebugInsts)
I->eraseFromParent();
}
}
static void findConstants(IRSimilarityCandidate &C, DenseSet<unsigned> &NotSame,
std::vector<unsigned> &Inputs) {
DenseSet<unsigned> Seen;
for (IRInstructionDataList::iterator IDIt = C.begin(), EndIDIt = C.end();
IDIt != EndIDIt; IDIt++) {
for (Value *V : (*IDIt).OperVals) {
unsigned GVN = *C.getGVN(V);
if (isa<Constant>(V))
if (NotSame.contains(GVN) && !Seen.contains(GVN)) {
Inputs.push_back(GVN);
Seen.insert(GVN);
}
}
}
}
static void mapInputsToGVNs(IRSimilarityCandidate &C,
SetVector<Value *> &CurrentInputs,
const DenseMap<Value *, Value *> &OutputMappings,
std::vector<unsigned> &EndInputNumbers) {
for (Value *Input : CurrentInputs) {
assert(Input && "Have a nullptr as an input");
if (OutputMappings.find(Input) != OutputMappings.end())
Input = OutputMappings.find(Input)->second;
assert(C.getGVN(Input) && "Could not find a numbering for the given input");
EndInputNumbers.push_back(C.getGVN(Input).value());
}
}
static void
remapExtractedInputs(const ArrayRef<Value *> ArgInputs,
const DenseMap<Value *, Value *> &OutputMappings,
SetVector<Value *> &RemappedArgInputs) {
for (Value *Input : ArgInputs) {
if (OutputMappings.find(Input) != OutputMappings.end())
Input = OutputMappings.find(Input)->second;
RemappedArgInputs.insert(Input);
}
}
static void getCodeExtractorArguments(
OutlinableRegion &Region, std::vector<unsigned> &InputGVNs,
DenseSet<unsigned> &NotSame, DenseMap<Value *, Value *> &OutputMappings,
SetVector<Value *> &ArgInputs, SetVector<Value *> &Outputs) {
IRSimilarityCandidate &C = *Region.Candidate;
SetVector<Value *> OverallInputs, PremappedInputs, SinkCands, HoistCands,
DummyOutputs;
CodeExtractor *CE = Region.CE;
CE->findInputsOutputs(OverallInputs, DummyOutputs, SinkCands);
assert(Region.StartBB && "Region must have a start BasicBlock!");
Function *OrigF = Region.StartBB->getParent();
CodeExtractorAnalysisCache CEAC(*OrigF);
BasicBlock *Dummy = nullptr;
if (!CE->isEligible()) {
Region.IgnoreRegion = true;
return;
}
CE->findAllocas(CEAC, SinkCands, HoistCands, Dummy);
CE->findInputsOutputs(PremappedInputs, Outputs, SinkCands);
if (OverallInputs.size() != PremappedInputs.size()) {
Region.IgnoreRegion = true;
return;
}
findConstants(C, NotSame, InputGVNs);
mapInputsToGVNs(C, OverallInputs, OutputMappings, InputGVNs);
remapExtractedInputs(PremappedInputs.getArrayRef(), OutputMappings,
ArgInputs);
stable_sort(InputGVNs);
}
static void
findExtractedInputToOverallInputMapping(OutlinableRegion &Region,
std::vector<unsigned> &InputGVNs,
SetVector<Value *> &ArgInputs) {
IRSimilarityCandidate &C = *Region.Candidate;
OutlinableGroup &Group = *Region.Parent;
unsigned TypeIndex = 0;
unsigned OriginalIndex = 0;
for (unsigned InputVal : InputGVNs) {
Optional<unsigned> CanonicalNumberOpt = C.getCanonicalNum(InputVal);
assert(CanonicalNumberOpt && "Canonical number not found?");
unsigned CanonicalNumber = CanonicalNumberOpt.value();
Optional<Value *> InputOpt = C.fromGVN(InputVal);
assert(InputOpt && "Global value number not found?");
Value *Input = InputOpt.value();
DenseMap<unsigned, unsigned>::iterator AggArgIt =
Group.CanonicalNumberToAggArg.find(CanonicalNumber);
if (!Group.InputTypesSet) {
Group.ArgumentTypes.push_back(Input->getType());
if (Input->isSwiftError()) {
assert(
!Group.SwiftErrorArgument &&
"Argument already marked with swifterr for this OutlinableGroup!");
Group.SwiftErrorArgument = TypeIndex;
}
}
if (Constant *CST = dyn_cast<Constant>(Input)) {
if (AggArgIt != Group.CanonicalNumberToAggArg.end())
Region.AggArgToConstant.insert(std::make_pair(AggArgIt->second, CST));
else {
Group.CanonicalNumberToAggArg.insert(
std::make_pair(CanonicalNumber, TypeIndex));
Region.AggArgToConstant.insert(std::make_pair(TypeIndex, CST));
}
TypeIndex++;
continue;
}
assert(ArgInputs.count(Input) && "Input cannot be found!");
if (AggArgIt != Group.CanonicalNumberToAggArg.end()) {
if (OriginalIndex != AggArgIt->second)
Region.ChangedArgOrder = true;
Region.ExtractedArgToAgg.insert(
std::make_pair(OriginalIndex, AggArgIt->second));
Region.AggArgToExtracted.insert(
std::make_pair(AggArgIt->second, OriginalIndex));
} else {
Group.CanonicalNumberToAggArg.insert(
std::make_pair(CanonicalNumber, TypeIndex));
Region.ExtractedArgToAgg.insert(std::make_pair(OriginalIndex, TypeIndex));
Region.AggArgToExtracted.insert(std::make_pair(TypeIndex, OriginalIndex));
}
OriginalIndex++;
TypeIndex++;
}
if (!Group.InputTypesSet) {
Group.NumAggregateInputs = TypeIndex;
Group.InputTypesSet = true;
}
Region.NumExtractedInputs = OriginalIndex;
}
static bool outputHasNonPHI(Value *V, unsigned PHILoc, PHINode &PN,
SmallPtrSet<BasicBlock *, 1> &Exits,
DenseSet<BasicBlock *> &BlocksInRegion) {
if (any_of(llvm::seq<unsigned>(0, PN.getNumIncomingValues()),
[PHILoc, &PN, V, &BlocksInRegion](unsigned Idx) {
return (Idx != PHILoc && V == PN.getIncomingValue(Idx) &&
!BlocksInRegion.contains(PN.getIncomingBlock(Idx)));
}))
return true;
return any_of(V->users(), [&Exits, &BlocksInRegion](User *U) {
Instruction *I = dyn_cast<Instruction>(U);
if (!I)
return false;
BasicBlock *Parent = I->getParent();
if (BlocksInRegion.contains(Parent))
return false;
if (!isa<PHINode>(I))
return true;
if (!Exits.contains(Parent))
return true;
return false;
});
}
static void analyzeExitPHIsForOutputUses(
BasicBlock *CurrentExitFromRegion,
SmallPtrSet<BasicBlock *, 1> &PotentialExitsFromRegion,
DenseSet<BasicBlock *> &RegionBlocks, SetVector<Value *> &Outputs,
DenseSet<Value *> &OutputsReplacedByPHINode,
DenseSet<Value *> &OutputsWithNonPhiUses) {
for (PHINode &PN : CurrentExitFromRegion->phis()) {
SmallVector<unsigned, 2> IncomingVals;
for (unsigned I = 0, E = PN.getNumIncomingValues(); I < E; ++I)
if (RegionBlocks.contains(PN.getIncomingBlock(I)))
IncomingVals.push_back(I);
unsigned NumIncomingVals = IncomingVals.size();
if (NumIncomingVals == 0)
continue;
if (NumIncomingVals == 1) {
Value *V = PN.getIncomingValue(*IncomingVals.begin());
OutputsWithNonPhiUses.insert(V);
OutputsReplacedByPHINode.erase(V);
continue;
}
Outputs.insert(&PN);
for (unsigned Idx : IncomingVals) {
Value *V = PN.getIncomingValue(Idx);
if (outputHasNonPHI(V, Idx, PN, PotentialExitsFromRegion, RegionBlocks)) {
OutputsWithNonPhiUses.insert(V);
OutputsReplacedByPHINode.erase(V);
continue;
}
if (!OutputsWithNonPhiUses.contains(V))
OutputsReplacedByPHINode.insert(V);
}
}
}
using ArgLocWithBBCanon = std::pair<unsigned, unsigned>;
using CanonList = SmallVector<unsigned, 2>;
using PHINodeData = std::pair<ArgLocWithBBCanon, CanonList>;
static hash_code encodePHINodeData(PHINodeData &PND) {
return llvm::hash_combine(
llvm::hash_value(PND.first.first), llvm::hash_value(PND.first.second),
llvm::hash_combine_range(PND.second.begin(), PND.second.end()));
}
static Optional<unsigned> getGVNForPHINode(OutlinableRegion &Region,
PHINode *PN,
DenseSet<BasicBlock *> &Blocks,
unsigned AggArgIdx) {
OutlinableGroup &Group = *Region.Parent;
IRSimilarityCandidate &Cand = *Region.Candidate;
BasicBlock *PHIBB = PN->getParent();
CanonList PHIGVNs;
Value *Incoming;
BasicBlock *IncomingBlock;
for (unsigned Idx = 0, EIdx = PN->getNumIncomingValues(); Idx < EIdx; Idx++) {
Incoming = PN->getIncomingValue(Idx);
IncomingBlock = PN->getIncomingBlock(Idx);
Optional<unsigned> OGVN = Cand.getGVN(Incoming);
if (!OGVN && Blocks.contains(IncomingBlock)) {
Region.IgnoreRegion = true;
return None;
}
if (!Blocks.contains(IncomingBlock))
continue;
unsigned GVN = *OGVN;
OGVN = Cand.getCanonicalNum(GVN);
assert(OGVN && "No GVN found for incoming value?");
PHIGVNs.push_back(*OGVN);
OGVN = Cand.getGVN(IncomingBlock);
if (!OGVN) {
assert(Cand.getStartBB() == IncomingBlock &&
"Unknown basic block used in exit path PHINode.");
BasicBlock *PrevBlock = nullptr;
for (BasicBlock *Pred : predecessors(IncomingBlock))
if (!Blocks.contains(Pred)) {
PrevBlock = Pred;
break;
}
assert(PrevBlock && "Expected a predecessor not in the reigon!");
OGVN = Cand.getGVN(PrevBlock);
}
GVN = *OGVN;
OGVN = Cand.getCanonicalNum(GVN);
assert(OGVN && "No GVN found for incoming block?");
PHIGVNs.push_back(*OGVN);
}
DenseMap<hash_code, unsigned>::iterator GVNToPHIIt;
DenseMap<unsigned, PHINodeData>::iterator PHIToGVNIt;
Optional<unsigned> BBGVN = Cand.getGVN(PHIBB);
assert(BBGVN && "Could not find GVN for the incoming block!");
BBGVN = Cand.getCanonicalNum(BBGVN.value());
assert(BBGVN && "Could not find canonical number for the incoming block!");
PHINodeData TemporaryPair =
std::make_pair(std::make_pair(BBGVN.value(), AggArgIdx), PHIGVNs);
hash_code PHINodeDataHash = encodePHINodeData(TemporaryPair);
GVNToPHIIt = Group.GVNsToPHINodeGVN.find(PHINodeDataHash);
if (GVNToPHIIt == Group.GVNsToPHINodeGVN.end()) {
bool Inserted = false;
std::tie(PHIToGVNIt, Inserted) = Group.PHINodeGVNToGVNs.insert(
std::make_pair(Group.PHINodeGVNTracker, TemporaryPair));
std::tie(GVNToPHIIt, Inserted) = Group.GVNsToPHINodeGVN.insert(
std::make_pair(PHINodeDataHash, Group.PHINodeGVNTracker--));
}
return GVNToPHIIt->second;
}
static void
findExtractedOutputToOverallOutputMapping(OutlinableRegion &Region,
SetVector<Value *> &Outputs) {
OutlinableGroup &Group = *Region.Parent;
IRSimilarityCandidate &C = *Region.Candidate;
SmallVector<BasicBlock *> BE;
DenseSet<BasicBlock *> BlocksInRegion;
C.getBasicBlocks(BlocksInRegion, BE);
SmallPtrSet<BasicBlock *, 1> Exits;
for (BasicBlock *Block : BE)
for (BasicBlock *Succ : successors(Block))
if (!BlocksInRegion.contains(Succ))
Exits.insert(Succ);
DenseSet<Value *> OutputsReplacedByPHINode;
DenseSet<Value *> OutputsWithNonPhiUses;
for (BasicBlock *ExitBB : Exits)
analyzeExitPHIsForOutputUses(ExitBB, Exits, BlocksInRegion, Outputs,
OutputsReplacedByPHINode,
OutputsWithNonPhiUses);
unsigned OriginalIndex = Region.NumExtractedInputs;
unsigned TypeIndex = Group.NumAggregateInputs;
bool TypeFound;
DenseSet<unsigned> AggArgsUsed;
for (Value *Output : Outputs) {
TypeFound = false;
unsigned ArgumentSize = Group.ArgumentTypes.size();
if (OutputsReplacedByPHINode.contains(Output))
continue;
unsigned AggArgIdx = 0;
for (unsigned Jdx = TypeIndex; Jdx < ArgumentSize; Jdx++) {
if (Group.ArgumentTypes[Jdx] != PointerType::getUnqual(Output->getType()))
continue;
if (AggArgsUsed.contains(Jdx))
continue;
TypeFound = true;
AggArgsUsed.insert(Jdx);
Region.ExtractedArgToAgg.insert(std::make_pair(OriginalIndex, Jdx));
Region.AggArgToExtracted.insert(std::make_pair(Jdx, OriginalIndex));
AggArgIdx = Jdx;
break;
}
if (!TypeFound) {
Group.ArgumentTypes.push_back(PointerType::getUnqual(Output->getType()));
unsigned ArgTypeIdx = Group.ArgumentTypes.size() - 1;
AggArgsUsed.insert(ArgTypeIdx);
Region.ExtractedArgToAgg.insert(
std::make_pair(OriginalIndex, ArgTypeIdx));
Region.AggArgToExtracted.insert(
std::make_pair(ArgTypeIdx, OriginalIndex));
AggArgIdx = ArgTypeIdx;
}
PHINode *PN = dyn_cast<PHINode>(Output);
Optional<unsigned> GVN;
if (PN && !BlocksInRegion.contains(PN->getParent())) {
GVN = getGVNForPHINode(Region, PN, BlocksInRegion, AggArgIdx);
if (!GVN)
return;
} else {
GVN = C.getGVN(Output);
GVN = C.getCanonicalNum(*GVN);
}
Region.GVNStores.push_back(*GVN);
OriginalIndex++;
TypeIndex++;
}
stable_sort(Region.GVNStores);
}
void IROutliner::findAddInputsOutputs(Module &M, OutlinableRegion &Region,
DenseSet<unsigned> &NotSame) {
std::vector<unsigned> Inputs;
SetVector<Value *> ArgInputs, Outputs;
getCodeExtractorArguments(Region, Inputs, NotSame, OutputMappings, ArgInputs,
Outputs);
if (Region.IgnoreRegion)
return;
findExtractedInputToOverallInputMapping(Region, Inputs, ArgInputs);
findExtractedOutputToOverallOutputMapping(Region, Outputs);
}
CallInst *replaceCalledFunction(Module &M, OutlinableRegion &Region) {
std::vector<Value *> NewCallArgs;
DenseMap<unsigned, unsigned>::iterator ArgPair;
OutlinableGroup &Group = *Region.Parent;
CallInst *Call = Region.Call;
assert(Call && "Call to replace is nullptr?");
Function *AggFunc = Group.OutlinedFunction;
assert(AggFunc && "Function to replace with is nullptr?");
if (!Region.ChangedArgOrder && AggFunc->arg_size() == Call->arg_size()) {
LLVM_DEBUG(dbgs() << "Replace call to " << *Call << " with call to "
<< *AggFunc << " with same number of arguments\n");
Call->setCalledFunction(AggFunc);
return Call;
}
for (unsigned AggArgIdx = 0; AggArgIdx < AggFunc->arg_size(); AggArgIdx++) {
if (AggArgIdx == AggFunc->arg_size() - 1 &&
Group.OutputGVNCombinations.size() > 1) {
LLVM_DEBUG(dbgs() << "Set switch block argument to "
<< Region.OutputBlockNum << "\n");
NewCallArgs.push_back(ConstantInt::get(Type::getInt32Ty(M.getContext()),
Region.OutputBlockNum));
continue;
}
ArgPair = Region.AggArgToExtracted.find(AggArgIdx);
if (ArgPair != Region.AggArgToExtracted.end()) {
Value *ArgumentValue = Call->getArgOperand(ArgPair->second);
LLVM_DEBUG(dbgs() << "Setting argument " << AggArgIdx << " to value "
<< *ArgumentValue << "\n");
NewCallArgs.push_back(ArgumentValue);
continue;
}
if (Region.AggArgToConstant.find(AggArgIdx) !=
Region.AggArgToConstant.end()) {
Constant *CST = Region.AggArgToConstant.find(AggArgIdx)->second;
LLVM_DEBUG(dbgs() << "Setting argument " << AggArgIdx << " to value "
<< *CST << "\n");
NewCallArgs.push_back(CST);
continue;
}
LLVM_DEBUG(dbgs() << "Setting argument " << AggArgIdx << " to nullptr\n");
NewCallArgs.push_back(ConstantPointerNull::get(
static_cast<PointerType *>(AggFunc->getArg(AggArgIdx)->getType())));
}
LLVM_DEBUG(dbgs() << "Replace call to " << *Call << " with call to "
<< *AggFunc << " with new set of arguments\n");
Call = CallInst::Create(AggFunc->getFunctionType(), AggFunc, NewCallArgs, "",
Call);
CallInst *OldCall = Region.Call;
if (Region.NewFront->Inst == OldCall)
Region.NewFront->Inst = Call;
if (Region.NewBack->Inst == OldCall)
Region.NewBack->Inst = Call;
Call->setDebugLoc(Region.Call->getDebugLoc());
OldCall->replaceAllUsesWith(Call);
OldCall->eraseFromParent();
Region.Call = Call;
if (Group.SwiftErrorArgument)
Call->addParamAttr(Group.SwiftErrorArgument.value(), Attribute::SwiftError);
return Call;
}
static BasicBlock *findOrCreatePHIBlock(OutlinableGroup &Group, Value *RetVal) {
DenseMap<Value *, BasicBlock *>::iterator PhiBlockForRetVal,
ReturnBlockForRetVal;
PhiBlockForRetVal = Group.PHIBlocks.find(RetVal);
ReturnBlockForRetVal = Group.EndBBs.find(RetVal);
assert(ReturnBlockForRetVal != Group.EndBBs.end() &&
"Could not find output value!");
BasicBlock *ReturnBB = ReturnBlockForRetVal->second;
PhiBlockForRetVal = Group.PHIBlocks.find(RetVal);
if (PhiBlockForRetVal != Group.PHIBlocks.end())
return PhiBlockForRetVal->second;
bool Inserted = false;
BasicBlock *PHIBlock = BasicBlock::Create(ReturnBB->getContext(), "phi_block",
ReturnBB->getParent());
std::tie(PhiBlockForRetVal, Inserted) =
Group.PHIBlocks.insert(std::make_pair(RetVal, PHIBlock));
SmallVector<BranchInst *, 2> BranchesToChange;
for (BasicBlock *Pred : predecessors(ReturnBB))
BranchesToChange.push_back(cast<BranchInst>(Pred->getTerminator()));
for (BranchInst *BI : BranchesToChange)
for (unsigned Succ = 0, End = BI->getNumSuccessors(); Succ < End; Succ++) {
if (BI->getSuccessor(Succ) != ReturnBB)
continue;
BI->setSuccessor(Succ, PHIBlock);
}
BranchInst::Create(ReturnBB, PHIBlock);
return PhiBlockForRetVal->second;
}
static Value *
getPassedArgumentInAlreadyOutlinedFunction(const Argument *A,
const OutlinableRegion &Region) {
return Region.Call->getArgOperand(A->getArgNo());
}
static Value *
getPassedArgumentAndAdjustArgumentLocation(const Argument *A,
const OutlinableRegion &Region) {
unsigned ArgNum = A->getArgNo();
if (Region.AggArgToConstant.count(ArgNum))
return Region.AggArgToConstant.find(ArgNum)->second;
ArgNum = Region.AggArgToExtracted.find(ArgNum)->second;
return Region.Call->getArgOperand(ArgNum);
}
static void findCanonNumsForPHI(
PHINode *PN, OutlinableRegion &Region,
const DenseMap<Value *, Value *> &OutputMappings,
SmallVector<std::pair<unsigned, BasicBlock *>> &CanonNums,
bool ReplacedWithOutlinedCall = true) {
for (unsigned Idx = 0, EIdx = PN->getNumIncomingValues(); Idx < EIdx; Idx++) {
Value *IVal = PN->getIncomingValue(Idx);
BasicBlock *IBlock = PN->getIncomingBlock(Idx);
if (Argument *A = dyn_cast<Argument>(IVal)) {
if (ReplacedWithOutlinedCall)
IVal = getPassedArgumentInAlreadyOutlinedFunction(A, Region);
else
IVal = getPassedArgumentAndAdjustArgumentLocation(A, Region);
}
IVal = findOutputMapping(OutputMappings, IVal);
Optional<unsigned> GVN = Region.Candidate->getGVN(IVal);
assert(GVN && "No GVN for incoming value");
Optional<unsigned> CanonNum = Region.Candidate->getCanonicalNum(*GVN);
assert(CanonNum && "No Canonical Number for GVN");
CanonNums.push_back(std::make_pair(*CanonNum, IBlock));
}
}
static PHINode*
findOrCreatePHIInBlock(PHINode &PN, OutlinableRegion &Region,
BasicBlock *OverallPhiBlock,
const DenseMap<Value *, Value *> &OutputMappings,
DenseSet<PHINode *> &UsedPHIs) {
OutlinableGroup &Group = *Region.Parent;
SmallVector<std::pair<unsigned, BasicBlock *>> PNCanonNums;
findCanonNumsForPHI(&PN, Region, OutputMappings, PNCanonNums,
false);
OutlinableRegion *FirstRegion = Group.Regions[0];
SmallVector<std::pair<unsigned, BasicBlock *>> CurrentCanonNums;
for (PHINode &CurrPN : OverallPhiBlock->phis()) {
if (UsedPHIs.contains(&CurrPN))
continue;
CurrentCanonNums.clear();
findCanonNumsForPHI(&CurrPN, *FirstRegion, OutputMappings, CurrentCanonNums,
true);
if (PNCanonNums.size() != CurrentCanonNums.size())
continue;
bool FoundMatch = true;
for (unsigned Idx = 0, Edx = PNCanonNums.size(); Idx < Edx; ++Idx) {
std::pair<unsigned, BasicBlock *> ToCompareTo = CurrentCanonNums[Idx];
std::pair<unsigned, BasicBlock *> ToAdd = PNCanonNums[Idx];
if (ToCompareTo.first != ToAdd.first) {
FoundMatch = false;
break;
}
BasicBlock *CorrespondingBlock =
Region.findCorrespondingBlockIn(*FirstRegion, ToAdd.second);
assert(CorrespondingBlock && "Found block is nullptr");
if (CorrespondingBlock != ToCompareTo.second) {
FoundMatch = false;
break;
}
}
if (FoundMatch) {
UsedPHIs.insert(&CurrPN);
return &CurrPN;
}
}
PHINode *NewPN = cast<PHINode>(PN.clone());
NewPN->insertBefore(&*OverallPhiBlock->begin());
for (unsigned Idx = 0, Edx = NewPN->getNumIncomingValues(); Idx < Edx;
Idx++) {
Value *IncomingVal = NewPN->getIncomingValue(Idx);
BasicBlock *IncomingBlock = NewPN->getIncomingBlock(Idx);
BasicBlock *BlockToUse =
Region.findCorrespondingBlockIn(*FirstRegion, IncomingBlock);
NewPN->setIncomingBlock(Idx, BlockToUse);
if (Argument *A = dyn_cast<Argument>(IncomingVal)) {
Value *Val = Group.OutlinedFunction->getArg(A->getArgNo());
NewPN->setIncomingValue(Idx, Val);
continue;
}
IncomingVal = findOutputMapping(OutputMappings, IncomingVal);
Value *Val = Region.findCorrespondingValueIn(*FirstRegion, IncomingVal);
assert(Val && "Value is nullptr?");
DenseMap<Value *, Value *>::iterator RemappedIt =
FirstRegion->RemappedArguments.find(Val);
if (RemappedIt != FirstRegion->RemappedArguments.end())
Val = RemappedIt->second;
NewPN->setIncomingValue(Idx, Val);
}
return NewPN;
}
static void
replaceArgumentUses(OutlinableRegion &Region,
DenseMap<Value *, BasicBlock *> &OutputBBs,
const DenseMap<Value *, Value *> &OutputMappings,
bool FirstFunction = false) {
OutlinableGroup &Group = *Region.Parent;
assert(Region.ExtractedFunction && "Region has no extracted function?");
Function *DominatingFunction = Region.ExtractedFunction;
if (FirstFunction)
DominatingFunction = Group.OutlinedFunction;
DominatorTree DT(*DominatingFunction);
DenseSet<PHINode *> UsedPHIs;
for (unsigned ArgIdx = 0; ArgIdx < Region.ExtractedFunction->arg_size();
ArgIdx++) {
assert(Region.ExtractedArgToAgg.find(ArgIdx) !=
Region.ExtractedArgToAgg.end() &&
"No mapping from extracted to outlined?");
unsigned AggArgIdx = Region.ExtractedArgToAgg.find(ArgIdx)->second;
Argument *AggArg = Group.OutlinedFunction->getArg(AggArgIdx);
Argument *Arg = Region.ExtractedFunction->getArg(ArgIdx);
if (ArgIdx < Region.NumExtractedInputs) {
LLVM_DEBUG(dbgs() << "Replacing uses of input " << *Arg << " in function "
<< *Region.ExtractedFunction << " with " << *AggArg
<< " in function " << *Group.OutlinedFunction << "\n");
Arg->replaceAllUsesWith(AggArg);
Value *V = Region.Call->getArgOperand(ArgIdx);
Region.RemappedArguments.insert(std::make_pair(V, AggArg));
continue;
}
assert(Arg->hasOneUse() && "Output argument can only have one use");
User *InstAsUser = Arg->user_back();
assert(InstAsUser && "User is nullptr!");
Instruction *I = cast<Instruction>(InstAsUser);
BasicBlock *BB = I->getParent();
SmallVector<BasicBlock *, 4> Descendants;
DT.getDescendants(BB, Descendants);
bool EdgeAdded = false;
if (Descendants.size() == 0) {
EdgeAdded = true;
DT.insertEdge(&DominatingFunction->getEntryBlock(), BB);
DT.getDescendants(BB, Descendants);
}
for (BasicBlock *DescendBB : Descendants) {
ReturnInst *RI = dyn_cast<ReturnInst>(DescendBB->getTerminator());
if (!RI)
continue;
Value *RetVal = RI->getReturnValue();
auto VBBIt = OutputBBs.find(RetVal);
assert(VBBIt != OutputBBs.end() && "Could not find output value!");
StoreInst *SI = cast<StoreInst>(I);
Value *ValueOperand = SI->getValueOperand();
StoreInst *NewI = cast<StoreInst>(I->clone());
NewI->setDebugLoc(DebugLoc());
BasicBlock *OutputBB = VBBIt->second;
OutputBB->getInstList().push_back(NewI);
LLVM_DEBUG(dbgs() << "Move store for instruction " << *I << " to "
<< *OutputBB << "\n");
if (!isa<PHINode>(ValueOperand) ||
Region.Candidate->getGVN(ValueOperand).has_value()) {
if (FirstFunction)
continue;
Value *CorrVal =
Region.findCorrespondingValueIn(*Group.Regions[0], ValueOperand);
assert(CorrVal && "Value is nullptr?");
NewI->setOperand(0, CorrVal);
continue;
}
PHINode *PN = cast<PHINode>(SI->getValueOperand());
if (Region.Candidate->getGVN(PN))
continue;
Region.PHIBlocks.insert(std::make_pair(RetVal, PN->getParent()));
if (FirstFunction) {
BasicBlock *PHIBlock = PN->getParent();
Group.PHIBlocks.insert(std::make_pair(RetVal, PHIBlock));
continue;
}
BasicBlock *OverallPhiBlock = findOrCreatePHIBlock(Group, RetVal);
PHINode *NewPN = findOrCreatePHIInBlock(*PN, Region, OverallPhiBlock,
OutputMappings, UsedPHIs);
NewI->setOperand(0, NewPN);
}
if (EdgeAdded)
DT.deleteEdge(&DominatingFunction->getEntryBlock(), BB);
I->eraseFromParent();
LLVM_DEBUG(dbgs() << "Replacing uses of output " << *Arg << " in function "
<< *Region.ExtractedFunction << " with " << *AggArg
<< " in function " << *Group.OutlinedFunction << "\n");
Arg->replaceAllUsesWith(AggArg);
}
}
void replaceConstants(OutlinableRegion &Region) {
OutlinableGroup &Group = *Region.Parent;
for (std::pair<unsigned, Constant *> &Const : Region.AggArgToConstant) {
unsigned AggArgIdx = Const.first;
Function *OutlinedFunction = Group.OutlinedFunction;
assert(OutlinedFunction && "Overall Function is not defined?");
Constant *CST = Const.second;
Argument *Arg = Group.OutlinedFunction->getArg(AggArgIdx);
LLVM_DEBUG(dbgs() << "Replacing uses of constant " << *CST
<< " in function " << *OutlinedFunction << " with "
<< *Arg << "\n");
CST->replaceUsesWithIf(Arg, [OutlinedFunction](Use &U) {
if (Instruction *I = dyn_cast<Instruction>(U.getUser()))
return I->getFunction() == OutlinedFunction;
return false;
});
}
}
Optional<unsigned> findDuplicateOutputBlock(
DenseMap<Value *, BasicBlock *> &OutputBBs,
std::vector<DenseMap<Value *, BasicBlock *>> &OutputStoreBBs) {
bool Mismatch = false;
unsigned MatchingNum = 0;
for (DenseMap<Value *, BasicBlock *> &CompBBs : OutputStoreBBs) {
Mismatch = false;
for (std::pair<Value *, BasicBlock *> &VToB : CompBBs) {
DenseMap<Value *, BasicBlock *>::iterator OutputBBIt =
OutputBBs.find(VToB.first);
if (OutputBBIt == OutputBBs.end()) {
Mismatch = true;
break;
}
BasicBlock *CompBB = VToB.second;
BasicBlock *OutputBB = OutputBBIt->second;
if (CompBB->size() - 1 != OutputBB->size()) {
Mismatch = true;
break;
}
BasicBlock::iterator NIt = OutputBB->begin();
for (Instruction &I : *CompBB) {
if (isa<BranchInst>(&I))
continue;
if (!I.isIdenticalTo(&(*NIt))) {
Mismatch = true;
break;
}
NIt++;
}
}
if (!Mismatch)
return MatchingNum;
MatchingNum++;
}
return None;
}
static bool
analyzeAndPruneOutputBlocks(DenseMap<Value *, BasicBlock *> &BlocksToPrune,
OutlinableRegion &Region) {
bool AllRemoved = true;
Value *RetValueForBB;
BasicBlock *NewBB;
SmallVector<Value *, 4> ToRemove;
for (std::pair<Value *, BasicBlock *> &VtoBB : BlocksToPrune) {
RetValueForBB = VtoBB.first;
NewBB = VtoBB.second;
if (NewBB->size() == 0) {
NewBB->eraseFromParent();
ToRemove.push_back(RetValueForBB);
continue;
}
AllRemoved = false;
}
for (Value *V : ToRemove)
BlocksToPrune.erase(V);
if (AllRemoved)
Region.OutputBlockNum = -1;
return AllRemoved;
}
static void alignOutputBlockWithAggFunc(
OutlinableGroup &OG, OutlinableRegion &Region,
DenseMap<Value *, BasicBlock *> &OutputBBs,
DenseMap<Value *, BasicBlock *> &EndBBs,
const DenseMap<Value *, Value *> &OutputMappings,
std::vector<DenseMap<Value *, BasicBlock *>> &OutputStoreBBs) {
if (analyzeAndPruneOutputBlocks(OutputBBs, Region))
return;
Optional<unsigned> MatchingBB =
findDuplicateOutputBlock(OutputBBs, OutputStoreBBs);
if (MatchingBB) {
LLVM_DEBUG(dbgs() << "Set output block for region in function"
<< Region.ExtractedFunction << " to "
<< MatchingBB.value());
Region.OutputBlockNum = MatchingBB.value();
for (std::pair<Value *, BasicBlock *> &VtoBB : OutputBBs)
VtoBB.second->eraseFromParent();
return;
}
Region.OutputBlockNum = OutputStoreBBs.size();
Value *RetValueForBB;
BasicBlock *NewBB;
OutputStoreBBs.push_back(DenseMap<Value *, BasicBlock *>());
for (std::pair<Value *, BasicBlock *> &VtoBB : OutputBBs) {
RetValueForBB = VtoBB.first;
NewBB = VtoBB.second;
DenseMap<Value *, BasicBlock *>::iterator VBBIt =
EndBBs.find(RetValueForBB);
LLVM_DEBUG(dbgs() << "Create output block for region in"
<< Region.ExtractedFunction << " to "
<< *NewBB);
BranchInst::Create(VBBIt->second, NewBB);
OutputStoreBBs.back().insert(std::make_pair(RetValueForBB, NewBB));
}
}
static void createAndInsertBasicBlocks(DenseMap<Value *, BasicBlock *> &OldMap,
DenseMap<Value *, BasicBlock *> &NewMap,
Function *ParentFunc, Twine BaseName) {
unsigned Idx = 0;
std::vector<Value *> SortedKeys;
getSortedConstantKeys(SortedKeys, OldMap);
for (Value *RetVal : SortedKeys) {
BasicBlock *NewBB = BasicBlock::Create(
ParentFunc->getContext(),
Twine(BaseName) + Twine("_") + Twine(static_cast<unsigned>(Idx++)),
ParentFunc);
NewMap.insert(std::make_pair(RetVal, NewBB));
}
}
void createSwitchStatement(
Module &M, OutlinableGroup &OG, DenseMap<Value *, BasicBlock *> &EndBBs,
std::vector<DenseMap<Value *, BasicBlock *>> &OutputStoreBBs) {
if (OG.OutputGVNCombinations.size() > 1) {
Function *AggFunc = OG.OutlinedFunction;
DenseMap<Value *, BasicBlock *> ReturnBBs;
createAndInsertBasicBlocks(OG.EndBBs, ReturnBBs, AggFunc, "final_block");
for (std::pair<Value *, BasicBlock *> &RetBlockPair : ReturnBBs) {
std::pair<Value *, BasicBlock *> &OutputBlock =
*OG.EndBBs.find(RetBlockPair.first);
BasicBlock *ReturnBlock = RetBlockPair.second;
BasicBlock *EndBB = OutputBlock.second;
Instruction *Term = EndBB->getTerminator();
Term->moveBefore(*ReturnBlock, ReturnBlock->end());
LLVM_DEBUG(dbgs() << "Create switch statement in " << *AggFunc << " for "
<< OutputStoreBBs.size() << "\n");
SwitchInst *SwitchI =
SwitchInst::Create(AggFunc->getArg(AggFunc->arg_size() - 1),
ReturnBlock, OutputStoreBBs.size(), EndBB);
unsigned Idx = 0;
for (DenseMap<Value *, BasicBlock *> &OutputStoreBB : OutputStoreBBs) {
DenseMap<Value *, BasicBlock *>::iterator OSBBIt =
OutputStoreBB.find(OutputBlock.first);
if (OSBBIt == OutputStoreBB.end())
continue;
BasicBlock *BB = OSBBIt->second;
SwitchI->addCase(
ConstantInt::get(Type::getInt32Ty(M.getContext()), Idx), BB);
Term = BB->getTerminator();
Term->setSuccessor(0, ReturnBlock);
Idx++;
}
}
return;
}
assert(OutputStoreBBs.size() < 2 && "Different store sets not handled!");
if (OutputStoreBBs.size() == 1) {
LLVM_DEBUG(dbgs() << "Move store instructions to the end block in "
<< *OG.OutlinedFunction << "\n");
DenseMap<Value *, BasicBlock *> OutputBlocks = OutputStoreBBs[0];
for (std::pair<Value *, BasicBlock *> &VBPair : OutputBlocks) {
DenseMap<Value *, BasicBlock *>::iterator EndBBIt =
EndBBs.find(VBPair.first);
assert(EndBBIt != EndBBs.end() && "Could not find end block");
BasicBlock *EndBB = EndBBIt->second;
BasicBlock *OutputBB = VBPair.second;
Instruction *Term = OutputBB->getTerminator();
Term->eraseFromParent();
Term = EndBB->getTerminator();
moveBBContents(*OutputBB, *EndBB);
Term->moveBefore(*EndBB, EndBB->end());
OutputBB->eraseFromParent();
}
}
}
static void fillOverallFunction(
Module &M, OutlinableGroup &CurrentGroup,
std::vector<DenseMap<Value *, BasicBlock *>> &OutputStoreBBs,
std::vector<Function *> &FuncsToRemove,
const DenseMap<Value *, Value *> &OutputMappings) {
OutlinableRegion *CurrentOS = CurrentGroup.Regions[0];
LLVM_DEBUG(dbgs() << "Move instructions from "
<< *CurrentOS->ExtractedFunction << " to instruction "
<< *CurrentGroup.OutlinedFunction << "\n");
moveFunctionData(*CurrentOS->ExtractedFunction,
*CurrentGroup.OutlinedFunction, CurrentGroup.EndBBs);
for (Attribute A : CurrentOS->ExtractedFunction->getAttributes().getFnAttrs())
CurrentGroup.OutlinedFunction->addFnAttr(A);
DenseMap<Value *, BasicBlock *> NewBBs;
createAndInsertBasicBlocks(CurrentGroup.EndBBs, NewBBs,
CurrentGroup.OutlinedFunction, "output_block_0");
CurrentOS->OutputBlockNum = 0;
replaceArgumentUses(*CurrentOS, NewBBs, OutputMappings, true);
replaceConstants(*CurrentOS);
if (!analyzeAndPruneOutputBlocks(NewBBs, *CurrentOS)) {
OutputStoreBBs.push_back(DenseMap<Value *, BasicBlock *>());
for (std::pair<Value *, BasicBlock *> &VToBB : NewBBs) {
DenseMap<Value *, BasicBlock *>::iterator VBBIt =
CurrentGroup.EndBBs.find(VToBB.first);
BasicBlock *EndBB = VBBIt->second;
BranchInst::Create(EndBB, VToBB.second);
OutputStoreBBs.back().insert(VToBB);
}
}
CurrentOS->Call = replaceCalledFunction(M, *CurrentOS);
FuncsToRemove.push_back(CurrentOS->ExtractedFunction);
}
void IROutliner::deduplicateExtractedSections(
Module &M, OutlinableGroup &CurrentGroup,
std::vector<Function *> &FuncsToRemove, unsigned &OutlinedFunctionNum) {
createFunction(M, CurrentGroup, OutlinedFunctionNum);
std::vector<DenseMap<Value *, BasicBlock *>> OutputStoreBBs;
OutlinableRegion *CurrentOS;
fillOverallFunction(M, CurrentGroup, OutputStoreBBs, FuncsToRemove,
OutputMappings);
std::vector<Value *> SortedKeys;
for (unsigned Idx = 1; Idx < CurrentGroup.Regions.size(); Idx++) {
CurrentOS = CurrentGroup.Regions[Idx];
AttributeFuncs::mergeAttributesForOutlining(*CurrentGroup.OutlinedFunction,
*CurrentOS->ExtractedFunction);
DenseMap<Value *, BasicBlock *> NewBBs;
createAndInsertBasicBlocks(
CurrentGroup.EndBBs, NewBBs, CurrentGroup.OutlinedFunction,
"output_block_" + Twine(static_cast<unsigned>(Idx)));
replaceArgumentUses(*CurrentOS, NewBBs, OutputMappings);
alignOutputBlockWithAggFunc(CurrentGroup, *CurrentOS, NewBBs,
CurrentGroup.EndBBs, OutputMappings,
OutputStoreBBs);
CurrentOS->Call = replaceCalledFunction(M, *CurrentOS);
FuncsToRemove.push_back(CurrentOS->ExtractedFunction);
}
createSwitchStatement(M, CurrentGroup, CurrentGroup.EndBBs, OutputStoreBBs);
OutlinedFunctionNum++;
}
static bool nextIRInstructionDataMatchesNextInst(IRInstructionData &ID) {
IRInstructionDataList::iterator NextIDIt = std::next(ID.getIterator());
Instruction *NextIDLInst = NextIDIt->Inst;
Instruction *NextModuleInst = nullptr;
if (!ID.Inst->isTerminator())
NextModuleInst = ID.Inst->getNextNonDebugInstruction();
else if (NextIDLInst != nullptr)
NextModuleInst =
&*NextIDIt->Inst->getParent()->instructionsWithoutDebug().begin();
if (NextIDLInst && NextIDLInst != NextModuleInst)
return false;
return true;
}
bool IROutliner::isCompatibleWithAlreadyOutlinedCode(
const OutlinableRegion &Region) {
IRSimilarityCandidate *IRSC = Region.Candidate;
unsigned StartIdx = IRSC->getStartIdx();
unsigned EndIdx = IRSC->getEndIdx();
for (unsigned Idx = StartIdx; Idx <= EndIdx; Idx++)
if (Outlined.contains(Idx))
return false;
if (!Region.Candidate->backInstruction()->isTerminator()) {
Instruction *NewEndInst =
Region.Candidate->backInstruction()->getNextNonDebugInstruction();
assert(NewEndInst && "Next instruction is a nullptr?");
if (Region.Candidate->end()->Inst != NewEndInst) {
IRInstructionDataList *IDL = Region.Candidate->front()->IDL;
IRInstructionData *NewEndIRID = new (InstDataAllocator.Allocate())
IRInstructionData(*NewEndInst,
InstructionClassifier.visit(*NewEndInst), *IDL);
IDL->insert(Region.Candidate->end(), *NewEndIRID);
}
}
return none_of(*IRSC, [this](IRInstructionData &ID) {
if (!nextIRInstructionDataMatchesNextInst(ID))
return true;
return !this->InstructionClassifier.visit(ID.Inst);
});
}
void IROutliner::pruneIncompatibleRegions(
std::vector<IRSimilarityCandidate> &CandidateVec,
OutlinableGroup &CurrentGroup) {
bool PreviouslyOutlined;
stable_sort(CandidateVec, [](const IRSimilarityCandidate &LHS,
const IRSimilarityCandidate &RHS) {
return LHS.getStartIdx() < RHS.getStartIdx();
});
IRSimilarityCandidate &FirstCandidate = CandidateVec[0];
if (FirstCandidate.getLength() == 2) {
if (isa<CallInst>(FirstCandidate.front()->Inst) &&
isa<BranchInst>(FirstCandidate.back()->Inst))
return;
}
unsigned CurrentEndIdx = 0;
for (IRSimilarityCandidate &IRSC : CandidateVec) {
PreviouslyOutlined = false;
unsigned StartIdx = IRSC.getStartIdx();
unsigned EndIdx = IRSC.getEndIdx();
for (unsigned Idx = StartIdx; Idx <= EndIdx; Idx++)
if (Outlined.contains(Idx)) {
PreviouslyOutlined = true;
break;
}
if (PreviouslyOutlined)
continue;
bool BBHasAddressTaken = any_of(IRSC, [](IRInstructionData &ID){
return ID.Inst->getParent()->hasAddressTaken();
});
if (BBHasAddressTaken)
continue;
if (IRSC.getFunction()->hasOptNone())
continue;
if (IRSC.front()->Inst->getFunction()->hasLinkOnceODRLinkage() &&
!OutlineFromLinkODRs)
continue;
if (CurrentEndIdx != 0 && StartIdx <= CurrentEndIdx)
continue;
bool BadInst = any_of(IRSC, [this](IRInstructionData &ID) {
if (!nextIRInstructionDataMatchesNextInst(ID))
return true;
return !this->InstructionClassifier.visit(ID.Inst);
});
if (BadInst)
continue;
OutlinableRegion *OS = new (RegionAllocator.Allocate())
OutlinableRegion(IRSC, CurrentGroup);
CurrentGroup.Regions.push_back(OS);
CurrentEndIdx = EndIdx;
}
}
InstructionCost
IROutliner::findBenefitFromAllRegions(OutlinableGroup &CurrentGroup) {
InstructionCost RegionBenefit = 0;
for (OutlinableRegion *Region : CurrentGroup.Regions) {
TargetTransformInfo &TTI = getTTI(*Region->StartBB->getParent());
RegionBenefit += Region->getBenefit(TTI);
LLVM_DEBUG(dbgs() << "Adding: " << RegionBenefit
<< " saved instructions to overfall benefit.\n");
}
return RegionBenefit;
}
static Value *findOutputValueInRegion(OutlinableRegion &Region,
unsigned OutputCanon) {
OutlinableGroup &CurrentGroup = *Region.Parent;
if (OutputCanon > CurrentGroup.PHINodeGVNTracker) {
auto It = CurrentGroup.PHINodeGVNToGVNs.find(OutputCanon);
assert(It != CurrentGroup.PHINodeGVNToGVNs.end() &&
"Could not find GVN set for PHINode number!");
assert(It->second.second.size() > 0 && "PHINode does not have any values!");
OutputCanon = *It->second.second.begin();
}
Optional<unsigned> OGVN = Region.Candidate->fromCanonicalNum(OutputCanon);
assert(OGVN && "Could not find GVN for Canonical Number?");
Optional<Value *> OV = Region.Candidate->fromGVN(*OGVN);
assert(OV && "Could not find value for GVN?");
return *OV;
}
InstructionCost
IROutliner::findCostOutputReloads(OutlinableGroup &CurrentGroup) {
InstructionCost OverallCost = 0;
for (OutlinableRegion *Region : CurrentGroup.Regions) {
TargetTransformInfo &TTI = getTTI(*Region->StartBB->getParent());
for (unsigned OutputCanon : Region->GVNStores) {
Value *V = findOutputValueInRegion(*Region, OutputCanon);
InstructionCost LoadCost =
TTI.getMemoryOpCost(Instruction::Load, V->getType(), Align(1), 0,
TargetTransformInfo::TCK_CodeSize);
LLVM_DEBUG(dbgs() << "Adding: " << LoadCost
<< " instructions to cost for output of type "
<< *V->getType() << "\n");
OverallCost += LoadCost;
}
}
return OverallCost;
}
static InstructionCost findCostForOutputBlocks(Module &M,
OutlinableGroup &CurrentGroup,
TargetTransformInfo &TTI) {
InstructionCost OutputCost = 0;
unsigned NumOutputBranches = 0;
OutlinableRegion &FirstRegion = *CurrentGroup.Regions[0];
IRSimilarityCandidate &Candidate = *CurrentGroup.Regions[0]->Candidate;
DenseSet<BasicBlock *> CandidateBlocks;
Candidate.getBasicBlocks(CandidateBlocks);
DenseSet<BasicBlock *> FoundBlocks;
for (IRInstructionData &ID : Candidate) {
if (!isa<BranchInst>(ID.Inst))
continue;
for (Value *V : ID.OperVals) {
BasicBlock *BB = static_cast<BasicBlock *>(V);
if (!CandidateBlocks.contains(BB) && FoundBlocks.insert(BB).second)
NumOutputBranches++;
}
}
CurrentGroup.BranchesToOutside = NumOutputBranches;
for (const ArrayRef<unsigned> &OutputUse :
CurrentGroup.OutputGVNCombinations) {
for (unsigned OutputCanon : OutputUse) {
Value *V = findOutputValueInRegion(FirstRegion, OutputCanon);
InstructionCost StoreCost =
TTI.getMemoryOpCost(Instruction::Load, V->getType(), Align(1), 0,
TargetTransformInfo::TCK_CodeSize);
LLVM_DEBUG(dbgs() << "Adding: " << StoreCost
<< " instructions to cost for output of type "
<< *V->getType() << "\n");
OutputCost += StoreCost * NumOutputBranches;
}
InstructionCost BranchCost =
TTI.getCFInstrCost(Instruction::Br, TargetTransformInfo::TCK_CodeSize);
LLVM_DEBUG(dbgs() << "Adding " << BranchCost << " to the current cost for"
<< " a branch instruction\n");
OutputCost += BranchCost * NumOutputBranches;
}
if (CurrentGroup.OutputGVNCombinations.size() > 1) {
InstructionCost ComparisonCost = TTI.getCmpSelInstrCost(
Instruction::ICmp, Type::getInt32Ty(M.getContext()),
Type::getInt32Ty(M.getContext()), CmpInst::BAD_ICMP_PREDICATE,
TargetTransformInfo::TCK_CodeSize);
InstructionCost BranchCost =
TTI.getCFInstrCost(Instruction::Br, TargetTransformInfo::TCK_CodeSize);
unsigned DifferentBlocks = CurrentGroup.OutputGVNCombinations.size();
InstructionCost TotalCost = ComparisonCost * BranchCost * DifferentBlocks;
LLVM_DEBUG(dbgs() << "Adding: " << TotalCost
<< " instructions for each switch case for each different"
<< " output path in a function\n");
OutputCost += TotalCost * NumOutputBranches;
}
return OutputCost;
}
void IROutliner::findCostBenefit(Module &M, OutlinableGroup &CurrentGroup) {
InstructionCost RegionBenefit = findBenefitFromAllRegions(CurrentGroup);
CurrentGroup.Benefit += RegionBenefit;
LLVM_DEBUG(dbgs() << "Current Benefit: " << CurrentGroup.Benefit << "\n");
InstructionCost OutputReloadCost = findCostOutputReloads(CurrentGroup);
CurrentGroup.Cost += OutputReloadCost;
LLVM_DEBUG(dbgs() << "Current Cost: " << CurrentGroup.Cost << "\n");
InstructionCost AverageRegionBenefit =
RegionBenefit / CurrentGroup.Regions.size();
unsigned OverallArgumentNum = CurrentGroup.ArgumentTypes.size();
unsigned NumRegions = CurrentGroup.Regions.size();
TargetTransformInfo &TTI =
getTTI(*CurrentGroup.Regions[0]->Candidate->getFunction());
LLVM_DEBUG(dbgs() << "Adding: " << AverageRegionBenefit
<< " instructions to cost for body of new function.\n");
CurrentGroup.Cost += AverageRegionBenefit;
LLVM_DEBUG(dbgs() << "Current Cost: " << CurrentGroup.Cost << "\n");
LLVM_DEBUG(dbgs() << "Adding: " << OverallArgumentNum
<< " instructions to cost for each argument in the new"
<< " function.\n");
CurrentGroup.Cost +=
OverallArgumentNum * TargetTransformInfo::TCC_Basic;
LLVM_DEBUG(dbgs() << "Current Cost: " << CurrentGroup.Cost << "\n");
LLVM_DEBUG(dbgs() << "Adding: " << OverallArgumentNum
<< " instructions to cost for each argument in the new"
<< " function " << NumRegions << " times for the "
<< "needed argument handling at the call site.\n");
CurrentGroup.Cost +=
2 * OverallArgumentNum * TargetTransformInfo::TCC_Basic * NumRegions;
LLVM_DEBUG(dbgs() << "Current Cost: " << CurrentGroup.Cost << "\n");
CurrentGroup.Cost += findCostForOutputBlocks(M, CurrentGroup, TTI);
LLVM_DEBUG(dbgs() << "Current Cost: " << CurrentGroup.Cost << "\n");
}
void IROutliner::updateOutputMapping(OutlinableRegion &Region,
ArrayRef<Value *> Outputs,
LoadInst *LI) {
Value *Operand = LI->getPointerOperand();
Optional<unsigned> OutputIdx = None;
for (unsigned ArgIdx = Region.NumExtractedInputs;
ArgIdx < Region.Call->arg_size(); ArgIdx++) {
if (Operand == Region.Call->getArgOperand(ArgIdx)) {
OutputIdx = ArgIdx - Region.NumExtractedInputs;
break;
}
}
if (!OutputIdx)
return;
if (OutputMappings.find(Outputs[OutputIdx.value()]) == OutputMappings.end()) {
LLVM_DEBUG(dbgs() << "Mapping extracted output " << *LI << " to "
<< *Outputs[OutputIdx.value()] << "\n");
OutputMappings.insert(std::make_pair(LI, Outputs[OutputIdx.value()]));
} else {
Value *Orig = OutputMappings.find(Outputs[OutputIdx.value()])->second;
LLVM_DEBUG(dbgs() << "Mapping extracted output " << *Orig << " to "
<< *Outputs[OutputIdx.value()] << "\n");
OutputMappings.insert(std::make_pair(LI, Orig));
}
}
bool IROutliner::extractSection(OutlinableRegion &Region) {
SetVector<Value *> ArgInputs, Outputs, SinkCands;
assert(Region.StartBB && "StartBB for the OutlinableRegion is nullptr!");
BasicBlock *InitialStart = Region.StartBB;
Function *OrigF = Region.StartBB->getParent();
CodeExtractorAnalysisCache CEAC(*OrigF);
Region.ExtractedFunction =
Region.CE->extractCodeRegion(CEAC, ArgInputs, Outputs);
if (!Region.ExtractedFunction) {
LLVM_DEBUG(dbgs() << "CodeExtractor failed to outline " << Region.StartBB
<< "\n");
Region.reattachCandidate();
return false;
}
User *InstAsUser = Region.ExtractedFunction->user_back();
BasicBlock *RewrittenBB = cast<Instruction>(InstAsUser)->getParent();
Region.PrevBB = RewrittenBB->getSinglePredecessor();
assert(Region.PrevBB && "PrevBB is nullptr?");
if (Region.PrevBB == InitialStart) {
BasicBlock *NewPrev = InitialStart->getSinglePredecessor();
Instruction *BI = NewPrev->getTerminator();
BI->eraseFromParent();
moveBBContents(*InitialStart, *NewPrev);
Region.PrevBB = NewPrev;
InitialStart->eraseFromParent();
}
Region.StartBB = RewrittenBB;
Region.EndBB = RewrittenBB;
IRInstructionDataList *IDL = Region.Candidate->front()->IDL;
Instruction *BeginRewritten = &*RewrittenBB->begin();
Instruction *EndRewritten = &*RewrittenBB->begin();
Region.NewFront = new (InstDataAllocator.Allocate()) IRInstructionData(
*BeginRewritten, InstructionClassifier.visit(*BeginRewritten), *IDL);
Region.NewBack = new (InstDataAllocator.Allocate()) IRInstructionData(
*EndRewritten, InstructionClassifier.visit(*EndRewritten), *IDL);
IDL->insert(Region.Candidate->begin(), *Region.NewFront);
IDL->insert(Region.Candidate->end(), *Region.NewBack);
IDL->erase(Region.Candidate->begin(), std::prev(Region.Candidate->end()));
assert(RewrittenBB != nullptr &&
"Could not find a predecessor after extraction!");
for (Instruction &I : *RewrittenBB)
if (CallInst *CI = dyn_cast<CallInst>(&I)) {
if (Region.ExtractedFunction == CI->getCalledFunction())
Region.Call = CI;
} else if (LoadInst *LI = dyn_cast<LoadInst>(&I))
updateOutputMapping(Region, Outputs.getArrayRef(), LI);
Region.reattachCandidate();
return true;
}
unsigned IROutliner::doOutline(Module &M) {
InstructionClassifier.EnableBranches = !DisableBranches;
InstructionClassifier.EnableIndirectCalls = !DisableIndirectCalls;
InstructionClassifier.EnableIntrinsics = !DisableIntrinsics;
IRSimilarityIdentifier &Identifier = getIRSI(M);
SimilarityGroupList &SimilarityCandidates = *Identifier.getSimilarity();
unsigned OutlinedFunctionNum = 0;
if (SimilarityCandidates.size() > 1)
llvm::stable_sort(SimilarityCandidates,
[](const std::vector<IRSimilarityCandidate> &LHS,
const std::vector<IRSimilarityCandidate> &RHS) {
return LHS[0].getLength() * LHS.size() >
RHS[0].getLength() * RHS.size();
});
std::vector<OutlinableGroup> PotentialGroups(SimilarityCandidates.size());
DenseSet<unsigned> NotSame;
std::vector<OutlinableGroup *> NegativeCostGroups;
std::vector<OutlinableRegion *> OutlinedRegions;
unsigned PotentialGroupIdx = 0;
for (SimilarityGroup &CandidateVec : SimilarityCandidates) {
OutlinableGroup &CurrentGroup = PotentialGroups[PotentialGroupIdx++];
pruneIncompatibleRegions(CandidateVec, CurrentGroup);
if (CurrentGroup.Regions.size() < 2)
continue;
NotSame.clear();
CurrentGroup.findSameConstants(NotSame);
if (CurrentGroup.IgnoreGroup)
continue;
OutlinedRegions.clear();
for (OutlinableRegion *OS : CurrentGroup.Regions) {
OS->splitCandidate();
if (!OS->CandidateSplit)
continue;
SmallVector<BasicBlock *> BE;
DenseSet<BasicBlock *> BlocksInRegion;
OS->Candidate->getBasicBlocks(BlocksInRegion, BE);
OS->CE = new (ExtractorAllocator.Allocate())
CodeExtractor(BE, nullptr, false, nullptr, nullptr, nullptr, false,
false, nullptr, "outlined");
findAddInputsOutputs(M, *OS, NotSame);
if (!OS->IgnoreRegion)
OutlinedRegions.push_back(OS);
OS->reattachCandidate();
}
CurrentGroup.Regions = std::move(OutlinedRegions);
if (CurrentGroup.Regions.empty())
continue;
CurrentGroup.collectGVNStoreSets(M);
if (CostModel)
findCostBenefit(M, CurrentGroup);
if (CurrentGroup.Cost >= CurrentGroup.Benefit && CostModel) {
OptimizationRemarkEmitter &ORE =
getORE(*CurrentGroup.Regions[0]->Candidate->getFunction());
ORE.emit([&]() {
IRSimilarityCandidate *C = CurrentGroup.Regions[0]->Candidate;
OptimizationRemarkMissed R(DEBUG_TYPE, "WouldNotDecreaseSize",
C->frontInstruction());
R << "did not outline "
<< ore::NV(std::to_string(CurrentGroup.Regions.size()))
<< " regions due to estimated increase of "
<< ore::NV("InstructionIncrease",
CurrentGroup.Cost - CurrentGroup.Benefit)
<< " instructions at locations ";
interleave(
CurrentGroup.Regions.begin(), CurrentGroup.Regions.end(),
[&R](OutlinableRegion *Region) {
R << ore::NV(
"DebugLoc",
Region->Candidate->frontInstruction()->getDebugLoc());
},
[&R]() { R << " "; });
return R;
});
continue;
}
NegativeCostGroups.push_back(&CurrentGroup);
}
ExtractorAllocator.DestroyAll();
if (NegativeCostGroups.size() > 1)
stable_sort(NegativeCostGroups,
[](const OutlinableGroup *LHS, const OutlinableGroup *RHS) {
return LHS->Benefit - LHS->Cost > RHS->Benefit - RHS->Cost;
});
std::vector<Function *> FuncsToRemove;
for (OutlinableGroup *CG : NegativeCostGroups) {
OutlinableGroup &CurrentGroup = *CG;
OutlinedRegions.clear();
for (OutlinableRegion *Region : CurrentGroup.Regions) {
if (!isCompatibleWithAlreadyOutlinedCode(*Region))
continue;
OutlinedRegions.push_back(Region);
}
if (OutlinedRegions.size() < 2)
continue;
CurrentGroup.Regions = std::move(OutlinedRegions);
if (CostModel) {
CurrentGroup.Benefit = 0;
CurrentGroup.Cost = 0;
findCostBenefit(M, CurrentGroup);
if (CurrentGroup.Cost >= CurrentGroup.Benefit)
continue;
}
OutlinedRegions.clear();
for (OutlinableRegion *Region : CurrentGroup.Regions) {
Region->splitCandidate();
if (!Region->CandidateSplit)
continue;
OutlinedRegions.push_back(Region);
}
CurrentGroup.Regions = std::move(OutlinedRegions);
if (CurrentGroup.Regions.size() < 2) {
for (OutlinableRegion *R : CurrentGroup.Regions)
R->reattachCandidate();
continue;
}
LLVM_DEBUG(dbgs() << "Outlining regions with cost " << CurrentGroup.Cost
<< " and benefit " << CurrentGroup.Benefit << "\n");
OutlinedRegions.clear();
for (OutlinableRegion *OS : CurrentGroup.Regions) {
SmallVector<BasicBlock *> BE;
DenseSet<BasicBlock *> BlocksInRegion;
OS->Candidate->getBasicBlocks(BlocksInRegion, BE);
OS->CE = new (ExtractorAllocator.Allocate())
CodeExtractor(BE, nullptr, false, nullptr, nullptr, nullptr, false,
false, nullptr, "outlined");
bool FunctionOutlined = extractSection(*OS);
if (FunctionOutlined) {
unsigned StartIdx = OS->Candidate->getStartIdx();
unsigned EndIdx = OS->Candidate->getEndIdx();
for (unsigned Idx = StartIdx; Idx <= EndIdx; Idx++)
Outlined.insert(Idx);
OutlinedRegions.push_back(OS);
}
}
LLVM_DEBUG(dbgs() << "Outlined " << OutlinedRegions.size()
<< " with benefit " << CurrentGroup.Benefit
<< " and cost " << CurrentGroup.Cost << "\n");
CurrentGroup.Regions = std::move(OutlinedRegions);
if (CurrentGroup.Regions.empty())
continue;
OptimizationRemarkEmitter &ORE =
getORE(*CurrentGroup.Regions[0]->Call->getFunction());
ORE.emit([&]() {
IRSimilarityCandidate *C = CurrentGroup.Regions[0]->Candidate;
OptimizationRemark R(DEBUG_TYPE, "Outlined", C->front()->Inst);
R << "outlined " << ore::NV(std::to_string(CurrentGroup.Regions.size()))
<< " regions with decrease of "
<< ore::NV("Benefit", CurrentGroup.Benefit - CurrentGroup.Cost)
<< " instructions at locations ";
interleave(
CurrentGroup.Regions.begin(), CurrentGroup.Regions.end(),
[&R](OutlinableRegion *Region) {
R << ore::NV("DebugLoc",
Region->Candidate->frontInstruction()->getDebugLoc());
},
[&R]() { R << " "; });
return R;
});
deduplicateExtractedSections(M, CurrentGroup, FuncsToRemove,
OutlinedFunctionNum);
}
for (Function *F : FuncsToRemove)
F->eraseFromParent();
return OutlinedFunctionNum;
}
bool IROutliner::run(Module &M) {
CostModel = !NoCostModel;
OutlineFromLinkODRs = EnableLinkOnceODRIROutlining;
return doOutline(M) > 0;
}
namespace {
class IROutlinerLegacyPass : public ModulePass {
public:
static char ID;
IROutlinerLegacyPass() : ModulePass(ID) {
initializeIROutlinerLegacyPassPass(*PassRegistry::getPassRegistry());
}
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
AU.addRequired<TargetTransformInfoWrapperPass>();
AU.addRequired<IRSimilarityIdentifierWrapperPass>();
}
bool runOnModule(Module &M) override;
};
}
bool IROutlinerLegacyPass::runOnModule(Module &M) {
if (skipModule(M))
return false;
std::unique_ptr<OptimizationRemarkEmitter> ORE;
auto GORE = [&ORE](Function &F) -> OptimizationRemarkEmitter & {
ORE.reset(new OptimizationRemarkEmitter(&F));
return *ORE;
};
auto GTTI = [this](Function &F) -> TargetTransformInfo & {
return this->getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
};
auto GIRSI = [this](Module &) -> IRSimilarityIdentifier & {
return this->getAnalysis<IRSimilarityIdentifierWrapperPass>().getIRSI();
};
return IROutliner(GTTI, GIRSI, GORE).run(M);
}
PreservedAnalyses IROutlinerPass::run(Module &M, ModuleAnalysisManager &AM) {
auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
std::function<TargetTransformInfo &(Function &)> GTTI =
[&FAM](Function &F) -> TargetTransformInfo & {
return FAM.getResult<TargetIRAnalysis>(F);
};
std::function<IRSimilarityIdentifier &(Module &)> GIRSI =
[&AM](Module &M) -> IRSimilarityIdentifier & {
return AM.getResult<IRSimilarityAnalysis>(M);
};
std::unique_ptr<OptimizationRemarkEmitter> ORE;
std::function<OptimizationRemarkEmitter &(Function &)> GORE =
[&ORE](Function &F) -> OptimizationRemarkEmitter & {
ORE.reset(new OptimizationRemarkEmitter(&F));
return *ORE;
};
if (IROutliner(GTTI, GIRSI, GORE).run(M))
return PreservedAnalyses::none();
return PreservedAnalyses::all();
}
char IROutlinerLegacyPass::ID = 0;
INITIALIZE_PASS_BEGIN(IROutlinerLegacyPass, "iroutliner", "IR Outliner", false,
false)
INITIALIZE_PASS_DEPENDENCY(IRSimilarityIdentifierWrapperPass)
INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
INITIALIZE_PASS_END(IROutlinerLegacyPass, "iroutliner", "IR Outliner", false,
false)
ModulePass *llvm::createIROutlinerPass() { return new IROutlinerLegacyPass(); }