Local.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  1. //===-- Local.cpp - Functions to perform local transformations ------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file was developed by the LLVM research group and is distributed under
  6. // the University of Illinois Open Source License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This family of functions perform various local transformations to the
  11. // program.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "llvm/Support/MathExtras.h"
  15. #include "llvm/Transforms/Utils/Local.h"
  16. #include "llvm/Constants.h"
  17. #include "llvm/Instructions.h"
  18. #include "llvm/Intrinsics.h"
  19. #include <cerrno>
  20. #include <cmath>
  21. using namespace llvm;
  22. //===----------------------------------------------------------------------===//
  23. // Local constant propagation...
  24. //
  25. /// doConstantPropagation - If an instruction references constants, try to fold
  26. /// them together...
  27. ///
  28. bool llvm::doConstantPropagation(BasicBlock::iterator &II) {
  29. if (Constant *C = ConstantFoldInstruction(II)) {
  30. // Replaces all of the uses of a variable with uses of the constant.
  31. II->replaceAllUsesWith(C);
  32. // Remove the instruction from the basic block...
  33. II = II->getParent()->getInstList().erase(II);
  34. return true;
  35. }
  36. return false;
  37. }
  38. /// ConstantFoldInstruction - Attempt to constant fold the specified
  39. /// instruction. If successful, the constant result is returned, if not, null
  40. /// is returned. Note that this function can only fail when attempting to fold
  41. /// instructions like loads and stores, which have no constant expression form.
  42. ///
  43. Constant *llvm::ConstantFoldInstruction(Instruction *I) {
  44. if (PHINode *PN = dyn_cast<PHINode>(I)) {
  45. if (PN->getNumIncomingValues() == 0)
  46. return Constant::getNullValue(PN->getType());
  47. Constant *Result = dyn_cast<Constant>(PN->getIncomingValue(0));
  48. if (Result == 0) return 0;
  49. // Handle PHI nodes specially here...
  50. for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i)
  51. if (PN->getIncomingValue(i) != Result && PN->getIncomingValue(i) != PN)
  52. return 0; // Not all the same incoming constants...
  53. // If we reach here, all incoming values are the same constant.
  54. return Result;
  55. } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
  56. if (Function *F = CI->getCalledFunction())
  57. if (canConstantFoldCallTo(F)) {
  58. std::vector<Constant*> Args;
  59. for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
  60. if (Constant *Op = dyn_cast<Constant>(CI->getOperand(i)))
  61. Args.push_back(Op);
  62. else
  63. return 0;
  64. return ConstantFoldCall(F, Args);
  65. }
  66. return 0;
  67. }
  68. Constant *Op0 = 0, *Op1 = 0;
  69. switch (I->getNumOperands()) {
  70. default:
  71. case 2:
  72. Op1 = dyn_cast<Constant>(I->getOperand(1));
  73. if (Op1 == 0) return 0; // Not a constant?, can't fold
  74. case 1:
  75. Op0 = dyn_cast<Constant>(I->getOperand(0));
  76. if (Op0 == 0) return 0; // Not a constant?, can't fold
  77. break;
  78. case 0: return 0;
  79. }
  80. if (isa<BinaryOperator>(I) || isa<ShiftInst>(I))
  81. return ConstantExpr::get(I->getOpcode(), Op0, Op1);
  82. switch (I->getOpcode()) {
  83. default: return 0;
  84. case Instruction::Cast:
  85. return ConstantExpr::getCast(Op0, I->getType());
  86. case Instruction::Select:
  87. if (Constant *Op2 = dyn_cast<Constant>(I->getOperand(2)))
  88. return ConstantExpr::getSelect(Op0, Op1, Op2);
  89. return 0;
  90. case Instruction::GetElementPtr:
  91. std::vector<Constant*> IdxList;
  92. IdxList.reserve(I->getNumOperands()-1);
  93. if (Op1) IdxList.push_back(Op1);
  94. for (unsigned i = 2, e = I->getNumOperands(); i != e; ++i)
  95. if (Constant *C = dyn_cast<Constant>(I->getOperand(i)))
  96. IdxList.push_back(C);
  97. else
  98. return 0; // Non-constant operand
  99. return ConstantExpr::getGetElementPtr(Op0, IdxList);
  100. }
  101. }
  102. // ConstantFoldTerminator - If a terminator instruction is predicated on a
  103. // constant value, convert it into an unconditional branch to the constant
  104. // destination.
  105. //
  106. bool llvm::ConstantFoldTerminator(BasicBlock *BB) {
  107. TerminatorInst *T = BB->getTerminator();
  108. // Branch - See if we are conditional jumping on constant
  109. if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
  110. if (BI->isUnconditional()) return false; // Can't optimize uncond branch
  111. BasicBlock *Dest1 = cast<BasicBlock>(BI->getOperand(0));
  112. BasicBlock *Dest2 = cast<BasicBlock>(BI->getOperand(1));
  113. if (ConstantBool *Cond = dyn_cast<ConstantBool>(BI->getCondition())) {
  114. // Are we branching on constant?
  115. // YES. Change to unconditional branch...
  116. BasicBlock *Destination = Cond->getValue() ? Dest1 : Dest2;
  117. BasicBlock *OldDest = Cond->getValue() ? Dest2 : Dest1;
  118. //cerr << "Function: " << T->getParent()->getParent()
  119. // << "\nRemoving branch from " << T->getParent()
  120. // << "\n\nTo: " << OldDest << endl;
  121. // Let the basic block know that we are letting go of it. Based on this,
  122. // it will adjust it's PHI nodes.
  123. assert(BI->getParent() && "Terminator not inserted in block!");
  124. OldDest->removePredecessor(BI->getParent());
  125. // Set the unconditional destination, and change the insn to be an
  126. // unconditional branch.
  127. BI->setUnconditionalDest(Destination);
  128. return true;
  129. } else if (Dest2 == Dest1) { // Conditional branch to same location?
  130. // This branch matches something like this:
  131. // br bool %cond, label %Dest, label %Dest
  132. // and changes it into: br label %Dest
  133. // Let the basic block know that we are letting go of one copy of it.
  134. assert(BI->getParent() && "Terminator not inserted in block!");
  135. Dest1->removePredecessor(BI->getParent());
  136. // Change a conditional branch to unconditional.
  137. BI->setUnconditionalDest(Dest1);
  138. return true;
  139. }
  140. } else if (SwitchInst *SI = dyn_cast<SwitchInst>(T)) {
  141. // If we are switching on a constant, we can convert the switch into a
  142. // single branch instruction!
  143. ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition());
  144. BasicBlock *TheOnlyDest = SI->getSuccessor(0); // The default dest
  145. BasicBlock *DefaultDest = TheOnlyDest;
  146. assert(TheOnlyDest == SI->getDefaultDest() &&
  147. "Default destination is not successor #0?");
  148. // Figure out which case it goes to...
  149. for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {
  150. // Found case matching a constant operand?
  151. if (SI->getSuccessorValue(i) == CI) {
  152. TheOnlyDest = SI->getSuccessor(i);
  153. break;
  154. }
  155. // Check to see if this branch is going to the same place as the default
  156. // dest. If so, eliminate it as an explicit compare.
  157. if (SI->getSuccessor(i) == DefaultDest) {
  158. // Remove this entry...
  159. DefaultDest->removePredecessor(SI->getParent());
  160. SI->removeCase(i);
  161. --i; --e; // Don't skip an entry...
  162. continue;
  163. }
  164. // Otherwise, check to see if the switch only branches to one destination.
  165. // We do this by reseting "TheOnlyDest" to null when we find two non-equal
  166. // destinations.
  167. if (SI->getSuccessor(i) != TheOnlyDest) TheOnlyDest = 0;
  168. }
  169. if (CI && !TheOnlyDest) {
  170. // Branching on a constant, but not any of the cases, go to the default
  171. // successor.
  172. TheOnlyDest = SI->getDefaultDest();
  173. }
  174. // If we found a single destination that we can fold the switch into, do so
  175. // now.
  176. if (TheOnlyDest) {
  177. // Insert the new branch..
  178. new BranchInst(TheOnlyDest, SI);
  179. BasicBlock *BB = SI->getParent();
  180. // Remove entries from PHI nodes which we no longer branch to...
  181. for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
  182. // Found case matching a constant operand?
  183. BasicBlock *Succ = SI->getSuccessor(i);
  184. if (Succ == TheOnlyDest)
  185. TheOnlyDest = 0; // Don't modify the first branch to TheOnlyDest
  186. else
  187. Succ->removePredecessor(BB);
  188. }
  189. // Delete the old switch...
  190. BB->getInstList().erase(SI);
  191. return true;
  192. } else if (SI->getNumSuccessors() == 2) {
  193. // Otherwise, we can fold this switch into a conditional branch
  194. // instruction if it has only one non-default destination.
  195. Value *Cond = new SetCondInst(Instruction::SetEQ, SI->getCondition(),
  196. SI->getSuccessorValue(1), "cond", SI);
  197. // Insert the new branch...
  198. new BranchInst(SI->getSuccessor(1), SI->getSuccessor(0), Cond, SI);
  199. // Delete the old switch...
  200. SI->getParent()->getInstList().erase(SI);
  201. return true;
  202. }
  203. }
  204. return false;
  205. }
  206. /// canConstantFoldCallTo - Return true if its even possible to fold a call to
  207. /// the specified function.
  208. bool llvm::canConstantFoldCallTo(Function *F) {
  209. const std::string &Name = F->getName();
  210. switch (F->getIntrinsicID()) {
  211. case Intrinsic::isunordered: return true;
  212. default: break;
  213. }
  214. switch (Name[0])
  215. {
  216. case 'a':
  217. return Name == "acos" || Name == "asin" || Name == "atan" ||
  218. Name == "atan2";
  219. case 'c':
  220. return Name == "ceil" || Name == "cos" || Name == "cosf" ||
  221. Name == "cosh";
  222. case 'e':
  223. return Name == "exp";
  224. case 'f':
  225. return Name == "fabs" || Name == "fmod" || Name == "floor";
  226. case 'l':
  227. return Name == "log" || Name == "log10";
  228. case 'p':
  229. return Name == "pow";
  230. case 's':
  231. return Name == "sin" || Name == "sinh" || Name == "sqrt";
  232. case 't':
  233. return Name == "tan" || Name == "tanh";
  234. default:
  235. return false;
  236. }
  237. }
  238. static Constant *ConstantFoldFP(double (*NativeFP)(double), double V,
  239. const Type *Ty) {
  240. errno = 0;
  241. V = NativeFP(V);
  242. if (errno == 0)
  243. return ConstantFP::get(Ty, V);
  244. return 0;
  245. }
  246. /// ConstantFoldCall - Attempt to constant fold a call to the specified function
  247. /// with the specified arguments, returning null if unsuccessful.
  248. Constant *llvm::ConstantFoldCall(Function *F,
  249. const std::vector<Constant*> &Operands) {
  250. const std::string &Name = F->getName();
  251. const Type *Ty = F->getReturnType();
  252. if (Operands.size() == 1) {
  253. if (ConstantFP *Op = dyn_cast<ConstantFP>(Operands[0])) {
  254. double V = Op->getValue();
  255. switch (Name[0])
  256. {
  257. case 'a':
  258. if (Name == "acos")
  259. return ConstantFoldFP(acos, V, Ty);
  260. else if (Name == "asin")
  261. return ConstantFoldFP(asin, V, Ty);
  262. else if (Name == "atan")
  263. return ConstantFP::get(Ty, atan(V));
  264. break;
  265. case 'c':
  266. if (Name == "ceil")
  267. return ConstantFoldFP(ceil, V, Ty);
  268. else if (Name == "cos")
  269. return ConstantFP::get(Ty, cos(V));
  270. else if (Name == "cosh")
  271. return ConstantFP::get(Ty, cosh(V));
  272. break;
  273. case 'e':
  274. if (Name == "exp")
  275. return ConstantFP::get(Ty, exp(V));
  276. break;
  277. case 'f':
  278. if (Name == "fabs")
  279. return ConstantFP::get(Ty, fabs(V));
  280. else if (Name == "floor")
  281. return ConstantFoldFP(floor, V, Ty);
  282. break;
  283. case 'l':
  284. if (Name == "log" && V > 0)
  285. return ConstantFP::get(Ty, log(V));
  286. else if (Name == "log10" && V > 0)
  287. return ConstantFoldFP(log10, V, Ty);
  288. break;
  289. case 's':
  290. if (Name == "sin")
  291. return ConstantFP::get(Ty, sin(V));
  292. else if (Name == "sinh")
  293. return ConstantFP::get(Ty, sinh(V));
  294. else if (Name == "sqrt" && V >= 0)
  295. return ConstantFP::get(Ty, sqrt(V));
  296. break;
  297. case 't':
  298. if (Name == "tan")
  299. return ConstantFP::get(Ty, tan(V));
  300. else if (Name == "tanh")
  301. return ConstantFP::get(Ty, tanh(V));
  302. break;
  303. default:
  304. break;
  305. }
  306. }
  307. } else if (Operands.size() == 2) {
  308. if (ConstantFP *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
  309. double Op1V = Op1->getValue();
  310. if (ConstantFP *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
  311. double Op2V = Op2->getValue();
  312. if (Name == "llvm.isunordered")
  313. return ConstantBool::get(IsNAN(Op1V) || IsNAN(Op2V));
  314. else
  315. if (Name == "pow") {
  316. errno = 0;
  317. double V = pow(Op1V, Op2V);
  318. if (errno == 0)
  319. return ConstantFP::get(Ty, V);
  320. } else if (Name == "fmod") {
  321. errno = 0;
  322. double V = fmod(Op1V, Op2V);
  323. if (errno == 0)
  324. return ConstantFP::get(Ty, V);
  325. } else if (Name == "atan2")
  326. return ConstantFP::get(Ty, atan2(Op1V,Op2V));
  327. }
  328. }
  329. }
  330. return 0;
  331. }
  332. //===----------------------------------------------------------------------===//
  333. // Local dead code elimination...
  334. //
  335. bool llvm::isInstructionTriviallyDead(Instruction *I) {
  336. if (!I->use_empty() || isa<TerminatorInst>(I)) return false;
  337. if (!I->mayWriteToMemory()) return true;
  338. if (CallInst *CI = dyn_cast<CallInst>(I))
  339. if (Function *F = CI->getCalledFunction())
  340. switch (F->getIntrinsicID()) {
  341. default: break;
  342. case Intrinsic::returnaddress:
  343. case Intrinsic::frameaddress:
  344. case Intrinsic::isunordered:
  345. case Intrinsic::ctpop:
  346. case Intrinsic::ctlz:
  347. case Intrinsic::cttz:
  348. case Intrinsic::sqrt:
  349. return true; // These intrinsics have no side effects.
  350. }
  351. return false;
  352. }
  353. // dceInstruction - Inspect the instruction at *BBI and figure out if it's
  354. // [trivially] dead. If so, remove the instruction and update the iterator
  355. // to point to the instruction that immediately succeeded the original
  356. // instruction.
  357. //
  358. bool llvm::dceInstruction(BasicBlock::iterator &BBI) {
  359. // Look for un"used" definitions...
  360. if (isInstructionTriviallyDead(BBI)) {
  361. BBI = BBI->getParent()->getInstList().erase(BBI); // Bye bye
  362. return true;
  363. }
  364. return false;
  365. }
  366. //===----------------------------------------------------------------------===//
  367. // PHI Instruction Simplification
  368. //
  369. /// hasConstantValue - If the specified PHI node always merges together the same
  370. /// value, return the value, otherwise return null.
  371. ///
  372. Value *llvm::hasConstantValue(PHINode *PN) {
  373. // If the PHI node only has one incoming value, eliminate the PHI node...
  374. if (PN->getNumIncomingValues() == 1)
  375. return PN->getIncomingValue(0);
  376. // Otherwise if all of the incoming values are the same for the PHI, replace
  377. // the PHI node with the incoming value.
  378. //
  379. Value *InVal = 0;
  380. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
  381. if (PN->getIncomingValue(i) != PN && // Not the PHI node itself...
  382. !isa<UndefValue>(PN->getIncomingValue(i)))
  383. if (InVal && PN->getIncomingValue(i) != InVal)
  384. return 0; // Not the same, bail out.
  385. else
  386. InVal = PN->getIncomingValue(i);
  387. // The only case that could cause InVal to be null is if we have a PHI node
  388. // that only has entries for itself. In this case, there is no entry into the
  389. // loop, so kill the PHI.
  390. //
  391. if (InVal == 0) InVal = UndefValue::get(PN->getType());
  392. // All of the incoming values are the same, return the value now.
  393. return InVal;
  394. }