InstCombinePHI.cpp 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564
  1. //===- InstCombinePHI.cpp -------------------------------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements the visitPHINode function.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "InstCombineInternal.h"
  13. #include "llvm/ADT/STLExtras.h"
  14. #include "llvm/ADT/SmallPtrSet.h"
  15. #include "llvm/ADT/Statistic.h"
  16. #include "llvm/Analysis/InstructionSimplify.h"
  17. #include "llvm/Analysis/ValueTracking.h"
  18. #include "llvm/IR/PatternMatch.h"
  19. #include "llvm/Support/CommandLine.h"
  20. #include "llvm/Transforms/InstCombine/InstCombiner.h"
  21. #include "llvm/Transforms/Utils/Local.h"
  22. #include <optional>
  23. using namespace llvm;
  24. using namespace llvm::PatternMatch;
  25. #define DEBUG_TYPE "instcombine"
  26. static cl::opt<unsigned>
  27. MaxNumPhis("instcombine-max-num-phis", cl::init(512),
  28. cl::desc("Maximum number phis to handle in intptr/ptrint folding"));
  29. STATISTIC(NumPHIsOfInsertValues,
  30. "Number of phi-of-insertvalue turned into insertvalue-of-phis");
  31. STATISTIC(NumPHIsOfExtractValues,
  32. "Number of phi-of-extractvalue turned into extractvalue-of-phi");
  33. STATISTIC(NumPHICSEs, "Number of PHI's that got CSE'd");
  34. /// The PHI arguments will be folded into a single operation with a PHI node
  35. /// as input. The debug location of the single operation will be the merged
  36. /// locations of the original PHI node arguments.
  37. void InstCombinerImpl::PHIArgMergedDebugLoc(Instruction *Inst, PHINode &PN) {
  38. auto *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
  39. Inst->setDebugLoc(FirstInst->getDebugLoc());
  40. // We do not expect a CallInst here, otherwise, N-way merging of DebugLoc
  41. // will be inefficient.
  42. assert(!isa<CallInst>(Inst));
  43. for (Value *V : drop_begin(PN.incoming_values())) {
  44. auto *I = cast<Instruction>(V);
  45. Inst->applyMergedLocation(Inst->getDebugLoc(), I->getDebugLoc());
  46. }
  47. }
  48. // Replace Integer typed PHI PN if the PHI's value is used as a pointer value.
  49. // If there is an existing pointer typed PHI that produces the same value as PN,
  50. // replace PN and the IntToPtr operation with it. Otherwise, synthesize a new
  51. // PHI node:
  52. //
  53. // Case-1:
  54. // bb1:
  55. // int_init = PtrToInt(ptr_init)
  56. // br label %bb2
  57. // bb2:
  58. // int_val = PHI([int_init, %bb1], [int_val_inc, %bb2]
  59. // ptr_val = PHI([ptr_init, %bb1], [ptr_val_inc, %bb2]
  60. // ptr_val2 = IntToPtr(int_val)
  61. // ...
  62. // use(ptr_val2)
  63. // ptr_val_inc = ...
  64. // inc_val_inc = PtrToInt(ptr_val_inc)
  65. //
  66. // ==>
  67. // bb1:
  68. // br label %bb2
  69. // bb2:
  70. // ptr_val = PHI([ptr_init, %bb1], [ptr_val_inc, %bb2]
  71. // ...
  72. // use(ptr_val)
  73. // ptr_val_inc = ...
  74. //
  75. // Case-2:
  76. // bb1:
  77. // int_ptr = BitCast(ptr_ptr)
  78. // int_init = Load(int_ptr)
  79. // br label %bb2
  80. // bb2:
  81. // int_val = PHI([int_init, %bb1], [int_val_inc, %bb2]
  82. // ptr_val2 = IntToPtr(int_val)
  83. // ...
  84. // use(ptr_val2)
  85. // ptr_val_inc = ...
  86. // inc_val_inc = PtrToInt(ptr_val_inc)
  87. // ==>
  88. // bb1:
  89. // ptr_init = Load(ptr_ptr)
  90. // br label %bb2
  91. // bb2:
  92. // ptr_val = PHI([ptr_init, %bb1], [ptr_val_inc, %bb2]
  93. // ...
  94. // use(ptr_val)
  95. // ptr_val_inc = ...
  96. // ...
  97. //
  98. bool InstCombinerImpl::foldIntegerTypedPHI(PHINode &PN) {
  99. if (!PN.getType()->isIntegerTy())
  100. return false;
  101. if (!PN.hasOneUse())
  102. return false;
  103. auto *IntToPtr = dyn_cast<IntToPtrInst>(PN.user_back());
  104. if (!IntToPtr)
  105. return false;
  106. // Check if the pointer is actually used as pointer:
  107. auto HasPointerUse = [](Instruction *IIP) {
  108. for (User *U : IIP->users()) {
  109. Value *Ptr = nullptr;
  110. if (LoadInst *LoadI = dyn_cast<LoadInst>(U)) {
  111. Ptr = LoadI->getPointerOperand();
  112. } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
  113. Ptr = SI->getPointerOperand();
  114. } else if (GetElementPtrInst *GI = dyn_cast<GetElementPtrInst>(U)) {
  115. Ptr = GI->getPointerOperand();
  116. }
  117. if (Ptr && Ptr == IIP)
  118. return true;
  119. }
  120. return false;
  121. };
  122. if (!HasPointerUse(IntToPtr))
  123. return false;
  124. if (DL.getPointerSizeInBits(IntToPtr->getAddressSpace()) !=
  125. DL.getTypeSizeInBits(IntToPtr->getOperand(0)->getType()))
  126. return false;
  127. SmallVector<Value *, 4> AvailablePtrVals;
  128. for (auto Incoming : zip(PN.blocks(), PN.incoming_values())) {
  129. BasicBlock *BB = std::get<0>(Incoming);
  130. Value *Arg = std::get<1>(Incoming);
  131. // First look backward:
  132. if (auto *PI = dyn_cast<PtrToIntInst>(Arg)) {
  133. AvailablePtrVals.emplace_back(PI->getOperand(0));
  134. continue;
  135. }
  136. // Next look forward:
  137. Value *ArgIntToPtr = nullptr;
  138. for (User *U : Arg->users()) {
  139. if (isa<IntToPtrInst>(U) && U->getType() == IntToPtr->getType() &&
  140. (DT.dominates(cast<Instruction>(U), BB) ||
  141. cast<Instruction>(U)->getParent() == BB)) {
  142. ArgIntToPtr = U;
  143. break;
  144. }
  145. }
  146. if (ArgIntToPtr) {
  147. AvailablePtrVals.emplace_back(ArgIntToPtr);
  148. continue;
  149. }
  150. // If Arg is defined by a PHI, allow it. This will also create
  151. // more opportunities iteratively.
  152. if (isa<PHINode>(Arg)) {
  153. AvailablePtrVals.emplace_back(Arg);
  154. continue;
  155. }
  156. // For a single use integer load:
  157. auto *LoadI = dyn_cast<LoadInst>(Arg);
  158. if (!LoadI)
  159. return false;
  160. if (!LoadI->hasOneUse())
  161. return false;
  162. // Push the integer typed Load instruction into the available
  163. // value set, and fix it up later when the pointer typed PHI
  164. // is synthesized.
  165. AvailablePtrVals.emplace_back(LoadI);
  166. }
  167. // Now search for a matching PHI
  168. auto *BB = PN.getParent();
  169. assert(AvailablePtrVals.size() == PN.getNumIncomingValues() &&
  170. "Not enough available ptr typed incoming values");
  171. PHINode *MatchingPtrPHI = nullptr;
  172. unsigned NumPhis = 0;
  173. for (PHINode &PtrPHI : BB->phis()) {
  174. // FIXME: consider handling this in AggressiveInstCombine
  175. if (NumPhis++ > MaxNumPhis)
  176. return false;
  177. if (&PtrPHI == &PN || PtrPHI.getType() != IntToPtr->getType())
  178. continue;
  179. if (any_of(zip(PN.blocks(), AvailablePtrVals),
  180. [&](const auto &BlockAndValue) {
  181. BasicBlock *BB = std::get<0>(BlockAndValue);
  182. Value *V = std::get<1>(BlockAndValue);
  183. return PtrPHI.getIncomingValueForBlock(BB) != V;
  184. }))
  185. continue;
  186. MatchingPtrPHI = &PtrPHI;
  187. break;
  188. }
  189. if (MatchingPtrPHI) {
  190. assert(MatchingPtrPHI->getType() == IntToPtr->getType() &&
  191. "Phi's Type does not match with IntToPtr");
  192. // Explicitly replace the inttoptr (rather than inserting a ptrtoint) here,
  193. // to make sure another transform can't undo it in the meantime.
  194. replaceInstUsesWith(*IntToPtr, MatchingPtrPHI);
  195. eraseInstFromFunction(*IntToPtr);
  196. eraseInstFromFunction(PN);
  197. return true;
  198. }
  199. // If it requires a conversion for every PHI operand, do not do it.
  200. if (all_of(AvailablePtrVals, [&](Value *V) {
  201. return (V->getType() != IntToPtr->getType()) || isa<IntToPtrInst>(V);
  202. }))
  203. return false;
  204. // If any of the operand that requires casting is a terminator
  205. // instruction, do not do it. Similarly, do not do the transform if the value
  206. // is PHI in a block with no insertion point, for example, a catchswitch
  207. // block, since we will not be able to insert a cast after the PHI.
  208. if (any_of(AvailablePtrVals, [&](Value *V) {
  209. if (V->getType() == IntToPtr->getType())
  210. return false;
  211. auto *Inst = dyn_cast<Instruction>(V);
  212. if (!Inst)
  213. return false;
  214. if (Inst->isTerminator())
  215. return true;
  216. auto *BB = Inst->getParent();
  217. if (isa<PHINode>(Inst) && BB->getFirstInsertionPt() == BB->end())
  218. return true;
  219. return false;
  220. }))
  221. return false;
  222. PHINode *NewPtrPHI = PHINode::Create(
  223. IntToPtr->getType(), PN.getNumIncomingValues(), PN.getName() + ".ptr");
  224. InsertNewInstBefore(NewPtrPHI, PN);
  225. SmallDenseMap<Value *, Instruction *> Casts;
  226. for (auto Incoming : zip(PN.blocks(), AvailablePtrVals)) {
  227. auto *IncomingBB = std::get<0>(Incoming);
  228. auto *IncomingVal = std::get<1>(Incoming);
  229. if (IncomingVal->getType() == IntToPtr->getType()) {
  230. NewPtrPHI->addIncoming(IncomingVal, IncomingBB);
  231. continue;
  232. }
  233. #ifndef NDEBUG
  234. LoadInst *LoadI = dyn_cast<LoadInst>(IncomingVal);
  235. assert((isa<PHINode>(IncomingVal) ||
  236. IncomingVal->getType()->isPointerTy() ||
  237. (LoadI && LoadI->hasOneUse())) &&
  238. "Can not replace LoadInst with multiple uses");
  239. #endif
  240. // Need to insert a BitCast.
  241. // For an integer Load instruction with a single use, the load + IntToPtr
  242. // cast will be simplified into a pointer load:
  243. // %v = load i64, i64* %a.ip, align 8
  244. // %v.cast = inttoptr i64 %v to float **
  245. // ==>
  246. // %v.ptrp = bitcast i64 * %a.ip to float **
  247. // %v.cast = load float *, float ** %v.ptrp, align 8
  248. Instruction *&CI = Casts[IncomingVal];
  249. if (!CI) {
  250. CI = CastInst::CreateBitOrPointerCast(IncomingVal, IntToPtr->getType(),
  251. IncomingVal->getName() + ".ptr");
  252. if (auto *IncomingI = dyn_cast<Instruction>(IncomingVal)) {
  253. BasicBlock::iterator InsertPos(IncomingI);
  254. InsertPos++;
  255. BasicBlock *BB = IncomingI->getParent();
  256. if (isa<PHINode>(IncomingI))
  257. InsertPos = BB->getFirstInsertionPt();
  258. assert(InsertPos != BB->end() && "should have checked above");
  259. InsertNewInstBefore(CI, *InsertPos);
  260. } else {
  261. auto *InsertBB = &IncomingBB->getParent()->getEntryBlock();
  262. InsertNewInstBefore(CI, *InsertBB->getFirstInsertionPt());
  263. }
  264. }
  265. NewPtrPHI->addIncoming(CI, IncomingBB);
  266. }
  267. // Explicitly replace the inttoptr (rather than inserting a ptrtoint) here,
  268. // to make sure another transform can't undo it in the meantime.
  269. replaceInstUsesWith(*IntToPtr, NewPtrPHI);
  270. eraseInstFromFunction(*IntToPtr);
  271. eraseInstFromFunction(PN);
  272. return true;
  273. }
  274. // Remove RoundTrip IntToPtr/PtrToInt Cast on PHI-Operand and
  275. // fold Phi-operand to bitcast.
  276. Instruction *InstCombinerImpl::foldPHIArgIntToPtrToPHI(PHINode &PN) {
  277. // convert ptr2int ( phi[ int2ptr(ptr2int(x))] ) --> ptr2int ( phi [ x ] )
  278. // Make sure all uses of phi are ptr2int.
  279. if (!all_of(PN.users(), [](User *U) { return isa<PtrToIntInst>(U); }))
  280. return nullptr;
  281. // Iterating over all operands to check presence of target pointers for
  282. // optimization.
  283. bool OperandWithRoundTripCast = false;
  284. for (unsigned OpNum = 0; OpNum != PN.getNumIncomingValues(); ++OpNum) {
  285. if (auto *NewOp =
  286. simplifyIntToPtrRoundTripCast(PN.getIncomingValue(OpNum))) {
  287. PN.setIncomingValue(OpNum, NewOp);
  288. OperandWithRoundTripCast = true;
  289. }
  290. }
  291. if (!OperandWithRoundTripCast)
  292. return nullptr;
  293. return &PN;
  294. }
  295. /// If we have something like phi [insertvalue(a,b,0), insertvalue(c,d,0)],
  296. /// turn this into a phi[a,c] and phi[b,d] and a single insertvalue.
  297. Instruction *
  298. InstCombinerImpl::foldPHIArgInsertValueInstructionIntoPHI(PHINode &PN) {
  299. auto *FirstIVI = cast<InsertValueInst>(PN.getIncomingValue(0));
  300. // Scan to see if all operands are `insertvalue`'s with the same indicies,
  301. // and all have a single use.
  302. for (Value *V : drop_begin(PN.incoming_values())) {
  303. auto *I = dyn_cast<InsertValueInst>(V);
  304. if (!I || !I->hasOneUser() || I->getIndices() != FirstIVI->getIndices())
  305. return nullptr;
  306. }
  307. // For each operand of an `insertvalue`
  308. std::array<PHINode *, 2> NewOperands;
  309. for (int OpIdx : {0, 1}) {
  310. auto *&NewOperand = NewOperands[OpIdx];
  311. // Create a new PHI node to receive the values the operand has in each
  312. // incoming basic block.
  313. NewOperand = PHINode::Create(
  314. FirstIVI->getOperand(OpIdx)->getType(), PN.getNumIncomingValues(),
  315. FirstIVI->getOperand(OpIdx)->getName() + ".pn");
  316. // And populate each operand's PHI with said values.
  317. for (auto Incoming : zip(PN.blocks(), PN.incoming_values()))
  318. NewOperand->addIncoming(
  319. cast<InsertValueInst>(std::get<1>(Incoming))->getOperand(OpIdx),
  320. std::get<0>(Incoming));
  321. InsertNewInstBefore(NewOperand, PN);
  322. }
  323. // And finally, create `insertvalue` over the newly-formed PHI nodes.
  324. auto *NewIVI = InsertValueInst::Create(NewOperands[0], NewOperands[1],
  325. FirstIVI->getIndices(), PN.getName());
  326. PHIArgMergedDebugLoc(NewIVI, PN);
  327. ++NumPHIsOfInsertValues;
  328. return NewIVI;
  329. }
  330. /// If we have something like phi [extractvalue(a,0), extractvalue(b,0)],
  331. /// turn this into a phi[a,b] and a single extractvalue.
  332. Instruction *
  333. InstCombinerImpl::foldPHIArgExtractValueInstructionIntoPHI(PHINode &PN) {
  334. auto *FirstEVI = cast<ExtractValueInst>(PN.getIncomingValue(0));
  335. // Scan to see if all operands are `extractvalue`'s with the same indicies,
  336. // and all have a single use.
  337. for (Value *V : drop_begin(PN.incoming_values())) {
  338. auto *I = dyn_cast<ExtractValueInst>(V);
  339. if (!I || !I->hasOneUser() || I->getIndices() != FirstEVI->getIndices() ||
  340. I->getAggregateOperand()->getType() !=
  341. FirstEVI->getAggregateOperand()->getType())
  342. return nullptr;
  343. }
  344. // Create a new PHI node to receive the values the aggregate operand has
  345. // in each incoming basic block.
  346. auto *NewAggregateOperand = PHINode::Create(
  347. FirstEVI->getAggregateOperand()->getType(), PN.getNumIncomingValues(),
  348. FirstEVI->getAggregateOperand()->getName() + ".pn");
  349. // And populate the PHI with said values.
  350. for (auto Incoming : zip(PN.blocks(), PN.incoming_values()))
  351. NewAggregateOperand->addIncoming(
  352. cast<ExtractValueInst>(std::get<1>(Incoming))->getAggregateOperand(),
  353. std::get<0>(Incoming));
  354. InsertNewInstBefore(NewAggregateOperand, PN);
  355. // And finally, create `extractvalue` over the newly-formed PHI nodes.
  356. auto *NewEVI = ExtractValueInst::Create(NewAggregateOperand,
  357. FirstEVI->getIndices(), PN.getName());
  358. PHIArgMergedDebugLoc(NewEVI, PN);
  359. ++NumPHIsOfExtractValues;
  360. return NewEVI;
  361. }
  362. /// If we have something like phi [add (a,b), add(a,c)] and if a/b/c and the
  363. /// adds all have a single user, turn this into a phi and a single binop.
  364. Instruction *InstCombinerImpl::foldPHIArgBinOpIntoPHI(PHINode &PN) {
  365. Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
  366. assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
  367. unsigned Opc = FirstInst->getOpcode();
  368. Value *LHSVal = FirstInst->getOperand(0);
  369. Value *RHSVal = FirstInst->getOperand(1);
  370. Type *LHSType = LHSVal->getType();
  371. Type *RHSType = RHSVal->getType();
  372. // Scan to see if all operands are the same opcode, and all have one user.
  373. for (Value *V : drop_begin(PN.incoming_values())) {
  374. Instruction *I = dyn_cast<Instruction>(V);
  375. if (!I || I->getOpcode() != Opc || !I->hasOneUser() ||
  376. // Verify type of the LHS matches so we don't fold cmp's of different
  377. // types.
  378. I->getOperand(0)->getType() != LHSType ||
  379. I->getOperand(1)->getType() != RHSType)
  380. return nullptr;
  381. // If they are CmpInst instructions, check their predicates
  382. if (CmpInst *CI = dyn_cast<CmpInst>(I))
  383. if (CI->getPredicate() != cast<CmpInst>(FirstInst)->getPredicate())
  384. return nullptr;
  385. // Keep track of which operand needs a phi node.
  386. if (I->getOperand(0) != LHSVal) LHSVal = nullptr;
  387. if (I->getOperand(1) != RHSVal) RHSVal = nullptr;
  388. }
  389. // If both LHS and RHS would need a PHI, don't do this transformation,
  390. // because it would increase the number of PHIs entering the block,
  391. // which leads to higher register pressure. This is especially
  392. // bad when the PHIs are in the header of a loop.
  393. if (!LHSVal && !RHSVal)
  394. return nullptr;
  395. // Otherwise, this is safe to transform!
  396. Value *InLHS = FirstInst->getOperand(0);
  397. Value *InRHS = FirstInst->getOperand(1);
  398. PHINode *NewLHS = nullptr, *NewRHS = nullptr;
  399. if (!LHSVal) {
  400. NewLHS = PHINode::Create(LHSType, PN.getNumIncomingValues(),
  401. FirstInst->getOperand(0)->getName() + ".pn");
  402. NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
  403. InsertNewInstBefore(NewLHS, PN);
  404. LHSVal = NewLHS;
  405. }
  406. if (!RHSVal) {
  407. NewRHS = PHINode::Create(RHSType, PN.getNumIncomingValues(),
  408. FirstInst->getOperand(1)->getName() + ".pn");
  409. NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
  410. InsertNewInstBefore(NewRHS, PN);
  411. RHSVal = NewRHS;
  412. }
  413. // Add all operands to the new PHIs.
  414. if (NewLHS || NewRHS) {
  415. for (auto Incoming : drop_begin(zip(PN.blocks(), PN.incoming_values()))) {
  416. BasicBlock *InBB = std::get<0>(Incoming);
  417. Value *InVal = std::get<1>(Incoming);
  418. Instruction *InInst = cast<Instruction>(InVal);
  419. if (NewLHS) {
  420. Value *NewInLHS = InInst->getOperand(0);
  421. NewLHS->addIncoming(NewInLHS, InBB);
  422. }
  423. if (NewRHS) {
  424. Value *NewInRHS = InInst->getOperand(1);
  425. NewRHS->addIncoming(NewInRHS, InBB);
  426. }
  427. }
  428. }
  429. if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst)) {
  430. CmpInst *NewCI = CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
  431. LHSVal, RHSVal);
  432. PHIArgMergedDebugLoc(NewCI, PN);
  433. return NewCI;
  434. }
  435. BinaryOperator *BinOp = cast<BinaryOperator>(FirstInst);
  436. BinaryOperator *NewBinOp =
  437. BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
  438. NewBinOp->copyIRFlags(PN.getIncomingValue(0));
  439. for (Value *V : drop_begin(PN.incoming_values()))
  440. NewBinOp->andIRFlags(V);
  441. PHIArgMergedDebugLoc(NewBinOp, PN);
  442. return NewBinOp;
  443. }
  444. Instruction *InstCombinerImpl::foldPHIArgGEPIntoPHI(PHINode &PN) {
  445. GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
  446. SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
  447. FirstInst->op_end());
  448. // This is true if all GEP bases are allocas and if all indices into them are
  449. // constants.
  450. bool AllBasePointersAreAllocas = true;
  451. // We don't want to replace this phi if the replacement would require
  452. // more than one phi, which leads to higher register pressure. This is
  453. // especially bad when the PHIs are in the header of a loop.
  454. bool NeededPhi = false;
  455. bool AllInBounds = true;
  456. // Scan to see if all operands are the same opcode, and all have one user.
  457. for (Value *V : drop_begin(PN.incoming_values())) {
  458. GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V);
  459. if (!GEP || !GEP->hasOneUser() ||
  460. GEP->getSourceElementType() != FirstInst->getSourceElementType() ||
  461. GEP->getNumOperands() != FirstInst->getNumOperands())
  462. return nullptr;
  463. AllInBounds &= GEP->isInBounds();
  464. // Keep track of whether or not all GEPs are of alloca pointers.
  465. if (AllBasePointersAreAllocas &&
  466. (!isa<AllocaInst>(GEP->getOperand(0)) ||
  467. !GEP->hasAllConstantIndices()))
  468. AllBasePointersAreAllocas = false;
  469. // Compare the operand lists.
  470. for (unsigned Op = 0, E = FirstInst->getNumOperands(); Op != E; ++Op) {
  471. if (FirstInst->getOperand(Op) == GEP->getOperand(Op))
  472. continue;
  473. // Don't merge two GEPs when two operands differ (introducing phi nodes)
  474. // if one of the PHIs has a constant for the index. The index may be
  475. // substantially cheaper to compute for the constants, so making it a
  476. // variable index could pessimize the path. This also handles the case
  477. // for struct indices, which must always be constant.
  478. if (isa<ConstantInt>(FirstInst->getOperand(Op)) ||
  479. isa<ConstantInt>(GEP->getOperand(Op)))
  480. return nullptr;
  481. if (FirstInst->getOperand(Op)->getType() !=
  482. GEP->getOperand(Op)->getType())
  483. return nullptr;
  484. // If we already needed a PHI for an earlier operand, and another operand
  485. // also requires a PHI, we'd be introducing more PHIs than we're
  486. // eliminating, which increases register pressure on entry to the PHI's
  487. // block.
  488. if (NeededPhi)
  489. return nullptr;
  490. FixedOperands[Op] = nullptr; // Needs a PHI.
  491. NeededPhi = true;
  492. }
  493. }
  494. // If all of the base pointers of the PHI'd GEPs are from allocas, don't
  495. // bother doing this transformation. At best, this will just save a bit of
  496. // offset calculation, but all the predecessors will have to materialize the
  497. // stack address into a register anyway. We'd actually rather *clone* the
  498. // load up into the predecessors so that we have a load of a gep of an alloca,
  499. // which can usually all be folded into the load.
  500. if (AllBasePointersAreAllocas)
  501. return nullptr;
  502. // Otherwise, this is safe to transform. Insert PHI nodes for each operand
  503. // that is variable.
  504. SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
  505. bool HasAnyPHIs = false;
  506. for (unsigned I = 0, E = FixedOperands.size(); I != E; ++I) {
  507. if (FixedOperands[I])
  508. continue; // operand doesn't need a phi.
  509. Value *FirstOp = FirstInst->getOperand(I);
  510. PHINode *NewPN =
  511. PHINode::Create(FirstOp->getType(), E, FirstOp->getName() + ".pn");
  512. InsertNewInstBefore(NewPN, PN);
  513. NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
  514. OperandPhis[I] = NewPN;
  515. FixedOperands[I] = NewPN;
  516. HasAnyPHIs = true;
  517. }
  518. // Add all operands to the new PHIs.
  519. if (HasAnyPHIs) {
  520. for (auto Incoming : drop_begin(zip(PN.blocks(), PN.incoming_values()))) {
  521. BasicBlock *InBB = std::get<0>(Incoming);
  522. Value *InVal = std::get<1>(Incoming);
  523. GetElementPtrInst *InGEP = cast<GetElementPtrInst>(InVal);
  524. for (unsigned Op = 0, E = OperandPhis.size(); Op != E; ++Op)
  525. if (PHINode *OpPhi = OperandPhis[Op])
  526. OpPhi->addIncoming(InGEP->getOperand(Op), InBB);
  527. }
  528. }
  529. Value *Base = FixedOperands[0];
  530. GetElementPtrInst *NewGEP =
  531. GetElementPtrInst::Create(FirstInst->getSourceElementType(), Base,
  532. ArrayRef(FixedOperands).slice(1));
  533. if (AllInBounds) NewGEP->setIsInBounds();
  534. PHIArgMergedDebugLoc(NewGEP, PN);
  535. return NewGEP;
  536. }
  537. /// Return true if we know that it is safe to sink the load out of the block
  538. /// that defines it. This means that it must be obvious the value of the load is
  539. /// not changed from the point of the load to the end of the block it is in.
  540. ///
  541. /// Finally, it is safe, but not profitable, to sink a load targeting a
  542. /// non-address-taken alloca. Doing so will cause us to not promote the alloca
  543. /// to a register.
  544. static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
  545. BasicBlock::iterator BBI = L->getIterator(), E = L->getParent()->end();
  546. for (++BBI; BBI != E; ++BBI)
  547. if (BBI->mayWriteToMemory()) {
  548. // Calls that only access inaccessible memory do not block sinking the
  549. // load.
  550. if (auto *CB = dyn_cast<CallBase>(BBI))
  551. if (CB->onlyAccessesInaccessibleMemory())
  552. continue;
  553. return false;
  554. }
  555. // Check for non-address taken alloca. If not address-taken already, it isn't
  556. // profitable to do this xform.
  557. if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
  558. bool IsAddressTaken = false;
  559. for (User *U : AI->users()) {
  560. if (isa<LoadInst>(U)) continue;
  561. if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
  562. // If storing TO the alloca, then the address isn't taken.
  563. if (SI->getOperand(1) == AI) continue;
  564. }
  565. IsAddressTaken = true;
  566. break;
  567. }
  568. if (!IsAddressTaken && AI->isStaticAlloca())
  569. return false;
  570. }
  571. // If this load is a load from a GEP with a constant offset from an alloca,
  572. // then we don't want to sink it. In its present form, it will be
  573. // load [constant stack offset]. Sinking it will cause us to have to
  574. // materialize the stack addresses in each predecessor in a register only to
  575. // do a shared load from register in the successor.
  576. if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
  577. if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
  578. if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
  579. return false;
  580. return true;
  581. }
  582. Instruction *InstCombinerImpl::foldPHIArgLoadIntoPHI(PHINode &PN) {
  583. LoadInst *FirstLI = cast<LoadInst>(PN.getIncomingValue(0));
  584. // Can't forward swifterror through a phi.
  585. if (FirstLI->getOperand(0)->isSwiftError())
  586. return nullptr;
  587. // FIXME: This is overconservative; this transform is allowed in some cases
  588. // for atomic operations.
  589. if (FirstLI->isAtomic())
  590. return nullptr;
  591. // When processing loads, we need to propagate two bits of information to the
  592. // sunk load: whether it is volatile, and what its alignment is.
  593. bool IsVolatile = FirstLI->isVolatile();
  594. Align LoadAlignment = FirstLI->getAlign();
  595. const unsigned LoadAddrSpace = FirstLI->getPointerAddressSpace();
  596. // We can't sink the load if the loaded value could be modified between the
  597. // load and the PHI.
  598. if (FirstLI->getParent() != PN.getIncomingBlock(0) ||
  599. !isSafeAndProfitableToSinkLoad(FirstLI))
  600. return nullptr;
  601. // If the PHI is of volatile loads and the load block has multiple
  602. // successors, sinking it would remove a load of the volatile value from
  603. // the path through the other successor.
  604. if (IsVolatile &&
  605. FirstLI->getParent()->getTerminator()->getNumSuccessors() != 1)
  606. return nullptr;
  607. for (auto Incoming : drop_begin(zip(PN.blocks(), PN.incoming_values()))) {
  608. BasicBlock *InBB = std::get<0>(Incoming);
  609. Value *InVal = std::get<1>(Incoming);
  610. LoadInst *LI = dyn_cast<LoadInst>(InVal);
  611. if (!LI || !LI->hasOneUser() || LI->isAtomic())
  612. return nullptr;
  613. // Make sure all arguments are the same type of operation.
  614. if (LI->isVolatile() != IsVolatile ||
  615. LI->getPointerAddressSpace() != LoadAddrSpace)
  616. return nullptr;
  617. // Can't forward swifterror through a phi.
  618. if (LI->getOperand(0)->isSwiftError())
  619. return nullptr;
  620. // We can't sink the load if the loaded value could be modified between
  621. // the load and the PHI.
  622. if (LI->getParent() != InBB || !isSafeAndProfitableToSinkLoad(LI))
  623. return nullptr;
  624. LoadAlignment = std::min(LoadAlignment, LI->getAlign());
  625. // If the PHI is of volatile loads and the load block has multiple
  626. // successors, sinking it would remove a load of the volatile value from
  627. // the path through the other successor.
  628. if (IsVolatile && LI->getParent()->getTerminator()->getNumSuccessors() != 1)
  629. return nullptr;
  630. }
  631. // Okay, they are all the same operation. Create a new PHI node of the
  632. // correct type, and PHI together all of the LHS's of the instructions.
  633. PHINode *NewPN = PHINode::Create(FirstLI->getOperand(0)->getType(),
  634. PN.getNumIncomingValues(),
  635. PN.getName()+".in");
  636. Value *InVal = FirstLI->getOperand(0);
  637. NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
  638. LoadInst *NewLI =
  639. new LoadInst(FirstLI->getType(), NewPN, "", IsVolatile, LoadAlignment);
  640. unsigned KnownIDs[] = {
  641. LLVMContext::MD_tbaa,
  642. LLVMContext::MD_range,
  643. LLVMContext::MD_invariant_load,
  644. LLVMContext::MD_alias_scope,
  645. LLVMContext::MD_noalias,
  646. LLVMContext::MD_nonnull,
  647. LLVMContext::MD_align,
  648. LLVMContext::MD_dereferenceable,
  649. LLVMContext::MD_dereferenceable_or_null,
  650. LLVMContext::MD_access_group,
  651. };
  652. for (unsigned ID : KnownIDs)
  653. NewLI->setMetadata(ID, FirstLI->getMetadata(ID));
  654. // Add all operands to the new PHI and combine TBAA metadata.
  655. for (auto Incoming : drop_begin(zip(PN.blocks(), PN.incoming_values()))) {
  656. BasicBlock *BB = std::get<0>(Incoming);
  657. Value *V = std::get<1>(Incoming);
  658. LoadInst *LI = cast<LoadInst>(V);
  659. combineMetadata(NewLI, LI, KnownIDs, true);
  660. Value *NewInVal = LI->getOperand(0);
  661. if (NewInVal != InVal)
  662. InVal = nullptr;
  663. NewPN->addIncoming(NewInVal, BB);
  664. }
  665. if (InVal) {
  666. // The new PHI unions all of the same values together. This is really
  667. // common, so we handle it intelligently here for compile-time speed.
  668. NewLI->setOperand(0, InVal);
  669. delete NewPN;
  670. } else {
  671. InsertNewInstBefore(NewPN, PN);
  672. }
  673. // If this was a volatile load that we are merging, make sure to loop through
  674. // and mark all the input loads as non-volatile. If we don't do this, we will
  675. // insert a new volatile load and the old ones will not be deletable.
  676. if (IsVolatile)
  677. for (Value *IncValue : PN.incoming_values())
  678. cast<LoadInst>(IncValue)->setVolatile(false);
  679. PHIArgMergedDebugLoc(NewLI, PN);
  680. return NewLI;
  681. }
  682. /// TODO: This function could handle other cast types, but then it might
  683. /// require special-casing a cast from the 'i1' type. See the comment in
  684. /// FoldPHIArgOpIntoPHI() about pessimizing illegal integer types.
  685. Instruction *InstCombinerImpl::foldPHIArgZextsIntoPHI(PHINode &Phi) {
  686. // We cannot create a new instruction after the PHI if the terminator is an
  687. // EHPad because there is no valid insertion point.
  688. if (Instruction *TI = Phi.getParent()->getTerminator())
  689. if (TI->isEHPad())
  690. return nullptr;
  691. // Early exit for the common case of a phi with two operands. These are
  692. // handled elsewhere. See the comment below where we check the count of zexts
  693. // and constants for more details.
  694. unsigned NumIncomingValues = Phi.getNumIncomingValues();
  695. if (NumIncomingValues < 3)
  696. return nullptr;
  697. // Find the narrower type specified by the first zext.
  698. Type *NarrowType = nullptr;
  699. for (Value *V : Phi.incoming_values()) {
  700. if (auto *Zext = dyn_cast<ZExtInst>(V)) {
  701. NarrowType = Zext->getSrcTy();
  702. break;
  703. }
  704. }
  705. if (!NarrowType)
  706. return nullptr;
  707. // Walk the phi operands checking that we only have zexts or constants that
  708. // we can shrink for free. Store the new operands for the new phi.
  709. SmallVector<Value *, 4> NewIncoming;
  710. unsigned NumZexts = 0;
  711. unsigned NumConsts = 0;
  712. for (Value *V : Phi.incoming_values()) {
  713. if (auto *Zext = dyn_cast<ZExtInst>(V)) {
  714. // All zexts must be identical and have one user.
  715. if (Zext->getSrcTy() != NarrowType || !Zext->hasOneUser())
  716. return nullptr;
  717. NewIncoming.push_back(Zext->getOperand(0));
  718. NumZexts++;
  719. } else if (auto *C = dyn_cast<Constant>(V)) {
  720. // Make sure that constants can fit in the new type.
  721. Constant *Trunc = ConstantExpr::getTrunc(C, NarrowType);
  722. if (ConstantExpr::getZExt(Trunc, C->getType()) != C)
  723. return nullptr;
  724. NewIncoming.push_back(Trunc);
  725. NumConsts++;
  726. } else {
  727. // If it's not a cast or a constant, bail out.
  728. return nullptr;
  729. }
  730. }
  731. // The more common cases of a phi with no constant operands or just one
  732. // variable operand are handled by FoldPHIArgOpIntoPHI() and foldOpIntoPhi()
  733. // respectively. foldOpIntoPhi() wants to do the opposite transform that is
  734. // performed here. It tries to replicate a cast in the phi operand's basic
  735. // block to expose other folding opportunities. Thus, InstCombine will
  736. // infinite loop without this check.
  737. if (NumConsts == 0 || NumZexts < 2)
  738. return nullptr;
  739. // All incoming values are zexts or constants that are safe to truncate.
  740. // Create a new phi node of the narrow type, phi together all of the new
  741. // operands, and zext the result back to the original type.
  742. PHINode *NewPhi = PHINode::Create(NarrowType, NumIncomingValues,
  743. Phi.getName() + ".shrunk");
  744. for (unsigned I = 0; I != NumIncomingValues; ++I)
  745. NewPhi->addIncoming(NewIncoming[I], Phi.getIncomingBlock(I));
  746. InsertNewInstBefore(NewPhi, Phi);
  747. return CastInst::CreateZExtOrBitCast(NewPhi, Phi.getType());
  748. }
  749. /// If all operands to a PHI node are the same "unary" operator and they all are
  750. /// only used by the PHI, PHI together their inputs, and do the operation once,
  751. /// to the result of the PHI.
  752. Instruction *InstCombinerImpl::foldPHIArgOpIntoPHI(PHINode &PN) {
  753. // We cannot create a new instruction after the PHI if the terminator is an
  754. // EHPad because there is no valid insertion point.
  755. if (Instruction *TI = PN.getParent()->getTerminator())
  756. if (TI->isEHPad())
  757. return nullptr;
  758. Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
  759. if (isa<GetElementPtrInst>(FirstInst))
  760. return foldPHIArgGEPIntoPHI(PN);
  761. if (isa<LoadInst>(FirstInst))
  762. return foldPHIArgLoadIntoPHI(PN);
  763. if (isa<InsertValueInst>(FirstInst))
  764. return foldPHIArgInsertValueInstructionIntoPHI(PN);
  765. if (isa<ExtractValueInst>(FirstInst))
  766. return foldPHIArgExtractValueInstructionIntoPHI(PN);
  767. // Scan the instruction, looking for input operations that can be folded away.
  768. // If all input operands to the phi are the same instruction (e.g. a cast from
  769. // the same type or "+42") we can pull the operation through the PHI, reducing
  770. // code size and simplifying code.
  771. Constant *ConstantOp = nullptr;
  772. Type *CastSrcTy = nullptr;
  773. if (isa<CastInst>(FirstInst)) {
  774. CastSrcTy = FirstInst->getOperand(0)->getType();
  775. // Be careful about transforming integer PHIs. We don't want to pessimize
  776. // the code by turning an i32 into an i1293.
  777. if (PN.getType()->isIntegerTy() && CastSrcTy->isIntegerTy()) {
  778. if (!shouldChangeType(PN.getType(), CastSrcTy))
  779. return nullptr;
  780. }
  781. } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
  782. // Can fold binop, compare or shift here if the RHS is a constant,
  783. // otherwise call FoldPHIArgBinOpIntoPHI.
  784. ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
  785. if (!ConstantOp)
  786. return foldPHIArgBinOpIntoPHI(PN);
  787. } else {
  788. return nullptr; // Cannot fold this operation.
  789. }
  790. // Check to see if all arguments are the same operation.
  791. for (Value *V : drop_begin(PN.incoming_values())) {
  792. Instruction *I = dyn_cast<Instruction>(V);
  793. if (!I || !I->hasOneUser() || !I->isSameOperationAs(FirstInst))
  794. return nullptr;
  795. if (CastSrcTy) {
  796. if (I->getOperand(0)->getType() != CastSrcTy)
  797. return nullptr; // Cast operation must match.
  798. } else if (I->getOperand(1) != ConstantOp) {
  799. return nullptr;
  800. }
  801. }
  802. // Okay, they are all the same operation. Create a new PHI node of the
  803. // correct type, and PHI together all of the LHS's of the instructions.
  804. PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
  805. PN.getNumIncomingValues(),
  806. PN.getName()+".in");
  807. Value *InVal = FirstInst->getOperand(0);
  808. NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
  809. // Add all operands to the new PHI.
  810. for (auto Incoming : drop_begin(zip(PN.blocks(), PN.incoming_values()))) {
  811. BasicBlock *BB = std::get<0>(Incoming);
  812. Value *V = std::get<1>(Incoming);
  813. Value *NewInVal = cast<Instruction>(V)->getOperand(0);
  814. if (NewInVal != InVal)
  815. InVal = nullptr;
  816. NewPN->addIncoming(NewInVal, BB);
  817. }
  818. Value *PhiVal;
  819. if (InVal) {
  820. // The new PHI unions all of the same values together. This is really
  821. // common, so we handle it intelligently here for compile-time speed.
  822. PhiVal = InVal;
  823. delete NewPN;
  824. } else {
  825. InsertNewInstBefore(NewPN, PN);
  826. PhiVal = NewPN;
  827. }
  828. // Insert and return the new operation.
  829. if (CastInst *FirstCI = dyn_cast<CastInst>(FirstInst)) {
  830. CastInst *NewCI = CastInst::Create(FirstCI->getOpcode(), PhiVal,
  831. PN.getType());
  832. PHIArgMergedDebugLoc(NewCI, PN);
  833. return NewCI;
  834. }
  835. if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst)) {
  836. BinOp = BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
  837. BinOp->copyIRFlags(PN.getIncomingValue(0));
  838. for (Value *V : drop_begin(PN.incoming_values()))
  839. BinOp->andIRFlags(V);
  840. PHIArgMergedDebugLoc(BinOp, PN);
  841. return BinOp;
  842. }
  843. CmpInst *CIOp = cast<CmpInst>(FirstInst);
  844. CmpInst *NewCI = CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
  845. PhiVal, ConstantOp);
  846. PHIArgMergedDebugLoc(NewCI, PN);
  847. return NewCI;
  848. }
  849. /// Return true if this PHI node is only used by a PHI node cycle that is dead.
  850. static bool isDeadPHICycle(PHINode *PN,
  851. SmallPtrSetImpl<PHINode *> &PotentiallyDeadPHIs) {
  852. if (PN->use_empty()) return true;
  853. if (!PN->hasOneUse()) return false;
  854. // Remember this node, and if we find the cycle, return.
  855. if (!PotentiallyDeadPHIs.insert(PN).second)
  856. return true;
  857. // Don't scan crazily complex things.
  858. if (PotentiallyDeadPHIs.size() == 16)
  859. return false;
  860. if (PHINode *PU = dyn_cast<PHINode>(PN->user_back()))
  861. return isDeadPHICycle(PU, PotentiallyDeadPHIs);
  862. return false;
  863. }
  864. /// Return true if this phi node is always equal to NonPhiInVal.
  865. /// This happens with mutually cyclic phi nodes like:
  866. /// z = some value; x = phi (y, z); y = phi (x, z)
  867. static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
  868. SmallPtrSetImpl<PHINode*> &ValueEqualPHIs) {
  869. // See if we already saw this PHI node.
  870. if (!ValueEqualPHIs.insert(PN).second)
  871. return true;
  872. // Don't scan crazily complex things.
  873. if (ValueEqualPHIs.size() == 16)
  874. return false;
  875. // Scan the operands to see if they are either phi nodes or are equal to
  876. // the value.
  877. for (Value *Op : PN->incoming_values()) {
  878. if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
  879. if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
  880. return false;
  881. } else if (Op != NonPhiInVal)
  882. return false;
  883. }
  884. return true;
  885. }
  886. /// Return an existing non-zero constant if this phi node has one, otherwise
  887. /// return constant 1.
  888. static ConstantInt *getAnyNonZeroConstInt(PHINode &PN) {
  889. assert(isa<IntegerType>(PN.getType()) && "Expect only integer type phi");
  890. for (Value *V : PN.operands())
  891. if (auto *ConstVA = dyn_cast<ConstantInt>(V))
  892. if (!ConstVA->isZero())
  893. return ConstVA;
  894. return ConstantInt::get(cast<IntegerType>(PN.getType()), 1);
  895. }
  896. namespace {
  897. struct PHIUsageRecord {
  898. unsigned PHIId; // The ID # of the PHI (something determinstic to sort on)
  899. unsigned Shift; // The amount shifted.
  900. Instruction *Inst; // The trunc instruction.
  901. PHIUsageRecord(unsigned Pn, unsigned Sh, Instruction *User)
  902. : PHIId(Pn), Shift(Sh), Inst(User) {}
  903. bool operator<(const PHIUsageRecord &RHS) const {
  904. if (PHIId < RHS.PHIId) return true;
  905. if (PHIId > RHS.PHIId) return false;
  906. if (Shift < RHS.Shift) return true;
  907. if (Shift > RHS.Shift) return false;
  908. return Inst->getType()->getPrimitiveSizeInBits() <
  909. RHS.Inst->getType()->getPrimitiveSizeInBits();
  910. }
  911. };
  912. struct LoweredPHIRecord {
  913. PHINode *PN; // The PHI that was lowered.
  914. unsigned Shift; // The amount shifted.
  915. unsigned Width; // The width extracted.
  916. LoweredPHIRecord(PHINode *Phi, unsigned Sh, Type *Ty)
  917. : PN(Phi), Shift(Sh), Width(Ty->getPrimitiveSizeInBits()) {}
  918. // Ctor form used by DenseMap.
  919. LoweredPHIRecord(PHINode *Phi, unsigned Sh) : PN(Phi), Shift(Sh), Width(0) {}
  920. };
  921. } // namespace
  922. namespace llvm {
  923. template<>
  924. struct DenseMapInfo<LoweredPHIRecord> {
  925. static inline LoweredPHIRecord getEmptyKey() {
  926. return LoweredPHIRecord(nullptr, 0);
  927. }
  928. static inline LoweredPHIRecord getTombstoneKey() {
  929. return LoweredPHIRecord(nullptr, 1);
  930. }
  931. static unsigned getHashValue(const LoweredPHIRecord &Val) {
  932. return DenseMapInfo<PHINode*>::getHashValue(Val.PN) ^ (Val.Shift>>3) ^
  933. (Val.Width>>3);
  934. }
  935. static bool isEqual(const LoweredPHIRecord &LHS,
  936. const LoweredPHIRecord &RHS) {
  937. return LHS.PN == RHS.PN && LHS.Shift == RHS.Shift &&
  938. LHS.Width == RHS.Width;
  939. }
  940. };
  941. } // namespace llvm
  942. /// This is an integer PHI and we know that it has an illegal type: see if it is
  943. /// only used by trunc or trunc(lshr) operations. If so, we split the PHI into
  944. /// the various pieces being extracted. This sort of thing is introduced when
  945. /// SROA promotes an aggregate to large integer values.
  946. ///
  947. /// TODO: The user of the trunc may be an bitcast to float/double/vector or an
  948. /// inttoptr. We should produce new PHIs in the right type.
  949. ///
  950. Instruction *InstCombinerImpl::SliceUpIllegalIntegerPHI(PHINode &FirstPhi) {
  951. // PHIUsers - Keep track of all of the truncated values extracted from a set
  952. // of PHIs, along with their offset. These are the things we want to rewrite.
  953. SmallVector<PHIUsageRecord, 16> PHIUsers;
  954. // PHIs are often mutually cyclic, so we keep track of a whole set of PHI
  955. // nodes which are extracted from. PHIsToSlice is a set we use to avoid
  956. // revisiting PHIs, PHIsInspected is a ordered list of PHIs that we need to
  957. // check the uses of (to ensure they are all extracts).
  958. SmallVector<PHINode*, 8> PHIsToSlice;
  959. SmallPtrSet<PHINode*, 8> PHIsInspected;
  960. PHIsToSlice.push_back(&FirstPhi);
  961. PHIsInspected.insert(&FirstPhi);
  962. for (unsigned PHIId = 0; PHIId != PHIsToSlice.size(); ++PHIId) {
  963. PHINode *PN = PHIsToSlice[PHIId];
  964. // Scan the input list of the PHI. If any input is an invoke, and if the
  965. // input is defined in the predecessor, then we won't be split the critical
  966. // edge which is required to insert a truncate. Because of this, we have to
  967. // bail out.
  968. for (auto Incoming : zip(PN->blocks(), PN->incoming_values())) {
  969. BasicBlock *BB = std::get<0>(Incoming);
  970. Value *V = std::get<1>(Incoming);
  971. InvokeInst *II = dyn_cast<InvokeInst>(V);
  972. if (!II)
  973. continue;
  974. if (II->getParent() != BB)
  975. continue;
  976. // If we have a phi, and if it's directly in the predecessor, then we have
  977. // a critical edge where we need to put the truncate. Since we can't
  978. // split the edge in instcombine, we have to bail out.
  979. return nullptr;
  980. }
  981. // If the incoming value is a PHI node before a catchswitch, we cannot
  982. // extract the value within that BB because we cannot insert any non-PHI
  983. // instructions in the BB.
  984. for (auto *Pred : PN->blocks())
  985. if (Pred->getFirstInsertionPt() == Pred->end())
  986. return nullptr;
  987. for (User *U : PN->users()) {
  988. Instruction *UserI = cast<Instruction>(U);
  989. // If the user is a PHI, inspect its uses recursively.
  990. if (PHINode *UserPN = dyn_cast<PHINode>(UserI)) {
  991. if (PHIsInspected.insert(UserPN).second)
  992. PHIsToSlice.push_back(UserPN);
  993. continue;
  994. }
  995. // Truncates are always ok.
  996. if (isa<TruncInst>(UserI)) {
  997. PHIUsers.push_back(PHIUsageRecord(PHIId, 0, UserI));
  998. continue;
  999. }
  1000. // Otherwise it must be a lshr which can only be used by one trunc.
  1001. if (UserI->getOpcode() != Instruction::LShr ||
  1002. !UserI->hasOneUse() || !isa<TruncInst>(UserI->user_back()) ||
  1003. !isa<ConstantInt>(UserI->getOperand(1)))
  1004. return nullptr;
  1005. // Bail on out of range shifts.
  1006. unsigned SizeInBits = UserI->getType()->getScalarSizeInBits();
  1007. if (cast<ConstantInt>(UserI->getOperand(1))->getValue().uge(SizeInBits))
  1008. return nullptr;
  1009. unsigned Shift = cast<ConstantInt>(UserI->getOperand(1))->getZExtValue();
  1010. PHIUsers.push_back(PHIUsageRecord(PHIId, Shift, UserI->user_back()));
  1011. }
  1012. }
  1013. // If we have no users, they must be all self uses, just nuke the PHI.
  1014. if (PHIUsers.empty())
  1015. return replaceInstUsesWith(FirstPhi, PoisonValue::get(FirstPhi.getType()));
  1016. // If this phi node is transformable, create new PHIs for all the pieces
  1017. // extracted out of it. First, sort the users by their offset and size.
  1018. array_pod_sort(PHIUsers.begin(), PHIUsers.end());
  1019. LLVM_DEBUG(dbgs() << "SLICING UP PHI: " << FirstPhi << '\n';
  1020. for (unsigned I = 1; I != PHIsToSlice.size(); ++I) dbgs()
  1021. << "AND USER PHI #" << I << ": " << *PHIsToSlice[I] << '\n');
  1022. // PredValues - This is a temporary used when rewriting PHI nodes. It is
  1023. // hoisted out here to avoid construction/destruction thrashing.
  1024. DenseMap<BasicBlock*, Value*> PredValues;
  1025. // ExtractedVals - Each new PHI we introduce is saved here so we don't
  1026. // introduce redundant PHIs.
  1027. DenseMap<LoweredPHIRecord, PHINode*> ExtractedVals;
  1028. for (unsigned UserI = 0, UserE = PHIUsers.size(); UserI != UserE; ++UserI) {
  1029. unsigned PHIId = PHIUsers[UserI].PHIId;
  1030. PHINode *PN = PHIsToSlice[PHIId];
  1031. unsigned Offset = PHIUsers[UserI].Shift;
  1032. Type *Ty = PHIUsers[UserI].Inst->getType();
  1033. PHINode *EltPHI;
  1034. // If we've already lowered a user like this, reuse the previously lowered
  1035. // value.
  1036. if ((EltPHI = ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)]) == nullptr) {
  1037. // Otherwise, Create the new PHI node for this user.
  1038. EltPHI = PHINode::Create(Ty, PN->getNumIncomingValues(),
  1039. PN->getName()+".off"+Twine(Offset), PN);
  1040. assert(EltPHI->getType() != PN->getType() &&
  1041. "Truncate didn't shrink phi?");
  1042. for (auto Incoming : zip(PN->blocks(), PN->incoming_values())) {
  1043. BasicBlock *Pred = std::get<0>(Incoming);
  1044. Value *InVal = std::get<1>(Incoming);
  1045. Value *&PredVal = PredValues[Pred];
  1046. // If we already have a value for this predecessor, reuse it.
  1047. if (PredVal) {
  1048. EltPHI->addIncoming(PredVal, Pred);
  1049. continue;
  1050. }
  1051. // Handle the PHI self-reuse case.
  1052. if (InVal == PN) {
  1053. PredVal = EltPHI;
  1054. EltPHI->addIncoming(PredVal, Pred);
  1055. continue;
  1056. }
  1057. if (PHINode *InPHI = dyn_cast<PHINode>(PN)) {
  1058. // If the incoming value was a PHI, and if it was one of the PHIs we
  1059. // already rewrote it, just use the lowered value.
  1060. if (Value *Res = ExtractedVals[LoweredPHIRecord(InPHI, Offset, Ty)]) {
  1061. PredVal = Res;
  1062. EltPHI->addIncoming(PredVal, Pred);
  1063. continue;
  1064. }
  1065. }
  1066. // Otherwise, do an extract in the predecessor.
  1067. Builder.SetInsertPoint(Pred->getTerminator());
  1068. Value *Res = InVal;
  1069. if (Offset)
  1070. Res = Builder.CreateLShr(
  1071. Res, ConstantInt::get(InVal->getType(), Offset), "extract");
  1072. Res = Builder.CreateTrunc(Res, Ty, "extract.t");
  1073. PredVal = Res;
  1074. EltPHI->addIncoming(Res, Pred);
  1075. // If the incoming value was a PHI, and if it was one of the PHIs we are
  1076. // rewriting, we will ultimately delete the code we inserted. This
  1077. // means we need to revisit that PHI to make sure we extract out the
  1078. // needed piece.
  1079. if (PHINode *OldInVal = dyn_cast<PHINode>(InVal))
  1080. if (PHIsInspected.count(OldInVal)) {
  1081. unsigned RefPHIId =
  1082. find(PHIsToSlice, OldInVal) - PHIsToSlice.begin();
  1083. PHIUsers.push_back(
  1084. PHIUsageRecord(RefPHIId, Offset, cast<Instruction>(Res)));
  1085. ++UserE;
  1086. }
  1087. }
  1088. PredValues.clear();
  1089. LLVM_DEBUG(dbgs() << " Made element PHI for offset " << Offset << ": "
  1090. << *EltPHI << '\n');
  1091. ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)] = EltPHI;
  1092. }
  1093. // Replace the use of this piece with the PHI node.
  1094. replaceInstUsesWith(*PHIUsers[UserI].Inst, EltPHI);
  1095. }
  1096. // Replace all the remaining uses of the PHI nodes (self uses and the lshrs)
  1097. // with poison.
  1098. Value *Poison = PoisonValue::get(FirstPhi.getType());
  1099. for (PHINode *PHI : drop_begin(PHIsToSlice))
  1100. replaceInstUsesWith(*PHI, Poison);
  1101. return replaceInstUsesWith(FirstPhi, Poison);
  1102. }
  1103. static Value *simplifyUsingControlFlow(InstCombiner &Self, PHINode &PN,
  1104. const DominatorTree &DT) {
  1105. // Simplify the following patterns:
  1106. // if (cond)
  1107. // / \
  1108. // ... ...
  1109. // \ /
  1110. // phi [true] [false]
  1111. // and
  1112. // switch (cond)
  1113. // case v1: / \ case v2:
  1114. // ... ...
  1115. // \ /
  1116. // phi [v1] [v2]
  1117. // Make sure all inputs are constants.
  1118. if (!all_of(PN.operands(), [](Value *V) { return isa<ConstantInt>(V); }))
  1119. return nullptr;
  1120. BasicBlock *BB = PN.getParent();
  1121. // Do not bother with unreachable instructions.
  1122. if (!DT.isReachableFromEntry(BB))
  1123. return nullptr;
  1124. // Determine which value the condition of the idom has for which successor.
  1125. LLVMContext &Context = PN.getContext();
  1126. auto *IDom = DT.getNode(BB)->getIDom()->getBlock();
  1127. Value *Cond;
  1128. SmallDenseMap<ConstantInt *, BasicBlock *, 8> SuccForValue;
  1129. SmallDenseMap<BasicBlock *, unsigned, 8> SuccCount;
  1130. auto AddSucc = [&](ConstantInt *C, BasicBlock *Succ) {
  1131. SuccForValue[C] = Succ;
  1132. ++SuccCount[Succ];
  1133. };
  1134. if (auto *BI = dyn_cast<BranchInst>(IDom->getTerminator())) {
  1135. if (BI->isUnconditional())
  1136. return nullptr;
  1137. Cond = BI->getCondition();
  1138. AddSucc(ConstantInt::getTrue(Context), BI->getSuccessor(0));
  1139. AddSucc(ConstantInt::getFalse(Context), BI->getSuccessor(1));
  1140. } else if (auto *SI = dyn_cast<SwitchInst>(IDom->getTerminator())) {
  1141. Cond = SI->getCondition();
  1142. ++SuccCount[SI->getDefaultDest()];
  1143. for (auto Case : SI->cases())
  1144. AddSucc(Case.getCaseValue(), Case.getCaseSuccessor());
  1145. } else {
  1146. return nullptr;
  1147. }
  1148. if (Cond->getType() != PN.getType())
  1149. return nullptr;
  1150. // Check that edges outgoing from the idom's terminators dominate respective
  1151. // inputs of the Phi.
  1152. std::optional<bool> Invert;
  1153. for (auto Pair : zip(PN.incoming_values(), PN.blocks())) {
  1154. auto *Input = cast<ConstantInt>(std::get<0>(Pair));
  1155. BasicBlock *Pred = std::get<1>(Pair);
  1156. auto IsCorrectInput = [&](ConstantInt *Input) {
  1157. // The input needs to be dominated by the corresponding edge of the idom.
  1158. // This edge cannot be a multi-edge, as that would imply that multiple
  1159. // different condition values follow the same edge.
  1160. auto It = SuccForValue.find(Input);
  1161. return It != SuccForValue.end() && SuccCount[It->second] == 1 &&
  1162. DT.dominates(BasicBlockEdge(IDom, It->second),
  1163. BasicBlockEdge(Pred, BB));
  1164. };
  1165. // Depending on the constant, the condition may need to be inverted.
  1166. bool NeedsInvert;
  1167. if (IsCorrectInput(Input))
  1168. NeedsInvert = false;
  1169. else if (IsCorrectInput(cast<ConstantInt>(ConstantExpr::getNot(Input))))
  1170. NeedsInvert = true;
  1171. else
  1172. return nullptr;
  1173. // Make sure the inversion requirement is always the same.
  1174. if (Invert && *Invert != NeedsInvert)
  1175. return nullptr;
  1176. Invert = NeedsInvert;
  1177. }
  1178. if (!*Invert)
  1179. return Cond;
  1180. // This Phi is actually opposite to branching condition of IDom. We invert
  1181. // the condition that will potentially open up some opportunities for
  1182. // sinking.
  1183. auto InsertPt = BB->getFirstInsertionPt();
  1184. if (InsertPt != BB->end()) {
  1185. Self.Builder.SetInsertPoint(&*InsertPt);
  1186. return Self.Builder.CreateNot(Cond);
  1187. }
  1188. return nullptr;
  1189. }
  1190. // PHINode simplification
  1191. //
  1192. Instruction *InstCombinerImpl::visitPHINode(PHINode &PN) {
  1193. if (Value *V = simplifyInstruction(&PN, SQ.getWithInstruction(&PN)))
  1194. return replaceInstUsesWith(PN, V);
  1195. if (Instruction *Result = foldPHIArgZextsIntoPHI(PN))
  1196. return Result;
  1197. if (Instruction *Result = foldPHIArgIntToPtrToPHI(PN))
  1198. return Result;
  1199. // If all PHI operands are the same operation, pull them through the PHI,
  1200. // reducing code size.
  1201. if (isa<Instruction>(PN.getIncomingValue(0)) &&
  1202. isa<Instruction>(PN.getIncomingValue(1)) &&
  1203. cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
  1204. cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
  1205. PN.getIncomingValue(0)->hasOneUser())
  1206. if (Instruction *Result = foldPHIArgOpIntoPHI(PN))
  1207. return Result;
  1208. // If the incoming values are pointer casts of the same original value,
  1209. // replace the phi with a single cast iff we can insert a non-PHI instruction.
  1210. if (PN.getType()->isPointerTy() &&
  1211. PN.getParent()->getFirstInsertionPt() != PN.getParent()->end()) {
  1212. Value *IV0 = PN.getIncomingValue(0);
  1213. Value *IV0Stripped = IV0->stripPointerCasts();
  1214. // Set to keep track of values known to be equal to IV0Stripped after
  1215. // stripping pointer casts.
  1216. SmallPtrSet<Value *, 4> CheckedIVs;
  1217. CheckedIVs.insert(IV0);
  1218. if (IV0 != IV0Stripped &&
  1219. all_of(PN.incoming_values(), [&CheckedIVs, IV0Stripped](Value *IV) {
  1220. return !CheckedIVs.insert(IV).second ||
  1221. IV0Stripped == IV->stripPointerCasts();
  1222. })) {
  1223. return CastInst::CreatePointerCast(IV0Stripped, PN.getType());
  1224. }
  1225. }
  1226. // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
  1227. // this PHI only has a single use (a PHI), and if that PHI only has one use (a
  1228. // PHI)... break the cycle.
  1229. if (PN.hasOneUse()) {
  1230. if (foldIntegerTypedPHI(PN))
  1231. return nullptr;
  1232. Instruction *PHIUser = cast<Instruction>(PN.user_back());
  1233. if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
  1234. SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
  1235. PotentiallyDeadPHIs.insert(&PN);
  1236. if (isDeadPHICycle(PU, PotentiallyDeadPHIs))
  1237. return replaceInstUsesWith(PN, PoisonValue::get(PN.getType()));
  1238. }
  1239. // If this phi has a single use, and if that use just computes a value for
  1240. // the next iteration of a loop, delete the phi. This occurs with unused
  1241. // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
  1242. // common case here is good because the only other things that catch this
  1243. // are induction variable analysis (sometimes) and ADCE, which is only run
  1244. // late.
  1245. if (PHIUser->hasOneUse() &&
  1246. (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
  1247. PHIUser->user_back() == &PN) {
  1248. return replaceInstUsesWith(PN, PoisonValue::get(PN.getType()));
  1249. }
  1250. // When a PHI is used only to be compared with zero, it is safe to replace
  1251. // an incoming value proved as known nonzero with any non-zero constant.
  1252. // For example, in the code below, the incoming value %v can be replaced
  1253. // with any non-zero constant based on the fact that the PHI is only used to
  1254. // be compared with zero and %v is a known non-zero value:
  1255. // %v = select %cond, 1, 2
  1256. // %p = phi [%v, BB] ...
  1257. // icmp eq, %p, 0
  1258. auto *CmpInst = dyn_cast<ICmpInst>(PHIUser);
  1259. // FIXME: To be simple, handle only integer type for now.
  1260. if (CmpInst && isa<IntegerType>(PN.getType()) && CmpInst->isEquality() &&
  1261. match(CmpInst->getOperand(1), m_Zero())) {
  1262. ConstantInt *NonZeroConst = nullptr;
  1263. bool MadeChange = false;
  1264. for (unsigned I = 0, E = PN.getNumIncomingValues(); I != E; ++I) {
  1265. Instruction *CtxI = PN.getIncomingBlock(I)->getTerminator();
  1266. Value *VA = PN.getIncomingValue(I);
  1267. if (isKnownNonZero(VA, DL, 0, &AC, CtxI, &DT)) {
  1268. if (!NonZeroConst)
  1269. NonZeroConst = getAnyNonZeroConstInt(PN);
  1270. if (NonZeroConst != VA) {
  1271. replaceOperand(PN, I, NonZeroConst);
  1272. MadeChange = true;
  1273. }
  1274. }
  1275. }
  1276. if (MadeChange)
  1277. return &PN;
  1278. }
  1279. }
  1280. // We sometimes end up with phi cycles that non-obviously end up being the
  1281. // same value, for example:
  1282. // z = some value; x = phi (y, z); y = phi (x, z)
  1283. // where the phi nodes don't necessarily need to be in the same block. Do a
  1284. // quick check to see if the PHI node only contains a single non-phi value, if
  1285. // so, scan to see if the phi cycle is actually equal to that value.
  1286. {
  1287. unsigned InValNo = 0, NumIncomingVals = PN.getNumIncomingValues();
  1288. // Scan for the first non-phi operand.
  1289. while (InValNo != NumIncomingVals &&
  1290. isa<PHINode>(PN.getIncomingValue(InValNo)))
  1291. ++InValNo;
  1292. if (InValNo != NumIncomingVals) {
  1293. Value *NonPhiInVal = PN.getIncomingValue(InValNo);
  1294. // Scan the rest of the operands to see if there are any conflicts, if so
  1295. // there is no need to recursively scan other phis.
  1296. for (++InValNo; InValNo != NumIncomingVals; ++InValNo) {
  1297. Value *OpVal = PN.getIncomingValue(InValNo);
  1298. if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
  1299. break;
  1300. }
  1301. // If we scanned over all operands, then we have one unique value plus
  1302. // phi values. Scan PHI nodes to see if they all merge in each other or
  1303. // the value.
  1304. if (InValNo == NumIncomingVals) {
  1305. SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
  1306. if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
  1307. return replaceInstUsesWith(PN, NonPhiInVal);
  1308. }
  1309. }
  1310. }
  1311. // If there are multiple PHIs, sort their operands so that they all list
  1312. // the blocks in the same order. This will help identical PHIs be eliminated
  1313. // by other passes. Other passes shouldn't depend on this for correctness
  1314. // however.
  1315. PHINode *FirstPN = cast<PHINode>(PN.getParent()->begin());
  1316. if (&PN != FirstPN)
  1317. for (unsigned I = 0, E = FirstPN->getNumIncomingValues(); I != E; ++I) {
  1318. BasicBlock *BBA = PN.getIncomingBlock(I);
  1319. BasicBlock *BBB = FirstPN->getIncomingBlock(I);
  1320. if (BBA != BBB) {
  1321. Value *VA = PN.getIncomingValue(I);
  1322. unsigned J = PN.getBasicBlockIndex(BBB);
  1323. Value *VB = PN.getIncomingValue(J);
  1324. PN.setIncomingBlock(I, BBB);
  1325. PN.setIncomingValue(I, VB);
  1326. PN.setIncomingBlock(J, BBA);
  1327. PN.setIncomingValue(J, VA);
  1328. // NOTE: Instcombine normally would want us to "return &PN" if we
  1329. // modified any of the operands of an instruction. However, since we
  1330. // aren't adding or removing uses (just rearranging them) we don't do
  1331. // this in this case.
  1332. }
  1333. }
  1334. // Is there an identical PHI node in this basic block?
  1335. for (PHINode &IdenticalPN : PN.getParent()->phis()) {
  1336. // Ignore the PHI node itself.
  1337. if (&IdenticalPN == &PN)
  1338. continue;
  1339. // Note that even though we've just canonicalized this PHI, due to the
  1340. // worklist visitation order, there are no guarantess that *every* PHI
  1341. // has been canonicalized, so we can't just compare operands ranges.
  1342. if (!PN.isIdenticalToWhenDefined(&IdenticalPN))
  1343. continue;
  1344. // Just use that PHI instead then.
  1345. ++NumPHICSEs;
  1346. return replaceInstUsesWith(PN, &IdenticalPN);
  1347. }
  1348. // If this is an integer PHI and we know that it has an illegal type, see if
  1349. // it is only used by trunc or trunc(lshr) operations. If so, we split the
  1350. // PHI into the various pieces being extracted. This sort of thing is
  1351. // introduced when SROA promotes an aggregate to a single large integer type.
  1352. if (PN.getType()->isIntegerTy() &&
  1353. !DL.isLegalInteger(PN.getType()->getPrimitiveSizeInBits()))
  1354. if (Instruction *Res = SliceUpIllegalIntegerPHI(PN))
  1355. return Res;
  1356. // Ultimately, try to replace this Phi with a dominating condition.
  1357. if (auto *V = simplifyUsingControlFlow(*this, PN, DT))
  1358. return replaceInstUsesWith(PN, V);
  1359. return nullptr;
  1360. }