InstCombinePHI.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899
  1. //===- InstCombinePHI.cpp -------------------------------------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements the visitPHINode function.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "InstCombineInternal.h"
  14. #include "llvm/ADT/STLExtras.h"
  15. #include "llvm/ADT/SmallPtrSet.h"
  16. #include "llvm/Analysis/InstructionSimplify.h"
  17. using namespace llvm;
  18. #define DEBUG_TYPE "instcombine"
  19. /// If we have something like phi [add (a,b), add(a,c)] and if a/b/c and the
  20. /// adds all have a single use, turn this into a phi and a single binop.
  21. Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
  22. Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
  23. assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
  24. unsigned Opc = FirstInst->getOpcode();
  25. Value *LHSVal = FirstInst->getOperand(0);
  26. Value *RHSVal = FirstInst->getOperand(1);
  27. Type *LHSType = LHSVal->getType();
  28. Type *RHSType = RHSVal->getType();
  29. bool isNUW = false, isNSW = false, isExact = false;
  30. if (OverflowingBinaryOperator *BO =
  31. dyn_cast<OverflowingBinaryOperator>(FirstInst)) {
  32. isNUW = BO->hasNoUnsignedWrap();
  33. isNSW = BO->hasNoSignedWrap();
  34. } else if (PossiblyExactOperator *PEO =
  35. dyn_cast<PossiblyExactOperator>(FirstInst))
  36. isExact = PEO->isExact();
  37. // Scan to see if all operands are the same opcode, and all have one use.
  38. for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
  39. Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
  40. if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
  41. // Verify type of the LHS matches so we don't fold cmp's of different
  42. // types.
  43. I->getOperand(0)->getType() != LHSType ||
  44. I->getOperand(1)->getType() != RHSType)
  45. return nullptr;
  46. // If they are CmpInst instructions, check their predicates
  47. if (CmpInst *CI = dyn_cast<CmpInst>(I))
  48. if (CI->getPredicate() != cast<CmpInst>(FirstInst)->getPredicate())
  49. return nullptr;
  50. if (isNUW)
  51. isNUW = cast<OverflowingBinaryOperator>(I)->hasNoUnsignedWrap();
  52. if (isNSW)
  53. isNSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
  54. if (isExact)
  55. isExact = cast<PossiblyExactOperator>(I)->isExact();
  56. // Keep track of which operand needs a phi node.
  57. if (I->getOperand(0) != LHSVal) LHSVal = nullptr;
  58. if (I->getOperand(1) != RHSVal) RHSVal = nullptr;
  59. }
  60. // If both LHS and RHS would need a PHI, don't do this transformation,
  61. // because it would increase the number of PHIs entering the block,
  62. // which leads to higher register pressure. This is especially
  63. // bad when the PHIs are in the header of a loop.
  64. if (!LHSVal && !RHSVal)
  65. return nullptr;
  66. // Otherwise, this is safe to transform!
  67. Value *InLHS = FirstInst->getOperand(0);
  68. Value *InRHS = FirstInst->getOperand(1);
  69. PHINode *NewLHS = nullptr, *NewRHS = nullptr;
  70. if (!LHSVal) {
  71. NewLHS = PHINode::Create(LHSType, PN.getNumIncomingValues(),
  72. FirstInst->getOperand(0)->getName() + ".pn");
  73. NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
  74. InsertNewInstBefore(NewLHS, PN);
  75. LHSVal = NewLHS;
  76. }
  77. if (!RHSVal) {
  78. NewRHS = PHINode::Create(RHSType, PN.getNumIncomingValues(),
  79. FirstInst->getOperand(1)->getName() + ".pn");
  80. NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
  81. InsertNewInstBefore(NewRHS, PN);
  82. RHSVal = NewRHS;
  83. }
  84. // Add all operands to the new PHIs.
  85. if (NewLHS || NewRHS) {
  86. for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
  87. Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
  88. if (NewLHS) {
  89. Value *NewInLHS = InInst->getOperand(0);
  90. NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
  91. }
  92. if (NewRHS) {
  93. Value *NewInRHS = InInst->getOperand(1);
  94. NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
  95. }
  96. }
  97. }
  98. if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst)) {
  99. CmpInst *NewCI = CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
  100. LHSVal, RHSVal);
  101. NewCI->setDebugLoc(FirstInst->getDebugLoc());
  102. return NewCI;
  103. }
  104. BinaryOperator *BinOp = cast<BinaryOperator>(FirstInst);
  105. BinaryOperator *NewBinOp =
  106. BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
  107. if (isNUW) NewBinOp->setHasNoUnsignedWrap();
  108. if (isNSW) NewBinOp->setHasNoSignedWrap();
  109. if (isExact) NewBinOp->setIsExact();
  110. NewBinOp->setDebugLoc(FirstInst->getDebugLoc());
  111. return NewBinOp;
  112. }
  113. Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
  114. GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
  115. SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
  116. FirstInst->op_end());
  117. // This is true if all GEP bases are allocas and if all indices into them are
  118. // constants.
  119. bool AllBasePointersAreAllocas = true;
  120. // We don't want to replace this phi if the replacement would require
  121. // more than one phi, which leads to higher register pressure. This is
  122. // especially bad when the PHIs are in the header of a loop.
  123. bool NeededPhi = false;
  124. bool AllInBounds = true;
  125. // Scan to see if all operands are the same opcode, and all have one use.
  126. for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
  127. GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
  128. if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
  129. GEP->getNumOperands() != FirstInst->getNumOperands())
  130. return nullptr;
  131. AllInBounds &= GEP->isInBounds();
  132. // Keep track of whether or not all GEPs are of alloca pointers.
  133. if (AllBasePointersAreAllocas &&
  134. (!isa<AllocaInst>(GEP->getOperand(0)) ||
  135. !GEP->hasAllConstantIndices()))
  136. AllBasePointersAreAllocas = false;
  137. // Compare the operand lists.
  138. for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
  139. if (FirstInst->getOperand(op) == GEP->getOperand(op))
  140. continue;
  141. // Don't merge two GEPs when two operands differ (introducing phi nodes)
  142. // if one of the PHIs has a constant for the index. The index may be
  143. // substantially cheaper to compute for the constants, so making it a
  144. // variable index could pessimize the path. This also handles the case
  145. // for struct indices, which must always be constant.
  146. if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
  147. isa<ConstantInt>(GEP->getOperand(op)))
  148. return nullptr;
  149. if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
  150. return nullptr;
  151. // If we already needed a PHI for an earlier operand, and another operand
  152. // also requires a PHI, we'd be introducing more PHIs than we're
  153. // eliminating, which increases register pressure on entry to the PHI's
  154. // block.
  155. if (NeededPhi)
  156. return nullptr;
  157. FixedOperands[op] = nullptr; // Needs a PHI.
  158. NeededPhi = true;
  159. }
  160. }
  161. // If all of the base pointers of the PHI'd GEPs are from allocas, don't
  162. // bother doing this transformation. At best, this will just save a bit of
  163. // offset calculation, but all the predecessors will have to materialize the
  164. // stack address into a register anyway. We'd actually rather *clone* the
  165. // load up into the predecessors so that we have a load of a gep of an alloca,
  166. // which can usually all be folded into the load.
  167. if (AllBasePointersAreAllocas)
  168. return nullptr;
  169. // Otherwise, this is safe to transform. Insert PHI nodes for each operand
  170. // that is variable.
  171. SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
  172. bool HasAnyPHIs = false;
  173. for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
  174. if (FixedOperands[i]) continue; // operand doesn't need a phi.
  175. Value *FirstOp = FirstInst->getOperand(i);
  176. PHINode *NewPN = PHINode::Create(FirstOp->getType(), e,
  177. FirstOp->getName()+".pn");
  178. InsertNewInstBefore(NewPN, PN);
  179. NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
  180. OperandPhis[i] = NewPN;
  181. FixedOperands[i] = NewPN;
  182. HasAnyPHIs = true;
  183. }
  184. // Add all operands to the new PHIs.
  185. if (HasAnyPHIs) {
  186. for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
  187. GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
  188. BasicBlock *InBB = PN.getIncomingBlock(i);
  189. for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
  190. if (PHINode *OpPhi = OperandPhis[op])
  191. OpPhi->addIncoming(InGEP->getOperand(op), InBB);
  192. }
  193. }
  194. Value *Base = FixedOperands[0];
  195. GetElementPtrInst *NewGEP =
  196. GetElementPtrInst::Create(FirstInst->getSourceElementType(), Base,
  197. makeArrayRef(FixedOperands).slice(1));
  198. if (AllInBounds) NewGEP->setIsInBounds();
  199. NewGEP->setDebugLoc(FirstInst->getDebugLoc());
  200. return NewGEP;
  201. }
  202. /// Return true if we know that it is safe to sink the load out of the block
  203. /// that defines it. This means that it must be obvious the value of the load is
  204. /// not changed from the point of the load to the end of the block it is in.
  205. ///
  206. /// Finally, it is safe, but not profitable, to sink a load targeting a
  207. /// non-address-taken alloca. Doing so will cause us to not promote the alloca
  208. /// to a register.
  209. static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
  210. BasicBlock::iterator BBI = L, E = L->getParent()->end();
  211. for (++BBI; BBI != E; ++BBI)
  212. if (BBI->mayWriteToMemory())
  213. return false;
  214. // Check for non-address taken alloca. If not address-taken already, it isn't
  215. // profitable to do this xform.
  216. if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
  217. bool isAddressTaken = false;
  218. for (User *U : AI->users()) {
  219. if (isa<LoadInst>(U)) continue;
  220. if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
  221. // If storing TO the alloca, then the address isn't taken.
  222. if (SI->getOperand(1) == AI) continue;
  223. }
  224. isAddressTaken = true;
  225. break;
  226. }
  227. if (!isAddressTaken && AI->isStaticAlloca())
  228. return false;
  229. }
  230. // If this load is a load from a GEP with a constant offset from an alloca,
  231. // then we don't want to sink it. In its present form, it will be
  232. // load [constant stack offset]. Sinking it will cause us to have to
  233. // materialize the stack addresses in each predecessor in a register only to
  234. // do a shared load from register in the successor.
  235. if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
  236. if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
  237. if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
  238. return false;
  239. return true;
  240. }
  241. Instruction *InstCombiner::FoldPHIArgLoadIntoPHI(PHINode &PN) {
  242. // HLSL Change Begin - Do not create phi on pointer.
  243. return nullptr;
  244. // HLSL Change End.
  245. LoadInst *FirstLI = cast<LoadInst>(PN.getIncomingValue(0));
  246. // FIXME: This is overconservative; this transform is allowed in some cases
  247. // for atomic operations.
  248. if (FirstLI->isAtomic())
  249. return nullptr;
  250. // When processing loads, we need to propagate two bits of information to the
  251. // sunk load: whether it is volatile, and what its alignment is. We currently
  252. // don't sink loads when some have their alignment specified and some don't.
  253. // visitLoadInst will propagate an alignment onto the load when TD is around,
  254. // and if TD isn't around, we can't handle the mixed case.
  255. bool isVolatile = FirstLI->isVolatile();
  256. unsigned LoadAlignment = FirstLI->getAlignment();
  257. unsigned LoadAddrSpace = FirstLI->getPointerAddressSpace();
  258. // We can't sink the load if the loaded value could be modified between the
  259. // load and the PHI.
  260. if (FirstLI->getParent() != PN.getIncomingBlock(0) ||
  261. !isSafeAndProfitableToSinkLoad(FirstLI))
  262. return nullptr;
  263. // If the PHI is of volatile loads and the load block has multiple
  264. // successors, sinking it would remove a load of the volatile value from
  265. // the path through the other successor.
  266. if (isVolatile &&
  267. FirstLI->getParent()->getTerminator()->getNumSuccessors() != 1)
  268. return nullptr;
  269. // Check to see if all arguments are the same operation.
  270. for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
  271. LoadInst *LI = dyn_cast<LoadInst>(PN.getIncomingValue(i));
  272. if (!LI || !LI->hasOneUse())
  273. return nullptr;
  274. // We can't sink the load if the loaded value could be modified between
  275. // the load and the PHI.
  276. if (LI->isVolatile() != isVolatile ||
  277. LI->getParent() != PN.getIncomingBlock(i) ||
  278. LI->getPointerAddressSpace() != LoadAddrSpace ||
  279. !isSafeAndProfitableToSinkLoad(LI))
  280. return nullptr;
  281. // If some of the loads have an alignment specified but not all of them,
  282. // we can't do the transformation.
  283. if ((LoadAlignment != 0) != (LI->getAlignment() != 0))
  284. return nullptr;
  285. LoadAlignment = std::min(LoadAlignment, LI->getAlignment());
  286. // If the PHI is of volatile loads and the load block has multiple
  287. // successors, sinking it would remove a load of the volatile value from
  288. // the path through the other successor.
  289. if (isVolatile &&
  290. LI->getParent()->getTerminator()->getNumSuccessors() != 1)
  291. return nullptr;
  292. }
  293. // Okay, they are all the same operation. Create a new PHI node of the
  294. // correct type, and PHI together all of the LHS's of the instructions.
  295. PHINode *NewPN = PHINode::Create(FirstLI->getOperand(0)->getType(),
  296. PN.getNumIncomingValues(),
  297. PN.getName()+".in");
  298. Value *InVal = FirstLI->getOperand(0);
  299. NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
  300. // Add all operands to the new PHI.
  301. for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
  302. Value *NewInVal = cast<LoadInst>(PN.getIncomingValue(i))->getOperand(0);
  303. if (NewInVal != InVal)
  304. InVal = nullptr;
  305. NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
  306. }
  307. Value *PhiVal;
  308. if (InVal) {
  309. // The new PHI unions all of the same values together. This is really
  310. // common, so we handle it intelligently here for compile-time speed.
  311. PhiVal = InVal;
  312. delete NewPN;
  313. } else {
  314. InsertNewInstBefore(NewPN, PN);
  315. PhiVal = NewPN;
  316. }
  317. // If this was a volatile load that we are merging, make sure to loop through
  318. // and mark all the input loads as non-volatile. If we don't do this, we will
  319. // insert a new volatile load and the old ones will not be deletable.
  320. if (isVolatile)
  321. for (Value *IncValue : PN.incoming_values())
  322. cast<LoadInst>(IncValue)->setVolatile(false);
  323. LoadInst *NewLI = new LoadInst(PhiVal, "", isVolatile, LoadAlignment);
  324. NewLI->setDebugLoc(FirstLI->getDebugLoc());
  325. return NewLI;
  326. }
  327. /// If all operands to a PHI node are the same "unary" operator and they all are
  328. /// only used by the PHI, PHI together their inputs, and do the operation once,
  329. /// to the result of the PHI.
  330. Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
  331. Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
  332. if (isa<GetElementPtrInst>(FirstInst))
  333. return FoldPHIArgGEPIntoPHI(PN);
  334. if (isa<LoadInst>(FirstInst))
  335. return FoldPHIArgLoadIntoPHI(PN);
  336. // Scan the instruction, looking for input operations that can be folded away.
  337. // If all input operands to the phi are the same instruction (e.g. a cast from
  338. // the same type or "+42") we can pull the operation through the PHI, reducing
  339. // code size and simplifying code.
  340. Constant *ConstantOp = nullptr;
  341. Type *CastSrcTy = nullptr;
  342. bool isNUW = false, isNSW = false, isExact = false;
  343. if (isa<CastInst>(FirstInst)) {
  344. CastSrcTy = FirstInst->getOperand(0)->getType();
  345. // Be careful about transforming integer PHIs. We don't want to pessimize
  346. // the code by turning an i32 into an i1293.
  347. if (PN.getType()->isIntegerTy() && CastSrcTy->isIntegerTy()) {
  348. if (!ShouldChangeType(PN.getType(), CastSrcTy))
  349. return nullptr;
  350. }
  351. } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
  352. // Can fold binop, compare or shift here if the RHS is a constant,
  353. // otherwise call FoldPHIArgBinOpIntoPHI.
  354. ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
  355. if (!ConstantOp)
  356. return FoldPHIArgBinOpIntoPHI(PN);
  357. if (OverflowingBinaryOperator *BO =
  358. dyn_cast<OverflowingBinaryOperator>(FirstInst)) {
  359. isNUW = BO->hasNoUnsignedWrap();
  360. isNSW = BO->hasNoSignedWrap();
  361. } else if (PossiblyExactOperator *PEO =
  362. dyn_cast<PossiblyExactOperator>(FirstInst))
  363. isExact = PEO->isExact();
  364. } else {
  365. return nullptr; // Cannot fold this operation.
  366. }
  367. // Check to see if all arguments are the same operation.
  368. for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
  369. Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
  370. if (!I || !I->hasOneUse() || !I->isSameOperationAs(FirstInst))
  371. return nullptr;
  372. if (CastSrcTy) {
  373. if (I->getOperand(0)->getType() != CastSrcTy)
  374. return nullptr; // Cast operation must match.
  375. } else if (I->getOperand(1) != ConstantOp) {
  376. return nullptr;
  377. }
  378. if (isNUW)
  379. isNUW = cast<OverflowingBinaryOperator>(I)->hasNoUnsignedWrap();
  380. if (isNSW)
  381. isNSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
  382. if (isExact)
  383. isExact = cast<PossiblyExactOperator>(I)->isExact();
  384. }
  385. // Okay, they are all the same operation. Create a new PHI node of the
  386. // correct type, and PHI together all of the LHS's of the instructions.
  387. PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
  388. PN.getNumIncomingValues(),
  389. PN.getName()+".in");
  390. Value *InVal = FirstInst->getOperand(0);
  391. NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
  392. // Add all operands to the new PHI.
  393. for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
  394. Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
  395. if (NewInVal != InVal)
  396. InVal = nullptr;
  397. NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
  398. }
  399. Value *PhiVal;
  400. if (InVal) {
  401. // The new PHI unions all of the same values together. This is really
  402. // common, so we handle it intelligently here for compile-time speed.
  403. PhiVal = InVal;
  404. delete NewPN;
  405. } else {
  406. InsertNewInstBefore(NewPN, PN);
  407. PhiVal = NewPN;
  408. }
  409. // Insert and return the new operation.
  410. if (CastInst *FirstCI = dyn_cast<CastInst>(FirstInst)) {
  411. CastInst *NewCI = CastInst::Create(FirstCI->getOpcode(), PhiVal,
  412. PN.getType());
  413. NewCI->setDebugLoc(FirstInst->getDebugLoc());
  414. return NewCI;
  415. }
  416. if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst)) {
  417. BinOp = BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
  418. if (isNUW) BinOp->setHasNoUnsignedWrap();
  419. if (isNSW) BinOp->setHasNoSignedWrap();
  420. if (isExact) BinOp->setIsExact();
  421. BinOp->setDebugLoc(FirstInst->getDebugLoc());
  422. return BinOp;
  423. }
  424. CmpInst *CIOp = cast<CmpInst>(FirstInst);
  425. CmpInst *NewCI = CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
  426. PhiVal, ConstantOp);
  427. NewCI->setDebugLoc(FirstInst->getDebugLoc());
  428. return NewCI;
  429. }
  430. /// Return true if this PHI node is only used by a PHI node cycle that is dead.
  431. static bool DeadPHICycle(PHINode *PN,
  432. SmallPtrSetImpl<PHINode*> &PotentiallyDeadPHIs) {
  433. if (PN->use_empty()) return true;
  434. if (!PN->hasOneUse()) return false;
  435. // Remember this node, and if we find the cycle, return.
  436. if (!PotentiallyDeadPHIs.insert(PN).second)
  437. return true;
  438. // Don't scan crazily complex things.
  439. if (PotentiallyDeadPHIs.size() == 16)
  440. return false;
  441. if (PHINode *PU = dyn_cast<PHINode>(PN->user_back()))
  442. return DeadPHICycle(PU, PotentiallyDeadPHIs);
  443. return false;
  444. }
  445. /// Return true if this phi node is always equal to NonPhiInVal.
  446. /// This happens with mutually cyclic phi nodes like:
  447. /// z = some value; x = phi (y, z); y = phi (x, z)
  448. static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
  449. SmallPtrSetImpl<PHINode*> &ValueEqualPHIs) {
  450. // See if we already saw this PHI node.
  451. if (!ValueEqualPHIs.insert(PN).second)
  452. return true;
  453. // Don't scan crazily complex things.
  454. if (ValueEqualPHIs.size() == 16)
  455. return false;
  456. // Scan the operands to see if they are either phi nodes or are equal to
  457. // the value.
  458. for (Value *Op : PN->incoming_values()) {
  459. if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
  460. if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
  461. return false;
  462. } else if (Op != NonPhiInVal)
  463. return false;
  464. }
  465. return true;
  466. }
  467. namespace {
  468. struct PHIUsageRecord {
  469. unsigned PHIId; // The ID # of the PHI (something determinstic to sort on)
  470. unsigned Shift; // The amount shifted.
  471. Instruction *Inst; // The trunc instruction.
  472. PHIUsageRecord(unsigned pn, unsigned Sh, Instruction *User)
  473. : PHIId(pn), Shift(Sh), Inst(User) {}
  474. bool operator<(const PHIUsageRecord &RHS) const {
  475. if (PHIId < RHS.PHIId) return true;
  476. if (PHIId > RHS.PHIId) return false;
  477. if (Shift < RHS.Shift) return true;
  478. if (Shift > RHS.Shift) return false;
  479. return Inst->getType()->getPrimitiveSizeInBits() <
  480. RHS.Inst->getType()->getPrimitiveSizeInBits();
  481. }
  482. };
  483. struct LoweredPHIRecord {
  484. PHINode *PN; // The PHI that was lowered.
  485. unsigned Shift; // The amount shifted.
  486. unsigned Width; // The width extracted.
  487. LoweredPHIRecord(PHINode *pn, unsigned Sh, Type *Ty)
  488. : PN(pn), Shift(Sh), Width(Ty->getPrimitiveSizeInBits()) {}
  489. // Ctor form used by DenseMap.
  490. LoweredPHIRecord(PHINode *pn, unsigned Sh)
  491. : PN(pn), Shift(Sh), Width(0) {}
  492. };
  493. }
  494. namespace llvm {
  495. template<>
  496. struct DenseMapInfo<LoweredPHIRecord> {
  497. static inline LoweredPHIRecord getEmptyKey() {
  498. return LoweredPHIRecord(nullptr, 0);
  499. }
  500. static inline LoweredPHIRecord getTombstoneKey() {
  501. return LoweredPHIRecord(nullptr, 1);
  502. }
  503. static unsigned getHashValue(const LoweredPHIRecord &Val) {
  504. return DenseMapInfo<PHINode*>::getHashValue(Val.PN) ^ (Val.Shift>>3) ^
  505. (Val.Width>>3);
  506. }
  507. static bool isEqual(const LoweredPHIRecord &LHS,
  508. const LoweredPHIRecord &RHS) {
  509. return LHS.PN == RHS.PN && LHS.Shift == RHS.Shift &&
  510. LHS.Width == RHS.Width;
  511. }
  512. };
  513. }
  514. /// This is an integer PHI and we know that it has an illegal type: see if it is
  515. /// only used by trunc or trunc(lshr) operations. If so, we split the PHI into
  516. /// the various pieces being extracted. This sort of thing is introduced when
  517. /// SROA promotes an aggregate to large integer values.
  518. ///
  519. /// TODO: The user of the trunc may be an bitcast to float/double/vector or an
  520. /// inttoptr. We should produce new PHIs in the right type.
  521. ///
  522. Instruction *InstCombiner::SliceUpIllegalIntegerPHI(PHINode &FirstPhi) {
  523. // PHIUsers - Keep track of all of the truncated values extracted from a set
  524. // of PHIs, along with their offset. These are the things we want to rewrite.
  525. SmallVector<PHIUsageRecord, 16> PHIUsers;
  526. // PHIs are often mutually cyclic, so we keep track of a whole set of PHI
  527. // nodes which are extracted from. PHIsToSlice is a set we use to avoid
  528. // revisiting PHIs, PHIsInspected is a ordered list of PHIs that we need to
  529. // check the uses of (to ensure they are all extracts).
  530. SmallVector<PHINode*, 8> PHIsToSlice;
  531. SmallPtrSet<PHINode*, 8> PHIsInspected;
  532. PHIsToSlice.push_back(&FirstPhi);
  533. PHIsInspected.insert(&FirstPhi);
  534. for (unsigned PHIId = 0; PHIId != PHIsToSlice.size(); ++PHIId) {
  535. PHINode *PN = PHIsToSlice[PHIId];
  536. // Scan the input list of the PHI. If any input is an invoke, and if the
  537. // input is defined in the predecessor, then we won't be split the critical
  538. // edge which is required to insert a truncate. Because of this, we have to
  539. // bail out.
  540. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
  541. InvokeInst *II = dyn_cast<InvokeInst>(PN->getIncomingValue(i));
  542. if (!II) continue;
  543. if (II->getParent() != PN->getIncomingBlock(i))
  544. continue;
  545. // If we have a phi, and if it's directly in the predecessor, then we have
  546. // a critical edge where we need to put the truncate. Since we can't
  547. // split the edge in instcombine, we have to bail out.
  548. return nullptr;
  549. }
  550. for (User *U : PN->users()) {
  551. Instruction *UserI = cast<Instruction>(U);
  552. // If the user is a PHI, inspect its uses recursively.
  553. if (PHINode *UserPN = dyn_cast<PHINode>(UserI)) {
  554. if (PHIsInspected.insert(UserPN).second)
  555. PHIsToSlice.push_back(UserPN);
  556. continue;
  557. }
  558. // Truncates are always ok.
  559. if (isa<TruncInst>(UserI)) {
  560. PHIUsers.push_back(PHIUsageRecord(PHIId, 0, UserI));
  561. continue;
  562. }
  563. // Otherwise it must be a lshr which can only be used by one trunc.
  564. if (UserI->getOpcode() != Instruction::LShr ||
  565. !UserI->hasOneUse() || !isa<TruncInst>(UserI->user_back()) ||
  566. !isa<ConstantInt>(UserI->getOperand(1)))
  567. return nullptr;
  568. unsigned Shift = cast<ConstantInt>(UserI->getOperand(1))->getZExtValue();
  569. PHIUsers.push_back(PHIUsageRecord(PHIId, Shift, UserI->user_back()));
  570. }
  571. }
  572. // If we have no users, they must be all self uses, just nuke the PHI.
  573. if (PHIUsers.empty())
  574. return ReplaceInstUsesWith(FirstPhi, UndefValue::get(FirstPhi.getType()));
  575. // If this phi node is transformable, create new PHIs for all the pieces
  576. // extracted out of it. First, sort the users by their offset and size.
  577. array_pod_sort(PHIUsers.begin(), PHIUsers.end());
  578. DEBUG(dbgs() << "SLICING UP PHI: " << FirstPhi << '\n';
  579. for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
  580. dbgs() << "AND USER PHI #" << i << ": " << *PHIsToSlice[i] << '\n';
  581. );
  582. // PredValues - This is a temporary used when rewriting PHI nodes. It is
  583. // hoisted out here to avoid construction/destruction thrashing.
  584. DenseMap<BasicBlock*, Value*> PredValues;
  585. // ExtractedVals - Each new PHI we introduce is saved here so we don't
  586. // introduce redundant PHIs.
  587. DenseMap<LoweredPHIRecord, PHINode*> ExtractedVals;
  588. for (unsigned UserI = 0, UserE = PHIUsers.size(); UserI != UserE; ++UserI) {
  589. unsigned PHIId = PHIUsers[UserI].PHIId;
  590. PHINode *PN = PHIsToSlice[PHIId];
  591. unsigned Offset = PHIUsers[UserI].Shift;
  592. Type *Ty = PHIUsers[UserI].Inst->getType();
  593. PHINode *EltPHI;
  594. // If we've already lowered a user like this, reuse the previously lowered
  595. // value.
  596. if ((EltPHI = ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)]) == nullptr) {
  597. // Otherwise, Create the new PHI node for this user.
  598. EltPHI = PHINode::Create(Ty, PN->getNumIncomingValues(),
  599. PN->getName()+".off"+Twine(Offset), PN);
  600. assert(EltPHI->getType() != PN->getType() &&
  601. "Truncate didn't shrink phi?");
  602. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
  603. BasicBlock *Pred = PN->getIncomingBlock(i);
  604. Value *&PredVal = PredValues[Pred];
  605. // If we already have a value for this predecessor, reuse it.
  606. if (PredVal) {
  607. EltPHI->addIncoming(PredVal, Pred);
  608. continue;
  609. }
  610. // Handle the PHI self-reuse case.
  611. Value *InVal = PN->getIncomingValue(i);
  612. if (InVal == PN) {
  613. PredVal = EltPHI;
  614. EltPHI->addIncoming(PredVal, Pred);
  615. continue;
  616. }
  617. if (PHINode *InPHI = dyn_cast<PHINode>(PN)) {
  618. // If the incoming value was a PHI, and if it was one of the PHIs we
  619. // already rewrote it, just use the lowered value.
  620. if (Value *Res = ExtractedVals[LoweredPHIRecord(InPHI, Offset, Ty)]) {
  621. PredVal = Res;
  622. EltPHI->addIncoming(PredVal, Pred);
  623. continue;
  624. }
  625. }
  626. // Otherwise, do an extract in the predecessor.
  627. Builder->SetInsertPoint(Pred, Pred->getTerminator());
  628. Value *Res = InVal;
  629. if (Offset)
  630. Res = Builder->CreateLShr(Res, ConstantInt::get(InVal->getType(),
  631. Offset), "extract");
  632. Res = Builder->CreateTrunc(Res, Ty, "extract.t");
  633. PredVal = Res;
  634. EltPHI->addIncoming(Res, Pred);
  635. // If the incoming value was a PHI, and if it was one of the PHIs we are
  636. // rewriting, we will ultimately delete the code we inserted. This
  637. // means we need to revisit that PHI to make sure we extract out the
  638. // needed piece.
  639. if (PHINode *OldInVal = dyn_cast<PHINode>(PN->getIncomingValue(i)))
  640. if (PHIsInspected.count(OldInVal)) {
  641. unsigned RefPHIId = std::find(PHIsToSlice.begin(),PHIsToSlice.end(),
  642. OldInVal)-PHIsToSlice.begin();
  643. PHIUsers.push_back(PHIUsageRecord(RefPHIId, Offset,
  644. cast<Instruction>(Res)));
  645. ++UserE;
  646. }
  647. }
  648. PredValues.clear();
  649. DEBUG(dbgs() << " Made element PHI for offset " << Offset << ": "
  650. << *EltPHI << '\n');
  651. ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)] = EltPHI;
  652. }
  653. // Replace the use of this piece with the PHI node.
  654. ReplaceInstUsesWith(*PHIUsers[UserI].Inst, EltPHI);
  655. }
  656. // Replace all the remaining uses of the PHI nodes (self uses and the lshrs)
  657. // with undefs.
  658. Value *Undef = UndefValue::get(FirstPhi.getType());
  659. for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
  660. ReplaceInstUsesWith(*PHIsToSlice[i], Undef);
  661. return ReplaceInstUsesWith(FirstPhi, Undef);
  662. }
  663. // PHINode simplification
  664. //
  665. Instruction *InstCombiner::visitPHINode(PHINode &PN) {
  666. if (Value *V = SimplifyInstruction(&PN, DL, TLI, DT, AC))
  667. return ReplaceInstUsesWith(PN, V);
  668. // If all PHI operands are the same operation, pull them through the PHI,
  669. // reducing code size.
  670. if (isa<Instruction>(PN.getIncomingValue(0)) &&
  671. isa<Instruction>(PN.getIncomingValue(1)) &&
  672. cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
  673. cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
  674. // FIXME: The hasOneUse check will fail for PHIs that use the value more
  675. // than themselves more than once.
  676. PN.getIncomingValue(0)->hasOneUse())
  677. if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
  678. return Result;
  679. // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
  680. // this PHI only has a single use (a PHI), and if that PHI only has one use (a
  681. // PHI)... break the cycle.
  682. if (PN.hasOneUse()) {
  683. Instruction *PHIUser = cast<Instruction>(PN.user_back());
  684. if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
  685. SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
  686. PotentiallyDeadPHIs.insert(&PN);
  687. if (DeadPHICycle(PU, PotentiallyDeadPHIs))
  688. return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
  689. }
  690. // If this phi has a single use, and if that use just computes a value for
  691. // the next iteration of a loop, delete the phi. This occurs with unused
  692. // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
  693. // common case here is good because the only other things that catch this
  694. // are induction variable analysis (sometimes) and ADCE, which is only run
  695. // late.
  696. if (PHIUser->hasOneUse() &&
  697. (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
  698. PHIUser->user_back() == &PN) {
  699. return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
  700. }
  701. }
  702. // We sometimes end up with phi cycles that non-obviously end up being the
  703. // same value, for example:
  704. // z = some value; x = phi (y, z); y = phi (x, z)
  705. // where the phi nodes don't necessarily need to be in the same block. Do a
  706. // quick check to see if the PHI node only contains a single non-phi value, if
  707. // so, scan to see if the phi cycle is actually equal to that value.
  708. {
  709. unsigned InValNo = 0, NumIncomingVals = PN.getNumIncomingValues();
  710. // Scan for the first non-phi operand.
  711. while (InValNo != NumIncomingVals &&
  712. isa<PHINode>(PN.getIncomingValue(InValNo)))
  713. ++InValNo;
  714. if (InValNo != NumIncomingVals) {
  715. Value *NonPhiInVal = PN.getIncomingValue(InValNo);
  716. // Scan the rest of the operands to see if there are any conflicts, if so
  717. // there is no need to recursively scan other phis.
  718. for (++InValNo; InValNo != NumIncomingVals; ++InValNo) {
  719. Value *OpVal = PN.getIncomingValue(InValNo);
  720. if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
  721. break;
  722. }
  723. // If we scanned over all operands, then we have one unique value plus
  724. // phi values. Scan PHI nodes to see if they all merge in each other or
  725. // the value.
  726. if (InValNo == NumIncomingVals) {
  727. SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
  728. if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
  729. return ReplaceInstUsesWith(PN, NonPhiInVal);
  730. }
  731. }
  732. }
  733. // If there are multiple PHIs, sort their operands so that they all list
  734. // the blocks in the same order. This will help identical PHIs be eliminated
  735. // by other passes. Other passes shouldn't depend on this for correctness
  736. // however.
  737. PHINode *FirstPN = cast<PHINode>(PN.getParent()->begin());
  738. if (&PN != FirstPN)
  739. for (unsigned i = 0, e = FirstPN->getNumIncomingValues(); i != e; ++i) {
  740. BasicBlock *BBA = PN.getIncomingBlock(i);
  741. BasicBlock *BBB = FirstPN->getIncomingBlock(i);
  742. if (BBA != BBB) {
  743. Value *VA = PN.getIncomingValue(i);
  744. unsigned j = PN.getBasicBlockIndex(BBB);
  745. Value *VB = PN.getIncomingValue(j);
  746. PN.setIncomingBlock(i, BBB);
  747. PN.setIncomingValue(i, VB);
  748. PN.setIncomingBlock(j, BBA);
  749. PN.setIncomingValue(j, VA);
  750. // NOTE: Instcombine normally would want us to "return &PN" if we
  751. // modified any of the operands of an instruction. However, since we
  752. // aren't adding or removing uses (just rearranging them) we don't do
  753. // this in this case.
  754. }
  755. }
  756. // If this is an integer PHI and we know that it has an illegal type, see if
  757. // it is only used by trunc or trunc(lshr) operations. If so, we split the
  758. // PHI into the various pieces being extracted. This sort of thing is
  759. // introduced when SROA promotes an aggregate to a single large integer type.
  760. if (PN.getType()->isIntegerTy() &&
  761. !DL.isLegalInteger(PN.getType()->getPrimitiveSizeInBits()))
  762. if (Instruction *Res = SliceUpIllegalIntegerPHI(PN))
  763. return Res;
  764. return nullptr;
  765. }