From 8159755faa3a484438ee6d87b046fa9b68e408eb Mon Sep 17 00:00:00 2001
From: Owen Anderson <resistor@mac.com>
Date: Mon, 19 Jul 2010 08:09:34 +0000
Subject: [PATCH] Reimplement r108639 in InstCombine rather than DAGCombine.

llvm-svn: 108687
---
 .../InstCombine/InstCombineCasts.cpp          | 26 +++++++++++++++++++
 1 file changed, 26 insertions(+)

diff --git a/lib/Transforms/InstCombine/InstCombineCasts.cpp b/lib/Transforms/InstCombine/InstCombineCasts.cpp
index 505a0bf8f4e..042bf1a9829 100644
--- a/lib/Transforms/InstCombine/InstCombineCasts.cpp
+++ b/lib/Transforms/InstCombine/InstCombineCasts.cpp
@@ -1097,6 +1097,32 @@ Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
       break;  
     }
   }
+  
+  // Fold (fptrunc (sqrt (fpext x))) -> (sqrtf x)
+  // NOTE: This should be disabled by -fno-builtin-sqrt if we ever support it.
+  CallInst *Call = dyn_cast<CallInst>(CI.getOperand(0));
+  if (Call && Call->getCalledFunction() &&
+      Call->getCalledFunction()->getName() == "sqrt" &&
+      Call->getNumArgOperands() == 1) {
+    CastInst *Arg = dyn_cast<CastInst>(Call->getArgOperand(0));
+    if (Arg && Arg->getOpcode() == Instruction::FPExt &&
+        CI.getType() == Builder->getFloatTy() &&
+        Call->getType() == Builder->getDoubleTy() &&
+        Arg->getType() == Builder->getDoubleTy() &&
+        Arg->getOperand(0)->getType() == Builder->getFloatTy()) {
+      Module* M = CI.getParent()->getParent()->getParent();
+      Constant* SqrtfFunc = M->getOrInsertFunction("sqrtf", 
+                                                   Call->getAttributes(),
+                                                   Builder->getFloatTy(),
+                                                   Builder->getFloatTy(),
+                                                   NULL);
+      CallInst *ret = CallInst::Create(SqrtfFunc, Arg->getOperand(0),
+                                       "sqrtfcall");
+      ret->setAttributes(Call->getAttributes());
+      return ret;
+    }
+  }
+  
   return 0;
 }