CodeGenPrepare.cpp 149 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031
  1. //===- CodeGenPrepare.cpp - Prepare a function for code generation --------===//
  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 pass munges the code in the input function to better prepare it for
  11. // SelectionDAG-based code generation. This works around limitations in it's
  12. // basic-block-at-a-time approach. It should eventually be removed.
  13. //
  14. //===----------------------------------------------------------------------===//
  15. #include "llvm/CodeGen/Passes.h"
  16. #include "llvm/ADT/DenseMap.h"
  17. #include "llvm/ADT/SmallSet.h"
  18. #include "llvm/ADT/Statistic.h"
  19. #include "llvm/Analysis/InstructionSimplify.h"
  20. #include "llvm/Analysis/TargetTransformInfo.h"
  21. #include "llvm/IR/CallSite.h"
  22. #include "llvm/IR/Constants.h"
  23. #include "llvm/IR/DataLayout.h"
  24. #include "llvm/IR/DerivedTypes.h"
  25. #include "llvm/IR/Dominators.h"
  26. #include "llvm/IR/Function.h"
  27. #include "llvm/IR/GetElementPtrTypeIterator.h"
  28. #include "llvm/IR/IRBuilder.h"
  29. #include "llvm/IR/InlineAsm.h"
  30. #include "llvm/IR/Instructions.h"
  31. #include "llvm/IR/IntrinsicInst.h"
  32. #include "llvm/IR/MDBuilder.h"
  33. #include "llvm/IR/PatternMatch.h"
  34. #include "llvm/IR/ValueHandle.h"
  35. #include "llvm/IR/ValueMap.h"
  36. #include "llvm/Pass.h"
  37. #include "llvm/Support/CommandLine.h"
  38. #include "llvm/Support/Debug.h"
  39. #include "llvm/Support/raw_ostream.h"
  40. #include "llvm/Target/TargetLibraryInfo.h"
  41. #include "llvm/Target/TargetLowering.h"
  42. #include "llvm/Target/TargetSubtargetInfo.h"
  43. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  44. #include "llvm/Transforms/Utils/BuildLibCalls.h"
  45. #include "llvm/Transforms/Utils/BypassSlowDivision.h"
  46. #include "llvm/Transforms/Utils/Local.h"
  47. using namespace llvm;
  48. using namespace llvm::PatternMatch;
  49. #define DEBUG_TYPE "codegenprepare"
  50. STATISTIC(NumBlocksElim, "Number of blocks eliminated");
  51. STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated");
  52. STATISTIC(NumGEPsElim, "Number of GEPs converted to casts");
  53. STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
  54. "sunken Cmps");
  55. STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
  56. "of sunken Casts");
  57. STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
  58. "computations were sunk");
  59. STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads");
  60. STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized");
  61. STATISTIC(NumRetsDup, "Number of return instructions duplicated");
  62. STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
  63. STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
  64. STATISTIC(NumAndCmpsMoved, "Number of and/cmp's pushed into branches");
  65. STATISTIC(NumStoreExtractExposed, "Number of store(extractelement) exposed");
  66. static cl::opt<bool> DisableBranchOpts(
  67. "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
  68. cl::desc("Disable branch optimizations in CodeGenPrepare"));
  69. static cl::opt<bool> DisableSelectToBranch(
  70. "disable-cgp-select2branch", cl::Hidden, cl::init(false),
  71. cl::desc("Disable select to branch conversion."));
  72. static cl::opt<bool> AddrSinkUsingGEPs(
  73. "addr-sink-using-gep", cl::Hidden, cl::init(false),
  74. cl::desc("Address sinking in CGP using GEPs."));
  75. static cl::opt<bool> EnableAndCmpSinking(
  76. "enable-andcmp-sinking", cl::Hidden, cl::init(true),
  77. cl::desc("Enable sinkinig and/cmp into branches."));
  78. static cl::opt<bool> DisableStoreExtract(
  79. "disable-cgp-store-extract", cl::Hidden, cl::init(false),
  80. cl::desc("Disable store(extract) optimizations in CodeGenPrepare"));
  81. static cl::opt<bool> StressStoreExtract(
  82. "stress-cgp-store-extract", cl::Hidden, cl::init(false),
  83. cl::desc("Stress test store(extract) optimizations in CodeGenPrepare"));
  84. namespace {
  85. typedef SmallPtrSet<Instruction *, 16> SetOfInstrs;
  86. struct TypeIsSExt {
  87. Type *Ty;
  88. bool IsSExt;
  89. TypeIsSExt(Type *Ty, bool IsSExt) : Ty(Ty), IsSExt(IsSExt) {}
  90. };
  91. typedef DenseMap<Instruction *, TypeIsSExt> InstrToOrigTy;
  92. class CodeGenPrepare : public FunctionPass {
  93. /// TLI - Keep a pointer of a TargetLowering to consult for determining
  94. /// transformation profitability.
  95. const TargetMachine *TM;
  96. const TargetLowering *TLI;
  97. const TargetTransformInfo *TTI;
  98. const TargetLibraryInfo *TLInfo;
  99. DominatorTree *DT;
  100. /// CurInstIterator - As we scan instructions optimizing them, this is the
  101. /// next instruction to optimize. Xforms that can invalidate this should
  102. /// update it.
  103. BasicBlock::iterator CurInstIterator;
  104. /// Keeps track of non-local addresses that have been sunk into a block.
  105. /// This allows us to avoid inserting duplicate code for blocks with
  106. /// multiple load/stores of the same address.
  107. ValueMap<Value*, Value*> SunkAddrs;
  108. /// Keeps track of all truncates inserted for the current function.
  109. SetOfInstrs InsertedTruncsSet;
  110. /// Keeps track of the type of the related instruction before their
  111. /// promotion for the current function.
  112. InstrToOrigTy PromotedInsts;
  113. /// ModifiedDT - If CFG is modified in anyway, dominator tree may need to
  114. /// be updated.
  115. bool ModifiedDT;
  116. /// OptSize - True if optimizing for size.
  117. bool OptSize;
  118. public:
  119. static char ID; // Pass identification, replacement for typeid
  120. explicit CodeGenPrepare(const TargetMachine *TM = nullptr)
  121. : FunctionPass(ID), TM(TM), TLI(nullptr), TTI(nullptr) {
  122. initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
  123. }
  124. bool runOnFunction(Function &F) override;
  125. const char *getPassName() const override { return "CodeGen Prepare"; }
  126. void getAnalysisUsage(AnalysisUsage &AU) const override {
  127. AU.addPreserved<DominatorTreeWrapperPass>();
  128. AU.addRequired<TargetLibraryInfo>();
  129. AU.addRequired<TargetTransformInfo>();
  130. }
  131. private:
  132. bool EliminateFallThrough(Function &F);
  133. bool EliminateMostlyEmptyBlocks(Function &F);
  134. bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
  135. void EliminateMostlyEmptyBlock(BasicBlock *BB);
  136. bool OptimizeBlock(BasicBlock &BB);
  137. bool OptimizeInst(Instruction *I);
  138. bool OptimizeMemoryInst(Instruction *I, Value *Addr, Type *AccessTy);
  139. bool OptimizeInlineAsmInst(CallInst *CS);
  140. bool OptimizeCallInst(CallInst *CI);
  141. bool MoveExtToFormExtLoad(Instruction *I);
  142. bool OptimizeExtUses(Instruction *I);
  143. bool OptimizeSelectInst(SelectInst *SI);
  144. bool OptimizeShuffleVectorInst(ShuffleVectorInst *SI);
  145. bool OptimizeExtractElementInst(Instruction *Inst);
  146. bool DupRetToEnableTailCallOpts(BasicBlock *BB);
  147. bool PlaceDbgValues(Function &F);
  148. bool sinkAndCmp(Function &F);
  149. bool splitBranchCondition(Function &F);
  150. };
  151. }
  152. char CodeGenPrepare::ID = 0;
  153. INITIALIZE_TM_PASS(CodeGenPrepare, "codegenprepare",
  154. "Optimize for code generation", false, false)
  155. FunctionPass *llvm::createCodeGenPreparePass(const TargetMachine *TM) {
  156. return new CodeGenPrepare(TM);
  157. }
  158. bool CodeGenPrepare::runOnFunction(Function &F) {
  159. if (skipOptnoneFunction(F))
  160. return false;
  161. bool EverMadeChange = false;
  162. // Clear per function information.
  163. InsertedTruncsSet.clear();
  164. PromotedInsts.clear();
  165. ModifiedDT = false;
  166. if (TM)
  167. TLI = TM->getSubtargetImpl()->getTargetLowering();
  168. TLInfo = &getAnalysis<TargetLibraryInfo>();
  169. TTI = &getAnalysis<TargetTransformInfo>();
  170. DominatorTreeWrapperPass *DTWP =
  171. getAnalysisIfAvailable<DominatorTreeWrapperPass>();
  172. DT = DTWP ? &DTWP->getDomTree() : nullptr;
  173. OptSize = F.getAttributes().hasAttribute(AttributeSet::FunctionIndex,
  174. Attribute::OptimizeForSize);
  175. /// This optimization identifies DIV instructions that can be
  176. /// profitably bypassed and carried out with a shorter, faster divide.
  177. if (!OptSize && TLI && TLI->isSlowDivBypassed()) {
  178. const DenseMap<unsigned int, unsigned int> &BypassWidths =
  179. TLI->getBypassSlowDivWidths();
  180. for (Function::iterator I = F.begin(); I != F.end(); I++)
  181. EverMadeChange |= bypassSlowDivision(F, I, BypassWidths);
  182. }
  183. // Eliminate blocks that contain only PHI nodes and an
  184. // unconditional branch.
  185. EverMadeChange |= EliminateMostlyEmptyBlocks(F);
  186. // llvm.dbg.value is far away from the value then iSel may not be able
  187. // handle it properly. iSel will drop llvm.dbg.value if it can not
  188. // find a node corresponding to the value.
  189. EverMadeChange |= PlaceDbgValues(F);
  190. // If there is a mask, compare against zero, and branch that can be combined
  191. // into a single target instruction, push the mask and compare into branch
  192. // users. Do this before OptimizeBlock -> OptimizeInst ->
  193. // OptimizeCmpExpression, which perturbs the pattern being searched for.
  194. if (!DisableBranchOpts) {
  195. EverMadeChange |= sinkAndCmp(F);
  196. EverMadeChange |= splitBranchCondition(F);
  197. }
  198. bool MadeChange = true;
  199. while (MadeChange) {
  200. MadeChange = false;
  201. for (Function::iterator I = F.begin(); I != F.end(); ) {
  202. BasicBlock *BB = I++;
  203. MadeChange |= OptimizeBlock(*BB);
  204. }
  205. EverMadeChange |= MadeChange;
  206. }
  207. SunkAddrs.clear();
  208. if (!DisableBranchOpts) {
  209. MadeChange = false;
  210. SmallPtrSet<BasicBlock*, 8> WorkList;
  211. for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
  212. SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
  213. MadeChange |= ConstantFoldTerminator(BB, true);
  214. if (!MadeChange) continue;
  215. for (SmallVectorImpl<BasicBlock*>::iterator
  216. II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
  217. if (pred_begin(*II) == pred_end(*II))
  218. WorkList.insert(*II);
  219. }
  220. // Delete the dead blocks and any of their dead successors.
  221. MadeChange |= !WorkList.empty();
  222. while (!WorkList.empty()) {
  223. BasicBlock *BB = *WorkList.begin();
  224. WorkList.erase(BB);
  225. SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
  226. DeleteDeadBlock(BB);
  227. for (SmallVectorImpl<BasicBlock*>::iterator
  228. II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
  229. if (pred_begin(*II) == pred_end(*II))
  230. WorkList.insert(*II);
  231. }
  232. // Merge pairs of basic blocks with unconditional branches, connected by
  233. // a single edge.
  234. if (EverMadeChange || MadeChange)
  235. MadeChange |= EliminateFallThrough(F);
  236. if (MadeChange)
  237. ModifiedDT = true;
  238. EverMadeChange |= MadeChange;
  239. }
  240. if (ModifiedDT && DT)
  241. DT->recalculate(F);
  242. return EverMadeChange;
  243. }
  244. /// EliminateFallThrough - Merge basic blocks which are connected
  245. /// by a single edge, where one of the basic blocks has a single successor
  246. /// pointing to the other basic block, which has a single predecessor.
  247. bool CodeGenPrepare::EliminateFallThrough(Function &F) {
  248. bool Changed = false;
  249. // Scan all of the blocks in the function, except for the entry block.
  250. for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
  251. BasicBlock *BB = I++;
  252. // If the destination block has a single pred, then this is a trivial
  253. // edge, just collapse it.
  254. BasicBlock *SinglePred = BB->getSinglePredecessor();
  255. // Don't merge if BB's address is taken.
  256. if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
  257. BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
  258. if (Term && !Term->isConditional()) {
  259. Changed = true;
  260. DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
  261. // Remember if SinglePred was the entry block of the function.
  262. // If so, we will need to move BB back to the entry position.
  263. bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
  264. MergeBasicBlockIntoOnlyPred(BB, this);
  265. if (isEntry && BB != &BB->getParent()->getEntryBlock())
  266. BB->moveBefore(&BB->getParent()->getEntryBlock());
  267. // We have erased a block. Update the iterator.
  268. I = BB;
  269. }
  270. }
  271. return Changed;
  272. }
  273. /// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
  274. /// debug info directives, and an unconditional branch. Passes before isel
  275. /// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
  276. /// isel. Start by eliminating these blocks so we can split them the way we
  277. /// want them.
  278. bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
  279. bool MadeChange = false;
  280. // Note that this intentionally skips the entry block.
  281. for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
  282. BasicBlock *BB = I++;
  283. // If this block doesn't end with an uncond branch, ignore it.
  284. BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
  285. if (!BI || !BI->isUnconditional())
  286. continue;
  287. // If the instruction before the branch (skipping debug info) isn't a phi
  288. // node, then other stuff is happening here.
  289. BasicBlock::iterator BBI = BI;
  290. if (BBI != BB->begin()) {
  291. --BBI;
  292. while (isa<DbgInfoIntrinsic>(BBI)) {
  293. if (BBI == BB->begin())
  294. break;
  295. --BBI;
  296. }
  297. if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
  298. continue;
  299. }
  300. // Do not break infinite loops.
  301. BasicBlock *DestBB = BI->getSuccessor(0);
  302. if (DestBB == BB)
  303. continue;
  304. if (!CanMergeBlocks(BB, DestBB))
  305. continue;
  306. EliminateMostlyEmptyBlock(BB);
  307. MadeChange = true;
  308. }
  309. return MadeChange;
  310. }
  311. /// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
  312. /// single uncond branch between them, and BB contains no other non-phi
  313. /// instructions.
  314. bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
  315. const BasicBlock *DestBB) const {
  316. // We only want to eliminate blocks whose phi nodes are used by phi nodes in
  317. // the successor. If there are more complex condition (e.g. preheaders),
  318. // don't mess around with them.
  319. BasicBlock::const_iterator BBI = BB->begin();
  320. while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
  321. for (const User *U : PN->users()) {
  322. const Instruction *UI = cast<Instruction>(U);
  323. if (UI->getParent() != DestBB || !isa<PHINode>(UI))
  324. return false;
  325. // If User is inside DestBB block and it is a PHINode then check
  326. // incoming value. If incoming value is not from BB then this is
  327. // a complex condition (e.g. preheaders) we want to avoid here.
  328. if (UI->getParent() == DestBB) {
  329. if (const PHINode *UPN = dyn_cast<PHINode>(UI))
  330. for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
  331. Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
  332. if (Insn && Insn->getParent() == BB &&
  333. Insn->getParent() != UPN->getIncomingBlock(I))
  334. return false;
  335. }
  336. }
  337. }
  338. }
  339. // If BB and DestBB contain any common predecessors, then the phi nodes in BB
  340. // and DestBB may have conflicting incoming values for the block. If so, we
  341. // can't merge the block.
  342. const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
  343. if (!DestBBPN) return true; // no conflict.
  344. // Collect the preds of BB.
  345. SmallPtrSet<const BasicBlock*, 16> BBPreds;
  346. if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
  347. // It is faster to get preds from a PHI than with pred_iterator.
  348. for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
  349. BBPreds.insert(BBPN->getIncomingBlock(i));
  350. } else {
  351. BBPreds.insert(pred_begin(BB), pred_end(BB));
  352. }
  353. // Walk the preds of DestBB.
  354. for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
  355. BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
  356. if (BBPreds.count(Pred)) { // Common predecessor?
  357. BBI = DestBB->begin();
  358. while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
  359. const Value *V1 = PN->getIncomingValueForBlock(Pred);
  360. const Value *V2 = PN->getIncomingValueForBlock(BB);
  361. // If V2 is a phi node in BB, look up what the mapped value will be.
  362. if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
  363. if (V2PN->getParent() == BB)
  364. V2 = V2PN->getIncomingValueForBlock(Pred);
  365. // If there is a conflict, bail out.
  366. if (V1 != V2) return false;
  367. }
  368. }
  369. }
  370. return true;
  371. }
  372. /// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
  373. /// an unconditional branch in it.
  374. void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
  375. BranchInst *BI = cast<BranchInst>(BB->getTerminator());
  376. BasicBlock *DestBB = BI->getSuccessor(0);
  377. DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
  378. // If the destination block has a single pred, then this is a trivial edge,
  379. // just collapse it.
  380. if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
  381. if (SinglePred != DestBB) {
  382. // Remember if SinglePred was the entry block of the function. If so, we
  383. // will need to move BB back to the entry position.
  384. bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
  385. MergeBasicBlockIntoOnlyPred(DestBB, this);
  386. if (isEntry && BB != &BB->getParent()->getEntryBlock())
  387. BB->moveBefore(&BB->getParent()->getEntryBlock());
  388. DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
  389. return;
  390. }
  391. }
  392. // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
  393. // to handle the new incoming edges it is about to have.
  394. PHINode *PN;
  395. for (BasicBlock::iterator BBI = DestBB->begin();
  396. (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
  397. // Remove the incoming value for BB, and remember it.
  398. Value *InVal = PN->removeIncomingValue(BB, false);
  399. // Two options: either the InVal is a phi node defined in BB or it is some
  400. // value that dominates BB.
  401. PHINode *InValPhi = dyn_cast<PHINode>(InVal);
  402. if (InValPhi && InValPhi->getParent() == BB) {
  403. // Add all of the input values of the input PHI as inputs of this phi.
  404. for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
  405. PN->addIncoming(InValPhi->getIncomingValue(i),
  406. InValPhi->getIncomingBlock(i));
  407. } else {
  408. // Otherwise, add one instance of the dominating value for each edge that
  409. // we will be adding.
  410. if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
  411. for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
  412. PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
  413. } else {
  414. for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
  415. PN->addIncoming(InVal, *PI);
  416. }
  417. }
  418. }
  419. // The PHIs are now updated, change everything that refers to BB to use
  420. // DestBB and remove BB.
  421. BB->replaceAllUsesWith(DestBB);
  422. if (DT && !ModifiedDT) {
  423. BasicBlock *BBIDom = DT->getNode(BB)->getIDom()->getBlock();
  424. BasicBlock *DestBBIDom = DT->getNode(DestBB)->getIDom()->getBlock();
  425. BasicBlock *NewIDom = DT->findNearestCommonDominator(BBIDom, DestBBIDom);
  426. DT->changeImmediateDominator(DestBB, NewIDom);
  427. DT->eraseNode(BB);
  428. }
  429. BB->eraseFromParent();
  430. ++NumBlocksElim;
  431. DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
  432. }
  433. /// SinkCast - Sink the specified cast instruction into its user blocks
  434. static bool SinkCast(CastInst *CI) {
  435. BasicBlock *DefBB = CI->getParent();
  436. /// InsertedCasts - Only insert a cast in each block once.
  437. DenseMap<BasicBlock*, CastInst*> InsertedCasts;
  438. bool MadeChange = false;
  439. for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
  440. UI != E; ) {
  441. Use &TheUse = UI.getUse();
  442. Instruction *User = cast<Instruction>(*UI);
  443. // Figure out which BB this cast is used in. For PHI's this is the
  444. // appropriate predecessor block.
  445. BasicBlock *UserBB = User->getParent();
  446. if (PHINode *PN = dyn_cast<PHINode>(User)) {
  447. UserBB = PN->getIncomingBlock(TheUse);
  448. }
  449. // Preincrement use iterator so we don't invalidate it.
  450. ++UI;
  451. // If this user is in the same block as the cast, don't change the cast.
  452. if (UserBB == DefBB) continue;
  453. // If we have already inserted a cast into this block, use it.
  454. CastInst *&InsertedCast = InsertedCasts[UserBB];
  455. if (!InsertedCast) {
  456. BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
  457. InsertedCast =
  458. CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
  459. InsertPt);
  460. MadeChange = true;
  461. }
  462. // Replace a use of the cast with a use of the new cast.
  463. TheUse = InsertedCast;
  464. ++NumCastUses;
  465. }
  466. // If we removed all uses, nuke the cast.
  467. if (CI->use_empty()) {
  468. CI->eraseFromParent();
  469. MadeChange = true;
  470. }
  471. return MadeChange;
  472. }
  473. /// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
  474. /// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
  475. /// sink it into user blocks to reduce the number of virtual
  476. /// registers that must be created and coalesced.
  477. ///
  478. /// Return true if any changes are made.
  479. ///
  480. static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
  481. // If this is a noop copy,
  482. EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
  483. EVT DstVT = TLI.getValueType(CI->getType());
  484. // This is an fp<->int conversion?
  485. if (SrcVT.isInteger() != DstVT.isInteger())
  486. return false;
  487. // If this is an extension, it will be a zero or sign extension, which
  488. // isn't a noop.
  489. if (SrcVT.bitsLT(DstVT)) return false;
  490. // If these values will be promoted, find out what they will be promoted
  491. // to. This helps us consider truncates on PPC as noop copies when they
  492. // are.
  493. if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
  494. TargetLowering::TypePromoteInteger)
  495. SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
  496. if (TLI.getTypeAction(CI->getContext(), DstVT) ==
  497. TargetLowering::TypePromoteInteger)
  498. DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
  499. // If, after promotion, these are the same types, this is a noop copy.
  500. if (SrcVT != DstVT)
  501. return false;
  502. return SinkCast(CI);
  503. }
  504. /// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
  505. /// the number of virtual registers that must be created and coalesced. This is
  506. /// a clear win except on targets with multiple condition code registers
  507. /// (PowerPC), where it might lose; some adjustment may be wanted there.
  508. ///
  509. /// Return true if any changes are made.
  510. static bool OptimizeCmpExpression(CmpInst *CI) {
  511. BasicBlock *DefBB = CI->getParent();
  512. /// InsertedCmp - Only insert a cmp in each block once.
  513. DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
  514. bool MadeChange = false;
  515. for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
  516. UI != E; ) {
  517. Use &TheUse = UI.getUse();
  518. Instruction *User = cast<Instruction>(*UI);
  519. // Preincrement use iterator so we don't invalidate it.
  520. ++UI;
  521. // Don't bother for PHI nodes.
  522. if (isa<PHINode>(User))
  523. continue;
  524. // Figure out which BB this cmp is used in.
  525. BasicBlock *UserBB = User->getParent();
  526. // If this user is in the same block as the cmp, don't change the cmp.
  527. if (UserBB == DefBB) continue;
  528. // If we have already inserted a cmp into this block, use it.
  529. CmpInst *&InsertedCmp = InsertedCmps[UserBB];
  530. if (!InsertedCmp) {
  531. BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
  532. InsertedCmp =
  533. CmpInst::Create(CI->getOpcode(),
  534. CI->getPredicate(), CI->getOperand(0),
  535. CI->getOperand(1), "", InsertPt);
  536. MadeChange = true;
  537. }
  538. // Replace a use of the cmp with a use of the new cmp.
  539. TheUse = InsertedCmp;
  540. ++NumCmpUses;
  541. }
  542. // If we removed all uses, nuke the cmp.
  543. if (CI->use_empty())
  544. CI->eraseFromParent();
  545. return MadeChange;
  546. }
  547. /// isExtractBitsCandidateUse - Check if the candidates could
  548. /// be combined with shift instruction, which includes:
  549. /// 1. Truncate instruction
  550. /// 2. And instruction and the imm is a mask of the low bits:
  551. /// imm & (imm+1) == 0
  552. static bool isExtractBitsCandidateUse(Instruction *User) {
  553. if (!isa<TruncInst>(User)) {
  554. if (User->getOpcode() != Instruction::And ||
  555. !isa<ConstantInt>(User->getOperand(1)))
  556. return false;
  557. const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
  558. if ((Cimm & (Cimm + 1)).getBoolValue())
  559. return false;
  560. }
  561. return true;
  562. }
  563. /// SinkShiftAndTruncate - sink both shift and truncate instruction
  564. /// to the use of truncate's BB.
  565. static bool
  566. SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI,
  567. DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts,
  568. const TargetLowering &TLI) {
  569. BasicBlock *UserBB = User->getParent();
  570. DenseMap<BasicBlock *, CastInst *> InsertedTruncs;
  571. TruncInst *TruncI = dyn_cast<TruncInst>(User);
  572. bool MadeChange = false;
  573. for (Value::user_iterator TruncUI = TruncI->user_begin(),
  574. TruncE = TruncI->user_end();
  575. TruncUI != TruncE;) {
  576. Use &TruncTheUse = TruncUI.getUse();
  577. Instruction *TruncUser = cast<Instruction>(*TruncUI);
  578. // Preincrement use iterator so we don't invalidate it.
  579. ++TruncUI;
  580. int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
  581. if (!ISDOpcode)
  582. continue;
  583. // If the use is actually a legal node, there will not be an
  584. // implicit truncate.
  585. // FIXME: always querying the result type is just an
  586. // approximation; some nodes' legality is determined by the
  587. // operand or other means. There's no good way to find out though.
  588. if (TLI.isOperationLegalOrCustom(
  589. ISDOpcode, TLI.getValueType(TruncUser->getType(), true)))
  590. continue;
  591. // Don't bother for PHI nodes.
  592. if (isa<PHINode>(TruncUser))
  593. continue;
  594. BasicBlock *TruncUserBB = TruncUser->getParent();
  595. if (UserBB == TruncUserBB)
  596. continue;
  597. BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
  598. CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
  599. if (!InsertedShift && !InsertedTrunc) {
  600. BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
  601. // Sink the shift
  602. if (ShiftI->getOpcode() == Instruction::AShr)
  603. InsertedShift =
  604. BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, "", InsertPt);
  605. else
  606. InsertedShift =
  607. BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, "", InsertPt);
  608. // Sink the trunc
  609. BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
  610. TruncInsertPt++;
  611. InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
  612. TruncI->getType(), "", TruncInsertPt);
  613. MadeChange = true;
  614. TruncTheUse = InsertedTrunc;
  615. }
  616. }
  617. return MadeChange;
  618. }
  619. /// OptimizeExtractBits - sink the shift *right* instruction into user blocks if
  620. /// the uses could potentially be combined with this shift instruction and
  621. /// generate BitExtract instruction. It will only be applied if the architecture
  622. /// supports BitExtract instruction. Here is an example:
  623. /// BB1:
  624. /// %x.extract.shift = lshr i64 %arg1, 32
  625. /// BB2:
  626. /// %x.extract.trunc = trunc i64 %x.extract.shift to i16
  627. /// ==>
  628. ///
  629. /// BB2:
  630. /// %x.extract.shift.1 = lshr i64 %arg1, 32
  631. /// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
  632. ///
  633. /// CodeGen will recoginze the pattern in BB2 and generate BitExtract
  634. /// instruction.
  635. /// Return true if any changes are made.
  636. static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI,
  637. const TargetLowering &TLI) {
  638. BasicBlock *DefBB = ShiftI->getParent();
  639. /// Only insert instructions in each block once.
  640. DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts;
  641. bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(ShiftI->getType()));
  642. bool MadeChange = false;
  643. for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
  644. UI != E;) {
  645. Use &TheUse = UI.getUse();
  646. Instruction *User = cast<Instruction>(*UI);
  647. // Preincrement use iterator so we don't invalidate it.
  648. ++UI;
  649. // Don't bother for PHI nodes.
  650. if (isa<PHINode>(User))
  651. continue;
  652. if (!isExtractBitsCandidateUse(User))
  653. continue;
  654. BasicBlock *UserBB = User->getParent();
  655. if (UserBB == DefBB) {
  656. // If the shift and truncate instruction are in the same BB. The use of
  657. // the truncate(TruncUse) may still introduce another truncate if not
  658. // legal. In this case, we would like to sink both shift and truncate
  659. // instruction to the BB of TruncUse.
  660. // for example:
  661. // BB1:
  662. // i64 shift.result = lshr i64 opnd, imm
  663. // trunc.result = trunc shift.result to i16
  664. //
  665. // BB2:
  666. // ----> We will have an implicit truncate here if the architecture does
  667. // not have i16 compare.
  668. // cmp i16 trunc.result, opnd2
  669. //
  670. if (isa<TruncInst>(User) && shiftIsLegal
  671. // If the type of the truncate is legal, no trucate will be
  672. // introduced in other basic blocks.
  673. && (!TLI.isTypeLegal(TLI.getValueType(User->getType()))))
  674. MadeChange =
  675. SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI);
  676. continue;
  677. }
  678. // If we have already inserted a shift into this block, use it.
  679. BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
  680. if (!InsertedShift) {
  681. BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
  682. if (ShiftI->getOpcode() == Instruction::AShr)
  683. InsertedShift =
  684. BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, "", InsertPt);
  685. else
  686. InsertedShift =
  687. BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, "", InsertPt);
  688. MadeChange = true;
  689. }
  690. // Replace a use of the shift with a use of the new shift.
  691. TheUse = InsertedShift;
  692. }
  693. // If we removed all uses, nuke the shift.
  694. if (ShiftI->use_empty())
  695. ShiftI->eraseFromParent();
  696. return MadeChange;
  697. }
  698. namespace {
  699. class CodeGenPrepareFortifiedLibCalls : public SimplifyFortifiedLibCalls {
  700. protected:
  701. void replaceCall(Value *With) override {
  702. CI->replaceAllUsesWith(With);
  703. CI->eraseFromParent();
  704. }
  705. bool isFoldable(unsigned SizeCIOp, unsigned, bool) const override {
  706. if (ConstantInt *SizeCI =
  707. dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp)))
  708. return SizeCI->isAllOnesValue();
  709. return false;
  710. }
  711. };
  712. } // end anonymous namespace
  713. bool CodeGenPrepare::OptimizeCallInst(CallInst *CI) {
  714. BasicBlock *BB = CI->getParent();
  715. // Lower inline assembly if we can.
  716. // If we found an inline asm expession, and if the target knows how to
  717. // lower it to normal LLVM code, do so now.
  718. if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
  719. if (TLI->ExpandInlineAsm(CI)) {
  720. // Avoid invalidating the iterator.
  721. CurInstIterator = BB->begin();
  722. // Avoid processing instructions out of order, which could cause
  723. // reuse before a value is defined.
  724. SunkAddrs.clear();
  725. return true;
  726. }
  727. // Sink address computing for memory operands into the block.
  728. if (OptimizeInlineAsmInst(CI))
  729. return true;
  730. }
  731. // Lower all uses of llvm.objectsize.*
  732. IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
  733. if (II && II->getIntrinsicID() == Intrinsic::objectsize) {
  734. bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
  735. Type *ReturnTy = CI->getType();
  736. Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
  737. // Substituting this can cause recursive simplifications, which can
  738. // invalidate our iterator. Use a WeakVH to hold onto it in case this
  739. // happens.
  740. WeakVH IterHandle(CurInstIterator);
  741. replaceAndRecursivelySimplify(CI, RetVal,
  742. TLI ? TLI->getDataLayout() : nullptr,
  743. TLInfo, ModifiedDT ? nullptr : DT);
  744. // If the iterator instruction was recursively deleted, start over at the
  745. // start of the block.
  746. if (IterHandle != CurInstIterator) {
  747. CurInstIterator = BB->begin();
  748. SunkAddrs.clear();
  749. }
  750. return true;
  751. }
  752. if (II && TLI) {
  753. SmallVector<Value*, 2> PtrOps;
  754. Type *AccessTy;
  755. if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy))
  756. while (!PtrOps.empty())
  757. if (OptimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy))
  758. return true;
  759. }
  760. // From here on out we're working with named functions.
  761. if (!CI->getCalledFunction()) return false;
  762. // We'll need DataLayout from here on out.
  763. const DataLayout *TD = TLI ? TLI->getDataLayout() : nullptr;
  764. if (!TD) return false;
  765. // Lower all default uses of _chk calls. This is very similar
  766. // to what InstCombineCalls does, but here we are only lowering calls
  767. // that have the default "don't know" as the objectsize. Anything else
  768. // should be left alone.
  769. CodeGenPrepareFortifiedLibCalls Simplifier;
  770. return Simplifier.fold(CI, TD, TLInfo);
  771. }
  772. /// DupRetToEnableTailCallOpts - Look for opportunities to duplicate return
  773. /// instructions to the predecessor to enable tail call optimizations. The
  774. /// case it is currently looking for is:
  775. /// @code
  776. /// bb0:
  777. /// %tmp0 = tail call i32 @f0()
  778. /// br label %return
  779. /// bb1:
  780. /// %tmp1 = tail call i32 @f1()
  781. /// br label %return
  782. /// bb2:
  783. /// %tmp2 = tail call i32 @f2()
  784. /// br label %return
  785. /// return:
  786. /// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
  787. /// ret i32 %retval
  788. /// @endcode
  789. ///
  790. /// =>
  791. ///
  792. /// @code
  793. /// bb0:
  794. /// %tmp0 = tail call i32 @f0()
  795. /// ret i32 %tmp0
  796. /// bb1:
  797. /// %tmp1 = tail call i32 @f1()
  798. /// ret i32 %tmp1
  799. /// bb2:
  800. /// %tmp2 = tail call i32 @f2()
  801. /// ret i32 %tmp2
  802. /// @endcode
  803. bool CodeGenPrepare::DupRetToEnableTailCallOpts(BasicBlock *BB) {
  804. if (!TLI)
  805. return false;
  806. ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
  807. if (!RI)
  808. return false;
  809. PHINode *PN = nullptr;
  810. BitCastInst *BCI = nullptr;
  811. Value *V = RI->getReturnValue();
  812. if (V) {
  813. BCI = dyn_cast<BitCastInst>(V);
  814. if (BCI)
  815. V = BCI->getOperand(0);
  816. PN = dyn_cast<PHINode>(V);
  817. if (!PN)
  818. return false;
  819. }
  820. if (PN && PN->getParent() != BB)
  821. return false;
  822. // It's not safe to eliminate the sign / zero extension of the return value.
  823. // See llvm::isInTailCallPosition().
  824. const Function *F = BB->getParent();
  825. AttributeSet CallerAttrs = F->getAttributes();
  826. if (CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::ZExt) ||
  827. CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::SExt))
  828. return false;
  829. // Make sure there are no instructions between the PHI and return, or that the
  830. // return is the first instruction in the block.
  831. if (PN) {
  832. BasicBlock::iterator BI = BB->begin();
  833. do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
  834. if (&*BI == BCI)
  835. // Also skip over the bitcast.
  836. ++BI;
  837. if (&*BI != RI)
  838. return false;
  839. } else {
  840. BasicBlock::iterator BI = BB->begin();
  841. while (isa<DbgInfoIntrinsic>(BI)) ++BI;
  842. if (&*BI != RI)
  843. return false;
  844. }
  845. /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
  846. /// call.
  847. SmallVector<CallInst*, 4> TailCalls;
  848. if (PN) {
  849. for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
  850. CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
  851. // Make sure the phi value is indeed produced by the tail call.
  852. if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
  853. TLI->mayBeEmittedAsTailCall(CI))
  854. TailCalls.push_back(CI);
  855. }
  856. } else {
  857. SmallPtrSet<BasicBlock*, 4> VisitedBBs;
  858. for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
  859. if (!VisitedBBs.insert(*PI).second)
  860. continue;
  861. BasicBlock::InstListType &InstList = (*PI)->getInstList();
  862. BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
  863. BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
  864. do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
  865. if (RI == RE)
  866. continue;
  867. CallInst *CI = dyn_cast<CallInst>(&*RI);
  868. if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI))
  869. TailCalls.push_back(CI);
  870. }
  871. }
  872. bool Changed = false;
  873. for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
  874. CallInst *CI = TailCalls[i];
  875. CallSite CS(CI);
  876. // Conservatively require the attributes of the call to match those of the
  877. // return. Ignore noalias because it doesn't affect the call sequence.
  878. AttributeSet CalleeAttrs = CS.getAttributes();
  879. if (AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
  880. removeAttribute(Attribute::NoAlias) !=
  881. AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
  882. removeAttribute(Attribute::NoAlias))
  883. continue;
  884. // Make sure the call instruction is followed by an unconditional branch to
  885. // the return block.
  886. BasicBlock *CallBB = CI->getParent();
  887. BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
  888. if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
  889. continue;
  890. // Duplicate the return into CallBB.
  891. (void)FoldReturnIntoUncondBranch(RI, BB, CallBB);
  892. ModifiedDT = Changed = true;
  893. ++NumRetsDup;
  894. }
  895. // If we eliminated all predecessors of the block, delete the block now.
  896. if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
  897. BB->eraseFromParent();
  898. return Changed;
  899. }
  900. //===----------------------------------------------------------------------===//
  901. // Memory Optimization
  902. //===----------------------------------------------------------------------===//
  903. namespace {
  904. /// ExtAddrMode - This is an extended version of TargetLowering::AddrMode
  905. /// which holds actual Value*'s for register values.
  906. struct ExtAddrMode : public TargetLowering::AddrMode {
  907. Value *BaseReg;
  908. Value *ScaledReg;
  909. ExtAddrMode() : BaseReg(nullptr), ScaledReg(nullptr) {}
  910. void print(raw_ostream &OS) const;
  911. void dump() const;
  912. bool operator==(const ExtAddrMode& O) const {
  913. return (BaseReg == O.BaseReg) && (ScaledReg == O.ScaledReg) &&
  914. (BaseGV == O.BaseGV) && (BaseOffs == O.BaseOffs) &&
  915. (HasBaseReg == O.HasBaseReg) && (Scale == O.Scale);
  916. }
  917. };
  918. #ifndef NDEBUG
  919. static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
  920. AM.print(OS);
  921. return OS;
  922. }
  923. #endif
  924. void ExtAddrMode::print(raw_ostream &OS) const {
  925. bool NeedPlus = false;
  926. OS << "[";
  927. if (BaseGV) {
  928. OS << (NeedPlus ? " + " : "")
  929. << "GV:";
  930. BaseGV->printAsOperand(OS, /*PrintType=*/false);
  931. NeedPlus = true;
  932. }
  933. if (BaseOffs) {
  934. OS << (NeedPlus ? " + " : "")
  935. << BaseOffs;
  936. NeedPlus = true;
  937. }
  938. if (BaseReg) {
  939. OS << (NeedPlus ? " + " : "")
  940. << "Base:";
  941. BaseReg->printAsOperand(OS, /*PrintType=*/false);
  942. NeedPlus = true;
  943. }
  944. if (Scale) {
  945. OS << (NeedPlus ? " + " : "")
  946. << Scale << "*";
  947. ScaledReg->printAsOperand(OS, /*PrintType=*/false);
  948. }
  949. OS << ']';
  950. }
  951. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  952. void ExtAddrMode::dump() const {
  953. print(dbgs());
  954. dbgs() << '\n';
  955. }
  956. #endif
  957. /// \brief This class provides transaction based operation on the IR.
  958. /// Every change made through this class is recorded in the internal state and
  959. /// can be undone (rollback) until commit is called.
  960. class TypePromotionTransaction {
  961. /// \brief This represents the common interface of the individual transaction.
  962. /// Each class implements the logic for doing one specific modification on
  963. /// the IR via the TypePromotionTransaction.
  964. class TypePromotionAction {
  965. protected:
  966. /// The Instruction modified.
  967. Instruction *Inst;
  968. public:
  969. /// \brief Constructor of the action.
  970. /// The constructor performs the related action on the IR.
  971. TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
  972. virtual ~TypePromotionAction() {}
  973. /// \brief Undo the modification done by this action.
  974. /// When this method is called, the IR must be in the same state as it was
  975. /// before this action was applied.
  976. /// \pre Undoing the action works if and only if the IR is in the exact same
  977. /// state as it was directly after this action was applied.
  978. virtual void undo() = 0;
  979. /// \brief Advocate every change made by this action.
  980. /// When the results on the IR of the action are to be kept, it is important
  981. /// to call this function, otherwise hidden information may be kept forever.
  982. virtual void commit() {
  983. // Nothing to be done, this action is not doing anything.
  984. }
  985. };
  986. /// \brief Utility to remember the position of an instruction.
  987. class InsertionHandler {
  988. /// Position of an instruction.
  989. /// Either an instruction:
  990. /// - Is the first in a basic block: BB is used.
  991. /// - Has a previous instructon: PrevInst is used.
  992. union {
  993. Instruction *PrevInst;
  994. BasicBlock *BB;
  995. } Point;
  996. /// Remember whether or not the instruction had a previous instruction.
  997. bool HasPrevInstruction;
  998. public:
  999. /// \brief Record the position of \p Inst.
  1000. InsertionHandler(Instruction *Inst) {
  1001. BasicBlock::iterator It = Inst;
  1002. HasPrevInstruction = (It != (Inst->getParent()->begin()));
  1003. if (HasPrevInstruction)
  1004. Point.PrevInst = --It;
  1005. else
  1006. Point.BB = Inst->getParent();
  1007. }
  1008. /// \brief Insert \p Inst at the recorded position.
  1009. void insert(Instruction *Inst) {
  1010. if (HasPrevInstruction) {
  1011. if (Inst->getParent())
  1012. Inst->removeFromParent();
  1013. Inst->insertAfter(Point.PrevInst);
  1014. } else {
  1015. Instruction *Position = Point.BB->getFirstInsertionPt();
  1016. if (Inst->getParent())
  1017. Inst->moveBefore(Position);
  1018. else
  1019. Inst->insertBefore(Position);
  1020. }
  1021. }
  1022. };
  1023. /// \brief Move an instruction before another.
  1024. class InstructionMoveBefore : public TypePromotionAction {
  1025. /// Original position of the instruction.
  1026. InsertionHandler Position;
  1027. public:
  1028. /// \brief Move \p Inst before \p Before.
  1029. InstructionMoveBefore(Instruction *Inst, Instruction *Before)
  1030. : TypePromotionAction(Inst), Position(Inst) {
  1031. DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n");
  1032. Inst->moveBefore(Before);
  1033. }
  1034. /// \brief Move the instruction back to its original position.
  1035. void undo() override {
  1036. DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
  1037. Position.insert(Inst);
  1038. }
  1039. };
  1040. /// \brief Set the operand of an instruction with a new value.
  1041. class OperandSetter : public TypePromotionAction {
  1042. /// Original operand of the instruction.
  1043. Value *Origin;
  1044. /// Index of the modified instruction.
  1045. unsigned Idx;
  1046. public:
  1047. /// \brief Set \p Idx operand of \p Inst with \p NewVal.
  1048. OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
  1049. : TypePromotionAction(Inst), Idx(Idx) {
  1050. DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
  1051. << "for:" << *Inst << "\n"
  1052. << "with:" << *NewVal << "\n");
  1053. Origin = Inst->getOperand(Idx);
  1054. Inst->setOperand(Idx, NewVal);
  1055. }
  1056. /// \brief Restore the original value of the instruction.
  1057. void undo() override {
  1058. DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
  1059. << "for: " << *Inst << "\n"
  1060. << "with: " << *Origin << "\n");
  1061. Inst->setOperand(Idx, Origin);
  1062. }
  1063. };
  1064. /// \brief Hide the operands of an instruction.
  1065. /// Do as if this instruction was not using any of its operands.
  1066. class OperandsHider : public TypePromotionAction {
  1067. /// The list of original operands.
  1068. SmallVector<Value *, 4> OriginalValues;
  1069. public:
  1070. /// \brief Remove \p Inst from the uses of the operands of \p Inst.
  1071. OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
  1072. DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
  1073. unsigned NumOpnds = Inst->getNumOperands();
  1074. OriginalValues.reserve(NumOpnds);
  1075. for (unsigned It = 0; It < NumOpnds; ++It) {
  1076. // Save the current operand.
  1077. Value *Val = Inst->getOperand(It);
  1078. OriginalValues.push_back(Val);
  1079. // Set a dummy one.
  1080. // We could use OperandSetter here, but that would implied an overhead
  1081. // that we are not willing to pay.
  1082. Inst->setOperand(It, UndefValue::get(Val->getType()));
  1083. }
  1084. }
  1085. /// \brief Restore the original list of uses.
  1086. void undo() override {
  1087. DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
  1088. for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
  1089. Inst->setOperand(It, OriginalValues[It]);
  1090. }
  1091. };
  1092. /// \brief Build a truncate instruction.
  1093. class TruncBuilder : public TypePromotionAction {
  1094. Value *Val;
  1095. public:
  1096. /// \brief Build a truncate instruction of \p Opnd producing a \p Ty
  1097. /// result.
  1098. /// trunc Opnd to Ty.
  1099. TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
  1100. IRBuilder<> Builder(Opnd);
  1101. Val = Builder.CreateTrunc(Opnd, Ty, "promoted");
  1102. DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n");
  1103. }
  1104. /// \brief Get the built value.
  1105. Value *getBuiltValue() { return Val; }
  1106. /// \brief Remove the built instruction.
  1107. void undo() override {
  1108. DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n");
  1109. if (Instruction *IVal = dyn_cast<Instruction>(Val))
  1110. IVal->eraseFromParent();
  1111. }
  1112. };
  1113. /// \brief Build a sign extension instruction.
  1114. class SExtBuilder : public TypePromotionAction {
  1115. Value *Val;
  1116. public:
  1117. /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty
  1118. /// result.
  1119. /// sext Opnd to Ty.
  1120. SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
  1121. : TypePromotionAction(InsertPt) {
  1122. IRBuilder<> Builder(InsertPt);
  1123. Val = Builder.CreateSExt(Opnd, Ty, "promoted");
  1124. DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n");
  1125. }
  1126. /// \brief Get the built value.
  1127. Value *getBuiltValue() { return Val; }
  1128. /// \brief Remove the built instruction.
  1129. void undo() override {
  1130. DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n");
  1131. if (Instruction *IVal = dyn_cast<Instruction>(Val))
  1132. IVal->eraseFromParent();
  1133. }
  1134. };
  1135. /// \brief Build a zero extension instruction.
  1136. class ZExtBuilder : public TypePromotionAction {
  1137. Value *Val;
  1138. public:
  1139. /// \brief Build a zero extension instruction of \p Opnd producing a \p Ty
  1140. /// result.
  1141. /// zext Opnd to Ty.
  1142. ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
  1143. : TypePromotionAction(InsertPt) {
  1144. IRBuilder<> Builder(InsertPt);
  1145. Val = Builder.CreateZExt(Opnd, Ty, "promoted");
  1146. DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n");
  1147. }
  1148. /// \brief Get the built value.
  1149. Value *getBuiltValue() { return Val; }
  1150. /// \brief Remove the built instruction.
  1151. void undo() override {
  1152. DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n");
  1153. if (Instruction *IVal = dyn_cast<Instruction>(Val))
  1154. IVal->eraseFromParent();
  1155. }
  1156. };
  1157. /// \brief Mutate an instruction to another type.
  1158. class TypeMutator : public TypePromotionAction {
  1159. /// Record the original type.
  1160. Type *OrigTy;
  1161. public:
  1162. /// \brief Mutate the type of \p Inst into \p NewTy.
  1163. TypeMutator(Instruction *Inst, Type *NewTy)
  1164. : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
  1165. DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
  1166. << "\n");
  1167. Inst->mutateType(NewTy);
  1168. }
  1169. /// \brief Mutate the instruction back to its original type.
  1170. void undo() override {
  1171. DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
  1172. << "\n");
  1173. Inst->mutateType(OrigTy);
  1174. }
  1175. };
  1176. /// \brief Replace the uses of an instruction by another instruction.
  1177. class UsesReplacer : public TypePromotionAction {
  1178. /// Helper structure to keep track of the replaced uses.
  1179. struct InstructionAndIdx {
  1180. /// The instruction using the instruction.
  1181. Instruction *Inst;
  1182. /// The index where this instruction is used for Inst.
  1183. unsigned Idx;
  1184. InstructionAndIdx(Instruction *Inst, unsigned Idx)
  1185. : Inst(Inst), Idx(Idx) {}
  1186. };
  1187. /// Keep track of the original uses (pair Instruction, Index).
  1188. SmallVector<InstructionAndIdx, 4> OriginalUses;
  1189. typedef SmallVectorImpl<InstructionAndIdx>::iterator use_iterator;
  1190. public:
  1191. /// \brief Replace all the use of \p Inst by \p New.
  1192. UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
  1193. DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
  1194. << "\n");
  1195. // Record the original uses.
  1196. for (Use &U : Inst->uses()) {
  1197. Instruction *UserI = cast<Instruction>(U.getUser());
  1198. OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
  1199. }
  1200. // Now, we can replace the uses.
  1201. Inst->replaceAllUsesWith(New);
  1202. }
  1203. /// \brief Reassign the original uses of Inst to Inst.
  1204. void undo() override {
  1205. DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
  1206. for (use_iterator UseIt = OriginalUses.begin(),
  1207. EndIt = OriginalUses.end();
  1208. UseIt != EndIt; ++UseIt) {
  1209. UseIt->Inst->setOperand(UseIt->Idx, Inst);
  1210. }
  1211. }
  1212. };
  1213. /// \brief Remove an instruction from the IR.
  1214. class InstructionRemover : public TypePromotionAction {
  1215. /// Original position of the instruction.
  1216. InsertionHandler Inserter;
  1217. /// Helper structure to hide all the link to the instruction. In other
  1218. /// words, this helps to do as if the instruction was removed.
  1219. OperandsHider Hider;
  1220. /// Keep track of the uses replaced, if any.
  1221. UsesReplacer *Replacer;
  1222. public:
  1223. /// \brief Remove all reference of \p Inst and optinally replace all its
  1224. /// uses with New.
  1225. /// \pre If !Inst->use_empty(), then New != nullptr
  1226. InstructionRemover(Instruction *Inst, Value *New = nullptr)
  1227. : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
  1228. Replacer(nullptr) {
  1229. if (New)
  1230. Replacer = new UsesReplacer(Inst, New);
  1231. DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
  1232. Inst->removeFromParent();
  1233. }
  1234. ~InstructionRemover() { delete Replacer; }
  1235. /// \brief Really remove the instruction.
  1236. void commit() override { delete Inst; }
  1237. /// \brief Resurrect the instruction and reassign it to the proper uses if
  1238. /// new value was provided when build this action.
  1239. void undo() override {
  1240. DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
  1241. Inserter.insert(Inst);
  1242. if (Replacer)
  1243. Replacer->undo();
  1244. Hider.undo();
  1245. }
  1246. };
  1247. public:
  1248. /// Restoration point.
  1249. /// The restoration point is a pointer to an action instead of an iterator
  1250. /// because the iterator may be invalidated but not the pointer.
  1251. typedef const TypePromotionAction *ConstRestorationPt;
  1252. /// Advocate every changes made in that transaction.
  1253. void commit();
  1254. /// Undo all the changes made after the given point.
  1255. void rollback(ConstRestorationPt Point);
  1256. /// Get the current restoration point.
  1257. ConstRestorationPt getRestorationPoint() const;
  1258. /// \name API for IR modification with state keeping to support rollback.
  1259. /// @{
  1260. /// Same as Instruction::setOperand.
  1261. void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
  1262. /// Same as Instruction::eraseFromParent.
  1263. void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
  1264. /// Same as Value::replaceAllUsesWith.
  1265. void replaceAllUsesWith(Instruction *Inst, Value *New);
  1266. /// Same as Value::mutateType.
  1267. void mutateType(Instruction *Inst, Type *NewTy);
  1268. /// Same as IRBuilder::createTrunc.
  1269. Value *createTrunc(Instruction *Opnd, Type *Ty);
  1270. /// Same as IRBuilder::createSExt.
  1271. Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
  1272. /// Same as IRBuilder::createZExt.
  1273. Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
  1274. /// Same as Instruction::moveBefore.
  1275. void moveBefore(Instruction *Inst, Instruction *Before);
  1276. /// @}
  1277. private:
  1278. /// The ordered list of actions made so far.
  1279. SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions;
  1280. typedef SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator CommitPt;
  1281. };
  1282. void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
  1283. Value *NewVal) {
  1284. Actions.push_back(
  1285. make_unique<TypePromotionTransaction::OperandSetter>(Inst, Idx, NewVal));
  1286. }
  1287. void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
  1288. Value *NewVal) {
  1289. Actions.push_back(
  1290. make_unique<TypePromotionTransaction::InstructionRemover>(Inst, NewVal));
  1291. }
  1292. void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
  1293. Value *New) {
  1294. Actions.push_back(make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
  1295. }
  1296. void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
  1297. Actions.push_back(make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
  1298. }
  1299. Value *TypePromotionTransaction::createTrunc(Instruction *Opnd,
  1300. Type *Ty) {
  1301. std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
  1302. Value *Val = Ptr->getBuiltValue();
  1303. Actions.push_back(std::move(Ptr));
  1304. return Val;
  1305. }
  1306. Value *TypePromotionTransaction::createSExt(Instruction *Inst,
  1307. Value *Opnd, Type *Ty) {
  1308. std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
  1309. Value *Val = Ptr->getBuiltValue();
  1310. Actions.push_back(std::move(Ptr));
  1311. return Val;
  1312. }
  1313. Value *TypePromotionTransaction::createZExt(Instruction *Inst,
  1314. Value *Opnd, Type *Ty) {
  1315. std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
  1316. Value *Val = Ptr->getBuiltValue();
  1317. Actions.push_back(std::move(Ptr));
  1318. return Val;
  1319. }
  1320. void TypePromotionTransaction::moveBefore(Instruction *Inst,
  1321. Instruction *Before) {
  1322. Actions.push_back(
  1323. make_unique<TypePromotionTransaction::InstructionMoveBefore>(Inst, Before));
  1324. }
  1325. TypePromotionTransaction::ConstRestorationPt
  1326. TypePromotionTransaction::getRestorationPoint() const {
  1327. return !Actions.empty() ? Actions.back().get() : nullptr;
  1328. }
  1329. void TypePromotionTransaction::commit() {
  1330. for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
  1331. ++It)
  1332. (*It)->commit();
  1333. Actions.clear();
  1334. }
  1335. void TypePromotionTransaction::rollback(
  1336. TypePromotionTransaction::ConstRestorationPt Point) {
  1337. while (!Actions.empty() && Point != Actions.back().get()) {
  1338. std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
  1339. Curr->undo();
  1340. }
  1341. }
  1342. /// \brief A helper class for matching addressing modes.
  1343. ///
  1344. /// This encapsulates the logic for matching the target-legal addressing modes.
  1345. class AddressingModeMatcher {
  1346. SmallVectorImpl<Instruction*> &AddrModeInsts;
  1347. const TargetLowering &TLI;
  1348. /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
  1349. /// the memory instruction that we're computing this address for.
  1350. Type *AccessTy;
  1351. Instruction *MemoryInst;
  1352. /// AddrMode - This is the addressing mode that we're building up. This is
  1353. /// part of the return value of this addressing mode matching stuff.
  1354. ExtAddrMode &AddrMode;
  1355. /// The truncate instruction inserted by other CodeGenPrepare optimizations.
  1356. const SetOfInstrs &InsertedTruncs;
  1357. /// A map from the instructions to their type before promotion.
  1358. InstrToOrigTy &PromotedInsts;
  1359. /// The ongoing transaction where every action should be registered.
  1360. TypePromotionTransaction &TPT;
  1361. /// IgnoreProfitability - This is set to true when we should not do
  1362. /// profitability checks. When true, IsProfitableToFoldIntoAddressingMode
  1363. /// always returns true.
  1364. bool IgnoreProfitability;
  1365. AddressingModeMatcher(SmallVectorImpl<Instruction*> &AMI,
  1366. const TargetLowering &T, Type *AT,
  1367. Instruction *MI, ExtAddrMode &AM,
  1368. const SetOfInstrs &InsertedTruncs,
  1369. InstrToOrigTy &PromotedInsts,
  1370. TypePromotionTransaction &TPT)
  1371. : AddrModeInsts(AMI), TLI(T), AccessTy(AT), MemoryInst(MI), AddrMode(AM),
  1372. InsertedTruncs(InsertedTruncs), PromotedInsts(PromotedInsts), TPT(TPT) {
  1373. IgnoreProfitability = false;
  1374. }
  1375. public:
  1376. /// Match - Find the maximal addressing mode that a load/store of V can fold,
  1377. /// give an access type of AccessTy. This returns a list of involved
  1378. /// instructions in AddrModeInsts.
  1379. /// \p InsertedTruncs The truncate instruction inserted by other
  1380. /// CodeGenPrepare
  1381. /// optimizations.
  1382. /// \p PromotedInsts maps the instructions to their type before promotion.
  1383. /// \p The ongoing transaction where every action should be registered.
  1384. static ExtAddrMode Match(Value *V, Type *AccessTy,
  1385. Instruction *MemoryInst,
  1386. SmallVectorImpl<Instruction*> &AddrModeInsts,
  1387. const TargetLowering &TLI,
  1388. const SetOfInstrs &InsertedTruncs,
  1389. InstrToOrigTy &PromotedInsts,
  1390. TypePromotionTransaction &TPT) {
  1391. ExtAddrMode Result;
  1392. bool Success = AddressingModeMatcher(AddrModeInsts, TLI, AccessTy,
  1393. MemoryInst, Result, InsertedTruncs,
  1394. PromotedInsts, TPT).MatchAddr(V, 0);
  1395. (void)Success; assert(Success && "Couldn't select *anything*?");
  1396. return Result;
  1397. }
  1398. private:
  1399. bool MatchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
  1400. bool MatchAddr(Value *V, unsigned Depth);
  1401. bool MatchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth,
  1402. bool *MovedAway = nullptr);
  1403. bool IsProfitableToFoldIntoAddressingMode(Instruction *I,
  1404. ExtAddrMode &AMBefore,
  1405. ExtAddrMode &AMAfter);
  1406. bool ValueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
  1407. bool IsPromotionProfitable(unsigned MatchedSize, unsigned SizeWithPromotion,
  1408. Value *PromotedOperand) const;
  1409. };
  1410. /// MatchScaledValue - Try adding ScaleReg*Scale to the current addressing mode.
  1411. /// Return true and update AddrMode if this addr mode is legal for the target,
  1412. /// false if not.
  1413. bool AddressingModeMatcher::MatchScaledValue(Value *ScaleReg, int64_t Scale,
  1414. unsigned Depth) {
  1415. // If Scale is 1, then this is the same as adding ScaleReg to the addressing
  1416. // mode. Just process that directly.
  1417. if (Scale == 1)
  1418. return MatchAddr(ScaleReg, Depth);
  1419. // If the scale is 0, it takes nothing to add this.
  1420. if (Scale == 0)
  1421. return true;
  1422. // If we already have a scale of this value, we can add to it, otherwise, we
  1423. // need an available scale field.
  1424. if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
  1425. return false;
  1426. ExtAddrMode TestAddrMode = AddrMode;
  1427. // Add scale to turn X*4+X*3 -> X*7. This could also do things like
  1428. // [A+B + A*7] -> [B+A*8].
  1429. TestAddrMode.Scale += Scale;
  1430. TestAddrMode.ScaledReg = ScaleReg;
  1431. // If the new address isn't legal, bail out.
  1432. if (!TLI.isLegalAddressingMode(TestAddrMode, AccessTy))
  1433. return false;
  1434. // It was legal, so commit it.
  1435. AddrMode = TestAddrMode;
  1436. // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
  1437. // to see if ScaleReg is actually X+C. If so, we can turn this into adding
  1438. // X*Scale + C*Scale to addr mode.
  1439. ConstantInt *CI = nullptr; Value *AddLHS = nullptr;
  1440. if (isa<Instruction>(ScaleReg) && // not a constant expr.
  1441. match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
  1442. TestAddrMode.ScaledReg = AddLHS;
  1443. TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
  1444. // If this addressing mode is legal, commit it and remember that we folded
  1445. // this instruction.
  1446. if (TLI.isLegalAddressingMode(TestAddrMode, AccessTy)) {
  1447. AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
  1448. AddrMode = TestAddrMode;
  1449. return true;
  1450. }
  1451. }
  1452. // Otherwise, not (x+c)*scale, just return what we have.
  1453. return true;
  1454. }
  1455. /// MightBeFoldableInst - This is a little filter, which returns true if an
  1456. /// addressing computation involving I might be folded into a load/store
  1457. /// accessing it. This doesn't need to be perfect, but needs to accept at least
  1458. /// the set of instructions that MatchOperationAddr can.
  1459. static bool MightBeFoldableInst(Instruction *I) {
  1460. switch (I->getOpcode()) {
  1461. case Instruction::BitCast:
  1462. case Instruction::AddrSpaceCast:
  1463. // Don't touch identity bitcasts.
  1464. if (I->getType() == I->getOperand(0)->getType())
  1465. return false;
  1466. return I->getType()->isPointerTy() || I->getType()->isIntegerTy();
  1467. case Instruction::PtrToInt:
  1468. // PtrToInt is always a noop, as we know that the int type is pointer sized.
  1469. return true;
  1470. case Instruction::IntToPtr:
  1471. // We know the input is intptr_t, so this is foldable.
  1472. return true;
  1473. case Instruction::Add:
  1474. return true;
  1475. case Instruction::Mul:
  1476. case Instruction::Shl:
  1477. // Can only handle X*C and X << C.
  1478. return isa<ConstantInt>(I->getOperand(1));
  1479. case Instruction::GetElementPtr:
  1480. return true;
  1481. default:
  1482. return false;
  1483. }
  1484. }
  1485. /// \brief Hepler class to perform type promotion.
  1486. class TypePromotionHelper {
  1487. /// \brief Utility function to check whether or not a sign or zero extension
  1488. /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by
  1489. /// either using the operands of \p Inst or promoting \p Inst.
  1490. /// The type of the extension is defined by \p IsSExt.
  1491. /// In other words, check if:
  1492. /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType.
  1493. /// #1 Promotion applies:
  1494. /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...).
  1495. /// #2 Operand reuses:
  1496. /// ext opnd1 to ConsideredExtType.
  1497. /// \p PromotedInsts maps the instructions to their type before promotion.
  1498. static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType,
  1499. const InstrToOrigTy &PromotedInsts, bool IsSExt);
  1500. /// \brief Utility function to determine if \p OpIdx should be promoted when
  1501. /// promoting \p Inst.
  1502. static bool shouldExtOperand(const Instruction *Inst, int OpIdx) {
  1503. if (isa<SelectInst>(Inst) && OpIdx == 0)
  1504. return false;
  1505. return true;
  1506. }
  1507. /// \brief Utility function to promote the operand of \p Ext when this
  1508. /// operand is a promotable trunc or sext or zext.
  1509. /// \p PromotedInsts maps the instructions to their type before promotion.
  1510. /// \p CreatedInsts[out] contains how many non-free instructions have been
  1511. /// created to promote the operand of Ext.
  1512. /// Should never be called directly.
  1513. /// \return The promoted value which is used instead of Ext.
  1514. static Value *promoteOperandForTruncAndAnyExt(Instruction *Ext,
  1515. TypePromotionTransaction &TPT,
  1516. InstrToOrigTy &PromotedInsts,
  1517. unsigned &CreatedInsts);
  1518. /// \brief Utility function to promote the operand of \p Ext when this
  1519. /// operand is promotable and is not a supported trunc or sext.
  1520. /// \p PromotedInsts maps the instructions to their type before promotion.
  1521. /// \p CreatedInsts[out] contains how many non-free instructions have been
  1522. /// created to promote the operand of Ext.
  1523. /// Should never be called directly.
  1524. /// \return The promoted value which is used instead of Ext.
  1525. static Value *promoteOperandForOther(Instruction *Ext,
  1526. TypePromotionTransaction &TPT,
  1527. InstrToOrigTy &PromotedInsts,
  1528. unsigned &CreatedInsts, bool IsSExt);
  1529. /// \see promoteOperandForOther.
  1530. static Value *signExtendOperandForOther(Instruction *Ext,
  1531. TypePromotionTransaction &TPT,
  1532. InstrToOrigTy &PromotedInsts,
  1533. unsigned &CreatedInsts) {
  1534. return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInsts, true);
  1535. }
  1536. /// \see promoteOperandForOther.
  1537. static Value *zeroExtendOperandForOther(Instruction *Ext,
  1538. TypePromotionTransaction &TPT,
  1539. InstrToOrigTy &PromotedInsts,
  1540. unsigned &CreatedInsts) {
  1541. return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInsts, false);
  1542. }
  1543. public:
  1544. /// Type for the utility function that promotes the operand of Ext.
  1545. typedef Value *(*Action)(Instruction *Ext, TypePromotionTransaction &TPT,
  1546. InstrToOrigTy &PromotedInsts,
  1547. unsigned &CreatedInsts);
  1548. /// \brief Given a sign/zero extend instruction \p Ext, return the approriate
  1549. /// action to promote the operand of \p Ext instead of using Ext.
  1550. /// \return NULL if no promotable action is possible with the current
  1551. /// sign extension.
  1552. /// \p InsertedTruncs keeps track of all the truncate instructions inserted by
  1553. /// the others CodeGenPrepare optimizations. This information is important
  1554. /// because we do not want to promote these instructions as CodeGenPrepare
  1555. /// will reinsert them later. Thus creating an infinite loop: create/remove.
  1556. /// \p PromotedInsts maps the instructions to their type before promotion.
  1557. static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedTruncs,
  1558. const TargetLowering &TLI,
  1559. const InstrToOrigTy &PromotedInsts);
  1560. };
  1561. bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
  1562. Type *ConsideredExtType,
  1563. const InstrToOrigTy &PromotedInsts,
  1564. bool IsSExt) {
  1565. // We can always get through zext.
  1566. if (isa<ZExtInst>(Inst))
  1567. return true;
  1568. // sext(sext) is ok too.
  1569. if (IsSExt && isa<SExtInst>(Inst))
  1570. return true;
  1571. // We can get through binary operator, if it is legal. In other words, the
  1572. // binary operator must have a nuw or nsw flag.
  1573. const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
  1574. if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
  1575. ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
  1576. (IsSExt && BinOp->hasNoSignedWrap())))
  1577. return true;
  1578. // Check if we can do the following simplification.
  1579. // ext(trunc(opnd)) --> ext(opnd)
  1580. if (!isa<TruncInst>(Inst))
  1581. return false;
  1582. Value *OpndVal = Inst->getOperand(0);
  1583. // Check if we can use this operand in the extension.
  1584. // If the type is larger than the result type of the extension,
  1585. // we cannot.
  1586. if (OpndVal->getType()->getIntegerBitWidth() >
  1587. ConsideredExtType->getIntegerBitWidth())
  1588. return false;
  1589. // If the operand of the truncate is not an instruction, we will not have
  1590. // any information on the dropped bits.
  1591. // (Actually we could for constant but it is not worth the extra logic).
  1592. Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
  1593. if (!Opnd)
  1594. return false;
  1595. // Check if the source of the type is narrow enough.
  1596. // I.e., check that trunc just drops extended bits of the same kind of
  1597. // the extension.
  1598. // #1 get the type of the operand and check the kind of the extended bits.
  1599. const Type *OpndType;
  1600. InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
  1601. if (It != PromotedInsts.end() && It->second.IsSExt == IsSExt)
  1602. OpndType = It->second.Ty;
  1603. else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
  1604. OpndType = Opnd->getOperand(0)->getType();
  1605. else
  1606. return false;
  1607. // #2 check that the truncate just drop extended bits.
  1608. if (Inst->getType()->getIntegerBitWidth() >= OpndType->getIntegerBitWidth())
  1609. return true;
  1610. return false;
  1611. }
  1612. TypePromotionHelper::Action TypePromotionHelper::getAction(
  1613. Instruction *Ext, const SetOfInstrs &InsertedTruncs,
  1614. const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
  1615. assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
  1616. "Unexpected instruction type");
  1617. Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0));
  1618. Type *ExtTy = Ext->getType();
  1619. bool IsSExt = isa<SExtInst>(Ext);
  1620. // If the operand of the extension is not an instruction, we cannot
  1621. // get through.
  1622. // If it, check we can get through.
  1623. if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
  1624. return nullptr;
  1625. // Do not promote if the operand has been added by codegenprepare.
  1626. // Otherwise, it means we are undoing an optimization that is likely to be
  1627. // redone, thus causing potential infinite loop.
  1628. if (isa<TruncInst>(ExtOpnd) && InsertedTruncs.count(ExtOpnd))
  1629. return nullptr;
  1630. // SExt or Trunc instructions.
  1631. // Return the related handler.
  1632. if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
  1633. isa<ZExtInst>(ExtOpnd))
  1634. return promoteOperandForTruncAndAnyExt;
  1635. // Regular instruction.
  1636. // Abort early if we will have to insert non-free instructions.
  1637. if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType()))
  1638. return nullptr;
  1639. return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
  1640. }
  1641. Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
  1642. llvm::Instruction *SExt, TypePromotionTransaction &TPT,
  1643. InstrToOrigTy &PromotedInsts, unsigned &CreatedInsts) {
  1644. // By construction, the operand of SExt is an instruction. Otherwise we cannot
  1645. // get through it and this method should not be called.
  1646. Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
  1647. Value *ExtVal = SExt;
  1648. if (isa<ZExtInst>(SExtOpnd)) {
  1649. // Replace s|zext(zext(opnd))
  1650. // => zext(opnd).
  1651. Value *ZExt =
  1652. TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
  1653. TPT.replaceAllUsesWith(SExt, ZExt);
  1654. TPT.eraseInstruction(SExt);
  1655. ExtVal = ZExt;
  1656. } else {
  1657. // Replace z|sext(trunc(opnd)) or sext(sext(opnd))
  1658. // => z|sext(opnd).
  1659. TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
  1660. }
  1661. CreatedInsts = 0;
  1662. // Remove dead code.
  1663. if (SExtOpnd->use_empty())
  1664. TPT.eraseInstruction(SExtOpnd);
  1665. // Check if the extension is still needed.
  1666. Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
  1667. if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType())
  1668. return ExtVal;
  1669. // At this point we have: ext ty opnd to ty.
  1670. // Reassign the uses of ExtInst to the opnd and remove ExtInst.
  1671. Value *NextVal = ExtInst->getOperand(0);
  1672. TPT.eraseInstruction(ExtInst, NextVal);
  1673. return NextVal;
  1674. }
  1675. Value *TypePromotionHelper::promoteOperandForOther(
  1676. Instruction *Ext, TypePromotionTransaction &TPT,
  1677. InstrToOrigTy &PromotedInsts, unsigned &CreatedInsts, bool IsSExt) {
  1678. // By construction, the operand of Ext is an instruction. Otherwise we cannot
  1679. // get through it and this method should not be called.
  1680. Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0));
  1681. CreatedInsts = 0;
  1682. if (!ExtOpnd->hasOneUse()) {
  1683. // ExtOpnd will be promoted.
  1684. // All its uses, but Ext, will need to use a truncated value of the
  1685. // promoted version.
  1686. // Create the truncate now.
  1687. Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType());
  1688. if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
  1689. ITrunc->removeFromParent();
  1690. // Insert it just after the definition.
  1691. ITrunc->insertAfter(ExtOpnd);
  1692. }
  1693. TPT.replaceAllUsesWith(ExtOpnd, Trunc);
  1694. // Restore the operand of Ext (which has been replace by the previous call
  1695. // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
  1696. TPT.setOperand(Ext, 0, ExtOpnd);
  1697. }
  1698. // Get through the Instruction:
  1699. // 1. Update its type.
  1700. // 2. Replace the uses of Ext by Inst.
  1701. // 3. Extend each operand that needs to be extended.
  1702. // Remember the original type of the instruction before promotion.
  1703. // This is useful to know that the high bits are sign extended bits.
  1704. PromotedInsts.insert(std::pair<Instruction *, TypeIsSExt>(
  1705. ExtOpnd, TypeIsSExt(ExtOpnd->getType(), IsSExt)));
  1706. // Step #1.
  1707. TPT.mutateType(ExtOpnd, Ext->getType());
  1708. // Step #2.
  1709. TPT.replaceAllUsesWith(Ext, ExtOpnd);
  1710. // Step #3.
  1711. Instruction *ExtForOpnd = Ext;
  1712. DEBUG(dbgs() << "Propagate Ext to operands\n");
  1713. for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
  1714. ++OpIdx) {
  1715. DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n');
  1716. if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() ||
  1717. !shouldExtOperand(ExtOpnd, OpIdx)) {
  1718. DEBUG(dbgs() << "No need to propagate\n");
  1719. continue;
  1720. }
  1721. // Check if we can statically extend the operand.
  1722. Value *Opnd = ExtOpnd->getOperand(OpIdx);
  1723. if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
  1724. DEBUG(dbgs() << "Statically extend\n");
  1725. unsigned BitWidth = Ext->getType()->getIntegerBitWidth();
  1726. APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
  1727. : Cst->getValue().zext(BitWidth);
  1728. TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal));
  1729. continue;
  1730. }
  1731. // UndefValue are typed, so we have to statically sign extend them.
  1732. if (isa<UndefValue>(Opnd)) {
  1733. DEBUG(dbgs() << "Statically extend\n");
  1734. TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType()));
  1735. continue;
  1736. }
  1737. // Otherwise we have to explicity sign extend the operand.
  1738. // Check if Ext was reused to extend an operand.
  1739. if (!ExtForOpnd) {
  1740. // If yes, create a new one.
  1741. DEBUG(dbgs() << "More operands to ext\n");
  1742. ExtForOpnd =
  1743. cast<Instruction>(IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType())
  1744. : TPT.createZExt(Ext, Opnd, Ext->getType()));
  1745. ++CreatedInsts;
  1746. }
  1747. TPT.setOperand(ExtForOpnd, 0, Opnd);
  1748. // Move the sign extension before the insertion point.
  1749. TPT.moveBefore(ExtForOpnd, ExtOpnd);
  1750. TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd);
  1751. // If more sext are required, new instructions will have to be created.
  1752. ExtForOpnd = nullptr;
  1753. }
  1754. if (ExtForOpnd == Ext) {
  1755. DEBUG(dbgs() << "Extension is useless now\n");
  1756. TPT.eraseInstruction(Ext);
  1757. }
  1758. return ExtOpnd;
  1759. }
  1760. /// IsPromotionProfitable - Check whether or not promoting an instruction
  1761. /// to a wider type was profitable.
  1762. /// \p MatchedSize gives the number of instructions that have been matched
  1763. /// in the addressing mode after the promotion was applied.
  1764. /// \p SizeWithPromotion gives the number of created instructions for
  1765. /// the promotion plus the number of instructions that have been
  1766. /// matched in the addressing mode before the promotion.
  1767. /// \p PromotedOperand is the value that has been promoted.
  1768. /// \return True if the promotion is profitable, false otherwise.
  1769. bool
  1770. AddressingModeMatcher::IsPromotionProfitable(unsigned MatchedSize,
  1771. unsigned SizeWithPromotion,
  1772. Value *PromotedOperand) const {
  1773. // We folded less instructions than what we created to promote the operand.
  1774. // This is not profitable.
  1775. if (MatchedSize < SizeWithPromotion)
  1776. return false;
  1777. if (MatchedSize > SizeWithPromotion)
  1778. return true;
  1779. // The promotion is neutral but it may help folding the sign extension in
  1780. // loads for instance.
  1781. // Check that we did not create an illegal instruction.
  1782. Instruction *PromotedInst = dyn_cast<Instruction>(PromotedOperand);
  1783. if (!PromotedInst)
  1784. return false;
  1785. int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
  1786. // If the ISDOpcode is undefined, it was undefined before the promotion.
  1787. if (!ISDOpcode)
  1788. return true;
  1789. // Otherwise, check if the promoted instruction is legal or not.
  1790. return TLI.isOperationLegalOrCustom(
  1791. ISDOpcode, TLI.getValueType(PromotedInst->getType()));
  1792. }
  1793. /// MatchOperationAddr - Given an instruction or constant expr, see if we can
  1794. /// fold the operation into the addressing mode. If so, update the addressing
  1795. /// mode and return true, otherwise return false without modifying AddrMode.
  1796. /// If \p MovedAway is not NULL, it contains the information of whether or
  1797. /// not AddrInst has to be folded into the addressing mode on success.
  1798. /// If \p MovedAway == true, \p AddrInst will not be part of the addressing
  1799. /// because it has been moved away.
  1800. /// Thus AddrInst must not be added in the matched instructions.
  1801. /// This state can happen when AddrInst is a sext, since it may be moved away.
  1802. /// Therefore, AddrInst may not be valid when MovedAway is true and it must
  1803. /// not be referenced anymore.
  1804. bool AddressingModeMatcher::MatchOperationAddr(User *AddrInst, unsigned Opcode,
  1805. unsigned Depth,
  1806. bool *MovedAway) {
  1807. // Avoid exponential behavior on extremely deep expression trees.
  1808. if (Depth >= 5) return false;
  1809. // By default, all matched instructions stay in place.
  1810. if (MovedAway)
  1811. *MovedAway = false;
  1812. switch (Opcode) {
  1813. case Instruction::PtrToInt:
  1814. // PtrToInt is always a noop, as we know that the int type is pointer sized.
  1815. return MatchAddr(AddrInst->getOperand(0), Depth);
  1816. case Instruction::IntToPtr:
  1817. // This inttoptr is a no-op if the integer type is pointer sized.
  1818. if (TLI.getValueType(AddrInst->getOperand(0)->getType()) ==
  1819. TLI.getPointerTy(AddrInst->getType()->getPointerAddressSpace()))
  1820. return MatchAddr(AddrInst->getOperand(0), Depth);
  1821. return false;
  1822. case Instruction::BitCast:
  1823. case Instruction::AddrSpaceCast:
  1824. // BitCast is always a noop, and we can handle it as long as it is
  1825. // int->int or pointer->pointer (we don't want int<->fp or something).
  1826. if ((AddrInst->getOperand(0)->getType()->isPointerTy() ||
  1827. AddrInst->getOperand(0)->getType()->isIntegerTy()) &&
  1828. // Don't touch identity bitcasts. These were probably put here by LSR,
  1829. // and we don't want to mess around with them. Assume it knows what it
  1830. // is doing.
  1831. AddrInst->getOperand(0)->getType() != AddrInst->getType())
  1832. return MatchAddr(AddrInst->getOperand(0), Depth);
  1833. return false;
  1834. case Instruction::Add: {
  1835. // Check to see if we can merge in the RHS then the LHS. If so, we win.
  1836. ExtAddrMode BackupAddrMode = AddrMode;
  1837. unsigned OldSize = AddrModeInsts.size();
  1838. // Start a transaction at this point.
  1839. // The LHS may match but not the RHS.
  1840. // Therefore, we need a higher level restoration point to undo partially
  1841. // matched operation.
  1842. TypePromotionTransaction::ConstRestorationPt LastKnownGood =
  1843. TPT.getRestorationPoint();
  1844. if (MatchAddr(AddrInst->getOperand(1), Depth+1) &&
  1845. MatchAddr(AddrInst->getOperand(0), Depth+1))
  1846. return true;
  1847. // Restore the old addr mode info.
  1848. AddrMode = BackupAddrMode;
  1849. AddrModeInsts.resize(OldSize);
  1850. TPT.rollback(LastKnownGood);
  1851. // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
  1852. if (MatchAddr(AddrInst->getOperand(0), Depth+1) &&
  1853. MatchAddr(AddrInst->getOperand(1), Depth+1))
  1854. return true;
  1855. // Otherwise we definitely can't merge the ADD in.
  1856. AddrMode = BackupAddrMode;
  1857. AddrModeInsts.resize(OldSize);
  1858. TPT.rollback(LastKnownGood);
  1859. break;
  1860. }
  1861. //case Instruction::Or:
  1862. // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
  1863. //break;
  1864. case Instruction::Mul:
  1865. case Instruction::Shl: {
  1866. // Can only handle X*C and X << C.
  1867. ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
  1868. if (!RHS)
  1869. return false;
  1870. int64_t Scale = RHS->getSExtValue();
  1871. if (Opcode == Instruction::Shl)
  1872. Scale = 1LL << Scale;
  1873. return MatchScaledValue(AddrInst->getOperand(0), Scale, Depth);
  1874. }
  1875. case Instruction::GetElementPtr: {
  1876. // Scan the GEP. We check it if it contains constant offsets and at most
  1877. // one variable offset.
  1878. int VariableOperand = -1;
  1879. unsigned VariableScale = 0;
  1880. int64_t ConstantOffset = 0;
  1881. const DataLayout *TD = TLI.getDataLayout();
  1882. gep_type_iterator GTI = gep_type_begin(AddrInst);
  1883. for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
  1884. if (StructType *STy = dyn_cast<StructType>(*GTI)) {
  1885. const StructLayout *SL = TD->getStructLayout(STy);
  1886. unsigned Idx =
  1887. cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
  1888. ConstantOffset += SL->getElementOffset(Idx);
  1889. } else {
  1890. uint64_t TypeSize = TD->getTypeAllocSize(GTI.getIndexedType());
  1891. if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
  1892. ConstantOffset += CI->getSExtValue()*TypeSize;
  1893. } else if (TypeSize) { // Scales of zero don't do anything.
  1894. // We only allow one variable index at the moment.
  1895. if (VariableOperand != -1)
  1896. return false;
  1897. // Remember the variable index.
  1898. VariableOperand = i;
  1899. VariableScale = TypeSize;
  1900. }
  1901. }
  1902. }
  1903. // A common case is for the GEP to only do a constant offset. In this case,
  1904. // just add it to the disp field and check validity.
  1905. if (VariableOperand == -1) {
  1906. AddrMode.BaseOffs += ConstantOffset;
  1907. if (ConstantOffset == 0 || TLI.isLegalAddressingMode(AddrMode, AccessTy)){
  1908. // Check to see if we can fold the base pointer in too.
  1909. if (MatchAddr(AddrInst->getOperand(0), Depth+1))
  1910. return true;
  1911. }
  1912. AddrMode.BaseOffs -= ConstantOffset;
  1913. return false;
  1914. }
  1915. // Save the valid addressing mode in case we can't match.
  1916. ExtAddrMode BackupAddrMode = AddrMode;
  1917. unsigned OldSize = AddrModeInsts.size();
  1918. // See if the scale and offset amount is valid for this target.
  1919. AddrMode.BaseOffs += ConstantOffset;
  1920. // Match the base operand of the GEP.
  1921. if (!MatchAddr(AddrInst->getOperand(0), Depth+1)) {
  1922. // If it couldn't be matched, just stuff the value in a register.
  1923. if (AddrMode.HasBaseReg) {
  1924. AddrMode = BackupAddrMode;
  1925. AddrModeInsts.resize(OldSize);
  1926. return false;
  1927. }
  1928. AddrMode.HasBaseReg = true;
  1929. AddrMode.BaseReg = AddrInst->getOperand(0);
  1930. }
  1931. // Match the remaining variable portion of the GEP.
  1932. if (!MatchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
  1933. Depth)) {
  1934. // If it couldn't be matched, try stuffing the base into a register
  1935. // instead of matching it, and retrying the match of the scale.
  1936. AddrMode = BackupAddrMode;
  1937. AddrModeInsts.resize(OldSize);
  1938. if (AddrMode.HasBaseReg)
  1939. return false;
  1940. AddrMode.HasBaseReg = true;
  1941. AddrMode.BaseReg = AddrInst->getOperand(0);
  1942. AddrMode.BaseOffs += ConstantOffset;
  1943. if (!MatchScaledValue(AddrInst->getOperand(VariableOperand),
  1944. VariableScale, Depth)) {
  1945. // If even that didn't work, bail.
  1946. AddrMode = BackupAddrMode;
  1947. AddrModeInsts.resize(OldSize);
  1948. return false;
  1949. }
  1950. }
  1951. return true;
  1952. }
  1953. case Instruction::SExt:
  1954. case Instruction::ZExt: {
  1955. Instruction *Ext = dyn_cast<Instruction>(AddrInst);
  1956. if (!Ext)
  1957. return false;
  1958. // Try to move this ext out of the way of the addressing mode.
  1959. // Ask for a method for doing so.
  1960. TypePromotionHelper::Action TPH =
  1961. TypePromotionHelper::getAction(Ext, InsertedTruncs, TLI, PromotedInsts);
  1962. if (!TPH)
  1963. return false;
  1964. TypePromotionTransaction::ConstRestorationPt LastKnownGood =
  1965. TPT.getRestorationPoint();
  1966. unsigned CreatedInsts = 0;
  1967. Value *PromotedOperand = TPH(Ext, TPT, PromotedInsts, CreatedInsts);
  1968. // SExt has been moved away.
  1969. // Thus either it will be rematched later in the recursive calls or it is
  1970. // gone. Anyway, we must not fold it into the addressing mode at this point.
  1971. // E.g.,
  1972. // op = add opnd, 1
  1973. // idx = ext op
  1974. // addr = gep base, idx
  1975. // is now:
  1976. // promotedOpnd = ext opnd <- no match here
  1977. // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls)
  1978. // addr = gep base, op <- match
  1979. if (MovedAway)
  1980. *MovedAway = true;
  1981. assert(PromotedOperand &&
  1982. "TypePromotionHelper should have filtered out those cases");
  1983. ExtAddrMode BackupAddrMode = AddrMode;
  1984. unsigned OldSize = AddrModeInsts.size();
  1985. if (!MatchAddr(PromotedOperand, Depth) ||
  1986. !IsPromotionProfitable(AddrModeInsts.size(), OldSize + CreatedInsts,
  1987. PromotedOperand)) {
  1988. AddrMode = BackupAddrMode;
  1989. AddrModeInsts.resize(OldSize);
  1990. DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
  1991. TPT.rollback(LastKnownGood);
  1992. return false;
  1993. }
  1994. return true;
  1995. }
  1996. }
  1997. return false;
  1998. }
  1999. /// MatchAddr - If we can, try to add the value of 'Addr' into the current
  2000. /// addressing mode. If Addr can't be added to AddrMode this returns false and
  2001. /// leaves AddrMode unmodified. This assumes that Addr is either a pointer type
  2002. /// or intptr_t for the target.
  2003. ///
  2004. bool AddressingModeMatcher::MatchAddr(Value *Addr, unsigned Depth) {
  2005. // Start a transaction at this point that we will rollback if the matching
  2006. // fails.
  2007. TypePromotionTransaction::ConstRestorationPt LastKnownGood =
  2008. TPT.getRestorationPoint();
  2009. if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
  2010. // Fold in immediates if legal for the target.
  2011. AddrMode.BaseOffs += CI->getSExtValue();
  2012. if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
  2013. return true;
  2014. AddrMode.BaseOffs -= CI->getSExtValue();
  2015. } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
  2016. // If this is a global variable, try to fold it into the addressing mode.
  2017. if (!AddrMode.BaseGV) {
  2018. AddrMode.BaseGV = GV;
  2019. if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
  2020. return true;
  2021. AddrMode.BaseGV = nullptr;
  2022. }
  2023. } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
  2024. ExtAddrMode BackupAddrMode = AddrMode;
  2025. unsigned OldSize = AddrModeInsts.size();
  2026. // Check to see if it is possible to fold this operation.
  2027. bool MovedAway = false;
  2028. if (MatchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
  2029. // This instruction may have been move away. If so, there is nothing
  2030. // to check here.
  2031. if (MovedAway)
  2032. return true;
  2033. // Okay, it's possible to fold this. Check to see if it is actually
  2034. // *profitable* to do so. We use a simple cost model to avoid increasing
  2035. // register pressure too much.
  2036. if (I->hasOneUse() ||
  2037. IsProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
  2038. AddrModeInsts.push_back(I);
  2039. return true;
  2040. }
  2041. // It isn't profitable to do this, roll back.
  2042. //cerr << "NOT FOLDING: " << *I;
  2043. AddrMode = BackupAddrMode;
  2044. AddrModeInsts.resize(OldSize);
  2045. TPT.rollback(LastKnownGood);
  2046. }
  2047. } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
  2048. if (MatchOperationAddr(CE, CE->getOpcode(), Depth))
  2049. return true;
  2050. TPT.rollback(LastKnownGood);
  2051. } else if (isa<ConstantPointerNull>(Addr)) {
  2052. // Null pointer gets folded without affecting the addressing mode.
  2053. return true;
  2054. }
  2055. // Worse case, the target should support [reg] addressing modes. :)
  2056. if (!AddrMode.HasBaseReg) {
  2057. AddrMode.HasBaseReg = true;
  2058. AddrMode.BaseReg = Addr;
  2059. // Still check for legality in case the target supports [imm] but not [i+r].
  2060. if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
  2061. return true;
  2062. AddrMode.HasBaseReg = false;
  2063. AddrMode.BaseReg = nullptr;
  2064. }
  2065. // If the base register is already taken, see if we can do [r+r].
  2066. if (AddrMode.Scale == 0) {
  2067. AddrMode.Scale = 1;
  2068. AddrMode.ScaledReg = Addr;
  2069. if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
  2070. return true;
  2071. AddrMode.Scale = 0;
  2072. AddrMode.ScaledReg = nullptr;
  2073. }
  2074. // Couldn't match.
  2075. TPT.rollback(LastKnownGood);
  2076. return false;
  2077. }
  2078. /// IsOperandAMemoryOperand - Check to see if all uses of OpVal by the specified
  2079. /// inline asm call are due to memory operands. If so, return true, otherwise
  2080. /// return false.
  2081. static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
  2082. const TargetLowering &TLI) {
  2083. TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(ImmutableCallSite(CI));
  2084. for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
  2085. TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
  2086. // Compute the constraint code and ConstraintType to use.
  2087. TLI.ComputeConstraintToUse(OpInfo, SDValue());
  2088. // If this asm operand is our Value*, and if it isn't an indirect memory
  2089. // operand, we can't fold it!
  2090. if (OpInfo.CallOperandVal == OpVal &&
  2091. (OpInfo.ConstraintType != TargetLowering::C_Memory ||
  2092. !OpInfo.isIndirect))
  2093. return false;
  2094. }
  2095. return true;
  2096. }
  2097. /// FindAllMemoryUses - Recursively walk all the uses of I until we find a
  2098. /// memory use. If we find an obviously non-foldable instruction, return true.
  2099. /// Add the ultimately found memory instructions to MemoryUses.
  2100. static bool FindAllMemoryUses(Instruction *I,
  2101. SmallVectorImpl<std::pair<Instruction*,unsigned> > &MemoryUses,
  2102. SmallPtrSetImpl<Instruction*> &ConsideredInsts,
  2103. const TargetLowering &TLI) {
  2104. // If we already considered this instruction, we're done.
  2105. if (!ConsideredInsts.insert(I).second)
  2106. return false;
  2107. // If this is an obviously unfoldable instruction, bail out.
  2108. if (!MightBeFoldableInst(I))
  2109. return true;
  2110. // Loop over all the uses, recursively processing them.
  2111. for (Use &U : I->uses()) {
  2112. Instruction *UserI = cast<Instruction>(U.getUser());
  2113. if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
  2114. MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
  2115. continue;
  2116. }
  2117. if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
  2118. unsigned opNo = U.getOperandNo();
  2119. if (opNo == 0) return true; // Storing addr, not into addr.
  2120. MemoryUses.push_back(std::make_pair(SI, opNo));
  2121. continue;
  2122. }
  2123. if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
  2124. InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
  2125. if (!IA) return true;
  2126. // If this is a memory operand, we're cool, otherwise bail out.
  2127. if (!IsOperandAMemoryOperand(CI, IA, I, TLI))
  2128. return true;
  2129. continue;
  2130. }
  2131. if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TLI))
  2132. return true;
  2133. }
  2134. return false;
  2135. }
  2136. /// ValueAlreadyLiveAtInst - Retrn true if Val is already known to be live at
  2137. /// the use site that we're folding it into. If so, there is no cost to
  2138. /// include it in the addressing mode. KnownLive1 and KnownLive2 are two values
  2139. /// that we know are live at the instruction already.
  2140. bool AddressingModeMatcher::ValueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
  2141. Value *KnownLive2) {
  2142. // If Val is either of the known-live values, we know it is live!
  2143. if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
  2144. return true;
  2145. // All values other than instructions and arguments (e.g. constants) are live.
  2146. if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
  2147. // If Val is a constant sized alloca in the entry block, it is live, this is
  2148. // true because it is just a reference to the stack/frame pointer, which is
  2149. // live for the whole function.
  2150. if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
  2151. if (AI->isStaticAlloca())
  2152. return true;
  2153. // Check to see if this value is already used in the memory instruction's
  2154. // block. If so, it's already live into the block at the very least, so we
  2155. // can reasonably fold it.
  2156. return Val->isUsedInBasicBlock(MemoryInst->getParent());
  2157. }
  2158. /// IsProfitableToFoldIntoAddressingMode - It is possible for the addressing
  2159. /// mode of the machine to fold the specified instruction into a load or store
  2160. /// that ultimately uses it. However, the specified instruction has multiple
  2161. /// uses. Given this, it may actually increase register pressure to fold it
  2162. /// into the load. For example, consider this code:
  2163. ///
  2164. /// X = ...
  2165. /// Y = X+1
  2166. /// use(Y) -> nonload/store
  2167. /// Z = Y+1
  2168. /// load Z
  2169. ///
  2170. /// In this case, Y has multiple uses, and can be folded into the load of Z
  2171. /// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
  2172. /// be live at the use(Y) line. If we don't fold Y into load Z, we use one
  2173. /// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
  2174. /// number of computations either.
  2175. ///
  2176. /// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
  2177. /// X was live across 'load Z' for other reasons, we actually *would* want to
  2178. /// fold the addressing mode in the Z case. This would make Y die earlier.
  2179. bool AddressingModeMatcher::
  2180. IsProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
  2181. ExtAddrMode &AMAfter) {
  2182. if (IgnoreProfitability) return true;
  2183. // AMBefore is the addressing mode before this instruction was folded into it,
  2184. // and AMAfter is the addressing mode after the instruction was folded. Get
  2185. // the set of registers referenced by AMAfter and subtract out those
  2186. // referenced by AMBefore: this is the set of values which folding in this
  2187. // address extends the lifetime of.
  2188. //
  2189. // Note that there are only two potential values being referenced here,
  2190. // BaseReg and ScaleReg (global addresses are always available, as are any
  2191. // folded immediates).
  2192. Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
  2193. // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
  2194. // lifetime wasn't extended by adding this instruction.
  2195. if (ValueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
  2196. BaseReg = nullptr;
  2197. if (ValueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
  2198. ScaledReg = nullptr;
  2199. // If folding this instruction (and it's subexprs) didn't extend any live
  2200. // ranges, we're ok with it.
  2201. if (!BaseReg && !ScaledReg)
  2202. return true;
  2203. // If all uses of this instruction are ultimately load/store/inlineasm's,
  2204. // check to see if their addressing modes will include this instruction. If
  2205. // so, we can fold it into all uses, so it doesn't matter if it has multiple
  2206. // uses.
  2207. SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
  2208. SmallPtrSet<Instruction*, 16> ConsideredInsts;
  2209. if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI))
  2210. return false; // Has a non-memory, non-foldable use!
  2211. // Now that we know that all uses of this instruction are part of a chain of
  2212. // computation involving only operations that could theoretically be folded
  2213. // into a memory use, loop over each of these uses and see if they could
  2214. // *actually* fold the instruction.
  2215. SmallVector<Instruction*, 32> MatchedAddrModeInsts;
  2216. for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
  2217. Instruction *User = MemoryUses[i].first;
  2218. unsigned OpNo = MemoryUses[i].second;
  2219. // Get the access type of this use. If the use isn't a pointer, we don't
  2220. // know what it accesses.
  2221. Value *Address = User->getOperand(OpNo);
  2222. if (!Address->getType()->isPointerTy())
  2223. return false;
  2224. Type *AddressAccessTy = Address->getType()->getPointerElementType();
  2225. // Do a match against the root of this address, ignoring profitability. This
  2226. // will tell us if the addressing mode for the memory operation will
  2227. // *actually* cover the shared instruction.
  2228. ExtAddrMode Result;
  2229. TypePromotionTransaction::ConstRestorationPt LastKnownGood =
  2230. TPT.getRestorationPoint();
  2231. AddressingModeMatcher Matcher(MatchedAddrModeInsts, TLI, AddressAccessTy,
  2232. MemoryInst, Result, InsertedTruncs,
  2233. PromotedInsts, TPT);
  2234. Matcher.IgnoreProfitability = true;
  2235. bool Success = Matcher.MatchAddr(Address, 0);
  2236. (void)Success; assert(Success && "Couldn't select *anything*?");
  2237. // The match was to check the profitability, the changes made are not
  2238. // part of the original matcher. Therefore, they should be dropped
  2239. // otherwise the original matcher will not present the right state.
  2240. TPT.rollback(LastKnownGood);
  2241. // If the match didn't cover I, then it won't be shared by it.
  2242. if (std::find(MatchedAddrModeInsts.begin(), MatchedAddrModeInsts.end(),
  2243. I) == MatchedAddrModeInsts.end())
  2244. return false;
  2245. MatchedAddrModeInsts.clear();
  2246. }
  2247. return true;
  2248. }
  2249. } // end anonymous namespace
  2250. /// IsNonLocalValue - Return true if the specified values are defined in a
  2251. /// different basic block than BB.
  2252. static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
  2253. if (Instruction *I = dyn_cast<Instruction>(V))
  2254. return I->getParent() != BB;
  2255. return false;
  2256. }
  2257. /// OptimizeMemoryInst - Load and Store Instructions often have
  2258. /// addressing modes that can do significant amounts of computation. As such,
  2259. /// instruction selection will try to get the load or store to do as much
  2260. /// computation as possible for the program. The problem is that isel can only
  2261. /// see within a single block. As such, we sink as much legal addressing mode
  2262. /// stuff into the block as possible.
  2263. ///
  2264. /// This method is used to optimize both load/store and inline asms with memory
  2265. /// operands.
  2266. bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
  2267. Type *AccessTy) {
  2268. Value *Repl = Addr;
  2269. // Try to collapse single-value PHI nodes. This is necessary to undo
  2270. // unprofitable PRE transformations.
  2271. SmallVector<Value*, 8> worklist;
  2272. SmallPtrSet<Value*, 16> Visited;
  2273. worklist.push_back(Addr);
  2274. // Use a worklist to iteratively look through PHI nodes, and ensure that
  2275. // the addressing mode obtained from the non-PHI roots of the graph
  2276. // are equivalent.
  2277. Value *Consensus = nullptr;
  2278. unsigned NumUsesConsensus = 0;
  2279. bool IsNumUsesConsensusValid = false;
  2280. SmallVector<Instruction*, 16> AddrModeInsts;
  2281. ExtAddrMode AddrMode;
  2282. TypePromotionTransaction TPT;
  2283. TypePromotionTransaction::ConstRestorationPt LastKnownGood =
  2284. TPT.getRestorationPoint();
  2285. while (!worklist.empty()) {
  2286. Value *V = worklist.back();
  2287. worklist.pop_back();
  2288. // Break use-def graph loops.
  2289. if (!Visited.insert(V).second) {
  2290. Consensus = nullptr;
  2291. break;
  2292. }
  2293. // For a PHI node, push all of its incoming values.
  2294. if (PHINode *P = dyn_cast<PHINode>(V)) {
  2295. for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i)
  2296. worklist.push_back(P->getIncomingValue(i));
  2297. continue;
  2298. }
  2299. // For non-PHIs, determine the addressing mode being computed.
  2300. SmallVector<Instruction*, 16> NewAddrModeInsts;
  2301. ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
  2302. V, AccessTy, MemoryInst, NewAddrModeInsts, *TLI, InsertedTruncsSet,
  2303. PromotedInsts, TPT);
  2304. // This check is broken into two cases with very similar code to avoid using
  2305. // getNumUses() as much as possible. Some values have a lot of uses, so
  2306. // calling getNumUses() unconditionally caused a significant compile-time
  2307. // regression.
  2308. if (!Consensus) {
  2309. Consensus = V;
  2310. AddrMode = NewAddrMode;
  2311. AddrModeInsts = NewAddrModeInsts;
  2312. continue;
  2313. } else if (NewAddrMode == AddrMode) {
  2314. if (!IsNumUsesConsensusValid) {
  2315. NumUsesConsensus = Consensus->getNumUses();
  2316. IsNumUsesConsensusValid = true;
  2317. }
  2318. // Ensure that the obtained addressing mode is equivalent to that obtained
  2319. // for all other roots of the PHI traversal. Also, when choosing one
  2320. // such root as representative, select the one with the most uses in order
  2321. // to keep the cost modeling heuristics in AddressingModeMatcher
  2322. // applicable.
  2323. unsigned NumUses = V->getNumUses();
  2324. if (NumUses > NumUsesConsensus) {
  2325. Consensus = V;
  2326. NumUsesConsensus = NumUses;
  2327. AddrModeInsts = NewAddrModeInsts;
  2328. }
  2329. continue;
  2330. }
  2331. Consensus = nullptr;
  2332. break;
  2333. }
  2334. // If the addressing mode couldn't be determined, or if multiple different
  2335. // ones were determined, bail out now.
  2336. if (!Consensus) {
  2337. TPT.rollback(LastKnownGood);
  2338. return false;
  2339. }
  2340. TPT.commit();
  2341. // Check to see if any of the instructions supersumed by this addr mode are
  2342. // non-local to I's BB.
  2343. bool AnyNonLocal = false;
  2344. for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
  2345. if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
  2346. AnyNonLocal = true;
  2347. break;
  2348. }
  2349. }
  2350. // If all the instructions matched are already in this BB, don't do anything.
  2351. if (!AnyNonLocal) {
  2352. DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
  2353. return false;
  2354. }
  2355. // Insert this computation right after this user. Since our caller is
  2356. // scanning from the top of the BB to the bottom, reuse of the expr are
  2357. // guaranteed to happen later.
  2358. IRBuilder<> Builder(MemoryInst);
  2359. // Now that we determined the addressing expression we want to use and know
  2360. // that we have to sink it into this block. Check to see if we have already
  2361. // done this for some other load/store instr in this block. If so, reuse the
  2362. // computation.
  2363. Value *&SunkAddr = SunkAddrs[Addr];
  2364. if (SunkAddr) {
  2365. DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
  2366. << *MemoryInst << "\n");
  2367. if (SunkAddr->getType() != Addr->getType())
  2368. SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
  2369. } else if (AddrSinkUsingGEPs || (!AddrSinkUsingGEPs.getNumOccurrences() &&
  2370. TM && TM->getSubtarget<TargetSubtargetInfo>().useAA())) {
  2371. // By default, we use the GEP-based method when AA is used later. This
  2372. // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
  2373. DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
  2374. << *MemoryInst << "\n");
  2375. Type *IntPtrTy = TLI->getDataLayout()->getIntPtrType(Addr->getType());
  2376. Value *ResultPtr = nullptr, *ResultIndex = nullptr;
  2377. // First, find the pointer.
  2378. if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
  2379. ResultPtr = AddrMode.BaseReg;
  2380. AddrMode.BaseReg = nullptr;
  2381. }
  2382. if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
  2383. // We can't add more than one pointer together, nor can we scale a
  2384. // pointer (both of which seem meaningless).
  2385. if (ResultPtr || AddrMode.Scale != 1)
  2386. return false;
  2387. ResultPtr = AddrMode.ScaledReg;
  2388. AddrMode.Scale = 0;
  2389. }
  2390. if (AddrMode.BaseGV) {
  2391. if (ResultPtr)
  2392. return false;
  2393. ResultPtr = AddrMode.BaseGV;
  2394. }
  2395. // If the real base value actually came from an inttoptr, then the matcher
  2396. // will look through it and provide only the integer value. In that case,
  2397. // use it here.
  2398. if (!ResultPtr && AddrMode.BaseReg) {
  2399. ResultPtr =
  2400. Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(), "sunkaddr");
  2401. AddrMode.BaseReg = nullptr;
  2402. } else if (!ResultPtr && AddrMode.Scale == 1) {
  2403. ResultPtr =
  2404. Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(), "sunkaddr");
  2405. AddrMode.Scale = 0;
  2406. }
  2407. if (!ResultPtr &&
  2408. !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
  2409. SunkAddr = Constant::getNullValue(Addr->getType());
  2410. } else if (!ResultPtr) {
  2411. return false;
  2412. } else {
  2413. Type *I8PtrTy =
  2414. Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace());
  2415. // Start with the base register. Do this first so that subsequent address
  2416. // matching finds it last, which will prevent it from trying to match it
  2417. // as the scaled value in case it happens to be a mul. That would be
  2418. // problematic if we've sunk a different mul for the scale, because then
  2419. // we'd end up sinking both muls.
  2420. if (AddrMode.BaseReg) {
  2421. Value *V = AddrMode.BaseReg;
  2422. if (V->getType() != IntPtrTy)
  2423. V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
  2424. ResultIndex = V;
  2425. }
  2426. // Add the scale value.
  2427. if (AddrMode.Scale) {
  2428. Value *V = AddrMode.ScaledReg;
  2429. if (V->getType() == IntPtrTy) {
  2430. // done.
  2431. } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
  2432. cast<IntegerType>(V->getType())->getBitWidth()) {
  2433. V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
  2434. } else {
  2435. // It is only safe to sign extend the BaseReg if we know that the math
  2436. // required to create it did not overflow before we extend it. Since
  2437. // the original IR value was tossed in favor of a constant back when
  2438. // the AddrMode was created we need to bail out gracefully if widths
  2439. // do not match instead of extending it.
  2440. Instruction *I = dyn_cast_or_null<Instruction>(ResultIndex);
  2441. if (I && (ResultIndex != AddrMode.BaseReg))
  2442. I->eraseFromParent();
  2443. return false;
  2444. }
  2445. if (AddrMode.Scale != 1)
  2446. V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
  2447. "sunkaddr");
  2448. if (ResultIndex)
  2449. ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
  2450. else
  2451. ResultIndex = V;
  2452. }
  2453. // Add in the Base Offset if present.
  2454. if (AddrMode.BaseOffs) {
  2455. Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
  2456. if (ResultIndex) {
  2457. // We need to add this separately from the scale above to help with
  2458. // SDAG consecutive load/store merging.
  2459. if (ResultPtr->getType() != I8PtrTy)
  2460. ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
  2461. ResultPtr = Builder.CreateGEP(ResultPtr, ResultIndex, "sunkaddr");
  2462. }
  2463. ResultIndex = V;
  2464. }
  2465. if (!ResultIndex) {
  2466. SunkAddr = ResultPtr;
  2467. } else {
  2468. if (ResultPtr->getType() != I8PtrTy)
  2469. ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
  2470. SunkAddr = Builder.CreateGEP(ResultPtr, ResultIndex, "sunkaddr");
  2471. }
  2472. if (SunkAddr->getType() != Addr->getType())
  2473. SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
  2474. }
  2475. } else {
  2476. DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
  2477. << *MemoryInst << "\n");
  2478. Type *IntPtrTy = TLI->getDataLayout()->getIntPtrType(Addr->getType());
  2479. Value *Result = nullptr;
  2480. // Start with the base register. Do this first so that subsequent address
  2481. // matching finds it last, which will prevent it from trying to match it
  2482. // as the scaled value in case it happens to be a mul. That would be
  2483. // problematic if we've sunk a different mul for the scale, because then
  2484. // we'd end up sinking both muls.
  2485. if (AddrMode.BaseReg) {
  2486. Value *V = AddrMode.BaseReg;
  2487. if (V->getType()->isPointerTy())
  2488. V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
  2489. if (V->getType() != IntPtrTy)
  2490. V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
  2491. Result = V;
  2492. }
  2493. // Add the scale value.
  2494. if (AddrMode.Scale) {
  2495. Value *V = AddrMode.ScaledReg;
  2496. if (V->getType() == IntPtrTy) {
  2497. // done.
  2498. } else if (V->getType()->isPointerTy()) {
  2499. V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
  2500. } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
  2501. cast<IntegerType>(V->getType())->getBitWidth()) {
  2502. V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
  2503. } else {
  2504. // It is only safe to sign extend the BaseReg if we know that the math
  2505. // required to create it did not overflow before we extend it. Since
  2506. // the original IR value was tossed in favor of a constant back when
  2507. // the AddrMode was created we need to bail out gracefully if widths
  2508. // do not match instead of extending it.
  2509. Instruction *I = dyn_cast_or_null<Instruction>(Result);
  2510. if (I && (Result != AddrMode.BaseReg))
  2511. I->eraseFromParent();
  2512. return false;
  2513. }
  2514. if (AddrMode.Scale != 1)
  2515. V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
  2516. "sunkaddr");
  2517. if (Result)
  2518. Result = Builder.CreateAdd(Result, V, "sunkaddr");
  2519. else
  2520. Result = V;
  2521. }
  2522. // Add in the BaseGV if present.
  2523. if (AddrMode.BaseGV) {
  2524. Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
  2525. if (Result)
  2526. Result = Builder.CreateAdd(Result, V, "sunkaddr");
  2527. else
  2528. Result = V;
  2529. }
  2530. // Add in the Base Offset if present.
  2531. if (AddrMode.BaseOffs) {
  2532. Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
  2533. if (Result)
  2534. Result = Builder.CreateAdd(Result, V, "sunkaddr");
  2535. else
  2536. Result = V;
  2537. }
  2538. if (!Result)
  2539. SunkAddr = Constant::getNullValue(Addr->getType());
  2540. else
  2541. SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
  2542. }
  2543. MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
  2544. // If we have no uses, recursively delete the value and all dead instructions
  2545. // using it.
  2546. if (Repl->use_empty()) {
  2547. // This can cause recursive deletion, which can invalidate our iterator.
  2548. // Use a WeakVH to hold onto it in case this happens.
  2549. WeakVH IterHandle(CurInstIterator);
  2550. BasicBlock *BB = CurInstIterator->getParent();
  2551. RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
  2552. if (IterHandle != CurInstIterator) {
  2553. // If the iterator instruction was recursively deleted, start over at the
  2554. // start of the block.
  2555. CurInstIterator = BB->begin();
  2556. SunkAddrs.clear();
  2557. }
  2558. }
  2559. ++NumMemoryInsts;
  2560. return true;
  2561. }
  2562. /// OptimizeInlineAsmInst - If there are any memory operands, use
  2563. /// OptimizeMemoryInst to sink their address computing into the block when
  2564. /// possible / profitable.
  2565. bool CodeGenPrepare::OptimizeInlineAsmInst(CallInst *CS) {
  2566. bool MadeChange = false;
  2567. TargetLowering::AsmOperandInfoVector
  2568. TargetConstraints = TLI->ParseConstraints(CS);
  2569. unsigned ArgNo = 0;
  2570. for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
  2571. TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
  2572. // Compute the constraint code and ConstraintType to use.
  2573. TLI->ComputeConstraintToUse(OpInfo, SDValue());
  2574. if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
  2575. OpInfo.isIndirect) {
  2576. Value *OpVal = CS->getArgOperand(ArgNo++);
  2577. MadeChange |= OptimizeMemoryInst(CS, OpVal, OpVal->getType());
  2578. } else if (OpInfo.Type == InlineAsm::isInput)
  2579. ArgNo++;
  2580. }
  2581. return MadeChange;
  2582. }
  2583. /// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
  2584. /// basic block as the load, unless conditions are unfavorable. This allows
  2585. /// SelectionDAG to fold the extend into the load.
  2586. ///
  2587. bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *I) {
  2588. // Look for a load being extended.
  2589. LoadInst *LI = dyn_cast<LoadInst>(I->getOperand(0));
  2590. if (!LI) return false;
  2591. // If they're already in the same block, there's nothing to do.
  2592. if (LI->getParent() == I->getParent())
  2593. return false;
  2594. EVT VT = TLI->getValueType(I->getType());
  2595. EVT LoadVT = TLI->getValueType(LI->getType());
  2596. // If the load has other users and the truncate is not free, this probably
  2597. // isn't worthwhile.
  2598. if (!LI->hasOneUse() && TLI &&
  2599. (TLI->isTypeLegal(LoadVT) || !TLI->isTypeLegal(VT)) &&
  2600. !TLI->isTruncateFree(I->getType(), LI->getType()))
  2601. return false;
  2602. // Check whether the target supports casts folded into loads.
  2603. unsigned LType;
  2604. if (isa<ZExtInst>(I))
  2605. LType = ISD::ZEXTLOAD;
  2606. else {
  2607. assert(isa<SExtInst>(I) && "Unexpected ext type!");
  2608. LType = ISD::SEXTLOAD;
  2609. }
  2610. if (TLI && !TLI->isLoadExtLegal(LType, LoadVT))
  2611. return false;
  2612. // Move the extend into the same block as the load, so that SelectionDAG
  2613. // can fold it.
  2614. I->removeFromParent();
  2615. I->insertAfter(LI);
  2616. ++NumExtsMoved;
  2617. return true;
  2618. }
  2619. bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
  2620. BasicBlock *DefBB = I->getParent();
  2621. // If the result of a {s|z}ext and its source are both live out, rewrite all
  2622. // other uses of the source with result of extension.
  2623. Value *Src = I->getOperand(0);
  2624. if (Src->hasOneUse())
  2625. return false;
  2626. // Only do this xform if truncating is free.
  2627. if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
  2628. return false;
  2629. // Only safe to perform the optimization if the source is also defined in
  2630. // this block.
  2631. if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
  2632. return false;
  2633. bool DefIsLiveOut = false;
  2634. for (User *U : I->users()) {
  2635. Instruction *UI = cast<Instruction>(U);
  2636. // Figure out which BB this ext is used in.
  2637. BasicBlock *UserBB = UI->getParent();
  2638. if (UserBB == DefBB) continue;
  2639. DefIsLiveOut = true;
  2640. break;
  2641. }
  2642. if (!DefIsLiveOut)
  2643. return false;
  2644. // Make sure none of the uses are PHI nodes.
  2645. for (User *U : Src->users()) {
  2646. Instruction *UI = cast<Instruction>(U);
  2647. BasicBlock *UserBB = UI->getParent();
  2648. if (UserBB == DefBB) continue;
  2649. // Be conservative. We don't want this xform to end up introducing
  2650. // reloads just before load / store instructions.
  2651. if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
  2652. return false;
  2653. }
  2654. // InsertedTruncs - Only insert one trunc in each block once.
  2655. DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
  2656. bool MadeChange = false;
  2657. for (Use &U : Src->uses()) {
  2658. Instruction *User = cast<Instruction>(U.getUser());
  2659. // Figure out which BB this ext is used in.
  2660. BasicBlock *UserBB = User->getParent();
  2661. if (UserBB == DefBB) continue;
  2662. // Both src and def are live in this block. Rewrite the use.
  2663. Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
  2664. if (!InsertedTrunc) {
  2665. BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
  2666. InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
  2667. InsertedTruncsSet.insert(InsertedTrunc);
  2668. }
  2669. // Replace a use of the {s|z}ext source with a use of the result.
  2670. U = InsertedTrunc;
  2671. ++NumExtUses;
  2672. MadeChange = true;
  2673. }
  2674. return MadeChange;
  2675. }
  2676. /// isFormingBranchFromSelectProfitable - Returns true if a SelectInst should be
  2677. /// turned into an explicit branch.
  2678. static bool isFormingBranchFromSelectProfitable(SelectInst *SI) {
  2679. // FIXME: This should use the same heuristics as IfConversion to determine
  2680. // whether a select is better represented as a branch. This requires that
  2681. // branch probability metadata is preserved for the select, which is not the
  2682. // case currently.
  2683. CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
  2684. // If the branch is predicted right, an out of order CPU can avoid blocking on
  2685. // the compare. Emit cmovs on compares with a memory operand as branches to
  2686. // avoid stalls on the load from memory. If the compare has more than one use
  2687. // there's probably another cmov or setcc around so it's not worth emitting a
  2688. // branch.
  2689. if (!Cmp)
  2690. return false;
  2691. Value *CmpOp0 = Cmp->getOperand(0);
  2692. Value *CmpOp1 = Cmp->getOperand(1);
  2693. // We check that the memory operand has one use to avoid uses of the loaded
  2694. // value directly after the compare, making branches unprofitable.
  2695. return Cmp->hasOneUse() &&
  2696. ((isa<LoadInst>(CmpOp0) && CmpOp0->hasOneUse()) ||
  2697. (isa<LoadInst>(CmpOp1) && CmpOp1->hasOneUse()));
  2698. }
  2699. /// If we have a SelectInst that will likely profit from branch prediction,
  2700. /// turn it into a branch.
  2701. bool CodeGenPrepare::OptimizeSelectInst(SelectInst *SI) {
  2702. bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
  2703. // Can we convert the 'select' to CF ?
  2704. if (DisableSelectToBranch || OptSize || !TLI || VectorCond)
  2705. return false;
  2706. TargetLowering::SelectSupportKind SelectKind;
  2707. if (VectorCond)
  2708. SelectKind = TargetLowering::VectorMaskSelect;
  2709. else if (SI->getType()->isVectorTy())
  2710. SelectKind = TargetLowering::ScalarCondVectorVal;
  2711. else
  2712. SelectKind = TargetLowering::ScalarValSelect;
  2713. // Do we have efficient codegen support for this kind of 'selects' ?
  2714. if (TLI->isSelectSupported(SelectKind)) {
  2715. // We have efficient codegen support for the select instruction.
  2716. // Check if it is profitable to keep this 'select'.
  2717. if (!TLI->isPredictableSelectExpensive() ||
  2718. !isFormingBranchFromSelectProfitable(SI))
  2719. return false;
  2720. }
  2721. ModifiedDT = true;
  2722. // First, we split the block containing the select into 2 blocks.
  2723. BasicBlock *StartBlock = SI->getParent();
  2724. BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(SI));
  2725. BasicBlock *NextBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
  2726. // Create a new block serving as the landing pad for the branch.
  2727. BasicBlock *SmallBlock = BasicBlock::Create(SI->getContext(), "select.mid",
  2728. NextBlock->getParent(), NextBlock);
  2729. // Move the unconditional branch from the block with the select in it into our
  2730. // landing pad block.
  2731. StartBlock->getTerminator()->eraseFromParent();
  2732. BranchInst::Create(NextBlock, SmallBlock);
  2733. // Insert the real conditional branch based on the original condition.
  2734. BranchInst::Create(NextBlock, SmallBlock, SI->getCondition(), SI);
  2735. // The select itself is replaced with a PHI Node.
  2736. PHINode *PN = PHINode::Create(SI->getType(), 2, "", NextBlock->begin());
  2737. PN->takeName(SI);
  2738. PN->addIncoming(SI->getTrueValue(), StartBlock);
  2739. PN->addIncoming(SI->getFalseValue(), SmallBlock);
  2740. SI->replaceAllUsesWith(PN);
  2741. SI->eraseFromParent();
  2742. // Instruct OptimizeBlock to skip to the next block.
  2743. CurInstIterator = StartBlock->end();
  2744. ++NumSelectsExpanded;
  2745. return true;
  2746. }
  2747. static bool isBroadcastShuffle(ShuffleVectorInst *SVI) {
  2748. SmallVector<int, 16> Mask(SVI->getShuffleMask());
  2749. int SplatElem = -1;
  2750. for (unsigned i = 0; i < Mask.size(); ++i) {
  2751. if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem)
  2752. return false;
  2753. SplatElem = Mask[i];
  2754. }
  2755. return true;
  2756. }
  2757. /// Some targets have expensive vector shifts if the lanes aren't all the same
  2758. /// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases
  2759. /// it's often worth sinking a shufflevector splat down to its use so that
  2760. /// codegen can spot all lanes are identical.
  2761. bool CodeGenPrepare::OptimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
  2762. BasicBlock *DefBB = SVI->getParent();
  2763. // Only do this xform if variable vector shifts are particularly expensive.
  2764. if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType()))
  2765. return false;
  2766. // We only expect better codegen by sinking a shuffle if we can recognise a
  2767. // constant splat.
  2768. if (!isBroadcastShuffle(SVI))
  2769. return false;
  2770. // InsertedShuffles - Only insert a shuffle in each block once.
  2771. DenseMap<BasicBlock*, Instruction*> InsertedShuffles;
  2772. bool MadeChange = false;
  2773. for (User *U : SVI->users()) {
  2774. Instruction *UI = cast<Instruction>(U);
  2775. // Figure out which BB this ext is used in.
  2776. BasicBlock *UserBB = UI->getParent();
  2777. if (UserBB == DefBB) continue;
  2778. // For now only apply this when the splat is used by a shift instruction.
  2779. if (!UI->isShift()) continue;
  2780. // Everything checks out, sink the shuffle if the user's block doesn't
  2781. // already have a copy.
  2782. Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
  2783. if (!InsertedShuffle) {
  2784. BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
  2785. InsertedShuffle = new ShuffleVectorInst(SVI->getOperand(0),
  2786. SVI->getOperand(1),
  2787. SVI->getOperand(2), "", InsertPt);
  2788. }
  2789. UI->replaceUsesOfWith(SVI, InsertedShuffle);
  2790. MadeChange = true;
  2791. }
  2792. // If we removed all uses, nuke the shuffle.
  2793. if (SVI->use_empty()) {
  2794. SVI->eraseFromParent();
  2795. MadeChange = true;
  2796. }
  2797. return MadeChange;
  2798. }
  2799. namespace {
  2800. /// \brief Helper class to promote a scalar operation to a vector one.
  2801. /// This class is used to move downward extractelement transition.
  2802. /// E.g.,
  2803. /// a = vector_op <2 x i32>
  2804. /// b = extractelement <2 x i32> a, i32 0
  2805. /// c = scalar_op b
  2806. /// store c
  2807. ///
  2808. /// =>
  2809. /// a = vector_op <2 x i32>
  2810. /// c = vector_op a (equivalent to scalar_op on the related lane)
  2811. /// * d = extractelement <2 x i32> c, i32 0
  2812. /// * store d
  2813. /// Assuming both extractelement and store can be combine, we get rid of the
  2814. /// transition.
  2815. class VectorPromoteHelper {
  2816. /// Used to perform some checks on the legality of vector operations.
  2817. const TargetLowering &TLI;
  2818. /// Used to estimated the cost of the promoted chain.
  2819. const TargetTransformInfo &TTI;
  2820. /// The transition being moved downwards.
  2821. Instruction *Transition;
  2822. /// The sequence of instructions to be promoted.
  2823. SmallVector<Instruction *, 4> InstsToBePromoted;
  2824. /// Cost of combining a store and an extract.
  2825. unsigned StoreExtractCombineCost;
  2826. /// Instruction that will be combined with the transition.
  2827. Instruction *CombineInst;
  2828. /// \brief The instruction that represents the current end of the transition.
  2829. /// Since we are faking the promotion until we reach the end of the chain
  2830. /// of computation, we need a way to get the current end of the transition.
  2831. Instruction *getEndOfTransition() const {
  2832. if (InstsToBePromoted.empty())
  2833. return Transition;
  2834. return InstsToBePromoted.back();
  2835. }
  2836. /// \brief Return the index of the original value in the transition.
  2837. /// E.g., for "extractelement <2 x i32> c, i32 1" the original value,
  2838. /// c, is at index 0.
  2839. unsigned getTransitionOriginalValueIdx() const {
  2840. assert(isa<ExtractElementInst>(Transition) &&
  2841. "Other kind of transitions are not supported yet");
  2842. return 0;
  2843. }
  2844. /// \brief Return the index of the index in the transition.
  2845. /// E.g., for "extractelement <2 x i32> c, i32 0" the index
  2846. /// is at index 1.
  2847. unsigned getTransitionIdx() const {
  2848. assert(isa<ExtractElementInst>(Transition) &&
  2849. "Other kind of transitions are not supported yet");
  2850. return 1;
  2851. }
  2852. /// \brief Get the type of the transition.
  2853. /// This is the type of the original value.
  2854. /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the
  2855. /// transition is <2 x i32>.
  2856. Type *getTransitionType() const {
  2857. return Transition->getOperand(getTransitionOriginalValueIdx())->getType();
  2858. }
  2859. /// \brief Promote \p ToBePromoted by moving \p Def downward through.
  2860. /// I.e., we have the following sequence:
  2861. /// Def = Transition <ty1> a to <ty2>
  2862. /// b = ToBePromoted <ty2> Def, ...
  2863. /// =>
  2864. /// b = ToBePromoted <ty1> a, ...
  2865. /// Def = Transition <ty1> ToBePromoted to <ty2>
  2866. void promoteImpl(Instruction *ToBePromoted);
  2867. /// \brief Check whether or not it is profitable to promote all the
  2868. /// instructions enqueued to be promoted.
  2869. bool isProfitableToPromote() {
  2870. Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx());
  2871. unsigned Index = isa<ConstantInt>(ValIdx)
  2872. ? cast<ConstantInt>(ValIdx)->getZExtValue()
  2873. : -1;
  2874. Type *PromotedType = getTransitionType();
  2875. StoreInst *ST = cast<StoreInst>(CombineInst);
  2876. unsigned AS = ST->getPointerAddressSpace();
  2877. unsigned Align = ST->getAlignment();
  2878. // Check if this store is supported.
  2879. if (!TLI.allowsMisalignedMemoryAccesses(
  2880. TLI.getValueType(ST->getValueOperand()->getType()), AS, Align)) {
  2881. // If this is not supported, there is no way we can combine
  2882. // the extract with the store.
  2883. return false;
  2884. }
  2885. // The scalar chain of computation has to pay for the transition
  2886. // scalar to vector.
  2887. // The vector chain has to account for the combining cost.
  2888. uint64_t ScalarCost =
  2889. TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index);
  2890. uint64_t VectorCost = StoreExtractCombineCost;
  2891. for (const auto &Inst : InstsToBePromoted) {
  2892. // Compute the cost.
  2893. // By construction, all instructions being promoted are arithmetic ones.
  2894. // Moreover, one argument is a constant that can be viewed as a splat
  2895. // constant.
  2896. Value *Arg0 = Inst->getOperand(0);
  2897. bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) ||
  2898. isa<ConstantFP>(Arg0);
  2899. TargetTransformInfo::OperandValueKind Arg0OVK =
  2900. IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
  2901. : TargetTransformInfo::OK_AnyValue;
  2902. TargetTransformInfo::OperandValueKind Arg1OVK =
  2903. !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
  2904. : TargetTransformInfo::OK_AnyValue;
  2905. ScalarCost += TTI.getArithmeticInstrCost(
  2906. Inst->getOpcode(), Inst->getType(), Arg0OVK, Arg1OVK);
  2907. VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType,
  2908. Arg0OVK, Arg1OVK);
  2909. }
  2910. DEBUG(dbgs() << "Estimated cost of computation to be promoted:\nScalar: "
  2911. << ScalarCost << "\nVector: " << VectorCost << '\n');
  2912. return ScalarCost > VectorCost;
  2913. }
  2914. /// \brief Generate a constant vector with \p Val with the same
  2915. /// number of elements as the transition.
  2916. /// \p UseSplat defines whether or not \p Val should be replicated
  2917. /// accross the whole vector.
  2918. /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>,
  2919. /// otherwise we generate a vector with as many undef as possible:
  2920. /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only
  2921. /// used at the index of the extract.
  2922. Value *getConstantVector(Constant *Val, bool UseSplat) const {
  2923. unsigned ExtractIdx = UINT_MAX;
  2924. if (!UseSplat) {
  2925. // If we cannot determine where the constant must be, we have to
  2926. // use a splat constant.
  2927. Value *ValExtractIdx = Transition->getOperand(getTransitionIdx());
  2928. if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx))
  2929. ExtractIdx = CstVal->getSExtValue();
  2930. else
  2931. UseSplat = true;
  2932. }
  2933. unsigned End = getTransitionType()->getVectorNumElements();
  2934. if (UseSplat)
  2935. return ConstantVector::getSplat(End, Val);
  2936. SmallVector<Constant *, 4> ConstVec;
  2937. UndefValue *UndefVal = UndefValue::get(Val->getType());
  2938. for (unsigned Idx = 0; Idx != End; ++Idx) {
  2939. if (Idx == ExtractIdx)
  2940. ConstVec.push_back(Val);
  2941. else
  2942. ConstVec.push_back(UndefVal);
  2943. }
  2944. return ConstantVector::get(ConstVec);
  2945. }
  2946. /// \brief Check if promoting to a vector type an operand at \p OperandIdx
  2947. /// in \p Use can trigger undefined behavior.
  2948. static bool canCauseUndefinedBehavior(const Instruction *Use,
  2949. unsigned OperandIdx) {
  2950. // This is not safe to introduce undef when the operand is on
  2951. // the right hand side of a division-like instruction.
  2952. if (OperandIdx != 1)
  2953. return false;
  2954. switch (Use->getOpcode()) {
  2955. default:
  2956. return false;
  2957. case Instruction::SDiv:
  2958. case Instruction::UDiv:
  2959. case Instruction::SRem:
  2960. case Instruction::URem:
  2961. return true;
  2962. case Instruction::FDiv:
  2963. case Instruction::FRem:
  2964. return !Use->hasNoNaNs();
  2965. }
  2966. llvm_unreachable(nullptr);
  2967. }
  2968. public:
  2969. VectorPromoteHelper(const TargetLowering &TLI, const TargetTransformInfo &TTI,
  2970. Instruction *Transition, unsigned CombineCost)
  2971. : TLI(TLI), TTI(TTI), Transition(Transition),
  2972. StoreExtractCombineCost(CombineCost), CombineInst(nullptr) {
  2973. assert(Transition && "Do not know how to promote null");
  2974. }
  2975. /// \brief Check if we can promote \p ToBePromoted to \p Type.
  2976. bool canPromote(const Instruction *ToBePromoted) const {
  2977. // We could support CastInst too.
  2978. return isa<BinaryOperator>(ToBePromoted);
  2979. }
  2980. /// \brief Check if it is profitable to promote \p ToBePromoted
  2981. /// by moving downward the transition through.
  2982. bool shouldPromote(const Instruction *ToBePromoted) const {
  2983. // Promote only if all the operands can be statically expanded.
  2984. // Indeed, we do not want to introduce any new kind of transitions.
  2985. for (const Use &U : ToBePromoted->operands()) {
  2986. const Value *Val = U.get();
  2987. if (Val == getEndOfTransition()) {
  2988. // If the use is a division and the transition is on the rhs,
  2989. // we cannot promote the operation, otherwise we may create a
  2990. // division by zero.
  2991. if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()))
  2992. return false;
  2993. continue;
  2994. }
  2995. if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) &&
  2996. !isa<ConstantFP>(Val))
  2997. return false;
  2998. }
  2999. // Check that the resulting operation is legal.
  3000. int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode());
  3001. if (!ISDOpcode)
  3002. return false;
  3003. return StressStoreExtract ||
  3004. TLI.isOperationLegalOrCustom(
  3005. ISDOpcode, TLI.getValueType(getTransitionType(), true));
  3006. }
  3007. /// \brief Check whether or not \p Use can be combined
  3008. /// with the transition.
  3009. /// I.e., is it possible to do Use(Transition) => AnotherUse?
  3010. bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); }
  3011. /// \brief Record \p ToBePromoted as part of the chain to be promoted.
  3012. void enqueueForPromotion(Instruction *ToBePromoted) {
  3013. InstsToBePromoted.push_back(ToBePromoted);
  3014. }
  3015. /// \brief Set the instruction that will be combined with the transition.
  3016. void recordCombineInstruction(Instruction *ToBeCombined) {
  3017. assert(canCombine(ToBeCombined) && "Unsupported instruction to combine");
  3018. CombineInst = ToBeCombined;
  3019. }
  3020. /// \brief Promote all the instructions enqueued for promotion if it is
  3021. /// is profitable.
  3022. /// \return True if the promotion happened, false otherwise.
  3023. bool promote() {
  3024. // Check if there is something to promote.
  3025. // Right now, if we do not have anything to combine with,
  3026. // we assume the promotion is not profitable.
  3027. if (InstsToBePromoted.empty() || !CombineInst)
  3028. return false;
  3029. // Check cost.
  3030. if (!StressStoreExtract && !isProfitableToPromote())
  3031. return false;
  3032. // Promote.
  3033. for (auto &ToBePromoted : InstsToBePromoted)
  3034. promoteImpl(ToBePromoted);
  3035. InstsToBePromoted.clear();
  3036. return true;
  3037. }
  3038. };
  3039. } // End of anonymous namespace.
  3040. void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) {
  3041. // At this point, we know that all the operands of ToBePromoted but Def
  3042. // can be statically promoted.
  3043. // For Def, we need to use its parameter in ToBePromoted:
  3044. // b = ToBePromoted ty1 a
  3045. // Def = Transition ty1 b to ty2
  3046. // Move the transition down.
  3047. // 1. Replace all uses of the promoted operation by the transition.
  3048. // = ... b => = ... Def.
  3049. assert(ToBePromoted->getType() == Transition->getType() &&
  3050. "The type of the result of the transition does not match "
  3051. "the final type");
  3052. ToBePromoted->replaceAllUsesWith(Transition);
  3053. // 2. Update the type of the uses.
  3054. // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def.
  3055. Type *TransitionTy = getTransitionType();
  3056. ToBePromoted->mutateType(TransitionTy);
  3057. // 3. Update all the operands of the promoted operation with promoted
  3058. // operands.
  3059. // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a.
  3060. for (Use &U : ToBePromoted->operands()) {
  3061. Value *Val = U.get();
  3062. Value *NewVal = nullptr;
  3063. if (Val == Transition)
  3064. NewVal = Transition->getOperand(getTransitionOriginalValueIdx());
  3065. else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) ||
  3066. isa<ConstantFP>(Val)) {
  3067. // Use a splat constant if it is not safe to use undef.
  3068. NewVal = getConstantVector(
  3069. cast<Constant>(Val),
  3070. isa<UndefValue>(Val) ||
  3071. canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()));
  3072. } else
  3073. assert(0 && "Did you modified shouldPromote and forgot to update this?");
  3074. ToBePromoted->setOperand(U.getOperandNo(), NewVal);
  3075. }
  3076. Transition->removeFromParent();
  3077. Transition->insertAfter(ToBePromoted);
  3078. Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
  3079. }
  3080. /// Some targets can do store(extractelement) with one instruction.
  3081. /// Try to push the extractelement towards the stores when the target
  3082. /// has this feature and this is profitable.
  3083. bool CodeGenPrepare::OptimizeExtractElementInst(Instruction *Inst) {
  3084. unsigned CombineCost = UINT_MAX;
  3085. if (DisableStoreExtract || !TLI ||
  3086. (!StressStoreExtract &&
  3087. !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(),
  3088. Inst->getOperand(1), CombineCost)))
  3089. return false;
  3090. // At this point we know that Inst is a vector to scalar transition.
  3091. // Try to move it down the def-use chain, until:
  3092. // - We can combine the transition with its single use
  3093. // => we got rid of the transition.
  3094. // - We escape the current basic block
  3095. // => we would need to check that we are moving it at a cheaper place and
  3096. // we do not do that for now.
  3097. BasicBlock *Parent = Inst->getParent();
  3098. DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n');
  3099. VectorPromoteHelper VPH(*TLI, *TTI, Inst, CombineCost);
  3100. // If the transition has more than one use, assume this is not going to be
  3101. // beneficial.
  3102. while (Inst->hasOneUse()) {
  3103. Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin());
  3104. DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n');
  3105. if (ToBePromoted->getParent() != Parent) {
  3106. DEBUG(dbgs() << "Instruction to promote is in a different block ("
  3107. << ToBePromoted->getParent()->getName()
  3108. << ") than the transition (" << Parent->getName() << ").\n");
  3109. return false;
  3110. }
  3111. if (VPH.canCombine(ToBePromoted)) {
  3112. DEBUG(dbgs() << "Assume " << *Inst << '\n'
  3113. << "will be combined with: " << *ToBePromoted << '\n');
  3114. VPH.recordCombineInstruction(ToBePromoted);
  3115. bool Changed = VPH.promote();
  3116. NumStoreExtractExposed += Changed;
  3117. return Changed;
  3118. }
  3119. DEBUG(dbgs() << "Try promoting.\n");
  3120. if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
  3121. return false;
  3122. DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n");
  3123. VPH.enqueueForPromotion(ToBePromoted);
  3124. Inst = ToBePromoted;
  3125. }
  3126. return false;
  3127. }
  3128. bool CodeGenPrepare::OptimizeInst(Instruction *I) {
  3129. if (PHINode *P = dyn_cast<PHINode>(I)) {
  3130. // It is possible for very late stage optimizations (such as SimplifyCFG)
  3131. // to introduce PHI nodes too late to be cleaned up. If we detect such a
  3132. // trivial PHI, go ahead and zap it here.
  3133. if (Value *V = SimplifyInstruction(P, TLI ? TLI->getDataLayout() : nullptr,
  3134. TLInfo, DT)) {
  3135. P->replaceAllUsesWith(V);
  3136. P->eraseFromParent();
  3137. ++NumPHIsElim;
  3138. return true;
  3139. }
  3140. return false;
  3141. }
  3142. if (CastInst *CI = dyn_cast<CastInst>(I)) {
  3143. // If the source of the cast is a constant, then this should have
  3144. // already been constant folded. The only reason NOT to constant fold
  3145. // it is if something (e.g. LSR) was careful to place the constant
  3146. // evaluation in a block other than then one that uses it (e.g. to hoist
  3147. // the address of globals out of a loop). If this is the case, we don't
  3148. // want to forward-subst the cast.
  3149. if (isa<Constant>(CI->getOperand(0)))
  3150. return false;
  3151. if (TLI && OptimizeNoopCopyExpression(CI, *TLI))
  3152. return true;
  3153. if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
  3154. /// Sink a zext or sext into its user blocks if the target type doesn't
  3155. /// fit in one register
  3156. if (TLI && TLI->getTypeAction(CI->getContext(),
  3157. TLI->getValueType(CI->getType())) ==
  3158. TargetLowering::TypeExpandInteger) {
  3159. return SinkCast(CI);
  3160. } else {
  3161. bool MadeChange = MoveExtToFormExtLoad(I);
  3162. return MadeChange | OptimizeExtUses(I);
  3163. }
  3164. }
  3165. return false;
  3166. }
  3167. if (CmpInst *CI = dyn_cast<CmpInst>(I))
  3168. if (!TLI || !TLI->hasMultipleConditionRegisters())
  3169. return OptimizeCmpExpression(CI);
  3170. if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
  3171. if (TLI)
  3172. return OptimizeMemoryInst(I, I->getOperand(0), LI->getType());
  3173. return false;
  3174. }
  3175. if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
  3176. if (TLI)
  3177. return OptimizeMemoryInst(I, SI->getOperand(1),
  3178. SI->getOperand(0)->getType());
  3179. return false;
  3180. }
  3181. BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I);
  3182. if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
  3183. BinOp->getOpcode() == Instruction::LShr)) {
  3184. ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1));
  3185. if (TLI && CI && TLI->hasExtractBitsInsn())
  3186. return OptimizeExtractBits(BinOp, CI, *TLI);
  3187. return false;
  3188. }
  3189. if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
  3190. if (GEPI->hasAllZeroIndices()) {
  3191. /// The GEP operand must be a pointer, so must its result -> BitCast
  3192. Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
  3193. GEPI->getName(), GEPI);
  3194. GEPI->replaceAllUsesWith(NC);
  3195. GEPI->eraseFromParent();
  3196. ++NumGEPsElim;
  3197. OptimizeInst(NC);
  3198. return true;
  3199. }
  3200. return false;
  3201. }
  3202. if (CallInst *CI = dyn_cast<CallInst>(I))
  3203. return OptimizeCallInst(CI);
  3204. if (SelectInst *SI = dyn_cast<SelectInst>(I))
  3205. return OptimizeSelectInst(SI);
  3206. if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I))
  3207. return OptimizeShuffleVectorInst(SVI);
  3208. if (isa<ExtractElementInst>(I))
  3209. return OptimizeExtractElementInst(I);
  3210. return false;
  3211. }
  3212. // In this pass we look for GEP and cast instructions that are used
  3213. // across basic blocks and rewrite them to improve basic-block-at-a-time
  3214. // selection.
  3215. bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
  3216. SunkAddrs.clear();
  3217. bool MadeChange = false;
  3218. CurInstIterator = BB.begin();
  3219. while (CurInstIterator != BB.end())
  3220. MadeChange |= OptimizeInst(CurInstIterator++);
  3221. MadeChange |= DupRetToEnableTailCallOpts(&BB);
  3222. return MadeChange;
  3223. }
  3224. // llvm.dbg.value is far away from the value then iSel may not be able
  3225. // handle it properly. iSel will drop llvm.dbg.value if it can not
  3226. // find a node corresponding to the value.
  3227. bool CodeGenPrepare::PlaceDbgValues(Function &F) {
  3228. bool MadeChange = false;
  3229. for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
  3230. Instruction *PrevNonDbgInst = nullptr;
  3231. for (BasicBlock::iterator BI = I->begin(), BE = I->end(); BI != BE;) {
  3232. Instruction *Insn = BI; ++BI;
  3233. DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
  3234. // Leave dbg.values that refer to an alloca alone. These
  3235. // instrinsics describe the address of a variable (= the alloca)
  3236. // being taken. They should not be moved next to the alloca
  3237. // (and to the beginning of the scope), but rather stay close to
  3238. // where said address is used.
  3239. if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) {
  3240. PrevNonDbgInst = Insn;
  3241. continue;
  3242. }
  3243. Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
  3244. if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
  3245. DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
  3246. DVI->removeFromParent();
  3247. if (isa<PHINode>(VI))
  3248. DVI->insertBefore(VI->getParent()->getFirstInsertionPt());
  3249. else
  3250. DVI->insertAfter(VI);
  3251. MadeChange = true;
  3252. ++NumDbgValueMoved;
  3253. }
  3254. }
  3255. }
  3256. return MadeChange;
  3257. }
  3258. // If there is a sequence that branches based on comparing a single bit
  3259. // against zero that can be combined into a single instruction, and the
  3260. // target supports folding these into a single instruction, sink the
  3261. // mask and compare into the branch uses. Do this before OptimizeBlock ->
  3262. // OptimizeInst -> OptimizeCmpExpression, which perturbs the pattern being
  3263. // searched for.
  3264. bool CodeGenPrepare::sinkAndCmp(Function &F) {
  3265. if (!EnableAndCmpSinking)
  3266. return false;
  3267. if (!TLI || !TLI->isMaskAndBranchFoldingLegal())
  3268. return false;
  3269. bool MadeChange = false;
  3270. for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
  3271. BasicBlock *BB = I++;
  3272. // Does this BB end with the following?
  3273. // %andVal = and %val, #single-bit-set
  3274. // %icmpVal = icmp %andResult, 0
  3275. // br i1 %cmpVal label %dest1, label %dest2"
  3276. BranchInst *Brcc = dyn_cast<BranchInst>(BB->getTerminator());
  3277. if (!Brcc || !Brcc->isConditional())
  3278. continue;
  3279. ICmpInst *Cmp = dyn_cast<ICmpInst>(Brcc->getOperand(0));
  3280. if (!Cmp || Cmp->getParent() != BB)
  3281. continue;
  3282. ConstantInt *Zero = dyn_cast<ConstantInt>(Cmp->getOperand(1));
  3283. if (!Zero || !Zero->isZero())
  3284. continue;
  3285. Instruction *And = dyn_cast<Instruction>(Cmp->getOperand(0));
  3286. if (!And || And->getOpcode() != Instruction::And || And->getParent() != BB)
  3287. continue;
  3288. ConstantInt* Mask = dyn_cast<ConstantInt>(And->getOperand(1));
  3289. if (!Mask || !Mask->getUniqueInteger().isPowerOf2())
  3290. continue;
  3291. DEBUG(dbgs() << "found and; icmp ?,0; brcc\n"); DEBUG(BB->dump());
  3292. // Push the "and; icmp" for any users that are conditional branches.
  3293. // Since there can only be one branch use per BB, we don't need to keep
  3294. // track of which BBs we insert into.
  3295. for (Value::use_iterator UI = Cmp->use_begin(), E = Cmp->use_end();
  3296. UI != E; ) {
  3297. Use &TheUse = *UI;
  3298. // Find brcc use.
  3299. BranchInst *BrccUser = dyn_cast<BranchInst>(*UI);
  3300. ++UI;
  3301. if (!BrccUser || !BrccUser->isConditional())
  3302. continue;
  3303. BasicBlock *UserBB = BrccUser->getParent();
  3304. if (UserBB == BB) continue;
  3305. DEBUG(dbgs() << "found Brcc use\n");
  3306. // Sink the "and; icmp" to use.
  3307. MadeChange = true;
  3308. BinaryOperator *NewAnd =
  3309. BinaryOperator::CreateAnd(And->getOperand(0), And->getOperand(1), "",
  3310. BrccUser);
  3311. CmpInst *NewCmp =
  3312. CmpInst::Create(Cmp->getOpcode(), Cmp->getPredicate(), NewAnd, Zero,
  3313. "", BrccUser);
  3314. TheUse = NewCmp;
  3315. ++NumAndCmpsMoved;
  3316. DEBUG(BrccUser->getParent()->dump());
  3317. }
  3318. }
  3319. return MadeChange;
  3320. }
  3321. /// \brief Retrieve the probabilities of a conditional branch. Returns true on
  3322. /// success, or returns false if no or invalid metadata was found.
  3323. static bool extractBranchMetadata(BranchInst *BI,
  3324. uint64_t &ProbTrue, uint64_t &ProbFalse) {
  3325. assert(BI->isConditional() &&
  3326. "Looking for probabilities on unconditional branch?");
  3327. auto *ProfileData = BI->getMetadata(LLVMContext::MD_prof);
  3328. if (!ProfileData || ProfileData->getNumOperands() != 3)
  3329. return false;
  3330. const auto *CITrue =
  3331. mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(1));
  3332. const auto *CIFalse =
  3333. mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(2));
  3334. if (!CITrue || !CIFalse)
  3335. return false;
  3336. ProbTrue = CITrue->getValue().getZExtValue();
  3337. ProbFalse = CIFalse->getValue().getZExtValue();
  3338. return true;
  3339. }
  3340. /// \brief Scale down both weights to fit into uint32_t.
  3341. static void scaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
  3342. uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
  3343. uint32_t Scale = (NewMax / UINT32_MAX) + 1;
  3344. NewTrue = NewTrue / Scale;
  3345. NewFalse = NewFalse / Scale;
  3346. }
  3347. /// \brief Some targets prefer to split a conditional branch like:
  3348. /// \code
  3349. /// %0 = icmp ne i32 %a, 0
  3350. /// %1 = icmp ne i32 %b, 0
  3351. /// %or.cond = or i1 %0, %1
  3352. /// br i1 %or.cond, label %TrueBB, label %FalseBB
  3353. /// \endcode
  3354. /// into multiple branch instructions like:
  3355. /// \code
  3356. /// bb1:
  3357. /// %0 = icmp ne i32 %a, 0
  3358. /// br i1 %0, label %TrueBB, label %bb2
  3359. /// bb2:
  3360. /// %1 = icmp ne i32 %b, 0
  3361. /// br i1 %1, label %TrueBB, label %FalseBB
  3362. /// \endcode
  3363. /// This usually allows instruction selection to do even further optimizations
  3364. /// and combine the compare with the branch instruction. Currently this is
  3365. /// applied for targets which have "cheap" jump instructions.
  3366. ///
  3367. /// FIXME: Remove the (equivalent?) implementation in SelectionDAG.
  3368. ///
  3369. bool CodeGenPrepare::splitBranchCondition(Function &F) {
  3370. if (!TM || TM->Options.EnableFastISel != true ||
  3371. !TLI || TLI->isJumpExpensive())
  3372. return false;
  3373. bool MadeChange = false;
  3374. for (auto &BB : F) {
  3375. // Does this BB end with the following?
  3376. // %cond1 = icmp|fcmp|binary instruction ...
  3377. // %cond2 = icmp|fcmp|binary instruction ...
  3378. // %cond.or = or|and i1 %cond1, cond2
  3379. // br i1 %cond.or label %dest1, label %dest2"
  3380. BinaryOperator *LogicOp;
  3381. BasicBlock *TBB, *FBB;
  3382. if (!match(BB.getTerminator(), m_Br(m_OneUse(m_BinOp(LogicOp)), TBB, FBB)))
  3383. continue;
  3384. unsigned Opc;
  3385. Value *Cond1, *Cond2;
  3386. if (match(LogicOp, m_And(m_OneUse(m_Value(Cond1)),
  3387. m_OneUse(m_Value(Cond2)))))
  3388. Opc = Instruction::And;
  3389. else if (match(LogicOp, m_Or(m_OneUse(m_Value(Cond1)),
  3390. m_OneUse(m_Value(Cond2)))))
  3391. Opc = Instruction::Or;
  3392. else
  3393. continue;
  3394. if (!match(Cond1, m_CombineOr(m_Cmp(), m_BinOp())) ||
  3395. !match(Cond2, m_CombineOr(m_Cmp(), m_BinOp())) )
  3396. continue;
  3397. DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump());
  3398. // Create a new BB.
  3399. auto *InsertBefore = std::next(Function::iterator(BB))
  3400. .getNodePtrUnchecked();
  3401. auto TmpBB = BasicBlock::Create(BB.getContext(),
  3402. BB.getName() + ".cond.split",
  3403. BB.getParent(), InsertBefore);
  3404. // Update original basic block by using the first condition directly by the
  3405. // branch instruction and removing the no longer needed and/or instruction.
  3406. auto *Br1 = cast<BranchInst>(BB.getTerminator());
  3407. Br1->setCondition(Cond1);
  3408. LogicOp->eraseFromParent();
  3409. // Depending on the conditon we have to either replace the true or the false
  3410. // successor of the original branch instruction.
  3411. if (Opc == Instruction::And)
  3412. Br1->setSuccessor(0, TmpBB);
  3413. else
  3414. Br1->setSuccessor(1, TmpBB);
  3415. // Fill in the new basic block.
  3416. auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB);
  3417. if (auto *I = dyn_cast<Instruction>(Cond2)) {
  3418. I->removeFromParent();
  3419. I->insertBefore(Br2);
  3420. }
  3421. // Update PHI nodes in both successors. The original BB needs to be
  3422. // replaced in one succesor's PHI nodes, because the branch comes now from
  3423. // the newly generated BB (NewBB). In the other successor we need to add one
  3424. // incoming edge to the PHI nodes, because both branch instructions target
  3425. // now the same successor. Depending on the original branch condition
  3426. // (and/or) we have to swap the successors (TrueDest, FalseDest), so that
  3427. // we perfrom the correct update for the PHI nodes.
  3428. // This doesn't change the successor order of the just created branch
  3429. // instruction (or any other instruction).
  3430. if (Opc == Instruction::Or)
  3431. std::swap(TBB, FBB);
  3432. // Replace the old BB with the new BB.
  3433. for (auto &I : *TBB) {
  3434. PHINode *PN = dyn_cast<PHINode>(&I);
  3435. if (!PN)
  3436. break;
  3437. int i;
  3438. while ((i = PN->getBasicBlockIndex(&BB)) >= 0)
  3439. PN->setIncomingBlock(i, TmpBB);
  3440. }
  3441. // Add another incoming edge form the new BB.
  3442. for (auto &I : *FBB) {
  3443. PHINode *PN = dyn_cast<PHINode>(&I);
  3444. if (!PN)
  3445. break;
  3446. auto *Val = PN->getIncomingValueForBlock(&BB);
  3447. PN->addIncoming(Val, TmpBB);
  3448. }
  3449. // Update the branch weights (from SelectionDAGBuilder::
  3450. // FindMergedConditions).
  3451. if (Opc == Instruction::Or) {
  3452. // Codegen X | Y as:
  3453. // BB1:
  3454. // jmp_if_X TBB
  3455. // jmp TmpBB
  3456. // TmpBB:
  3457. // jmp_if_Y TBB
  3458. // jmp FBB
  3459. //
  3460. // We have flexibility in setting Prob for BB1 and Prob for NewBB.
  3461. // The requirement is that
  3462. // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
  3463. // = TrueProb for orignal BB.
  3464. // Assuming the orignal weights are A and B, one choice is to set BB1's
  3465. // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
  3466. // assumes that
  3467. // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
  3468. // Another choice is to assume TrueProb for BB1 equals to TrueProb for
  3469. // TmpBB, but the math is more complicated.
  3470. uint64_t TrueWeight, FalseWeight;
  3471. if (extractBranchMetadata(Br1, TrueWeight, FalseWeight)) {
  3472. uint64_t NewTrueWeight = TrueWeight;
  3473. uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight;
  3474. scaleWeights(NewTrueWeight, NewFalseWeight);
  3475. Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
  3476. .createBranchWeights(TrueWeight, FalseWeight));
  3477. NewTrueWeight = TrueWeight;
  3478. NewFalseWeight = 2 * FalseWeight;
  3479. scaleWeights(NewTrueWeight, NewFalseWeight);
  3480. Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
  3481. .createBranchWeights(TrueWeight, FalseWeight));
  3482. }
  3483. } else {
  3484. // Codegen X & Y as:
  3485. // BB1:
  3486. // jmp_if_X TmpBB
  3487. // jmp FBB
  3488. // TmpBB:
  3489. // jmp_if_Y TBB
  3490. // jmp FBB
  3491. //
  3492. // This requires creation of TmpBB after CurBB.
  3493. // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
  3494. // The requirement is that
  3495. // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
  3496. // = FalseProb for orignal BB.
  3497. // Assuming the orignal weights are A and B, one choice is to set BB1's
  3498. // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
  3499. // assumes that
  3500. // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
  3501. uint64_t TrueWeight, FalseWeight;
  3502. if (extractBranchMetadata(Br1, TrueWeight, FalseWeight)) {
  3503. uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight;
  3504. uint64_t NewFalseWeight = FalseWeight;
  3505. scaleWeights(NewTrueWeight, NewFalseWeight);
  3506. Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
  3507. .createBranchWeights(TrueWeight, FalseWeight));
  3508. NewTrueWeight = 2 * TrueWeight;
  3509. NewFalseWeight = FalseWeight;
  3510. scaleWeights(NewTrueWeight, NewFalseWeight);
  3511. Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
  3512. .createBranchWeights(TrueWeight, FalseWeight));
  3513. }
  3514. }
  3515. // Request DOM Tree update.
  3516. // Note: No point in getting fancy here, since the DT info is never
  3517. // available to CodeGenPrepare and the existing update code is broken
  3518. // anyways.
  3519. ModifiedDT = true;
  3520. MadeChange = true;
  3521. DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump();
  3522. TmpBB->dump());
  3523. }
  3524. return MadeChange;
  3525. }