Update LoopInfo correctly

When the Polly code generation was written we did not correctly update the
LoopInfo data, but still claimed that the loop information is correct. This
does not only lead to missed optimizations, but it can also cause
miscompilations in case passes such as LoopSimplify are run after Polly.

Reported-by: Sergei Larin <slarin@codeaurora.org>
llvm-svn: 181987
diff --git a/polly/lib/CodeGen/LoopGenerators.cpp b/polly/lib/CodeGen/LoopGenerators.cpp
index 881a0ac..da0c782 100644
--- a/polly/lib/CodeGen/LoopGenerators.cpp
+++ b/polly/lib/CodeGen/LoopGenerators.cpp
@@ -15,6 +15,7 @@
 #include "polly/ScopDetection.h"
 #include "polly/CodeGen/LoopGenerators.h"
 #include "llvm/Analysis/Dominators.h"
+#include "llvm/Analysis/LoopInfo.h"
 #include "llvm/IR/DataLayout.h"
 #include "llvm/IR/Module.h"
 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
@@ -50,6 +51,7 @@
                          ICmpInst::Predicate Predicate) {
 
   DominatorTree &DT = P->getAnalysis<DominatorTree>();
+  LoopInfo &LI = P->getAnalysis<LoopInfo>();
   Function *F = Builder.GetInsertBlock()->getParent();
   LLVMContext &Context = F->getContext();
 
@@ -63,6 +65,23 @@
   BasicBlock *PreHeaderBB =
       BasicBlock::Create(Context, "polly.loop_preheader", F);
 
+  // Update LoopInfo
+  Loop *OuterLoop = LI.getLoopFor(BeforeBB);
+  Loop *NewLoop = new Loop();
+
+  if (OuterLoop) {
+    OuterLoop->addChildLoop(NewLoop);
+  } else {
+    LI.addTopLevelLoop(NewLoop);
+  }
+
+  if (OuterLoop) {
+    OuterLoop->addBasicBlockToLoop(GuardBB, LI.getBase());
+    OuterLoop->addBasicBlockToLoop(PreHeaderBB, LI.getBase());
+  }
+
+  NewLoop->addBasicBlockToLoop(HeaderBB, LI.getBase());
+
   // ExitBB
   ExitBB = SplitBlock(BeforeBB, Builder.GetInsertPoint()++, P);
   ExitBB->setName("polly.loop_exit");