Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

More general for loop structure #12

Merged
merged 3 commits into from
Sep 23, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
117 changes: 36 additions & 81 deletions enzyme/Enzyme/Enzyme.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -877,7 +877,7 @@ void forceRecursiveInlining(Function *NewF, const Function* F) {

class GradientUtils;

PHINode* canonicalizeIVs(Type *Ty, Loop *L, ScalarEvolution &SE, DominatorTree &DT, GradientUtils* gutils);
PHINode* canonicalizeIVs(fake::SCEVExpander &exp, Type *Ty, Loop *L, DominatorTree &DT, GradientUtils* gutils);

Function* preprocessForClone(Function *F, AAResults &AA, TargetLibraryInfo &TLI) {
static std::map<Function*,Function*> cache;
Expand Down Expand Up @@ -3484,6 +3484,9 @@ std::pair<Function*,StructType*> CreateAugmentedPrimal(Function* todiff, AAResul
if (NewF->hasAttribute(llvm::AttributeList::ReturnIndex, llvm::Attribute::NoAlias)) {
NewF->removeAttribute(llvm::AttributeList::ReturnIndex, llvm::Attribute::NoAlias);
}
if (NewF->hasAttribute(llvm::AttributeList::ReturnIndex, llvm::Attribute::ZExt)) {
NewF->removeAttribute(llvm::AttributeList::ReturnIndex, llvm::Attribute::ZExt);
}

if (llvm::verifyFunction(*NewF, &llvm::errs())) {
llvm::errs() << *gutils->oldFunc << "\n";
Expand Down Expand Up @@ -3575,10 +3578,10 @@ void createInvertedTerminator(DiffeGradientUtils* gutils, BasicBlock *BB, Alloca
Value* phi = nullptr;

if (inLoop && BB2 == gutils->reverseBlocks[loopContext.var->getParent()]) {
assert( ((preds[0] == loopContext.latch) && (preds[1] == loopContext.preheader)) || ((preds[1] == loopContext.latch) && (preds[0] == loopContext.preheader)) );
if (preds[0] == loopContext.latch)
assert( ((preds[0] == loopContext.preheader) || (preds[1] == loopContext.preheader)) );
if (preds[1] == loopContext.preheader)
phi = Builder.CreateICmpNE(loopContext.antivar, Constant::getNullValue(loopContext.antivar->getType()));
else if(preds[1] == loopContext.latch)
else if(preds[0] == loopContext.preheader)
phi = Builder.CreateICmpEQ(loopContext.antivar, Constant::getNullValue(loopContext.antivar->getType()));
else {
llvm::errs() << "weird behavior for loopContext\n";
Expand Down Expand Up @@ -4073,7 +4076,7 @@ Function* CreatePrimalAndGradient(Function* todiff, const std::set<unsigned>& co
ConstantInt::get(op->getOperand(2)->getType(), Builder2.GetInsertBlock()->getParent()->getParent()->getDataLayout().getTypeAllocSizeInBits(secretty)/8)
));
auto dmemcpy = getOrInsertDifferentialFloatMemcpy(*M, secretpt);
auto cal = Builder2.CreateCall(dmemcpy, args);
Builder2.CreateCall(dmemcpy, args);
} else {
if (topLevel) {
SmallVector<Value*, 4> args;
Expand Down Expand Up @@ -5010,6 +5013,9 @@ Function* CreatePrimalAndGradient(Function* todiff, const std::set<unsigned>& co
if (gutils->newFunc->hasAttribute(llvm::AttributeList::ReturnIndex, llvm::Attribute::NoAlias)) {
gutils->newFunc->removeAttribute(llvm::AttributeList::ReturnIndex, llvm::Attribute::NoAlias);
}
if (gutils->newFunc->hasAttribute(llvm::AttributeList::ReturnIndex, llvm::Attribute::ZExt)) {
gutils->newFunc->removeAttribute(llvm::AttributeList::ReturnIndex, llvm::Attribute::ZExt);
}

if (llvm::verifyFunction(*gutils->newFunc, &llvm::errs())) {
llvm::errs() << *gutils->oldFunc << "\n";
Expand Down Expand Up @@ -5184,16 +5190,17 @@ static bool lowerAutodiffIntrinsic(Function &F, TargetLibraryInfo &TLI, AAResult
return Changed;
}

PHINode* canonicalizeIVs(Type *Ty, Loop *L, ScalarEvolution &SE, DominatorTree &DT, GradientUtils* gutils) {
PHINode* canonicalizeIVs(fake::SCEVExpander &e, Type *Ty, Loop *L, DominatorTree &DT, GradientUtils* gutils) {

fake::SCEVExpander e(SE, L->getHeader()->getParent()->getParent()->getDataLayout(), "ad");

PHINode *CanonicalIV = e.getOrInsertCanonicalInductionVariable(L, Ty);

assert (CanonicalIV && "canonicalizing IV");

llvm::errs() << " after inserting var \n" << *CanonicalIV->getParent()->getParent() << "\n";

SmallVector<WeakTrackingVH, 16> DeadInst0;
e.replaceCongruentIVs(L, &DT, DeadInst0);
llvm::errs() << " after inserting var \n" << *CanonicalIV->getParent()->getParent() << "\n";
for (WeakTrackingVH V : DeadInst0) {
gutils->erase(cast<Instruction>(V)); //->eraseFromParent();
}
Expand All @@ -5210,67 +5217,21 @@ bool getContextM(BasicBlock *BB, LoopContext &loopContext, std::map<Loop*,LoopCo
return true;
}

SmallVector<BasicBlock *, 8> PotentialExitBlocks;
SmallPtrSet<BasicBlock *, 8> ExitBlocks;
L->getExitBlocks(PotentialExitBlocks);
for(auto a:PotentialExitBlocks) {

SmallVector<BasicBlock*, 4> tocheck;
SmallPtrSet<BasicBlock*, 4> checked;
tocheck.push_back(a);

bool isExit = false;

while(tocheck.size()) {
auto foo = tocheck.back();
tocheck.pop_back();
if (checked.count(foo)) {
isExit = true;
goto exitblockcheck;
}
checked.insert(foo);
if(auto bi = dyn_cast<BranchInst>(foo->getTerminator())) {
for(auto nb : bi->successors()) {
if (L->contains(nb)) continue;
tocheck.push_back(nb);
}
} else if (isa<UnreachableInst>(foo->getTerminator())) {
continue;
} else {
isExit = true;
goto exitblockcheck;
}
}


exitblockcheck:
if (isExit) {
ExitBlocks.insert(a);
}
}
BasicBlock *Header = L->getHeader();
assert(Header && "loop must have header");
BasicBlock *Preheader = L->getLoopPreheader();
assert(Preheader && "loop must have preheader");

if (ExitBlocks.size() != 1) {
assert(BB);
assert(BB->getParent());
assert(L);
llvm::errs() << *BB->getParent() << "\n";
llvm::errs() << *L << "\n";
for(auto b:ExitBlocks) {
assert(b);
llvm::errs() << *b << "\n";
}
llvm::errs() << "offending: \n";
llvm::errs() << "No unique exit block (1)\n";
}
fake::SCEVExpander Exp(SE, BB->getParent()->getParent()->getDataLayout(), "enzyme");
BasicBlock* ExitBlock = Exp.getExitBlock(L);

BasicBlock* ExitBlock = *ExitBlocks.begin(); //[0];
// This contains the block that branches to the exit
BasicBlock* Latch = Exp.getLatch(L, ExitBlock);

BasicBlock *Header = L->getHeader();
BasicBlock *Preheader = L->getLoopPreheader();
assert(Preheader && "requires preheader");
BasicBlock *Latch = L->getLoopLatch();
// Note exitcount needs the true latch (e.g. the one that branches back to header)
// tather than the latch that contains the branch (as we define latch)
const SCEV *Limit = SE.getBackedgeTakenCount(L); //getExitCount(L, ExitckedgeTakenCountBlock); //L->getLoopLatch());

const SCEV *Limit = SE.getExitCount(L, Latch);
SmallVector<PHINode*, 8> IVsToRemove;

PHINode *CanonicalIV = nullptr;
Expand All @@ -5280,36 +5241,31 @@ bool getContextM(BasicBlock *BB, LoopContext &loopContext, std::map<Loop*,LoopCo

if (SE.getCouldNotCompute() != Limit) {

CanonicalIV = canonicalizeIVs(Limit->getType(), L, SE, DT, &gutils);
CanonicalIV = canonicalizeIVs(Exp, Limit->getType(), L, DT, &gutils);
if (!CanonicalIV) {
report_fatal_error("Couldn't get canonical IV.");
}

const SCEVAddRecExpr *CanonicalSCEV = cast<const SCEVAddRecExpr>(SE.getSCEV(CanonicalIV));

assert(SE.isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT,
CanonicalSCEV, Limit) &&
"Loop backedge is not guarded by canonical comparison with limit.");

fake::SCEVExpander Exp(SE, Preheader->getParent()->getParent()->getDataLayout(), "ad");
LimitVar = Exp.expandCodeFor(Limit, CanonicalIV->getType(),
Preheader->getTerminator());

loopContext.dynamic = false;
} else {

//llvm::errs() << "Se has any info: " << SE.getBackedgeTakenInfo(L).hasAnyInfo() << "\n";
llvm::errs() << "SE could not compute loop limit.\n";

IRBuilder <>B(&Header->front());
CanonicalIV = B.CreatePHI(Type::getInt64Ty(Header->getContext()), 1); // should be Header->getNumPredecessors());
CanonicalIV = B.CreatePHI(Type::getInt64Ty(Header->getContext()), 1); //Header->getNumPredecessors());

B.SetInsertPoint(Header->getTerminator());
auto inc = B.CreateNUWAdd(CanonicalIV, ConstantInt::get(CanonicalIV->getType(), 1));
CanonicalIV->addIncoming(inc, Latch);
for (BasicBlock *Pred : predecessors(Header)) {
if (Pred != Latch) {
CanonicalIV->addIncoming(ConstantInt::get(CanonicalIV->getType(), 0), Pred);
assert(Pred);
if (L->contains(Pred)) {
assert(Pred->getTerminator());
IRBuilder<> bld(Pred->getTerminator());
auto inc = bld.CreateNUWAdd(CanonicalIV, ConstantInt::get(CanonicalIV->getType(), 1));
CanonicalIV->addIncoming(inc, Pred);
} else {
CanonicalIV->addIncoming(ConstantInt::get(CanonicalIV->getType(), 0), Pred);
}
}

Expand All @@ -5327,7 +5283,6 @@ bool getContextM(BasicBlock *BB, LoopContext &loopContext, std::map<Loop*,LoopCo

// Remove Canonicalizable IV's
{
fake::SCEVExpander Exp(SE, Preheader->getParent()->getParent()->getDataLayout(), "ad");
for (BasicBlock::iterator II = Header->begin(); isa<PHINode>(II); ++II) {
PHINode *PN = cast<PHINode>(II);
if (PN == CanonicalIV) continue;
Expand Down
Loading