Instructions.h 201 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- llvm/Instructions.h - Instruction subclass definitions ---*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. //
  14. // This file exposes the class definitions of all of the subclasses of the
  15. // Instruction class. This is meant to be an easy way to get access to all
  16. // instruction subclasses.
  17. //
  18. //===----------------------------------------------------------------------===//
  19. #ifndef LLVM_IR_INSTRUCTIONS_H
  20. #define LLVM_IR_INSTRUCTIONS_H
  21. #include "llvm/ADT/ArrayRef.h"
  22. #include "llvm/ADT/Bitfields.h"
  23. #include "llvm/ADT/None.h"
  24. #include "llvm/ADT/STLExtras.h"
  25. #include "llvm/ADT/SmallVector.h"
  26. #include "llvm/ADT/StringRef.h"
  27. #include "llvm/ADT/Twine.h"
  28. #include "llvm/ADT/iterator.h"
  29. #include "llvm/ADT/iterator_range.h"
  30. #include "llvm/IR/Attributes.h"
  31. #include "llvm/IR/BasicBlock.h"
  32. #include "llvm/IR/CallingConv.h"
  33. #include "llvm/IR/CFG.h"
  34. #include "llvm/IR/Constant.h"
  35. #include "llvm/IR/DerivedTypes.h"
  36. #include "llvm/IR/Function.h"
  37. #include "llvm/IR/InstrTypes.h"
  38. #include "llvm/IR/Instruction.h"
  39. #include "llvm/IR/OperandTraits.h"
  40. #include "llvm/IR/Type.h"
  41. #include "llvm/IR/Use.h"
  42. #include "llvm/IR/User.h"
  43. #include "llvm/IR/Value.h"
  44. #include "llvm/Support/AtomicOrdering.h"
  45. #include "llvm/Support/Casting.h"
  46. #include "llvm/Support/ErrorHandling.h"
  47. #include <cassert>
  48. #include <cstddef>
  49. #include <cstdint>
  50. #include <iterator>
  51. namespace llvm {
  52. class APInt;
  53. class ConstantInt;
  54. class DataLayout;
  55. class LLVMContext;
  56. //===----------------------------------------------------------------------===//
  57. // AllocaInst Class
  58. //===----------------------------------------------------------------------===//
  59. /// an instruction to allocate memory on the stack
  60. class AllocaInst : public UnaryInstruction {
  61. Type *AllocatedType;
  62. using AlignmentField = AlignmentBitfieldElementT<0>;
  63. using UsedWithInAllocaField = BoolBitfieldElementT<AlignmentField::NextBit>;
  64. using SwiftErrorField = BoolBitfieldElementT<UsedWithInAllocaField::NextBit>;
  65. static_assert(Bitfield::areContiguous<AlignmentField, UsedWithInAllocaField,
  66. SwiftErrorField>(),
  67. "Bitfields must be contiguous");
  68. protected:
  69. // Note: Instruction needs to be a friend here to call cloneImpl.
  70. friend class Instruction;
  71. AllocaInst *cloneImpl() const;
  72. public:
  73. explicit AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize,
  74. const Twine &Name, Instruction *InsertBefore);
  75. AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize,
  76. const Twine &Name, BasicBlock *InsertAtEnd);
  77. AllocaInst(Type *Ty, unsigned AddrSpace, const Twine &Name,
  78. Instruction *InsertBefore);
  79. AllocaInst(Type *Ty, unsigned AddrSpace,
  80. const Twine &Name, BasicBlock *InsertAtEnd);
  81. AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize, Align Align,
  82. const Twine &Name = "", Instruction *InsertBefore = nullptr);
  83. AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize, Align Align,
  84. const Twine &Name, BasicBlock *InsertAtEnd);
  85. /// Return true if there is an allocation size parameter to the allocation
  86. /// instruction that is not 1.
  87. bool isArrayAllocation() const;
  88. /// Get the number of elements allocated. For a simple allocation of a single
  89. /// element, this will return a constant 1 value.
  90. const Value *getArraySize() const { return getOperand(0); }
  91. Value *getArraySize() { return getOperand(0); }
  92. /// Overload to return most specific pointer type.
  93. PointerType *getType() const {
  94. return cast<PointerType>(Instruction::getType());
  95. }
  96. /// Get allocation size in bits. Returns None if size can't be determined,
  97. /// e.g. in case of a VLA.
  98. Optional<TypeSize> getAllocationSizeInBits(const DataLayout &DL) const;
  99. /// Return the type that is being allocated by the instruction.
  100. Type *getAllocatedType() const { return AllocatedType; }
  101. /// for use only in special circumstances that need to generically
  102. /// transform a whole instruction (eg: IR linking and vectorization).
  103. void setAllocatedType(Type *Ty) { AllocatedType = Ty; }
  104. /// Return the alignment of the memory that is being allocated by the
  105. /// instruction.
  106. Align getAlign() const {
  107. return Align(1ULL << getSubclassData<AlignmentField>());
  108. }
  109. void setAlignment(Align Align) {
  110. setSubclassData<AlignmentField>(Log2(Align));
  111. }
  112. // FIXME: Remove this one transition to Align is over.
  113. unsigned getAlignment() const { return getAlign().value(); }
  114. /// Return true if this alloca is in the entry block of the function and is a
  115. /// constant size. If so, the code generator will fold it into the
  116. /// prolog/epilog code, so it is basically free.
  117. bool isStaticAlloca() const;
  118. /// Return true if this alloca is used as an inalloca argument to a call. Such
  119. /// allocas are never considered static even if they are in the entry block.
  120. bool isUsedWithInAlloca() const {
  121. return getSubclassData<UsedWithInAllocaField>();
  122. }
  123. /// Specify whether this alloca is used to represent the arguments to a call.
  124. void setUsedWithInAlloca(bool V) {
  125. setSubclassData<UsedWithInAllocaField>(V);
  126. }
  127. /// Return true if this alloca is used as a swifterror argument to a call.
  128. bool isSwiftError() const { return getSubclassData<SwiftErrorField>(); }
  129. /// Specify whether this alloca is used to represent a swifterror.
  130. void setSwiftError(bool V) { setSubclassData<SwiftErrorField>(V); }
  131. // Methods for support type inquiry through isa, cast, and dyn_cast:
  132. static bool classof(const Instruction *I) {
  133. return (I->getOpcode() == Instruction::Alloca);
  134. }
  135. static bool classof(const Value *V) {
  136. return isa<Instruction>(V) && classof(cast<Instruction>(V));
  137. }
  138. private:
  139. // Shadow Instruction::setInstructionSubclassData with a private forwarding
  140. // method so that subclasses cannot accidentally use it.
  141. template <typename Bitfield>
  142. void setSubclassData(typename Bitfield::Type Value) {
  143. Instruction::setSubclassData<Bitfield>(Value);
  144. }
  145. };
  146. //===----------------------------------------------------------------------===//
  147. // LoadInst Class
  148. //===----------------------------------------------------------------------===//
  149. /// An instruction for reading from memory. This uses the SubclassData field in
  150. /// Value to store whether or not the load is volatile.
  151. class LoadInst : public UnaryInstruction {
  152. using VolatileField = BoolBitfieldElementT<0>;
  153. using AlignmentField = AlignmentBitfieldElementT<VolatileField::NextBit>;
  154. using OrderingField = AtomicOrderingBitfieldElementT<AlignmentField::NextBit>;
  155. static_assert(
  156. Bitfield::areContiguous<VolatileField, AlignmentField, OrderingField>(),
  157. "Bitfields must be contiguous");
  158. void AssertOK();
  159. protected:
  160. // Note: Instruction needs to be a friend here to call cloneImpl.
  161. friend class Instruction;
  162. LoadInst *cloneImpl() const;
  163. public:
  164. LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr,
  165. Instruction *InsertBefore);
  166. LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, BasicBlock *InsertAtEnd);
  167. LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
  168. Instruction *InsertBefore);
  169. LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
  170. BasicBlock *InsertAtEnd);
  171. LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
  172. Align Align, Instruction *InsertBefore = nullptr);
  173. LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
  174. Align Align, BasicBlock *InsertAtEnd);
  175. LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
  176. Align Align, AtomicOrdering Order,
  177. SyncScope::ID SSID = SyncScope::System,
  178. Instruction *InsertBefore = nullptr);
  179. LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
  180. Align Align, AtomicOrdering Order, SyncScope::ID SSID,
  181. BasicBlock *InsertAtEnd);
  182. // Deprecated [opaque pointer types]
  183. explicit LoadInst(Value *Ptr, const Twine &NameStr = "",
  184. Instruction *InsertBefore = nullptr)
  185. : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
  186. InsertBefore) {}
  187. LoadInst(Value *Ptr, const Twine &NameStr, BasicBlock *InsertAtEnd)
  188. : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
  189. InsertAtEnd) {}
  190. LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile,
  191. Instruction *InsertBefore = nullptr)
  192. : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
  193. isVolatile, InsertBefore) {}
  194. LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile,
  195. BasicBlock *InsertAtEnd)
  196. : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
  197. isVolatile, InsertAtEnd) {}
  198. /// Return true if this is a load from a volatile memory location.
  199. bool isVolatile() const { return getSubclassData<VolatileField>(); }
  200. /// Specify whether this is a volatile load or not.
  201. void setVolatile(bool V) { setSubclassData<VolatileField>(V); }
  202. /// Return the alignment of the access that is being performed.
  203. /// FIXME: Remove this function once transition to Align is over.
  204. /// Use getAlign() instead.
  205. unsigned getAlignment() const { return getAlign().value(); }
  206. /// Return the alignment of the access that is being performed.
  207. Align getAlign() const {
  208. return Align(1ULL << (getSubclassData<AlignmentField>()));
  209. }
  210. void setAlignment(Align Align) {
  211. setSubclassData<AlignmentField>(Log2(Align));
  212. }
  213. /// Returns the ordering constraint of this load instruction.
  214. AtomicOrdering getOrdering() const {
  215. return getSubclassData<OrderingField>();
  216. }
  217. /// Sets the ordering constraint of this load instruction. May not be Release
  218. /// or AcquireRelease.
  219. void setOrdering(AtomicOrdering Ordering) {
  220. setSubclassData<OrderingField>(Ordering);
  221. }
  222. /// Returns the synchronization scope ID of this load instruction.
  223. SyncScope::ID getSyncScopeID() const {
  224. return SSID;
  225. }
  226. /// Sets the synchronization scope ID of this load instruction.
  227. void setSyncScopeID(SyncScope::ID SSID) {
  228. this->SSID = SSID;
  229. }
  230. /// Sets the ordering constraint and the synchronization scope ID of this load
  231. /// instruction.
  232. void setAtomic(AtomicOrdering Ordering,
  233. SyncScope::ID SSID = SyncScope::System) {
  234. setOrdering(Ordering);
  235. setSyncScopeID(SSID);
  236. }
  237. bool isSimple() const { return !isAtomic() && !isVolatile(); }
  238. bool isUnordered() const {
  239. return (getOrdering() == AtomicOrdering::NotAtomic ||
  240. getOrdering() == AtomicOrdering::Unordered) &&
  241. !isVolatile();
  242. }
  243. Value *getPointerOperand() { return getOperand(0); }
  244. const Value *getPointerOperand() const { return getOperand(0); }
  245. static unsigned getPointerOperandIndex() { return 0U; }
  246. Type *getPointerOperandType() const { return getPointerOperand()->getType(); }
  247. /// Returns the address space of the pointer operand.
  248. unsigned getPointerAddressSpace() const {
  249. return getPointerOperandType()->getPointerAddressSpace();
  250. }
  251. // Methods for support type inquiry through isa, cast, and dyn_cast:
  252. static bool classof(const Instruction *I) {
  253. return I->getOpcode() == Instruction::Load;
  254. }
  255. static bool classof(const Value *V) {
  256. return isa<Instruction>(V) && classof(cast<Instruction>(V));
  257. }
  258. private:
  259. // Shadow Instruction::setInstructionSubclassData with a private forwarding
  260. // method so that subclasses cannot accidentally use it.
  261. template <typename Bitfield>
  262. void setSubclassData(typename Bitfield::Type Value) {
  263. Instruction::setSubclassData<Bitfield>(Value);
  264. }
  265. /// The synchronization scope ID of this load instruction. Not quite enough
  266. /// room in SubClassData for everything, so synchronization scope ID gets its
  267. /// own field.
  268. SyncScope::ID SSID;
  269. };
  270. //===----------------------------------------------------------------------===//
  271. // StoreInst Class
  272. //===----------------------------------------------------------------------===//
  273. /// An instruction for storing to memory.
  274. class StoreInst : public Instruction {
  275. using VolatileField = BoolBitfieldElementT<0>;
  276. using AlignmentField = AlignmentBitfieldElementT<VolatileField::NextBit>;
  277. using OrderingField = AtomicOrderingBitfieldElementT<AlignmentField::NextBit>;
  278. static_assert(
  279. Bitfield::areContiguous<VolatileField, AlignmentField, OrderingField>(),
  280. "Bitfields must be contiguous");
  281. void AssertOK();
  282. protected:
  283. // Note: Instruction needs to be a friend here to call cloneImpl.
  284. friend class Instruction;
  285. StoreInst *cloneImpl() const;
  286. public:
  287. StoreInst(Value *Val, Value *Ptr, Instruction *InsertBefore);
  288. StoreInst(Value *Val, Value *Ptr, BasicBlock *InsertAtEnd);
  289. StoreInst(Value *Val, Value *Ptr, bool isVolatile, Instruction *InsertBefore);
  290. StoreInst(Value *Val, Value *Ptr, bool isVolatile, BasicBlock *InsertAtEnd);
  291. StoreInst(Value *Val, Value *Ptr, bool isVolatile, Align Align,
  292. Instruction *InsertBefore = nullptr);
  293. StoreInst(Value *Val, Value *Ptr, bool isVolatile, Align Align,
  294. BasicBlock *InsertAtEnd);
  295. StoreInst(Value *Val, Value *Ptr, bool isVolatile, Align Align,
  296. AtomicOrdering Order, SyncScope::ID SSID = SyncScope::System,
  297. Instruction *InsertBefore = nullptr);
  298. StoreInst(Value *Val, Value *Ptr, bool isVolatile, Align Align,
  299. AtomicOrdering Order, SyncScope::ID SSID, BasicBlock *InsertAtEnd);
  300. // allocate space for exactly two operands
  301. void *operator new(size_t s) {
  302. return User::operator new(s, 2);
  303. }
  304. /// Return true if this is a store to a volatile memory location.
  305. bool isVolatile() const { return getSubclassData<VolatileField>(); }
  306. /// Specify whether this is a volatile store or not.
  307. void setVolatile(bool V) { setSubclassData<VolatileField>(V); }
  308. /// Transparently provide more efficient getOperand methods.
  309. DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
  310. /// Return the alignment of the access that is being performed
  311. /// FIXME: Remove this function once transition to Align is over.
  312. /// Use getAlign() instead.
  313. unsigned getAlignment() const { return getAlign().value(); }
  314. Align getAlign() const {
  315. return Align(1ULL << (getSubclassData<AlignmentField>()));
  316. }
  317. void setAlignment(Align Align) {
  318. setSubclassData<AlignmentField>(Log2(Align));
  319. }
  320. /// Returns the ordering constraint of this store instruction.
  321. AtomicOrdering getOrdering() const {
  322. return getSubclassData<OrderingField>();
  323. }
  324. /// Sets the ordering constraint of this store instruction. May not be
  325. /// Acquire or AcquireRelease.
  326. void setOrdering(AtomicOrdering Ordering) {
  327. setSubclassData<OrderingField>(Ordering);
  328. }
  329. /// Returns the synchronization scope ID of this store instruction.
  330. SyncScope::ID getSyncScopeID() const {
  331. return SSID;
  332. }
  333. /// Sets the synchronization scope ID of this store instruction.
  334. void setSyncScopeID(SyncScope::ID SSID) {
  335. this->SSID = SSID;
  336. }
  337. /// Sets the ordering constraint and the synchronization scope ID of this
  338. /// store instruction.
  339. void setAtomic(AtomicOrdering Ordering,
  340. SyncScope::ID SSID = SyncScope::System) {
  341. setOrdering(Ordering);
  342. setSyncScopeID(SSID);
  343. }
  344. bool isSimple() const { return !isAtomic() && !isVolatile(); }
  345. bool isUnordered() const {
  346. return (getOrdering() == AtomicOrdering::NotAtomic ||
  347. getOrdering() == AtomicOrdering::Unordered) &&
  348. !isVolatile();
  349. }
  350. Value *getValueOperand() { return getOperand(0); }
  351. const Value *getValueOperand() const { return getOperand(0); }
  352. Value *getPointerOperand() { return getOperand(1); }
  353. const Value *getPointerOperand() const { return getOperand(1); }
  354. static unsigned getPointerOperandIndex() { return 1U; }
  355. Type *getPointerOperandType() const { return getPointerOperand()->getType(); }
  356. /// Returns the address space of the pointer operand.
  357. unsigned getPointerAddressSpace() const {
  358. return getPointerOperandType()->getPointerAddressSpace();
  359. }
  360. // Methods for support type inquiry through isa, cast, and dyn_cast:
  361. static bool classof(const Instruction *I) {
  362. return I->getOpcode() == Instruction::Store;
  363. }
  364. static bool classof(const Value *V) {
  365. return isa<Instruction>(V) && classof(cast<Instruction>(V));
  366. }
  367. private:
  368. // Shadow Instruction::setInstructionSubclassData with a private forwarding
  369. // method so that subclasses cannot accidentally use it.
  370. template <typename Bitfield>
  371. void setSubclassData(typename Bitfield::Type Value) {
  372. Instruction::setSubclassData<Bitfield>(Value);
  373. }
  374. /// The synchronization scope ID of this store instruction. Not quite enough
  375. /// room in SubClassData for everything, so synchronization scope ID gets its
  376. /// own field.
  377. SyncScope::ID SSID;
  378. };
  379. template <>
  380. struct OperandTraits<StoreInst> : public FixedNumOperandTraits<StoreInst, 2> {
  381. };
  382. DEFINE_TRANSPARENT_OPERAND_ACCESSORS(StoreInst, Value)
  383. //===----------------------------------------------------------------------===//
  384. // FenceInst Class
  385. //===----------------------------------------------------------------------===//
  386. /// An instruction for ordering other memory operations.
  387. class FenceInst : public Instruction {
  388. using OrderingField = AtomicOrderingBitfieldElementT<0>;
  389. void Init(AtomicOrdering Ordering, SyncScope::ID SSID);
  390. protected:
  391. // Note: Instruction needs to be a friend here to call cloneImpl.
  392. friend class Instruction;
  393. FenceInst *cloneImpl() const;
  394. public:
  395. // Ordering may only be Acquire, Release, AcquireRelease, or
  396. // SequentiallyConsistent.
  397. FenceInst(LLVMContext &C, AtomicOrdering Ordering,
  398. SyncScope::ID SSID = SyncScope::System,
  399. Instruction *InsertBefore = nullptr);
  400. FenceInst(LLVMContext &C, AtomicOrdering Ordering, SyncScope::ID SSID,
  401. BasicBlock *InsertAtEnd);
  402. // allocate space for exactly zero operands
  403. void *operator new(size_t s) {
  404. return User::operator new(s, 0);
  405. }
  406. /// Returns the ordering constraint of this fence instruction.
  407. AtomicOrdering getOrdering() const {
  408. return getSubclassData<OrderingField>();
  409. }
  410. /// Sets the ordering constraint of this fence instruction. May only be
  411. /// Acquire, Release, AcquireRelease, or SequentiallyConsistent.
  412. void setOrdering(AtomicOrdering Ordering) {
  413. setSubclassData<OrderingField>(Ordering);
  414. }
  415. /// Returns the synchronization scope ID of this fence instruction.
  416. SyncScope::ID getSyncScopeID() const {
  417. return SSID;
  418. }
  419. /// Sets the synchronization scope ID of this fence instruction.
  420. void setSyncScopeID(SyncScope::ID SSID) {
  421. this->SSID = SSID;
  422. }
  423. // Methods for support type inquiry through isa, cast, and dyn_cast:
  424. static bool classof(const Instruction *I) {
  425. return I->getOpcode() == Instruction::Fence;
  426. }
  427. static bool classof(const Value *V) {
  428. return isa<Instruction>(V) && classof(cast<Instruction>(V));
  429. }
  430. private:
  431. // Shadow Instruction::setInstructionSubclassData with a private forwarding
  432. // method so that subclasses cannot accidentally use it.
  433. template <typename Bitfield>
  434. void setSubclassData(typename Bitfield::Type Value) {
  435. Instruction::setSubclassData<Bitfield>(Value);
  436. }
  437. /// The synchronization scope ID of this fence instruction. Not quite enough
  438. /// room in SubClassData for everything, so synchronization scope ID gets its
  439. /// own field.
  440. SyncScope::ID SSID;
  441. };
  442. //===----------------------------------------------------------------------===//
  443. // AtomicCmpXchgInst Class
  444. //===----------------------------------------------------------------------===//
  445. /// An instruction that atomically checks whether a
  446. /// specified value is in a memory location, and, if it is, stores a new value
  447. /// there. The value returned by this instruction is a pair containing the
  448. /// original value as first element, and an i1 indicating success (true) or
  449. /// failure (false) as second element.
  450. ///
  451. class AtomicCmpXchgInst : public Instruction {
  452. void Init(Value *Ptr, Value *Cmp, Value *NewVal, Align Align,
  453. AtomicOrdering SuccessOrdering, AtomicOrdering FailureOrdering,
  454. SyncScope::ID SSID);
  455. template <unsigned Offset>
  456. using AtomicOrderingBitfieldElement =
  457. typename Bitfield::Element<AtomicOrdering, Offset, 3,
  458. AtomicOrdering::LAST>;
  459. protected:
  460. // Note: Instruction needs to be a friend here to call cloneImpl.
  461. friend class Instruction;
  462. AtomicCmpXchgInst *cloneImpl() const;
  463. public:
  464. AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal, Align Alignment,
  465. AtomicOrdering SuccessOrdering,
  466. AtomicOrdering FailureOrdering, SyncScope::ID SSID,
  467. Instruction *InsertBefore = nullptr);
  468. AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal, Align Alignment,
  469. AtomicOrdering SuccessOrdering,
  470. AtomicOrdering FailureOrdering, SyncScope::ID SSID,
  471. BasicBlock *InsertAtEnd);
  472. // allocate space for exactly three operands
  473. void *operator new(size_t s) {
  474. return User::operator new(s, 3);
  475. }
  476. using VolatileField = BoolBitfieldElementT<0>;
  477. using WeakField = BoolBitfieldElementT<VolatileField::NextBit>;
  478. using SuccessOrderingField =
  479. AtomicOrderingBitfieldElementT<WeakField::NextBit>;
  480. using FailureOrderingField =
  481. AtomicOrderingBitfieldElementT<SuccessOrderingField::NextBit>;
  482. using AlignmentField =
  483. AlignmentBitfieldElementT<FailureOrderingField::NextBit>;
  484. static_assert(
  485. Bitfield::areContiguous<VolatileField, WeakField, SuccessOrderingField,
  486. FailureOrderingField, AlignmentField>(),
  487. "Bitfields must be contiguous");
  488. /// Return the alignment of the memory that is being allocated by the
  489. /// instruction.
  490. Align getAlign() const {
  491. return Align(1ULL << getSubclassData<AlignmentField>());
  492. }
  493. void setAlignment(Align Align) {
  494. setSubclassData<AlignmentField>(Log2(Align));
  495. }
  496. /// Return true if this is a cmpxchg from a volatile memory
  497. /// location.
  498. ///
  499. bool isVolatile() const { return getSubclassData<VolatileField>(); }
  500. /// Specify whether this is a volatile cmpxchg.
  501. ///
  502. void setVolatile(bool V) { setSubclassData<VolatileField>(V); }
  503. /// Return true if this cmpxchg may spuriously fail.
  504. bool isWeak() const { return getSubclassData<WeakField>(); }
  505. void setWeak(bool IsWeak) { setSubclassData<WeakField>(IsWeak); }
  506. /// Transparently provide more efficient getOperand methods.
  507. DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
  508. /// Returns the success ordering constraint of this cmpxchg instruction.
  509. AtomicOrdering getSuccessOrdering() const {
  510. return getSubclassData<SuccessOrderingField>();
  511. }
  512. /// Sets the success ordering constraint of this cmpxchg instruction.
  513. void setSuccessOrdering(AtomicOrdering Ordering) {
  514. assert(Ordering != AtomicOrdering::NotAtomic &&
  515. "CmpXchg instructions can only be atomic.");
  516. setSubclassData<SuccessOrderingField>(Ordering);
  517. }
  518. /// Returns the failure ordering constraint of this cmpxchg instruction.
  519. AtomicOrdering getFailureOrdering() const {
  520. return getSubclassData<FailureOrderingField>();
  521. }
  522. /// Sets the failure ordering constraint of this cmpxchg instruction.
  523. void setFailureOrdering(AtomicOrdering Ordering) {
  524. assert(Ordering != AtomicOrdering::NotAtomic &&
  525. "CmpXchg instructions can only be atomic.");
  526. setSubclassData<FailureOrderingField>(Ordering);
  527. }
  528. /// Returns the synchronization scope ID of this cmpxchg instruction.
  529. SyncScope::ID getSyncScopeID() const {
  530. return SSID;
  531. }
  532. /// Sets the synchronization scope ID of this cmpxchg instruction.
  533. void setSyncScopeID(SyncScope::ID SSID) {
  534. this->SSID = SSID;
  535. }
  536. Value *getPointerOperand() { return getOperand(0); }
  537. const Value *getPointerOperand() const { return getOperand(0); }
  538. static unsigned getPointerOperandIndex() { return 0U; }
  539. Value *getCompareOperand() { return getOperand(1); }
  540. const Value *getCompareOperand() const { return getOperand(1); }
  541. Value *getNewValOperand() { return getOperand(2); }
  542. const Value *getNewValOperand() const { return getOperand(2); }
  543. /// Returns the address space of the pointer operand.
  544. unsigned getPointerAddressSpace() const {
  545. return getPointerOperand()->getType()->getPointerAddressSpace();
  546. }
  547. /// Returns the strongest permitted ordering on failure, given the
  548. /// desired ordering on success.
  549. ///
  550. /// If the comparison in a cmpxchg operation fails, there is no atomic store
  551. /// so release semantics cannot be provided. So this function drops explicit
  552. /// Release requests from the AtomicOrdering. A SequentiallyConsistent
  553. /// operation would remain SequentiallyConsistent.
  554. static AtomicOrdering
  555. getStrongestFailureOrdering(AtomicOrdering SuccessOrdering) {
  556. switch (SuccessOrdering) {
  557. default:
  558. llvm_unreachable("invalid cmpxchg success ordering");
  559. case AtomicOrdering::Release:
  560. case AtomicOrdering::Monotonic:
  561. return AtomicOrdering::Monotonic;
  562. case AtomicOrdering::AcquireRelease:
  563. case AtomicOrdering::Acquire:
  564. return AtomicOrdering::Acquire;
  565. case AtomicOrdering::SequentiallyConsistent:
  566. return AtomicOrdering::SequentiallyConsistent;
  567. }
  568. }
  569. // Methods for support type inquiry through isa, cast, and dyn_cast:
  570. static bool classof(const Instruction *I) {
  571. return I->getOpcode() == Instruction::AtomicCmpXchg;
  572. }
  573. static bool classof(const Value *V) {
  574. return isa<Instruction>(V) && classof(cast<Instruction>(V));
  575. }
  576. private:
  577. // Shadow Instruction::setInstructionSubclassData with a private forwarding
  578. // method so that subclasses cannot accidentally use it.
  579. template <typename Bitfield>
  580. void setSubclassData(typename Bitfield::Type Value) {
  581. Instruction::setSubclassData<Bitfield>(Value);
  582. }
  583. /// The synchronization scope ID of this cmpxchg instruction. Not quite
  584. /// enough room in SubClassData for everything, so synchronization scope ID
  585. /// gets its own field.
  586. SyncScope::ID SSID;
  587. };
  588. template <>
  589. struct OperandTraits<AtomicCmpXchgInst> :
  590. public FixedNumOperandTraits<AtomicCmpXchgInst, 3> {
  591. };
  592. DEFINE_TRANSPARENT_OPERAND_ACCESSORS(AtomicCmpXchgInst, Value)
  593. //===----------------------------------------------------------------------===//
  594. // AtomicRMWInst Class
  595. //===----------------------------------------------------------------------===//
  596. /// an instruction that atomically reads a memory location,
  597. /// combines it with another value, and then stores the result back. Returns
  598. /// the old value.
  599. ///
  600. class AtomicRMWInst : public Instruction {
  601. protected:
  602. // Note: Instruction needs to be a friend here to call cloneImpl.
  603. friend class Instruction;
  604. AtomicRMWInst *cloneImpl() const;
  605. public:
  606. /// This enumeration lists the possible modifications atomicrmw can make. In
  607. /// the descriptions, 'p' is the pointer to the instruction's memory location,
  608. /// 'old' is the initial value of *p, and 'v' is the other value passed to the
  609. /// instruction. These instructions always return 'old'.
  610. enum BinOp : unsigned {
  611. /// *p = v
  612. Xchg,
  613. /// *p = old + v
  614. Add,
  615. /// *p = old - v
  616. Sub,
  617. /// *p = old & v
  618. And,
  619. /// *p = ~(old & v)
  620. Nand,
  621. /// *p = old | v
  622. Or,
  623. /// *p = old ^ v
  624. Xor,
  625. /// *p = old >signed v ? old : v
  626. Max,
  627. /// *p = old <signed v ? old : v
  628. Min,
  629. /// *p = old >unsigned v ? old : v
  630. UMax,
  631. /// *p = old <unsigned v ? old : v
  632. UMin,
  633. /// *p = old + v
  634. FAdd,
  635. /// *p = old - v
  636. FSub,
  637. FIRST_BINOP = Xchg,
  638. LAST_BINOP = FSub,
  639. BAD_BINOP
  640. };
  641. private:
  642. template <unsigned Offset>
  643. using AtomicOrderingBitfieldElement =
  644. typename Bitfield::Element<AtomicOrdering, Offset, 3,
  645. AtomicOrdering::LAST>;
  646. template <unsigned Offset>
  647. using BinOpBitfieldElement =
  648. typename Bitfield::Element<BinOp, Offset, 4, BinOp::LAST_BINOP>;
  649. public:
  650. AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val, Align Alignment,
  651. AtomicOrdering Ordering, SyncScope::ID SSID,
  652. Instruction *InsertBefore = nullptr);
  653. AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val, Align Alignment,
  654. AtomicOrdering Ordering, SyncScope::ID SSID,
  655. BasicBlock *InsertAtEnd);
  656. // allocate space for exactly two operands
  657. void *operator new(size_t s) {
  658. return User::operator new(s, 2);
  659. }
  660. using VolatileField = BoolBitfieldElementT<0>;
  661. using AtomicOrderingField =
  662. AtomicOrderingBitfieldElementT<VolatileField::NextBit>;
  663. using OperationField = BinOpBitfieldElement<AtomicOrderingField::NextBit>;
  664. using AlignmentField = AlignmentBitfieldElementT<OperationField::NextBit>;
  665. static_assert(Bitfield::areContiguous<VolatileField, AtomicOrderingField,
  666. OperationField, AlignmentField>(),
  667. "Bitfields must be contiguous");
  668. BinOp getOperation() const { return getSubclassData<OperationField>(); }
  669. static StringRef getOperationName(BinOp Op);
  670. static bool isFPOperation(BinOp Op) {
  671. switch (Op) {
  672. case AtomicRMWInst::FAdd:
  673. case AtomicRMWInst::FSub:
  674. return true;
  675. default:
  676. return false;
  677. }
  678. }
  679. void setOperation(BinOp Operation) {
  680. setSubclassData<OperationField>(Operation);
  681. }
  682. /// Return the alignment of the memory that is being allocated by the
  683. /// instruction.
  684. Align getAlign() const {
  685. return Align(1ULL << getSubclassData<AlignmentField>());
  686. }
  687. void setAlignment(Align Align) {
  688. setSubclassData<AlignmentField>(Log2(Align));
  689. }
  690. /// Return true if this is a RMW on a volatile memory location.
  691. ///
  692. bool isVolatile() const { return getSubclassData<VolatileField>(); }
  693. /// Specify whether this is a volatile RMW or not.
  694. ///
  695. void setVolatile(bool V) { setSubclassData<VolatileField>(V); }
  696. /// Transparently provide more efficient getOperand methods.
  697. DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
  698. /// Returns the ordering constraint of this rmw instruction.
  699. AtomicOrdering getOrdering() const {
  700. return getSubclassData<AtomicOrderingField>();
  701. }
  702. /// Sets the ordering constraint of this rmw instruction.
  703. void setOrdering(AtomicOrdering Ordering) {
  704. assert(Ordering != AtomicOrdering::NotAtomic &&
  705. "atomicrmw instructions can only be atomic.");
  706. setSubclassData<AtomicOrderingField>(Ordering);
  707. }
  708. /// Returns the synchronization scope ID of this rmw instruction.
  709. SyncScope::ID getSyncScopeID() const {
  710. return SSID;
  711. }
  712. /// Sets the synchronization scope ID of this rmw instruction.
  713. void setSyncScopeID(SyncScope::ID SSID) {
  714. this->SSID = SSID;
  715. }
  716. Value *getPointerOperand() { return getOperand(0); }
  717. const Value *getPointerOperand() const { return getOperand(0); }
  718. static unsigned getPointerOperandIndex() { return 0U; }
  719. Value *getValOperand() { return getOperand(1); }
  720. const Value *getValOperand() const { return getOperand(1); }
  721. /// Returns the address space of the pointer operand.
  722. unsigned getPointerAddressSpace() const {
  723. return getPointerOperand()->getType()->getPointerAddressSpace();
  724. }
  725. bool isFloatingPointOperation() const {
  726. return isFPOperation(getOperation());
  727. }
  728. // Methods for support type inquiry through isa, cast, and dyn_cast:
  729. static bool classof(const Instruction *I) {
  730. return I->getOpcode() == Instruction::AtomicRMW;
  731. }
  732. static bool classof(const Value *V) {
  733. return isa<Instruction>(V) && classof(cast<Instruction>(V));
  734. }
  735. private:
  736. void Init(BinOp Operation, Value *Ptr, Value *Val, Align Align,
  737. AtomicOrdering Ordering, SyncScope::ID SSID);
  738. // Shadow Instruction::setInstructionSubclassData with a private forwarding
  739. // method so that subclasses cannot accidentally use it.
  740. template <typename Bitfield>
  741. void setSubclassData(typename Bitfield::Type Value) {
  742. Instruction::setSubclassData<Bitfield>(Value);
  743. }
  744. /// The synchronization scope ID of this rmw instruction. Not quite enough
  745. /// room in SubClassData for everything, so synchronization scope ID gets its
  746. /// own field.
  747. SyncScope::ID SSID;
  748. };
  749. template <>
  750. struct OperandTraits<AtomicRMWInst>
  751. : public FixedNumOperandTraits<AtomicRMWInst,2> {
  752. };
  753. DEFINE_TRANSPARENT_OPERAND_ACCESSORS(AtomicRMWInst, Value)
  754. //===----------------------------------------------------------------------===//
  755. // GetElementPtrInst Class
  756. //===----------------------------------------------------------------------===//
  757. // checkGEPType - Simple wrapper function to give a better assertion failure
  758. // message on bad indexes for a gep instruction.
  759. //
  760. inline Type *checkGEPType(Type *Ty) {
  761. assert(Ty && "Invalid GetElementPtrInst indices for type!");
  762. return Ty;
  763. }
  764. /// an instruction for type-safe pointer arithmetic to
  765. /// access elements of arrays and structs
  766. ///
  767. class GetElementPtrInst : public Instruction {
  768. Type *SourceElementType;
  769. Type *ResultElementType;
  770. GetElementPtrInst(const GetElementPtrInst &GEPI);
  771. /// Constructors - Create a getelementptr instruction with a base pointer an
  772. /// list of indices. The first ctor can optionally insert before an existing
  773. /// instruction, the second appends the new instruction to the specified
  774. /// BasicBlock.
  775. inline GetElementPtrInst(Type *PointeeType, Value *Ptr,
  776. ArrayRef<Value *> IdxList, unsigned Values,
  777. const Twine &NameStr, Instruction *InsertBefore);
  778. inline GetElementPtrInst(Type *PointeeType, Value *Ptr,
  779. ArrayRef<Value *> IdxList, unsigned Values,
  780. const Twine &NameStr, BasicBlock *InsertAtEnd);
  781. void init(Value *Ptr, ArrayRef<Value *> IdxList, const Twine &NameStr);
  782. protected:
  783. // Note: Instruction needs to be a friend here to call cloneImpl.
  784. friend class Instruction;
  785. GetElementPtrInst *cloneImpl() const;
  786. public:
  787. static GetElementPtrInst *Create(Type *PointeeType, Value *Ptr,
  788. ArrayRef<Value *> IdxList,
  789. const Twine &NameStr = "",
  790. Instruction *InsertBefore = nullptr) {
  791. unsigned Values = 1 + unsigned(IdxList.size());
  792. if (!PointeeType)
  793. PointeeType =
  794. cast<PointerType>(Ptr->getType()->getScalarType())->getElementType();
  795. else
  796. assert(
  797. PointeeType ==
  798. cast<PointerType>(Ptr->getType()->getScalarType())->getElementType());
  799. return new (Values) GetElementPtrInst(PointeeType, Ptr, IdxList, Values,
  800. NameStr, InsertBefore);
  801. }
  802. static GetElementPtrInst *Create(Type *PointeeType, Value *Ptr,
  803. ArrayRef<Value *> IdxList,
  804. const Twine &NameStr,
  805. BasicBlock *InsertAtEnd) {
  806. unsigned Values = 1 + unsigned(IdxList.size());
  807. if (!PointeeType)
  808. PointeeType =
  809. cast<PointerType>(Ptr->getType()->getScalarType())->getElementType();
  810. else
  811. assert(
  812. PointeeType ==
  813. cast<PointerType>(Ptr->getType()->getScalarType())->getElementType());
  814. return new (Values) GetElementPtrInst(PointeeType, Ptr, IdxList, Values,
  815. NameStr, InsertAtEnd);
  816. }
  817. /// Create an "inbounds" getelementptr. See the documentation for the
  818. /// "inbounds" flag in LangRef.html for details.
  819. static GetElementPtrInst *CreateInBounds(Value *Ptr,
  820. ArrayRef<Value *> IdxList,
  821. const Twine &NameStr = "",
  822. Instruction *InsertBefore = nullptr){
  823. return CreateInBounds(nullptr, Ptr, IdxList, NameStr, InsertBefore);
  824. }
  825. static GetElementPtrInst *
  826. CreateInBounds(Type *PointeeType, Value *Ptr, ArrayRef<Value *> IdxList,
  827. const Twine &NameStr = "",
  828. Instruction *InsertBefore = nullptr) {
  829. GetElementPtrInst *GEP =
  830. Create(PointeeType, Ptr, IdxList, NameStr, InsertBefore);
  831. GEP->setIsInBounds(true);
  832. return GEP;
  833. }
  834. static GetElementPtrInst *CreateInBounds(Value *Ptr,
  835. ArrayRef<Value *> IdxList,
  836. const Twine &NameStr,
  837. BasicBlock *InsertAtEnd) {
  838. return CreateInBounds(nullptr, Ptr, IdxList, NameStr, InsertAtEnd);
  839. }
  840. static GetElementPtrInst *CreateInBounds(Type *PointeeType, Value *Ptr,
  841. ArrayRef<Value *> IdxList,
  842. const Twine &NameStr,
  843. BasicBlock *InsertAtEnd) {
  844. GetElementPtrInst *GEP =
  845. Create(PointeeType, Ptr, IdxList, NameStr, InsertAtEnd);
  846. GEP->setIsInBounds(true);
  847. return GEP;
  848. }
  849. /// Transparently provide more efficient getOperand methods.
  850. DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
  851. Type *getSourceElementType() const { return SourceElementType; }
  852. void setSourceElementType(Type *Ty) { SourceElementType = Ty; }
  853. void setResultElementType(Type *Ty) { ResultElementType = Ty; }
  854. Type *getResultElementType() const {
  855. assert(ResultElementType ==
  856. cast<PointerType>(getType()->getScalarType())->getElementType());
  857. return ResultElementType;
  858. }
  859. /// Returns the address space of this instruction's pointer type.
  860. unsigned getAddressSpace() const {
  861. // Note that this is always the same as the pointer operand's address space
  862. // and that is cheaper to compute, so cheat here.
  863. return getPointerAddressSpace();
  864. }
  865. /// Returns the result type of a getelementptr with the given source
  866. /// element type and indexes.
  867. ///
  868. /// Null is returned if the indices are invalid for the specified
  869. /// source element type.
  870. static Type *getIndexedType(Type *Ty, ArrayRef<Value *> IdxList);
  871. static Type *getIndexedType(Type *Ty, ArrayRef<Constant *> IdxList);
  872. static Type *getIndexedType(Type *Ty, ArrayRef<uint64_t> IdxList);
  873. /// Return the type of the element at the given index of an indexable
  874. /// type. This is equivalent to "getIndexedType(Agg, {Zero, Idx})".
  875. ///
  876. /// Returns null if the type can't be indexed, or the given index is not
  877. /// legal for the given type.
  878. static Type *getTypeAtIndex(Type *Ty, Value *Idx);
  879. static Type *getTypeAtIndex(Type *Ty, uint64_t Idx);
  880. inline op_iterator idx_begin() { return op_begin()+1; }
  881. inline const_op_iterator idx_begin() const { return op_begin()+1; }
  882. inline op_iterator idx_end() { return op_end(); }
  883. inline const_op_iterator idx_end() const { return op_end(); }
  884. inline iterator_range<op_iterator> indices() {
  885. return make_range(idx_begin(), idx_end());
  886. }
  887. inline iterator_range<const_op_iterator> indices() const {
  888. return make_range(idx_begin(), idx_end());
  889. }
  890. Value *getPointerOperand() {
  891. return getOperand(0);
  892. }
  893. const Value *getPointerOperand() const {
  894. return getOperand(0);
  895. }
  896. static unsigned getPointerOperandIndex() {
  897. return 0U; // get index for modifying correct operand.
  898. }
  899. /// Method to return the pointer operand as a
  900. /// PointerType.
  901. Type *getPointerOperandType() const {
  902. return getPointerOperand()->getType();
  903. }
  904. /// Returns the address space of the pointer operand.
  905. unsigned getPointerAddressSpace() const {
  906. return getPointerOperandType()->getPointerAddressSpace();
  907. }
  908. /// Returns the pointer type returned by the GEP
  909. /// instruction, which may be a vector of pointers.
  910. static Type *getGEPReturnType(Type *ElTy, Value *Ptr,
  911. ArrayRef<Value *> IdxList) {
  912. Type *PtrTy = PointerType::get(checkGEPType(getIndexedType(ElTy, IdxList)),
  913. Ptr->getType()->getPointerAddressSpace());
  914. // Vector GEP
  915. if (auto *PtrVTy = dyn_cast<VectorType>(Ptr->getType())) {
  916. ElementCount EltCount = PtrVTy->getElementCount();
  917. return VectorType::get(PtrTy, EltCount);
  918. }
  919. for (Value *Index : IdxList)
  920. if (auto *IndexVTy = dyn_cast<VectorType>(Index->getType())) {
  921. ElementCount EltCount = IndexVTy->getElementCount();
  922. return VectorType::get(PtrTy, EltCount);
  923. }
  924. // Scalar GEP
  925. return PtrTy;
  926. }
  927. unsigned getNumIndices() const { // Note: always non-negative
  928. return getNumOperands() - 1;
  929. }
  930. bool hasIndices() const {
  931. return getNumOperands() > 1;
  932. }
  933. /// Return true if all of the indices of this GEP are
  934. /// zeros. If so, the result pointer and the first operand have the same
  935. /// value, just potentially different types.
  936. bool hasAllZeroIndices() const;
  937. /// Return true if all of the indices of this GEP are
  938. /// constant integers. If so, the result pointer and the first operand have
  939. /// a constant offset between them.
  940. bool hasAllConstantIndices() const;
  941. /// Set or clear the inbounds flag on this GEP instruction.
  942. /// See LangRef.html for the meaning of inbounds on a getelementptr.
  943. void setIsInBounds(bool b = true);
  944. /// Determine whether the GEP has the inbounds flag.
  945. bool isInBounds() const;
  946. /// Accumulate the constant address offset of this GEP if possible.
  947. ///
  948. /// This routine accepts an APInt into which it will accumulate the constant
  949. /// offset of this GEP if the GEP is in fact constant. If the GEP is not
  950. /// all-constant, it returns false and the value of the offset APInt is
  951. /// undefined (it is *not* preserved!). The APInt passed into this routine
  952. /// must be at least as wide as the IntPtr type for the address space of
  953. /// the base GEP pointer.
  954. bool accumulateConstantOffset(const DataLayout &DL, APInt &Offset) const;
  955. // Methods for support type inquiry through isa, cast, and dyn_cast:
  956. static bool classof(const Instruction *I) {
  957. return (I->getOpcode() == Instruction::GetElementPtr);
  958. }
  959. static bool classof(const Value *V) {
  960. return isa<Instruction>(V) && classof(cast<Instruction>(V));
  961. }
  962. };
  963. template <>
  964. struct OperandTraits<GetElementPtrInst> :
  965. public VariadicOperandTraits<GetElementPtrInst, 1> {
  966. };
  967. GetElementPtrInst::GetElementPtrInst(Type *PointeeType, Value *Ptr,
  968. ArrayRef<Value *> IdxList, unsigned Values,
  969. const Twine &NameStr,
  970. Instruction *InsertBefore)
  971. : Instruction(getGEPReturnType(PointeeType, Ptr, IdxList), GetElementPtr,
  972. OperandTraits<GetElementPtrInst>::op_end(this) - Values,
  973. Values, InsertBefore),
  974. SourceElementType(PointeeType),
  975. ResultElementType(getIndexedType(PointeeType, IdxList)) {
  976. assert(ResultElementType ==
  977. cast<PointerType>(getType()->getScalarType())->getElementType());
  978. init(Ptr, IdxList, NameStr);
  979. }
  980. GetElementPtrInst::GetElementPtrInst(Type *PointeeType, Value *Ptr,
  981. ArrayRef<Value *> IdxList, unsigned Values,
  982. const Twine &NameStr,
  983. BasicBlock *InsertAtEnd)
  984. : Instruction(getGEPReturnType(PointeeType, Ptr, IdxList), GetElementPtr,
  985. OperandTraits<GetElementPtrInst>::op_end(this) - Values,
  986. Values, InsertAtEnd),
  987. SourceElementType(PointeeType),
  988. ResultElementType(getIndexedType(PointeeType, IdxList)) {
  989. assert(ResultElementType ==
  990. cast<PointerType>(getType()->getScalarType())->getElementType());
  991. init(Ptr, IdxList, NameStr);
  992. }
  993. DEFINE_TRANSPARENT_OPERAND_ACCESSORS(GetElementPtrInst, Value)
  994. //===----------------------------------------------------------------------===//
  995. // ICmpInst Class
  996. //===----------------------------------------------------------------------===//
  997. /// This instruction compares its operands according to the predicate given
  998. /// to the constructor. It only operates on integers or pointers. The operands
  999. /// must be identical types.
  1000. /// Represent an integer comparison operator.
  1001. class ICmpInst: public CmpInst {
  1002. void AssertOK() {
  1003. assert(isIntPredicate() &&
  1004. "Invalid ICmp predicate value");
  1005. assert(getOperand(0)->getType() == getOperand(1)->getType() &&
  1006. "Both operands to ICmp instruction are not of the same type!");
  1007. // Check that the operands are the right type
  1008. assert((getOperand(0)->getType()->isIntOrIntVectorTy() ||
  1009. getOperand(0)->getType()->isPtrOrPtrVectorTy()) &&
  1010. "Invalid operand types for ICmp instruction");
  1011. }
  1012. protected:
  1013. // Note: Instruction needs to be a friend here to call cloneImpl.
  1014. friend class Instruction;
  1015. /// Clone an identical ICmpInst
  1016. ICmpInst *cloneImpl() const;
  1017. public:
  1018. /// Constructor with insert-before-instruction semantics.
  1019. ICmpInst(
  1020. Instruction *InsertBefore, ///< Where to insert
  1021. Predicate pred, ///< The predicate to use for the comparison
  1022. Value *LHS, ///< The left-hand-side of the expression
  1023. Value *RHS, ///< The right-hand-side of the expression
  1024. const Twine &NameStr = "" ///< Name of the instruction
  1025. ) : CmpInst(makeCmpResultType(LHS->getType()),
  1026. Instruction::ICmp, pred, LHS, RHS, NameStr,
  1027. InsertBefore) {
  1028. #ifndef NDEBUG
  1029. AssertOK();
  1030. #endif
  1031. }
  1032. /// Constructor with insert-at-end semantics.
  1033. ICmpInst(
  1034. BasicBlock &InsertAtEnd, ///< Block to insert into.
  1035. Predicate pred, ///< The predicate to use for the comparison
  1036. Value *LHS, ///< The left-hand-side of the expression
  1037. Value *RHS, ///< The right-hand-side of the expression
  1038. const Twine &NameStr = "" ///< Name of the instruction
  1039. ) : CmpInst(makeCmpResultType(LHS->getType()),
  1040. Instruction::ICmp, pred, LHS, RHS, NameStr,
  1041. &InsertAtEnd) {
  1042. #ifndef NDEBUG
  1043. AssertOK();
  1044. #endif
  1045. }
  1046. /// Constructor with no-insertion semantics
  1047. ICmpInst(
  1048. Predicate pred, ///< The predicate to use for the comparison
  1049. Value *LHS, ///< The left-hand-side of the expression
  1050. Value *RHS, ///< The right-hand-side of the expression
  1051. const Twine &NameStr = "" ///< Name of the instruction
  1052. ) : CmpInst(makeCmpResultType(LHS->getType()),
  1053. Instruction::ICmp, pred, LHS, RHS, NameStr) {
  1054. #ifndef NDEBUG
  1055. AssertOK();
  1056. #endif
  1057. }
  1058. /// For example, EQ->EQ, SLE->SLE, UGT->SGT, etc.
  1059. /// @returns the predicate that would be the result if the operand were
  1060. /// regarded as signed.
  1061. /// Return the signed version of the predicate
  1062. Predicate getSignedPredicate() const {
  1063. return getSignedPredicate(getPredicate());
  1064. }
  1065. /// This is a static version that you can use without an instruction.
  1066. /// Return the signed version of the predicate.
  1067. static Predicate getSignedPredicate(Predicate pred);
  1068. /// For example, EQ->EQ, SLE->ULE, UGT->UGT, etc.
  1069. /// @returns the predicate that would be the result if the operand were
  1070. /// regarded as unsigned.
  1071. /// Return the unsigned version of the predicate
  1072. Predicate getUnsignedPredicate() const {
  1073. return getUnsignedPredicate(getPredicate());
  1074. }
  1075. /// This is a static version that you can use without an instruction.
  1076. /// Return the unsigned version of the predicate.
  1077. static Predicate getUnsignedPredicate(Predicate pred);
  1078. /// Return true if this predicate is either EQ or NE. This also
  1079. /// tests for commutativity.
  1080. static bool isEquality(Predicate P) {
  1081. return P == ICMP_EQ || P == ICMP_NE;
  1082. }
  1083. /// Return true if this predicate is either EQ or NE. This also
  1084. /// tests for commutativity.
  1085. bool isEquality() const {
  1086. return isEquality(getPredicate());
  1087. }
  1088. /// @returns true if the predicate of this ICmpInst is commutative
  1089. /// Determine if this relation is commutative.
  1090. bool isCommutative() const { return isEquality(); }
  1091. /// Return true if the predicate is relational (not EQ or NE).
  1092. ///
  1093. bool isRelational() const {
  1094. return !isEquality();
  1095. }
  1096. /// Return true if the predicate is relational (not EQ or NE).
  1097. ///
  1098. static bool isRelational(Predicate P) {
  1099. return !isEquality(P);
  1100. }
  1101. /// Return true if the predicate is SGT or UGT.
  1102. ///
  1103. static bool isGT(Predicate P) {
  1104. return P == ICMP_SGT || P == ICMP_UGT;
  1105. }
  1106. /// Return true if the predicate is SLT or ULT.
  1107. ///
  1108. static bool isLT(Predicate P) {
  1109. return P == ICMP_SLT || P == ICMP_ULT;
  1110. }
  1111. /// Return true if the predicate is SGE or UGE.
  1112. ///
  1113. static bool isGE(Predicate P) {
  1114. return P == ICMP_SGE || P == ICMP_UGE;
  1115. }
  1116. /// Return true if the predicate is SLE or ULE.
  1117. ///
  1118. static bool isLE(Predicate P) {
  1119. return P == ICMP_SLE || P == ICMP_ULE;
  1120. }
  1121. /// Exchange the two operands to this instruction in such a way that it does
  1122. /// not modify the semantics of the instruction. The predicate value may be
  1123. /// changed to retain the same result if the predicate is order dependent
  1124. /// (e.g. ult).
  1125. /// Swap operands and adjust predicate.
  1126. void swapOperands() {
  1127. setPredicate(getSwappedPredicate());
  1128. Op<0>().swap(Op<1>());
  1129. }
  1130. // Methods for support type inquiry through isa, cast, and dyn_cast:
  1131. static bool classof(const Instruction *I) {
  1132. return I->getOpcode() == Instruction::ICmp;
  1133. }
  1134. static bool classof(const Value *V) {
  1135. return isa<Instruction>(V) && classof(cast<Instruction>(V));
  1136. }
  1137. };
  1138. //===----------------------------------------------------------------------===//
  1139. // FCmpInst Class
  1140. //===----------------------------------------------------------------------===//
  1141. /// This instruction compares its operands according to the predicate given
  1142. /// to the constructor. It only operates on floating point values or packed
  1143. /// vectors of floating point values. The operands must be identical types.
  1144. /// Represents a floating point comparison operator.
  1145. class FCmpInst: public CmpInst {
  1146. void AssertOK() {
  1147. assert(isFPPredicate() && "Invalid FCmp predicate value");
  1148. assert(getOperand(0)->getType() == getOperand(1)->getType() &&
  1149. "Both operands to FCmp instruction are not of the same type!");
  1150. // Check that the operands are the right type
  1151. assert(getOperand(0)->getType()->isFPOrFPVectorTy() &&
  1152. "Invalid operand types for FCmp instruction");
  1153. }
  1154. protected:
  1155. // Note: Instruction needs to be a friend here to call cloneImpl.
  1156. friend class Instruction;
  1157. /// Clone an identical FCmpInst
  1158. FCmpInst *cloneImpl() const;
  1159. public:
  1160. /// Constructor with insert-before-instruction semantics.
  1161. FCmpInst(
  1162. Instruction *InsertBefore, ///< Where to insert
  1163. Predicate pred, ///< The predicate to use for the comparison
  1164. Value *LHS, ///< The left-hand-side of the expression
  1165. Value *RHS, ///< The right-hand-side of the expression
  1166. const Twine &NameStr = "" ///< Name of the instruction
  1167. ) : CmpInst(makeCmpResultType(LHS->getType()),
  1168. Instruction::FCmp, pred, LHS, RHS, NameStr,
  1169. InsertBefore) {
  1170. AssertOK();
  1171. }
  1172. /// Constructor with insert-at-end semantics.
  1173. FCmpInst(
  1174. BasicBlock &InsertAtEnd, ///< Block to insert into.
  1175. Predicate pred, ///< The predicate to use for the comparison
  1176. Value *LHS, ///< The left-hand-side of the expression
  1177. Value *RHS, ///< The right-hand-side of the expression
  1178. const Twine &NameStr = "" ///< Name of the instruction
  1179. ) : CmpInst(makeCmpResultType(LHS->getType()),
  1180. Instruction::FCmp, pred, LHS, RHS, NameStr,
  1181. &InsertAtEnd) {
  1182. AssertOK();
  1183. }
  1184. /// Constructor with no-insertion semantics
  1185. FCmpInst(
  1186. Predicate Pred, ///< The predicate to use for the comparison
  1187. Value *LHS, ///< The left-hand-side of the expression
  1188. Value *RHS, ///< The right-hand-side of the expression
  1189. const Twine &NameStr = "", ///< Name of the instruction
  1190. Instruction *FlagsSource = nullptr
  1191. ) : CmpInst(makeCmpResultType(LHS->getType()), Instruction::FCmp, Pred, LHS,
  1192. RHS, NameStr, nullptr, FlagsSource) {
  1193. AssertOK();
  1194. }
  1195. /// @returns true if the predicate of this instruction is EQ or NE.
  1196. /// Determine if this is an equality predicate.
  1197. static bool isEquality(Predicate Pred) {
  1198. return Pred == FCMP_OEQ || Pred == FCMP_ONE || Pred == FCMP_UEQ ||
  1199. Pred == FCMP_UNE;
  1200. }
  1201. /// @returns true if the predicate of this instruction is EQ or NE.
  1202. /// Determine if this is an equality predicate.
  1203. bool isEquality() const { return isEquality(getPredicate()); }
  1204. /// @returns true if the predicate of this instruction is commutative.
  1205. /// Determine if this is a commutative predicate.
  1206. bool isCommutative() const {
  1207. return isEquality() ||
  1208. getPredicate() == FCMP_FALSE ||
  1209. getPredicate() == FCMP_TRUE ||
  1210. getPredicate() == FCMP_ORD ||
  1211. getPredicate() == FCMP_UNO;
  1212. }
  1213. /// @returns true if the predicate is relational (not EQ or NE).
  1214. /// Determine if this a relational predicate.
  1215. bool isRelational() const { return !isEquality(); }
  1216. /// Exchange the two operands to this instruction in such a way that it does
  1217. /// not modify the semantics of the instruction. The predicate value may be
  1218. /// changed to retain the same result if the predicate is order dependent
  1219. /// (e.g. ult).
  1220. /// Swap operands and adjust predicate.
  1221. void swapOperands() {
  1222. setPredicate(getSwappedPredicate());
  1223. Op<0>().swap(Op<1>());
  1224. }
  1225. /// Methods for support type inquiry through isa, cast, and dyn_cast:
  1226. static bool classof(const Instruction *I) {
  1227. return I->getOpcode() == Instruction::FCmp;
  1228. }
  1229. static bool classof(const Value *V) {
  1230. return isa<Instruction>(V) && classof(cast<Instruction>(V));
  1231. }
  1232. };
  1233. //===----------------------------------------------------------------------===//
  1234. /// This class represents a function call, abstracting a target
  1235. /// machine's calling convention. This class uses low bit of the SubClassData
  1236. /// field to indicate whether or not this is a tail call. The rest of the bits
  1237. /// hold the calling convention of the call.
  1238. ///
  1239. class CallInst : public CallBase {
  1240. CallInst(const CallInst &CI);
  1241. /// Construct a CallInst given a range of arguments.
  1242. /// Construct a CallInst from a range of arguments
  1243. inline CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
  1244. ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
  1245. Instruction *InsertBefore);
  1246. inline CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
  1247. const Twine &NameStr, Instruction *InsertBefore)
  1248. : CallInst(Ty, Func, Args, None, NameStr, InsertBefore) {}
  1249. /// Construct a CallInst given a range of arguments.
  1250. /// Construct a CallInst from a range of arguments
  1251. inline CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
  1252. ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
  1253. BasicBlock *InsertAtEnd);
  1254. explicit CallInst(FunctionType *Ty, Value *F, const Twine &NameStr,
  1255. Instruction *InsertBefore);
  1256. CallInst(FunctionType *ty, Value *F, const Twine &NameStr,
  1257. BasicBlock *InsertAtEnd);
  1258. void init(FunctionType *FTy, Value *Func, ArrayRef<Value *> Args,
  1259. ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr);
  1260. void init(FunctionType *FTy, Value *Func, const Twine &NameStr);
  1261. /// Compute the number of operands to allocate.
  1262. static int ComputeNumOperands(int NumArgs, int NumBundleInputs = 0) {
  1263. // We need one operand for the called function, plus the input operand
  1264. // counts provided.
  1265. return 1 + NumArgs + NumBundleInputs;
  1266. }
  1267. protected:
  1268. // Note: Instruction needs to be a friend here to call cloneImpl.
  1269. friend class Instruction;
  1270. CallInst *cloneImpl() const;
  1271. public:
  1272. static CallInst *Create(FunctionType *Ty, Value *F, const Twine &NameStr = "",
  1273. Instruction *InsertBefore = nullptr) {
  1274. return new (ComputeNumOperands(0)) CallInst(Ty, F, NameStr, InsertBefore);
  1275. }
  1276. static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
  1277. const Twine &NameStr,
  1278. Instruction *InsertBefore = nullptr) {
  1279. return new (ComputeNumOperands(Args.size()))
  1280. CallInst(Ty, Func, Args, None, NameStr, InsertBefore);
  1281. }
  1282. static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
  1283. ArrayRef<OperandBundleDef> Bundles = None,
  1284. const Twine &NameStr = "",
  1285. Instruction *InsertBefore = nullptr) {
  1286. const int NumOperands =
  1287. ComputeNumOperands(Args.size(), CountBundleInputs(Bundles));
  1288. const unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
  1289. return new (NumOperands, DescriptorBytes)
  1290. CallInst(Ty, Func, Args, Bundles, NameStr, InsertBefore);
  1291. }
  1292. static CallInst *Create(FunctionType *Ty, Value *F, const Twine &NameStr,
  1293. BasicBlock *InsertAtEnd) {
  1294. return new (ComputeNumOperands(0)) CallInst(Ty, F, NameStr, InsertAtEnd);
  1295. }
  1296. static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
  1297. const Twine &NameStr, BasicBlock *InsertAtEnd) {
  1298. return new (ComputeNumOperands(Args.size()))
  1299. CallInst(Ty, Func, Args, None, NameStr, InsertAtEnd);
  1300. }
  1301. static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
  1302. ArrayRef<OperandBundleDef> Bundles,
  1303. const Twine &NameStr, BasicBlock *InsertAtEnd) {
  1304. const int NumOperands =
  1305. ComputeNumOperands(Args.size(), CountBundleInputs(Bundles));
  1306. const unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
  1307. return new (NumOperands, DescriptorBytes)
  1308. CallInst(Ty, Func, Args, Bundles, NameStr, InsertAtEnd);
  1309. }
  1310. static CallInst *Create(FunctionCallee Func, const Twine &NameStr = "",
  1311. Instruction *InsertBefore = nullptr) {
  1312. return Create(Func.getFunctionType(), Func.getCallee(), NameStr,
  1313. InsertBefore);
  1314. }
  1315. static CallInst *Create(FunctionCallee Func, ArrayRef<Value *> Args,
  1316. ArrayRef<OperandBundleDef> Bundles = None,
  1317. const Twine &NameStr = "",
  1318. Instruction *InsertBefore = nullptr) {
  1319. return Create(Func.getFunctionType(), Func.getCallee(), Args, Bundles,
  1320. NameStr, InsertBefore);
  1321. }
  1322. static CallInst *Create(FunctionCallee Func, ArrayRef<Value *> Args,
  1323. const Twine &NameStr,
  1324. Instruction *InsertBefore = nullptr) {
  1325. return Create(Func.getFunctionType(), Func.getCallee(), Args, NameStr,
  1326. InsertBefore);
  1327. }
  1328. static CallInst *Create(FunctionCallee Func, const Twine &NameStr,
  1329. BasicBlock *InsertAtEnd) {
  1330. return Create(Func.getFunctionType(), Func.getCallee(), NameStr,
  1331. InsertAtEnd);
  1332. }
  1333. static CallInst *Create(FunctionCallee Func, ArrayRef<Value *> Args,
  1334. const Twine &NameStr, BasicBlock *InsertAtEnd) {
  1335. return Create(Func.getFunctionType(), Func.getCallee(), Args, NameStr,
  1336. InsertAtEnd);
  1337. }
  1338. static CallInst *Create(FunctionCallee Func, ArrayRef<Value *> Args,
  1339. ArrayRef<OperandBundleDef> Bundles,
  1340. const Twine &NameStr, BasicBlock *InsertAtEnd) {
  1341. return Create(Func.getFunctionType(), Func.getCallee(), Args, Bundles,
  1342. NameStr, InsertAtEnd);
  1343. }
  1344. // Deprecated [opaque pointer types]
  1345. static CallInst *Create(Value *Func, const Twine &NameStr = "",
  1346. Instruction *InsertBefore = nullptr) {
  1347. return Create(cast<FunctionType>(
  1348. cast<PointerType>(Func->getType())->getElementType()),
  1349. Func, NameStr, InsertBefore);
  1350. }
  1351. // Deprecated [opaque pointer types]
  1352. static CallInst *Create(Value *Func, ArrayRef<Value *> Args,
  1353. const Twine &NameStr,
  1354. Instruction *InsertBefore = nullptr) {
  1355. return Create(cast<FunctionType>(
  1356. cast<PointerType>(Func->getType())->getElementType()),
  1357. Func, Args, NameStr, InsertBefore);
  1358. }
  1359. // Deprecated [opaque pointer types]
  1360. static CallInst *Create(Value *Func, ArrayRef<Value *> Args,
  1361. ArrayRef<OperandBundleDef> Bundles = None,
  1362. const Twine &NameStr = "",
  1363. Instruction *InsertBefore = nullptr) {
  1364. return Create(cast<FunctionType>(
  1365. cast<PointerType>(Func->getType())->getElementType()),
  1366. Func, Args, Bundles, NameStr, InsertBefore);
  1367. }
  1368. // Deprecated [opaque pointer types]
  1369. static CallInst *Create(Value *Func, const Twine &NameStr,
  1370. BasicBlock *InsertAtEnd) {
  1371. return Create(cast<FunctionType>(
  1372. cast<PointerType>(Func->getType())->getElementType()),
  1373. Func, NameStr, InsertAtEnd);
  1374. }
  1375. // Deprecated [opaque pointer types]
  1376. static CallInst *Create(Value *Func, ArrayRef<Value *> Args,
  1377. const Twine &NameStr, BasicBlock *InsertAtEnd) {
  1378. return Create(cast<FunctionType>(
  1379. cast<PointerType>(Func->getType())->getElementType()),
  1380. Func, Args, NameStr, InsertAtEnd);
  1381. }
  1382. // Deprecated [opaque pointer types]
  1383. static CallInst *Create(Value *Func, ArrayRef<Value *> Args,
  1384. ArrayRef<OperandBundleDef> Bundles,
  1385. const Twine &NameStr, BasicBlock *InsertAtEnd) {
  1386. return Create(cast<FunctionType>(
  1387. cast<PointerType>(Func->getType())->getElementType()),
  1388. Func, Args, Bundles, NameStr, InsertAtEnd);
  1389. }
  1390. /// Create a clone of \p CI with a different set of operand bundles and
  1391. /// insert it before \p InsertPt.
  1392. ///
  1393. /// The returned call instruction is identical \p CI in every way except that
  1394. /// the operand bundles for the new instruction are set to the operand bundles
  1395. /// in \p Bundles.
  1396. static CallInst *Create(CallInst *CI, ArrayRef<OperandBundleDef> Bundles,
  1397. Instruction *InsertPt = nullptr);
  1398. /// Create a clone of \p CI with a different set of operand bundles and
  1399. /// insert it before \p InsertPt.
  1400. ///
  1401. /// The returned call instruction is identical \p CI in every way except that
  1402. /// the operand bundle for the new instruction is set to the operand bundle
  1403. /// in \p Bundle.
  1404. static CallInst *CreateWithReplacedBundle(CallInst *CI,
  1405. OperandBundleDef Bundle,
  1406. Instruction *InsertPt = nullptr);
  1407. /// Generate the IR for a call to malloc:
  1408. /// 1. Compute the malloc call's argument as the specified type's size,
  1409. /// possibly multiplied by the array size if the array size is not
  1410. /// constant 1.
  1411. /// 2. Call malloc with that argument.
  1412. /// 3. Bitcast the result of the malloc call to the specified type.
  1413. static Instruction *CreateMalloc(Instruction *InsertBefore, Type *IntPtrTy,
  1414. Type *AllocTy, Value *AllocSize,
  1415. Value *ArraySize = nullptr,
  1416. Function *MallocF = nullptr,
  1417. const Twine &Name = "");
  1418. static Instruction *CreateMalloc(BasicBlock *InsertAtEnd, Type *IntPtrTy,
  1419. Type *AllocTy, Value *AllocSize,
  1420. Value *ArraySize = nullptr,
  1421. Function *MallocF = nullptr,
  1422. const Twine &Name = "");
  1423. static Instruction *CreateMalloc(Instruction *InsertBefore, Type *IntPtrTy,
  1424. Type *AllocTy, Value *AllocSize,
  1425. Value *ArraySize = nullptr,
  1426. ArrayRef<OperandBundleDef> Bundles = None,
  1427. Function *MallocF = nullptr,
  1428. const Twine &Name = "");
  1429. static Instruction *CreateMalloc(BasicBlock *InsertAtEnd, Type *IntPtrTy,
  1430. Type *AllocTy, Value *AllocSize,
  1431. Value *ArraySize = nullptr,
  1432. ArrayRef<OperandBundleDef> Bundles = None,
  1433. Function *MallocF = nullptr,
  1434. const Twine &Name = "");
  1435. /// Generate the IR for a call to the builtin free function.
  1436. static Instruction *CreateFree(Value *Source, Instruction *InsertBefore);
  1437. static Instruction *CreateFree(Value *Source, BasicBlock *InsertAtEnd);
  1438. static Instruction *CreateFree(Value *Source,
  1439. ArrayRef<OperandBundleDef> Bundles,
  1440. Instruction *InsertBefore);
  1441. static Instruction *CreateFree(Value *Source,
  1442. ArrayRef<OperandBundleDef> Bundles,
  1443. BasicBlock *InsertAtEnd);
  1444. // Note that 'musttail' implies 'tail'.
  1445. enum TailCallKind : unsigned {
  1446. TCK_None = 0,
  1447. TCK_Tail = 1,
  1448. TCK_MustTail = 2,
  1449. TCK_NoTail = 3,
  1450. TCK_LAST = TCK_NoTail
  1451. };
  1452. using TailCallKindField = Bitfield::Element<TailCallKind, 0, 2, TCK_LAST>;
  1453. static_assert(
  1454. Bitfield::areContiguous<TailCallKindField, CallBase::CallingConvField>(),
  1455. "Bitfields must be contiguous");
  1456. TailCallKind getTailCallKind() const {
  1457. return getSubclassData<TailCallKindField>();
  1458. }
  1459. bool isTailCall() const {
  1460. TailCallKind Kind = getTailCallKind();
  1461. return Kind == TCK_Tail || Kind == TCK_MustTail;
  1462. }
  1463. bool isMustTailCall() const { return getTailCallKind() == TCK_MustTail; }
  1464. bool isNoTailCall() const { return getTailCallKind() == TCK_NoTail; }
  1465. void setTailCallKind(TailCallKind TCK) {
  1466. setSubclassData<TailCallKindField>(TCK);
  1467. }
  1468. void setTailCall(bool IsTc = true) {
  1469. setTailCallKind(IsTc ? TCK_Tail : TCK_None);
  1470. }
  1471. /// Return true if the call can return twice
  1472. bool canReturnTwice() const { return hasFnAttr(Attribute::ReturnsTwice); }
  1473. void setCanReturnTwice() {
  1474. addAttribute(AttributeList::FunctionIndex, Attribute::ReturnsTwice);
  1475. }
  1476. // Methods for support type inquiry through isa, cast, and dyn_cast:
  1477. static bool classof(const Instruction *I) {
  1478. return I->getOpcode() == Instruction::Call;
  1479. }
  1480. static bool classof(const Value *V) {
  1481. return isa<Instruction>(V) && classof(cast<Instruction>(V));
  1482. }
  1483. /// Updates profile metadata by scaling it by \p S / \p T.
  1484. void updateProfWeight(uint64_t S, uint64_t T);
  1485. private:
  1486. // Shadow Instruction::setInstructionSubclassData with a private forwarding
  1487. // method so that subclasses cannot accidentally use it.
  1488. template <typename Bitfield>
  1489. void setSubclassData(typename Bitfield::Type Value) {
  1490. Instruction::setSubclassData<Bitfield>(Value);
  1491. }
  1492. };
  1493. CallInst::CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
  1494. ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
  1495. BasicBlock *InsertAtEnd)
  1496. : CallBase(Ty->getReturnType(), Instruction::Call,
  1497. OperandTraits<CallBase>::op_end(this) -
  1498. (Args.size() + CountBundleInputs(Bundles) + 1),
  1499. unsigned(Args.size() + CountBundleInputs(Bundles) + 1),
  1500. InsertAtEnd) {
  1501. init(Ty, Func, Args, Bundles, NameStr);
  1502. }
  1503. CallInst::CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
  1504. ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
  1505. Instruction *InsertBefore)
  1506. : CallBase(Ty->getReturnType(), Instruction::Call,
  1507. OperandTraits<CallBase>::op_end(this) -
  1508. (Args.size() + CountBundleInputs(Bundles) + 1),
  1509. unsigned(Args.size() + CountBundleInputs(Bundles) + 1),
  1510. InsertBefore) {
  1511. init(Ty, Func, Args, Bundles, NameStr);
  1512. }
  1513. //===----------------------------------------------------------------------===//
  1514. // SelectInst Class
  1515. //===----------------------------------------------------------------------===//
  1516. /// This class represents the LLVM 'select' instruction.
  1517. ///
  1518. class SelectInst : public Instruction {
  1519. SelectInst(Value *C, Value *S1, Value *S2, const Twine &NameStr,
  1520. Instruction *InsertBefore)
  1521. : Instruction(S1->getType(), Instruction::Select,
  1522. &Op<0>(), 3, InsertBefore) {
  1523. init(C, S1, S2);
  1524. setName(NameStr);
  1525. }
  1526. SelectInst(Value *C, Value *S1, Value *S2, const Twine &NameStr,
  1527. BasicBlock *InsertAtEnd)
  1528. : Instruction(S1->getType(), Instruction::Select,
  1529. &Op<0>(), 3, InsertAtEnd) {
  1530. init(C, S1, S2);
  1531. setName(NameStr);
  1532. }
  1533. void init(Value *C, Value *S1, Value *S2) {
  1534. assert(!areInvalidOperands(C, S1, S2) && "Invalid operands for select");
  1535. Op<0>() = C;
  1536. Op<1>() = S1;
  1537. Op<2>() = S2;
  1538. }
  1539. protected:
  1540. // Note: Instruction needs to be a friend here to call cloneImpl.
  1541. friend class Instruction;
  1542. SelectInst *cloneImpl() const;
  1543. public:
  1544. static SelectInst *Create(Value *C, Value *S1, Value *S2,
  1545. const Twine &NameStr = "",
  1546. Instruction *InsertBefore = nullptr,
  1547. Instruction *MDFrom = nullptr) {
  1548. SelectInst *Sel = new(3) SelectInst(C, S1, S2, NameStr, InsertBefore);
  1549. if (MDFrom)
  1550. Sel->copyMetadata(*MDFrom);
  1551. return Sel;
  1552. }
  1553. static SelectInst *Create(Value *C, Value *S1, Value *S2,
  1554. const Twine &NameStr,
  1555. BasicBlock *InsertAtEnd) {
  1556. return new(3) SelectInst(C, S1, S2, NameStr, InsertAtEnd);
  1557. }
  1558. const Value *getCondition() const { return Op<0>(); }
  1559. const Value *getTrueValue() const { return Op<1>(); }
  1560. const Value *getFalseValue() const { return Op<2>(); }
  1561. Value *getCondition() { return Op<0>(); }
  1562. Value *getTrueValue() { return Op<1>(); }
  1563. Value *getFalseValue() { return Op<2>(); }
  1564. void setCondition(Value *V) { Op<0>() = V; }
  1565. void setTrueValue(Value *V) { Op<1>() = V; }
  1566. void setFalseValue(Value *V) { Op<2>() = V; }
  1567. /// Swap the true and false values of the select instruction.
  1568. /// This doesn't swap prof metadata.
  1569. void swapValues() { Op<1>().swap(Op<2>()); }
  1570. /// Return a string if the specified operands are invalid
  1571. /// for a select operation, otherwise return null.
  1572. static const char *areInvalidOperands(Value *Cond, Value *True, Value *False);
  1573. /// Transparently provide more efficient getOperand methods.
  1574. DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
  1575. OtherOps getOpcode() const {
  1576. return static_cast<OtherOps>(Instruction::getOpcode());
  1577. }
  1578. // Methods for support type inquiry through isa, cast, and dyn_cast:
  1579. static bool classof(const Instruction *I) {
  1580. return I->getOpcode() == Instruction::Select;
  1581. }
  1582. static bool classof(const Value *V) {
  1583. return isa<Instruction>(V) && classof(cast<Instruction>(V));
  1584. }
  1585. };
  1586. template <>
  1587. struct OperandTraits<SelectInst> : public FixedNumOperandTraits<SelectInst, 3> {
  1588. };
  1589. DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SelectInst, Value)
  1590. //===----------------------------------------------------------------------===//
  1591. // VAArgInst Class
  1592. //===----------------------------------------------------------------------===//
  1593. /// This class represents the va_arg llvm instruction, which returns
  1594. /// an argument of the specified type given a va_list and increments that list
  1595. ///
  1596. class VAArgInst : public UnaryInstruction {
  1597. protected:
  1598. // Note: Instruction needs to be a friend here to call cloneImpl.
  1599. friend class Instruction;
  1600. VAArgInst *cloneImpl() const;
  1601. public:
  1602. VAArgInst(Value *List, Type *Ty, const Twine &NameStr = "",
  1603. Instruction *InsertBefore = nullptr)
  1604. : UnaryInstruction(Ty, VAArg, List, InsertBefore) {
  1605. setName(NameStr);
  1606. }
  1607. VAArgInst(Value *List, Type *Ty, const Twine &NameStr,
  1608. BasicBlock *InsertAtEnd)
  1609. : UnaryInstruction(Ty, VAArg, List, InsertAtEnd) {
  1610. setName(NameStr);
  1611. }
  1612. Value *getPointerOperand() { return getOperand(0); }
  1613. const Value *getPointerOperand() const { return getOperand(0); }
  1614. static unsigned getPointerOperandIndex() { return 0U; }
  1615. // Methods for support type inquiry through isa, cast, and dyn_cast:
  1616. static bool classof(const Instruction *I) {
  1617. return I->getOpcode() == VAArg;
  1618. }
  1619. static bool classof(const Value *V) {
  1620. return isa<Instruction>(V) && classof(cast<Instruction>(V));
  1621. }
  1622. };
  1623. //===----------------------------------------------------------------------===//
  1624. // ExtractElementInst Class
  1625. //===----------------------------------------------------------------------===//
  1626. /// This instruction extracts a single (scalar)
  1627. /// element from a VectorType value
  1628. ///
  1629. class ExtractElementInst : public Instruction {
  1630. ExtractElementInst(Value *Vec, Value *Idx, const Twine &NameStr = "",
  1631. Instruction *InsertBefore = nullptr);
  1632. ExtractElementInst(Value *Vec, Value *Idx, const Twine &NameStr,
  1633. BasicBlock *InsertAtEnd);
  1634. protected:
  1635. // Note: Instruction needs to be a friend here to call cloneImpl.
  1636. friend class Instruction;
  1637. ExtractElementInst *cloneImpl() const;
  1638. public:
  1639. static ExtractElementInst *Create(Value *Vec, Value *Idx,
  1640. const Twine &NameStr = "",
  1641. Instruction *InsertBefore = nullptr) {
  1642. return new(2) ExtractElementInst(Vec, Idx, NameStr, InsertBefore);
  1643. }
  1644. static ExtractElementInst *Create(Value *Vec, Value *Idx,
  1645. const Twine &NameStr,
  1646. BasicBlock *InsertAtEnd) {
  1647. return new(2) ExtractElementInst(Vec, Idx, NameStr, InsertAtEnd);
  1648. }
  1649. /// Return true if an extractelement instruction can be
  1650. /// formed with the specified operands.
  1651. static bool isValidOperands(const Value *Vec, const Value *Idx);
  1652. Value *getVectorOperand() { return Op<0>(); }
  1653. Value *getIndexOperand() { return Op<1>(); }
  1654. const Value *getVectorOperand() const { return Op<0>(); }
  1655. const Value *getIndexOperand() const { return Op<1>(); }
  1656. VectorType *getVectorOperandType() const {
  1657. return cast<VectorType>(getVectorOperand()->getType());
  1658. }
  1659. /// Transparently provide more efficient getOperand methods.
  1660. DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
  1661. // Methods for support type inquiry through isa, cast, and dyn_cast:
  1662. static bool classof(const Instruction *I) {
  1663. return I->getOpcode() == Instruction::ExtractElement;
  1664. }
  1665. static bool classof(const Value *V) {
  1666. return isa<Instruction>(V) && classof(cast<Instruction>(V));
  1667. }
  1668. };
  1669. template <>
  1670. struct OperandTraits<ExtractElementInst> :
  1671. public FixedNumOperandTraits<ExtractElementInst, 2> {
  1672. };
  1673. DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractElementInst, Value)
  1674. //===----------------------------------------------------------------------===//
  1675. // InsertElementInst Class
  1676. //===----------------------------------------------------------------------===//
  1677. /// This instruction inserts a single (scalar)
  1678. /// element into a VectorType value
  1679. ///
  1680. class InsertElementInst : public Instruction {
  1681. InsertElementInst(Value *Vec, Value *NewElt, Value *Idx,
  1682. const Twine &NameStr = "",
  1683. Instruction *InsertBefore = nullptr);
  1684. InsertElementInst(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr,
  1685. BasicBlock *InsertAtEnd);
  1686. protected:
  1687. // Note: Instruction needs to be a friend here to call cloneImpl.
  1688. friend class Instruction;
  1689. InsertElementInst *cloneImpl() const;
  1690. public:
  1691. static InsertElementInst *Create(Value *Vec, Value *NewElt, Value *Idx,
  1692. const Twine &NameStr = "",
  1693. Instruction *InsertBefore = nullptr) {
  1694. return new(3) InsertElementInst(Vec, NewElt, Idx, NameStr, InsertBefore);
  1695. }
  1696. static InsertElementInst *Create(Value *Vec, Value *NewElt, Value *Idx,
  1697. const Twine &NameStr,
  1698. BasicBlock *InsertAtEnd) {
  1699. return new(3) InsertElementInst(Vec, NewElt, Idx, NameStr, InsertAtEnd);
  1700. }
  1701. /// Return true if an insertelement instruction can be
  1702. /// formed with the specified operands.
  1703. static bool isValidOperands(const Value *Vec, const Value *NewElt,
  1704. const Value *Idx);
  1705. /// Overload to return most specific vector type.
  1706. ///
  1707. VectorType *getType() const {
  1708. return cast<VectorType>(Instruction::getType());
  1709. }
  1710. /// Transparently provide more efficient getOperand methods.
  1711. DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
  1712. // Methods for support type inquiry through isa, cast, and dyn_cast:
  1713. static bool classof(const Instruction *I) {
  1714. return I->getOpcode() == Instruction::InsertElement;
  1715. }
  1716. static bool classof(const Value *V) {
  1717. return isa<Instruction>(V) && classof(cast<Instruction>(V));
  1718. }
  1719. };
  1720. template <>
  1721. struct OperandTraits<InsertElementInst> :
  1722. public FixedNumOperandTraits<InsertElementInst, 3> {
  1723. };
  1724. DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertElementInst, Value)
  1725. //===----------------------------------------------------------------------===//
  1726. // ShuffleVectorInst Class
  1727. //===----------------------------------------------------------------------===//
  1728. constexpr int UndefMaskElem = -1;
  1729. /// This instruction constructs a fixed permutation of two
  1730. /// input vectors.
  1731. ///
  1732. /// For each element of the result vector, the shuffle mask selects an element
  1733. /// from one of the input vectors to copy to the result. Non-negative elements
  1734. /// in the mask represent an index into the concatenated pair of input vectors.
  1735. /// UndefMaskElem (-1) specifies that the result element is undefined.
  1736. ///
  1737. /// For scalable vectors, all the elements of the mask must be 0 or -1. This
  1738. /// requirement may be relaxed in the future.
  1739. class ShuffleVectorInst : public Instruction {
  1740. SmallVector<int, 4> ShuffleMask;
  1741. Constant *ShuffleMaskForBitcode;
  1742. protected:
  1743. // Note: Instruction needs to be a friend here to call cloneImpl.
  1744. friend class Instruction;
  1745. ShuffleVectorInst *cloneImpl() const;
  1746. public:
  1747. ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
  1748. const Twine &NameStr = "",
  1749. Instruction *InsertBefor = nullptr);
  1750. ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
  1751. const Twine &NameStr, BasicBlock *InsertAtEnd);
  1752. ShuffleVectorInst(Value *V1, Value *V2, ArrayRef<int> Mask,
  1753. const Twine &NameStr = "",
  1754. Instruction *InsertBefor = nullptr);
  1755. ShuffleVectorInst(Value *V1, Value *V2, ArrayRef<int> Mask,
  1756. const Twine &NameStr, BasicBlock *InsertAtEnd);
  1757. void *operator new(size_t s) { return User::operator new(s, 2); }
  1758. /// Swap the operands and adjust the mask to preserve the semantics
  1759. /// of the instruction.
  1760. void commute();
  1761. /// Return true if a shufflevector instruction can be
  1762. /// formed with the specified operands.
  1763. static bool isValidOperands(const Value *V1, const Value *V2,
  1764. const Value *Mask);
  1765. static bool isValidOperands(const Value *V1, const Value *V2,
  1766. ArrayRef<int> Mask);
  1767. /// Overload to return most specific vector type.
  1768. ///
  1769. VectorType *getType() const {
  1770. return cast<VectorType>(Instruction::getType());
  1771. }
  1772. /// Transparently provide more efficient getOperand methods.
  1773. DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
  1774. /// Return the shuffle mask value of this instruction for the given element
  1775. /// index. Return UndefMaskElem if the element is undef.
  1776. int getMaskValue(unsigned Elt) const { return ShuffleMask[Elt]; }
  1777. /// Convert the input shuffle mask operand to a vector of integers. Undefined
  1778. /// elements of the mask are returned as UndefMaskElem.
  1779. static void getShuffleMask(const Constant *Mask,
  1780. SmallVectorImpl<int> &Result);
  1781. /// Return the mask for this instruction as a vector of integers. Undefined
  1782. /// elements of the mask are returned as UndefMaskElem.
  1783. void getShuffleMask(SmallVectorImpl<int> &Result) const {
  1784. Result.assign(ShuffleMask.begin(), ShuffleMask.end());
  1785. }
  1786. /// Return the mask for this instruction, for use in bitcode.
  1787. ///
  1788. /// TODO: This is temporary until we decide a new bitcode encoding for
  1789. /// shufflevector.
  1790. Constant *getShuffleMaskForBitcode() const { return ShuffleMaskForBitcode; }
  1791. static Constant *convertShuffleMaskForBitcode(ArrayRef<int> Mask,
  1792. Type *ResultTy);
  1793. void setShuffleMask(ArrayRef<int> Mask);
  1794. ArrayRef<int> getShuffleMask() const { return ShuffleMask; }
  1795. /// Return true if this shuffle returns a vector with a different number of
  1796. /// elements than its source vectors.
  1797. /// Examples: shufflevector <4 x n> A, <4 x n> B, <1,2,3>
  1798. /// shufflevector <4 x n> A, <4 x n> B, <1,2,3,4,5>
  1799. bool changesLength() const {
  1800. unsigned NumSourceElts = cast<VectorType>(Op<0>()->getType())
  1801. ->getElementCount()
  1802. .getKnownMinValue();
  1803. unsigned NumMaskElts = ShuffleMask.size();
  1804. return NumSourceElts != NumMaskElts;
  1805. }
  1806. /// Return true if this shuffle returns a vector with a greater number of
  1807. /// elements than its source vectors.
  1808. /// Example: shufflevector <2 x n> A, <2 x n> B, <1,2,3>
  1809. bool increasesLength() const {
  1810. unsigned NumSourceElts = cast<VectorType>(Op<0>()->getType())
  1811. ->getElementCount()
  1812. .getKnownMinValue();
  1813. unsigned NumMaskElts = ShuffleMask.size();
  1814. return NumSourceElts < NumMaskElts;
  1815. }
  1816. /// Return true if this shuffle mask chooses elements from exactly one source
  1817. /// vector.
  1818. /// Example: <7,5,undef,7>
  1819. /// This assumes that vector operands are the same length as the mask.
  1820. static bool isSingleSourceMask(ArrayRef<int> Mask);
  1821. static bool isSingleSourceMask(const Constant *Mask) {
  1822. assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.");
  1823. SmallVector<int, 16> MaskAsInts;
  1824. getShuffleMask(Mask, MaskAsInts);
  1825. return isSingleSourceMask(MaskAsInts);
  1826. }
  1827. /// Return true if this shuffle chooses elements from exactly one source
  1828. /// vector without changing the length of that vector.
  1829. /// Example: shufflevector <4 x n> A, <4 x n> B, <3,0,undef,3>
  1830. /// TODO: Optionally allow length-changing shuffles.
  1831. bool isSingleSource() const {
  1832. return !changesLength() && isSingleSourceMask(ShuffleMask);
  1833. }
  1834. /// Return true if this shuffle mask chooses elements from exactly one source
  1835. /// vector without lane crossings. A shuffle using this mask is not
  1836. /// necessarily a no-op because it may change the number of elements from its
  1837. /// input vectors or it may provide demanded bits knowledge via undef lanes.
  1838. /// Example: <undef,undef,2,3>
  1839. static bool isIdentityMask(ArrayRef<int> Mask);
  1840. static bool isIdentityMask(const Constant *Mask) {
  1841. assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.");
  1842. SmallVector<int, 16> MaskAsInts;
  1843. getShuffleMask(Mask, MaskAsInts);
  1844. return isIdentityMask(MaskAsInts);
  1845. }
  1846. /// Return true if this shuffle chooses elements from exactly one source
  1847. /// vector without lane crossings and does not change the number of elements
  1848. /// from its input vectors.
  1849. /// Example: shufflevector <4 x n> A, <4 x n> B, <4,undef,6,undef>
  1850. bool isIdentity() const {
  1851. return !changesLength() && isIdentityMask(ShuffleMask);
  1852. }
  1853. /// Return true if this shuffle lengthens exactly one source vector with
  1854. /// undefs in the high elements.
  1855. bool isIdentityWithPadding() const;
  1856. /// Return true if this shuffle extracts the first N elements of exactly one
  1857. /// source vector.
  1858. bool isIdentityWithExtract() const;
  1859. /// Return true if this shuffle concatenates its 2 source vectors. This
  1860. /// returns false if either input is undefined. In that case, the shuffle is
  1861. /// is better classified as an identity with padding operation.
  1862. bool isConcat() const;
  1863. /// Return true if this shuffle mask chooses elements from its source vectors
  1864. /// without lane crossings. A shuffle using this mask would be
  1865. /// equivalent to a vector select with a constant condition operand.
  1866. /// Example: <4,1,6,undef>
  1867. /// This returns false if the mask does not choose from both input vectors.
  1868. /// In that case, the shuffle is better classified as an identity shuffle.
  1869. /// This assumes that vector operands are the same length as the mask
  1870. /// (a length-changing shuffle can never be equivalent to a vector select).
  1871. static bool isSelectMask(ArrayRef<int> Mask);
  1872. static bool isSelectMask(const Constant *Mask) {
  1873. assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.");
  1874. SmallVector<int, 16> MaskAsInts;
  1875. getShuffleMask(Mask, MaskAsInts);
  1876. return isSelectMask(MaskAsInts);
  1877. }
  1878. /// Return true if this shuffle chooses elements from its source vectors
  1879. /// without lane crossings and all operands have the same number of elements.
  1880. /// In other words, this shuffle is equivalent to a vector select with a
  1881. /// constant condition operand.
  1882. /// Example: shufflevector <4 x n> A, <4 x n> B, <undef,1,6,3>
  1883. /// This returns false if the mask does not choose from both input vectors.
  1884. /// In that case, the shuffle is better classified as an identity shuffle.
  1885. /// TODO: Optionally allow length-changing shuffles.
  1886. bool isSelect() const {
  1887. return !changesLength() && isSelectMask(ShuffleMask);
  1888. }
  1889. /// Return true if this shuffle mask swaps the order of elements from exactly
  1890. /// one source vector.
  1891. /// Example: <7,6,undef,4>
  1892. /// This assumes that vector operands are the same length as the mask.
  1893. static bool isReverseMask(ArrayRef<int> Mask);
  1894. static bool isReverseMask(const Constant *Mask) {
  1895. assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.");
  1896. SmallVector<int, 16> MaskAsInts;
  1897. getShuffleMask(Mask, MaskAsInts);
  1898. return isReverseMask(MaskAsInts);
  1899. }
  1900. /// Return true if this shuffle swaps the order of elements from exactly
  1901. /// one source vector.
  1902. /// Example: shufflevector <4 x n> A, <4 x n> B, <3,undef,1,undef>
  1903. /// TODO: Optionally allow length-changing shuffles.
  1904. bool isReverse() const {
  1905. return !changesLength() && isReverseMask(ShuffleMask);
  1906. }
  1907. /// Return true if this shuffle mask chooses all elements with the same value
  1908. /// as the first element of exactly one source vector.
  1909. /// Example: <4,undef,undef,4>
  1910. /// This assumes that vector operands are the same length as the mask.
  1911. static bool isZeroEltSplatMask(ArrayRef<int> Mask);
  1912. static bool isZeroEltSplatMask(const Constant *Mask) {
  1913. assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.");
  1914. SmallVector<int, 16> MaskAsInts;
  1915. getShuffleMask(Mask, MaskAsInts);
  1916. return isZeroEltSplatMask(MaskAsInts);
  1917. }
  1918. /// Return true if all elements of this shuffle are the same value as the
  1919. /// first element of exactly one source vector without changing the length
  1920. /// of that vector.
  1921. /// Example: shufflevector <4 x n> A, <4 x n> B, <undef,0,undef,0>
  1922. /// TODO: Optionally allow length-changing shuffles.
  1923. /// TODO: Optionally allow splats from other elements.
  1924. bool isZeroEltSplat() const {
  1925. return !changesLength() && isZeroEltSplatMask(ShuffleMask);
  1926. }
  1927. /// Return true if this shuffle mask is a transpose mask.
  1928. /// Transpose vector masks transpose a 2xn matrix. They read corresponding
  1929. /// even- or odd-numbered vector elements from two n-dimensional source
  1930. /// vectors and write each result into consecutive elements of an
  1931. /// n-dimensional destination vector. Two shuffles are necessary to complete
  1932. /// the transpose, one for the even elements and another for the odd elements.
  1933. /// This description closely follows how the TRN1 and TRN2 AArch64
  1934. /// instructions operate.
  1935. ///
  1936. /// For example, a simple 2x2 matrix can be transposed with:
  1937. ///
  1938. /// ; Original matrix
  1939. /// m0 = < a, b >
  1940. /// m1 = < c, d >
  1941. ///
  1942. /// ; Transposed matrix
  1943. /// t0 = < a, c > = shufflevector m0, m1, < 0, 2 >
  1944. /// t1 = < b, d > = shufflevector m0, m1, < 1, 3 >
  1945. ///
  1946. /// For matrices having greater than n columns, the resulting nx2 transposed
  1947. /// matrix is stored in two result vectors such that one vector contains
  1948. /// interleaved elements from all the even-numbered rows and the other vector
  1949. /// contains interleaved elements from all the odd-numbered rows. For example,
  1950. /// a 2x4 matrix can be transposed with:
  1951. ///
  1952. /// ; Original matrix
  1953. /// m0 = < a, b, c, d >
  1954. /// m1 = < e, f, g, h >
  1955. ///
  1956. /// ; Transposed matrix
  1957. /// t0 = < a, e, c, g > = shufflevector m0, m1 < 0, 4, 2, 6 >
  1958. /// t1 = < b, f, d, h > = shufflevector m0, m1 < 1, 5, 3, 7 >
  1959. static bool isTransposeMask(ArrayRef<int> Mask);
  1960. static bool isTransposeMask(const Constant *Mask) {
  1961. assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.");
  1962. SmallVector<int, 16> MaskAsInts;
  1963. getShuffleMask(Mask, MaskAsInts);
  1964. return isTransposeMask(MaskAsInts);
  1965. }
  1966. /// Return true if this shuffle transposes the elements of its inputs without
  1967. /// changing the length of the vectors. This operation may also be known as a
  1968. /// merge or interleave. See the description for isTransposeMask() for the
  1969. /// exact specification.
  1970. /// Example: shufflevector <4 x n> A, <4 x n> B, <0,4,2,6>
  1971. bool isTranspose() const {
  1972. return !changesLength() && isTransposeMask(ShuffleMask);
  1973. }
  1974. /// Return true if this shuffle mask is an extract subvector mask.
  1975. /// A valid extract subvector mask returns a smaller vector from a single
  1976. /// source operand. The base extraction index is returned as well.
  1977. static bool isExtractSubvectorMask(ArrayRef<int> Mask, int NumSrcElts,
  1978. int &Index);
  1979. static bool isExtractSubvectorMask(const Constant *Mask, int NumSrcElts,
  1980. int &Index) {
  1981. assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.");
  1982. // Not possible to express a shuffle mask for a scalable vector for this
  1983. // case.
  1984. if (isa<ScalableVectorType>(Mask->getType()))
  1985. return false;
  1986. SmallVector<int, 16> MaskAsInts;
  1987. getShuffleMask(Mask, MaskAsInts);
  1988. return isExtractSubvectorMask(MaskAsInts, NumSrcElts, Index);
  1989. }
  1990. /// Return true if this shuffle mask is an extract subvector mask.
  1991. bool isExtractSubvectorMask(int &Index) const {
  1992. // Not possible to express a shuffle mask for a scalable vector for this
  1993. // case.
  1994. if (isa<ScalableVectorType>(getType()))
  1995. return false;
  1996. int NumSrcElts =
  1997. cast<FixedVectorType>(Op<0>()->getType())->getNumElements();
  1998. return isExtractSubvectorMask(ShuffleMask, NumSrcElts, Index);
  1999. }
  2000. /// Change values in a shuffle permute mask assuming the two vector operands
  2001. /// of length InVecNumElts have swapped position.
  2002. static void commuteShuffleMask(MutableArrayRef<int> Mask,
  2003. unsigned InVecNumElts) {
  2004. for (int &Idx : Mask) {
  2005. if (Idx == -1)
  2006. continue;
  2007. Idx = Idx < (int)InVecNumElts ? Idx + InVecNumElts : Idx - InVecNumElts;
  2008. assert(Idx >= 0 && Idx < (int)InVecNumElts * 2 &&
  2009. "shufflevector mask index out of range");
  2010. }
  2011. }
  2012. // Methods for support type inquiry through isa, cast, and dyn_cast:
  2013. static bool classof(const Instruction *I) {
  2014. return I->getOpcode() == Instruction::ShuffleVector;
  2015. }
  2016. static bool classof(const Value *V) {
  2017. return isa<Instruction>(V) && classof(cast<Instruction>(V));
  2018. }
  2019. };
  2020. template <>
  2021. struct OperandTraits<ShuffleVectorInst>
  2022. : public FixedNumOperandTraits<ShuffleVectorInst, 2> {};
  2023. DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ShuffleVectorInst, Value)
  2024. //===----------------------------------------------------------------------===//
  2025. // ExtractValueInst Class
  2026. //===----------------------------------------------------------------------===//
  2027. /// This instruction extracts a struct member or array
  2028. /// element value from an aggregate value.
  2029. ///
  2030. class ExtractValueInst : public UnaryInstruction {
  2031. SmallVector<unsigned, 4> Indices;
  2032. ExtractValueInst(const ExtractValueInst &EVI);
  2033. /// Constructors - Create a extractvalue instruction with a base aggregate
  2034. /// value and a list of indices. The first ctor can optionally insert before
  2035. /// an existing instruction, the second appends the new instruction to the
  2036. /// specified BasicBlock.
  2037. inline ExtractValueInst(Value *Agg,
  2038. ArrayRef<unsigned> Idxs,
  2039. const Twine &NameStr,
  2040. Instruction *InsertBefore);
  2041. inline ExtractValueInst(Value *Agg,
  2042. ArrayRef<unsigned> Idxs,
  2043. const Twine &NameStr, BasicBlock *InsertAtEnd);
  2044. void init(ArrayRef<unsigned> Idxs, const Twine &NameStr);
  2045. protected:
  2046. // Note: Instruction needs to be a friend here to call cloneImpl.
  2047. friend class Instruction;
  2048. ExtractValueInst *cloneImpl() const;
  2049. public:
  2050. static ExtractValueInst *Create(Value *Agg,
  2051. ArrayRef<unsigned> Idxs,
  2052. const Twine &NameStr = "",
  2053. Instruction *InsertBefore = nullptr) {
  2054. return new
  2055. ExtractValueInst(Agg, Idxs, NameStr, InsertBefore);
  2056. }
  2057. static ExtractValueInst *Create(Value *Agg,
  2058. ArrayRef<unsigned> Idxs,
  2059. const Twine &NameStr,
  2060. BasicBlock *InsertAtEnd) {
  2061. return new ExtractValueInst(Agg, Idxs, NameStr, InsertAtEnd);
  2062. }
  2063. /// Returns the type of the element that would be extracted
  2064. /// with an extractvalue instruction with the specified parameters.
  2065. ///
  2066. /// Null is returned if the indices are invalid for the specified type.
  2067. static Type *getIndexedType(Type *Agg, ArrayRef<unsigned> Idxs);
  2068. using idx_iterator = const unsigned*;
  2069. inline idx_iterator idx_begin() const { return Indices.begin(); }
  2070. inline idx_iterator idx_end() const { return Indices.end(); }
  2071. inline iterator_range<idx_iterator> indices() const {
  2072. return make_range(idx_begin(), idx_end());
  2073. }
  2074. Value *getAggregateOperand() {
  2075. return getOperand(0);
  2076. }
  2077. const Value *getAggregateOperand() const {
  2078. return getOperand(0);
  2079. }
  2080. static unsigned getAggregateOperandIndex() {
  2081. return 0U; // get index for modifying correct operand
  2082. }
  2083. ArrayRef<unsigned> getIndices() const {
  2084. return Indices;
  2085. }
  2086. unsigned getNumIndices() const {
  2087. return (unsigned)Indices.size();
  2088. }
  2089. bool hasIndices() const {
  2090. return true;
  2091. }
  2092. // Methods for support type inquiry through isa, cast, and dyn_cast:
  2093. static bool classof(const Instruction *I) {
  2094. return I->getOpcode() == Instruction::ExtractValue;
  2095. }
  2096. static bool classof(const Value *V) {
  2097. return isa<Instruction>(V) && classof(cast<Instruction>(V));
  2098. }
  2099. };
  2100. ExtractValueInst::ExtractValueInst(Value *Agg,
  2101. ArrayRef<unsigned> Idxs,
  2102. const Twine &NameStr,
  2103. Instruction *InsertBefore)
  2104. : UnaryInstruction(checkGEPType(getIndexedType(Agg->getType(), Idxs)),
  2105. ExtractValue, Agg, InsertBefore) {
  2106. init(Idxs, NameStr);
  2107. }
  2108. ExtractValueInst::ExtractValueInst(Value *Agg,
  2109. ArrayRef<unsigned> Idxs,
  2110. const Twine &NameStr,
  2111. BasicBlock *InsertAtEnd)
  2112. : UnaryInstruction(checkGEPType(getIndexedType(Agg->getType(), Idxs)),
  2113. ExtractValue, Agg, InsertAtEnd) {
  2114. init(Idxs, NameStr);
  2115. }
  2116. //===----------------------------------------------------------------------===//
  2117. // InsertValueInst Class
  2118. //===----------------------------------------------------------------------===//
  2119. /// This instruction inserts a struct field of array element
  2120. /// value into an aggregate value.
  2121. ///
  2122. class InsertValueInst : public Instruction {
  2123. SmallVector<unsigned, 4> Indices;
  2124. InsertValueInst(const InsertValueInst &IVI);
  2125. /// Constructors - Create a insertvalue instruction with a base aggregate
  2126. /// value, a value to insert, and a list of indices. The first ctor can
  2127. /// optionally insert before an existing instruction, the second appends
  2128. /// the new instruction to the specified BasicBlock.
  2129. inline InsertValueInst(Value *Agg, Value *Val,
  2130. ArrayRef<unsigned> Idxs,
  2131. const Twine &NameStr,
  2132. Instruction *InsertBefore);
  2133. inline InsertValueInst(Value *Agg, Value *Val,
  2134. ArrayRef<unsigned> Idxs,
  2135. const Twine &NameStr, BasicBlock *InsertAtEnd);
  2136. /// Constructors - These two constructors are convenience methods because one
  2137. /// and two index insertvalue instructions are so common.
  2138. InsertValueInst(Value *Agg, Value *Val, unsigned Idx,
  2139. const Twine &NameStr = "",
  2140. Instruction *InsertBefore = nullptr);
  2141. InsertValueInst(Value *Agg, Value *Val, unsigned Idx, const Twine &NameStr,
  2142. BasicBlock *InsertAtEnd);
  2143. void init(Value *Agg, Value *Val, ArrayRef<unsigned> Idxs,
  2144. const Twine &NameStr);
  2145. protected:
  2146. // Note: Instruction needs to be a friend here to call cloneImpl.
  2147. friend class Instruction;
  2148. InsertValueInst *cloneImpl() const;
  2149. public:
  2150. // allocate space for exactly two operands
  2151. void *operator new(size_t s) {
  2152. return User::operator new(s, 2);
  2153. }
  2154. static InsertValueInst *Create(Value *Agg, Value *Val,
  2155. ArrayRef<unsigned> Idxs,
  2156. const Twine &NameStr = "",
  2157. Instruction *InsertBefore = nullptr) {
  2158. return new InsertValueInst(Agg, Val, Idxs, NameStr, InsertBefore);
  2159. }
  2160. static InsertValueInst *Create(Value *Agg, Value *Val,
  2161. ArrayRef<unsigned> Idxs,
  2162. const Twine &NameStr,
  2163. BasicBlock *InsertAtEnd) {
  2164. return new InsertValueInst(Agg, Val, Idxs, NameStr, InsertAtEnd);
  2165. }
  2166. /// Transparently provide more efficient getOperand methods.
  2167. DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
  2168. using idx_iterator = const unsigned*;
  2169. inline idx_iterator idx_begin() const { return Indices.begin(); }
  2170. inline idx_iterator idx_end() const { return Indices.end(); }
  2171. inline iterator_range<idx_iterator> indices() const {
  2172. return make_range(idx_begin(), idx_end());
  2173. }
  2174. Value *getAggregateOperand() {
  2175. return getOperand(0);
  2176. }
  2177. const Value *getAggregateOperand() const {
  2178. return getOperand(0);
  2179. }
  2180. static unsigned getAggregateOperandIndex() {
  2181. return 0U; // get index for modifying correct operand
  2182. }
  2183. Value *getInsertedValueOperand() {
  2184. return getOperand(1);
  2185. }
  2186. const Value *getInsertedValueOperand() const {
  2187. return getOperand(1);
  2188. }
  2189. static unsigned getInsertedValueOperandIndex() {
  2190. return 1U; // get index for modifying correct operand
  2191. }
  2192. ArrayRef<unsigned> getIndices() const {
  2193. return Indices;
  2194. }
  2195. unsigned getNumIndices() const {
  2196. return (unsigned)Indices.size();
  2197. }
  2198. bool hasIndices() const {
  2199. return true;
  2200. }
  2201. // Methods for support type inquiry through isa, cast, and dyn_cast:
  2202. static bool classof(const Instruction *I) {
  2203. return I->getOpcode() == Instruction::InsertValue;
  2204. }
  2205. static bool classof(const Value *V) {
  2206. return isa<Instruction>(V) && classof(cast<Instruction>(V));
  2207. }
  2208. };
  2209. template <>
  2210. struct OperandTraits<InsertValueInst> :
  2211. public FixedNumOperandTraits<InsertValueInst, 2> {
  2212. };
  2213. InsertValueInst::InsertValueInst(Value *Agg,
  2214. Value *Val,
  2215. ArrayRef<unsigned> Idxs,
  2216. const Twine &NameStr,
  2217. Instruction *InsertBefore)
  2218. : Instruction(Agg->getType(), InsertValue,
  2219. OperandTraits<InsertValueInst>::op_begin(this),
  2220. 2, InsertBefore) {
  2221. init(Agg, Val, Idxs, NameStr);
  2222. }
  2223. InsertValueInst::InsertValueInst(Value *Agg,
  2224. Value *Val,
  2225. ArrayRef<unsigned> Idxs,
  2226. const Twine &NameStr,
  2227. BasicBlock *InsertAtEnd)
  2228. : Instruction(Agg->getType(), InsertValue,
  2229. OperandTraits<InsertValueInst>::op_begin(this),
  2230. 2, InsertAtEnd) {
  2231. init(Agg, Val, Idxs, NameStr);
  2232. }
  2233. DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertValueInst, Value)
  2234. //===----------------------------------------------------------------------===//
  2235. // PHINode Class
  2236. //===----------------------------------------------------------------------===//
  2237. // PHINode - The PHINode class is used to represent the magical mystical PHI
  2238. // node, that can not exist in nature, but can be synthesized in a computer
  2239. // scientist's overactive imagination.
  2240. //
  2241. class PHINode : public Instruction {
  2242. /// The number of operands actually allocated. NumOperands is
  2243. /// the number actually in use.
  2244. unsigned ReservedSpace;
  2245. PHINode(const PHINode &PN);
  2246. explicit PHINode(Type *Ty, unsigned NumReservedValues,
  2247. const Twine &NameStr = "",
  2248. Instruction *InsertBefore = nullptr)
  2249. : Instruction(Ty, Instruction::PHI, nullptr, 0, InsertBefore),
  2250. ReservedSpace(NumReservedValues) {
  2251. setName(NameStr);
  2252. allocHungoffUses(ReservedSpace);
  2253. }
  2254. PHINode(Type *Ty, unsigned NumReservedValues, const Twine &NameStr,
  2255. BasicBlock *InsertAtEnd)
  2256. : Instruction(Ty, Instruction::PHI, nullptr, 0, InsertAtEnd),
  2257. ReservedSpace(NumReservedValues) {
  2258. setName(NameStr);
  2259. allocHungoffUses(ReservedSpace);
  2260. }
  2261. protected:
  2262. // Note: Instruction needs to be a friend here to call cloneImpl.
  2263. friend class Instruction;
  2264. PHINode *cloneImpl() const;
  2265. // allocHungoffUses - this is more complicated than the generic
  2266. // User::allocHungoffUses, because we have to allocate Uses for the incoming
  2267. // values and pointers to the incoming blocks, all in one allocation.
  2268. void allocHungoffUses(unsigned N) {
  2269. User::allocHungoffUses(N, /* IsPhi */ true);
  2270. }
  2271. public:
  2272. /// Constructors - NumReservedValues is a hint for the number of incoming
  2273. /// edges that this phi node will have (use 0 if you really have no idea).
  2274. static PHINode *Create(Type *Ty, unsigned NumReservedValues,
  2275. const Twine &NameStr = "",
  2276. Instruction *InsertBefore = nullptr) {
  2277. return new PHINode(Ty, NumReservedValues, NameStr, InsertBefore);
  2278. }
  2279. static PHINode *Create(Type *Ty, unsigned NumReservedValues,
  2280. const Twine &NameStr, BasicBlock *InsertAtEnd) {
  2281. return new PHINode(Ty, NumReservedValues, NameStr, InsertAtEnd);
  2282. }
  2283. /// Provide fast operand accessors
  2284. DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
  2285. // Block iterator interface. This provides access to the list of incoming
  2286. // basic blocks, which parallels the list of incoming values.
  2287. using block_iterator = BasicBlock **;
  2288. using const_block_iterator = BasicBlock * const *;
  2289. block_iterator block_begin() {
  2290. return reinterpret_cast<block_iterator>(op_begin() + ReservedSpace);
  2291. }
  2292. const_block_iterator block_begin() const {
  2293. return reinterpret_cast<const_block_iterator>(op_begin() + ReservedSpace);
  2294. }
  2295. block_iterator block_end() {
  2296. return block_begin() + getNumOperands();
  2297. }
  2298. const_block_iterator block_end() const {
  2299. return block_begin() + getNumOperands();
  2300. }
  2301. iterator_range<block_iterator> blocks() {
  2302. return make_range(block_begin(), block_end());
  2303. }
  2304. iterator_range<const_block_iterator> blocks() const {
  2305. return make_range(block_begin(), block_end());
  2306. }
  2307. op_range incoming_values() { return operands(); }
  2308. const_op_range incoming_values() const { return operands(); }
  2309. /// Return the number of incoming edges
  2310. ///
  2311. unsigned getNumIncomingValues() const { return getNumOperands(); }
  2312. /// Return incoming value number x
  2313. ///
  2314. Value *getIncomingValue(unsigned i) const {
  2315. return getOperand(i);
  2316. }
  2317. void setIncomingValue(unsigned i, Value *V) {
  2318. assert(V && "PHI node got a null value!");
  2319. assert(getType() == V->getType() &&
  2320. "All operands to PHI node must be the same type as the PHI node!");
  2321. setOperand(i, V);
  2322. }
  2323. static unsigned getOperandNumForIncomingValue(unsigned i) {
  2324. return i;
  2325. }
  2326. static unsigned getIncomingValueNumForOperand(unsigned i) {
  2327. return i;
  2328. }
  2329. /// Return incoming basic block number @p i.
  2330. ///
  2331. BasicBlock *getIncomingBlock(unsigned i) const {
  2332. return block_begin()[i];
  2333. }
  2334. /// Return incoming basic block corresponding
  2335. /// to an operand of the PHI.
  2336. ///
  2337. BasicBlock *getIncomingBlock(const Use &U) const {
  2338. assert(this == U.getUser() && "Iterator doesn't point to PHI's Uses?");
  2339. return getIncomingBlock(unsigned(&U - op_begin()));
  2340. }
  2341. /// Return incoming basic block corresponding
  2342. /// to value use iterator.
  2343. ///
  2344. BasicBlock *getIncomingBlock(Value::const_user_iterator I) const {
  2345. return getIncomingBlock(I.getUse());
  2346. }
  2347. void setIncomingBlock(unsigned i, BasicBlock *BB) {
  2348. assert(BB && "PHI node got a null basic block!");
  2349. block_begin()[i] = BB;
  2350. }
  2351. /// Replace every incoming basic block \p Old to basic block \p New.
  2352. void replaceIncomingBlockWith(const BasicBlock *Old, BasicBlock *New) {
  2353. assert(New && Old && "PHI node got a null basic block!");
  2354. for (unsigned Op = 0, NumOps = getNumOperands(); Op != NumOps; ++Op)
  2355. if (getIncomingBlock(Op) == Old)
  2356. setIncomingBlock(Op, New);
  2357. }
  2358. /// Add an incoming value to the end of the PHI list
  2359. ///
  2360. void addIncoming(Value *V, BasicBlock *BB) {
  2361. if (getNumOperands() == ReservedSpace)
  2362. growOperands(); // Get more space!
  2363. // Initialize some new operands.
  2364. setNumHungOffUseOperands(getNumOperands() + 1);
  2365. setIncomingValue(getNumOperands() - 1, V);
  2366. setIncomingBlock(getNumOperands() - 1, BB);
  2367. }
  2368. /// Remove an incoming value. This is useful if a
  2369. /// predecessor basic block is deleted. The value removed is returned.
  2370. ///
  2371. /// If the last incoming value for a PHI node is removed (and DeletePHIIfEmpty
  2372. /// is true), the PHI node is destroyed and any uses of it are replaced with
  2373. /// dummy values. The only time there should be zero incoming values to a PHI
  2374. /// node is when the block is dead, so this strategy is sound.
  2375. ///
  2376. Value *removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty = true);
  2377. Value *removeIncomingValue(const BasicBlock *BB, bool DeletePHIIfEmpty=true) {
  2378. int Idx = getBasicBlockIndex(BB);
  2379. assert(Idx >= 0 && "Invalid basic block argument to remove!");
  2380. return removeIncomingValue(Idx, DeletePHIIfEmpty);
  2381. }
  2382. /// Return the first index of the specified basic
  2383. /// block in the value list for this PHI. Returns -1 if no instance.
  2384. ///
  2385. int getBasicBlockIndex(const BasicBlock *BB) const {
  2386. for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
  2387. if (block_begin()[i] == BB)
  2388. return i;
  2389. return -1;
  2390. }
  2391. Value *getIncomingValueForBlock(const BasicBlock *BB) const {
  2392. int Idx = getBasicBlockIndex(BB);
  2393. assert(Idx >= 0 && "Invalid basic block argument!");
  2394. return getIncomingValue(Idx);
  2395. }
  2396. /// Set every incoming value(s) for block \p BB to \p V.
  2397. void setIncomingValueForBlock(const BasicBlock *BB, Value *V) {
  2398. assert(BB && "PHI node got a null basic block!");
  2399. bool Found = false;
  2400. for (unsigned Op = 0, NumOps = getNumOperands(); Op != NumOps; ++Op)
  2401. if (getIncomingBlock(Op) == BB) {
  2402. Found = true;
  2403. setIncomingValue(Op, V);
  2404. }
  2405. (void)Found;
  2406. assert(Found && "Invalid basic block argument to set!");
  2407. }
  2408. /// If the specified PHI node always merges together the
  2409. /// same value, return the value, otherwise return null.
  2410. Value *hasConstantValue() const;
  2411. /// Whether the specified PHI node always merges
  2412. /// together the same value, assuming undefs are equal to a unique
  2413. /// non-undef value.
  2414. bool hasConstantOrUndefValue() const;
  2415. /// If the PHI node is complete which means all of its parent's predecessors
  2416. /// have incoming value in this PHI, return true, otherwise return false.
  2417. bool isComplete() const {
  2418. return llvm::all_of(predecessors(getParent()),
  2419. [this](const BasicBlock *Pred) {
  2420. return getBasicBlockIndex(Pred) >= 0;
  2421. });
  2422. }
  2423. /// Methods for support type inquiry through isa, cast, and dyn_cast:
  2424. static bool classof(const Instruction *I) {
  2425. return I->getOpcode() == Instruction::PHI;
  2426. }
  2427. static bool classof(const Value *V) {
  2428. return isa<Instruction>(V) && classof(cast<Instruction>(V));
  2429. }
  2430. private:
  2431. void growOperands();
  2432. };
  2433. template <>
  2434. struct OperandTraits<PHINode> : public HungoffOperandTraits<2> {
  2435. };
  2436. DEFINE_TRANSPARENT_OPERAND_ACCESSORS(PHINode, Value)
  2437. //===----------------------------------------------------------------------===//
  2438. // LandingPadInst Class
  2439. //===----------------------------------------------------------------------===//
  2440. //===---------------------------------------------------------------------------
  2441. /// The landingpad instruction holds all of the information
  2442. /// necessary to generate correct exception handling. The landingpad instruction
  2443. /// cannot be moved from the top of a landing pad block, which itself is
  2444. /// accessible only from the 'unwind' edge of an invoke. This uses the
  2445. /// SubclassData field in Value to store whether or not the landingpad is a
  2446. /// cleanup.
  2447. ///
  2448. class LandingPadInst : public Instruction {
  2449. using CleanupField = BoolBitfieldElementT<0>;
  2450. /// The number of operands actually allocated. NumOperands is
  2451. /// the number actually in use.
  2452. unsigned ReservedSpace;
  2453. LandingPadInst(const LandingPadInst &LP);
  2454. public:
  2455. enum ClauseType { Catch, Filter };
  2456. private:
  2457. explicit LandingPadInst(Type *RetTy, unsigned NumReservedValues,
  2458. const Twine &NameStr, Instruction *InsertBefore);
  2459. explicit LandingPadInst(Type *RetTy, unsigned NumReservedValues,
  2460. const Twine &NameStr, BasicBlock *InsertAtEnd);
  2461. // Allocate space for exactly zero operands.
  2462. void *operator new(size_t s) {
  2463. return User::operator new(s);
  2464. }
  2465. void growOperands(unsigned Size);
  2466. void init(unsigned NumReservedValues, const Twine &NameStr);
  2467. protected:
  2468. // Note: Instruction needs to be a friend here to call cloneImpl.
  2469. friend class Instruction;
  2470. LandingPadInst *cloneImpl() const;
  2471. public:
  2472. /// Constructors - NumReservedClauses is a hint for the number of incoming
  2473. /// clauses that this landingpad will have (use 0 if you really have no idea).
  2474. static LandingPadInst *Create(Type *RetTy, unsigned NumReservedClauses,
  2475. const Twine &NameStr = "",
  2476. Instruction *InsertBefore = nullptr);
  2477. static LandingPadInst *Create(Type *RetTy, unsigned NumReservedClauses,
  2478. const Twine &NameStr, BasicBlock *InsertAtEnd);
  2479. /// Provide fast operand accessors
  2480. DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
  2481. /// Return 'true' if this landingpad instruction is a
  2482. /// cleanup. I.e., it should be run when unwinding even if its landing pad
  2483. /// doesn't catch the exception.
  2484. bool isCleanup() const { return getSubclassData<CleanupField>(); }
  2485. /// Indicate that this landingpad instruction is a cleanup.
  2486. void setCleanup(bool V) { setSubclassData<CleanupField>(V); }
  2487. /// Add a catch or filter clause to the landing pad.
  2488. void addClause(Constant *ClauseVal);
  2489. /// Get the value of the clause at index Idx. Use isCatch/isFilter to
  2490. /// determine what type of clause this is.
  2491. Constant *getClause(unsigned Idx) const {
  2492. return cast<Constant>(getOperandList()[Idx]);
  2493. }
  2494. /// Return 'true' if the clause and index Idx is a catch clause.
  2495. bool isCatch(unsigned Idx) const {
  2496. return !isa<ArrayType>(getOperandList()[Idx]->getType());
  2497. }
  2498. /// Return 'true' if the clause and index Idx is a filter clause.
  2499. bool isFilter(unsigned Idx) const {
  2500. return isa<ArrayType>(getOperandList()[Idx]->getType());
  2501. }
  2502. /// Get the number of clauses for this landing pad.
  2503. unsigned getNumClauses() const { return getNumOperands(); }
  2504. /// Grow the size of the operand list to accommodate the new
  2505. /// number of clauses.
  2506. void reserveClauses(unsigned Size) { growOperands(Size); }
  2507. // Methods for support type inquiry through isa, cast, and dyn_cast:
  2508. static bool classof(const Instruction *I) {
  2509. return I->getOpcode() == Instruction::LandingPad;
  2510. }
  2511. static bool classof(const Value *V) {
  2512. return isa<Instruction>(V) && classof(cast<Instruction>(V));
  2513. }
  2514. };
  2515. template <>
  2516. struct OperandTraits<LandingPadInst> : public HungoffOperandTraits<1> {
  2517. };
  2518. DEFINE_TRANSPARENT_OPERAND_ACCESSORS(LandingPadInst, Value)
  2519. //===----------------------------------------------------------------------===//
  2520. // ReturnInst Class
  2521. //===----------------------------------------------------------------------===//
  2522. //===---------------------------------------------------------------------------
  2523. /// Return a value (possibly void), from a function. Execution
  2524. /// does not continue in this function any longer.
  2525. ///
  2526. class ReturnInst : public Instruction {
  2527. ReturnInst(const ReturnInst &RI);
  2528. private:
  2529. // ReturnInst constructors:
  2530. // ReturnInst() - 'ret void' instruction
  2531. // ReturnInst( null) - 'ret void' instruction
  2532. // ReturnInst(Value* X) - 'ret X' instruction
  2533. // ReturnInst( null, Inst *I) - 'ret void' instruction, insert before I
  2534. // ReturnInst(Value* X, Inst *I) - 'ret X' instruction, insert before I
  2535. // ReturnInst( null, BB *B) - 'ret void' instruction, insert @ end of B
  2536. // ReturnInst(Value* X, BB *B) - 'ret X' instruction, insert @ end of B
  2537. //
  2538. // NOTE: If the Value* passed is of type void then the constructor behaves as
  2539. // if it was passed NULL.
  2540. explicit ReturnInst(LLVMContext &C, Value *retVal = nullptr,
  2541. Instruction *InsertBefore = nullptr);
  2542. ReturnInst(LLVMContext &C, Value *retVal, BasicBlock *InsertAtEnd);
  2543. explicit ReturnInst(LLVMContext &C, BasicBlock *InsertAtEnd);
  2544. protected:
  2545. // Note: Instruction needs to be a friend here to call cloneImpl.
  2546. friend class Instruction;
  2547. ReturnInst *cloneImpl() const;
  2548. public:
  2549. static ReturnInst* Create(LLVMContext &C, Value *retVal = nullptr,
  2550. Instruction *InsertBefore = nullptr) {
  2551. return new(!!retVal) ReturnInst(C, retVal, InsertBefore);
  2552. }
  2553. static ReturnInst* Create(LLVMContext &C, Value *retVal,
  2554. BasicBlock *InsertAtEnd) {
  2555. return new(!!retVal) ReturnInst(C, retVal, InsertAtEnd);
  2556. }
  2557. static ReturnInst* Create(LLVMContext &C, BasicBlock *InsertAtEnd) {
  2558. return new(0) ReturnInst(C, InsertAtEnd);
  2559. }
  2560. /// Provide fast operand accessors
  2561. DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
  2562. /// Convenience accessor. Returns null if there is no return value.
  2563. Value *getReturnValue() const {
  2564. return getNumOperands() != 0 ? getOperand(0) : nullptr;
  2565. }
  2566. unsigned getNumSuccessors() const { return 0; }
  2567. // Methods for support type inquiry through isa, cast, and dyn_cast:
  2568. static bool classof(const Instruction *I) {
  2569. return (I->getOpcode() == Instruction::Ret);
  2570. }
  2571. static bool classof(const Value *V) {
  2572. return isa<Instruction>(V) && classof(cast<Instruction>(V));
  2573. }
  2574. private:
  2575. BasicBlock *getSuccessor(unsigned idx) const {
  2576. llvm_unreachable("ReturnInst has no successors!");
  2577. }
  2578. void setSuccessor(unsigned idx, BasicBlock *B) {
  2579. llvm_unreachable("ReturnInst has no successors!");
  2580. }
  2581. };
  2582. template <>
  2583. struct OperandTraits<ReturnInst> : public VariadicOperandTraits<ReturnInst> {
  2584. };
  2585. DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ReturnInst, Value)
  2586. //===----------------------------------------------------------------------===//
  2587. // BranchInst Class
  2588. //===----------------------------------------------------------------------===//
  2589. //===---------------------------------------------------------------------------
  2590. /// Conditional or Unconditional Branch instruction.
  2591. ///
  2592. class BranchInst : public Instruction {
  2593. /// Ops list - Branches are strange. The operands are ordered:
  2594. /// [Cond, FalseDest,] TrueDest. This makes some accessors faster because
  2595. /// they don't have to check for cond/uncond branchness. These are mostly
  2596. /// accessed relative from op_end().
  2597. BranchInst(const BranchInst &BI);
  2598. // BranchInst constructors (where {B, T, F} are blocks, and C is a condition):
  2599. // BranchInst(BB *B) - 'br B'
  2600. // BranchInst(BB* T, BB *F, Value *C) - 'br C, T, F'
  2601. // BranchInst(BB* B, Inst *I) - 'br B' insert before I
  2602. // BranchInst(BB* T, BB *F, Value *C, Inst *I) - 'br C, T, F', insert before I
  2603. // BranchInst(BB* B, BB *I) - 'br B' insert at end
  2604. // BranchInst(BB* T, BB *F, Value *C, BB *I) - 'br C, T, F', insert at end
  2605. explicit BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore = nullptr);
  2606. BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
  2607. Instruction *InsertBefore = nullptr);
  2608. BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd);
  2609. BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
  2610. BasicBlock *InsertAtEnd);
  2611. void AssertOK();
  2612. protected:
  2613. // Note: Instruction needs to be a friend here to call cloneImpl.
  2614. friend class Instruction;
  2615. BranchInst *cloneImpl() const;
  2616. public:
  2617. /// Iterator type that casts an operand to a basic block.
  2618. ///
  2619. /// This only makes sense because the successors are stored as adjacent
  2620. /// operands for branch instructions.
  2621. struct succ_op_iterator
  2622. : iterator_adaptor_base<succ_op_iterator, value_op_iterator,
  2623. std::random_access_iterator_tag, BasicBlock *,
  2624. ptrdiff_t, BasicBlock *, BasicBlock *> {
  2625. explicit succ_op_iterator(value_op_iterator I) : iterator_adaptor_base(I) {}
  2626. BasicBlock *operator*() const { return cast<BasicBlock>(*I); }
  2627. BasicBlock *operator->() const { return operator*(); }
  2628. };
  2629. /// The const version of `succ_op_iterator`.
  2630. struct const_succ_op_iterator
  2631. : iterator_adaptor_base<const_succ_op_iterator, const_value_op_iterator,
  2632. std::random_access_iterator_tag,
  2633. const BasicBlock *, ptrdiff_t, const BasicBlock *,
  2634. const BasicBlock *> {
  2635. explicit const_succ_op_iterator(const_value_op_iterator I)
  2636. : iterator_adaptor_base(I) {}
  2637. const BasicBlock *operator*() const { return cast<BasicBlock>(*I); }
  2638. const BasicBlock *operator->() const { return operator*(); }
  2639. };
  2640. static BranchInst *Create(BasicBlock *IfTrue,
  2641. Instruction *InsertBefore = nullptr) {
  2642. return new(1) BranchInst(IfTrue, InsertBefore);
  2643. }
  2644. static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *IfFalse,
  2645. Value *Cond, Instruction *InsertBefore = nullptr) {
  2646. return new(3) BranchInst(IfTrue, IfFalse, Cond, InsertBefore);
  2647. }
  2648. static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *InsertAtEnd) {
  2649. return new(1) BranchInst(IfTrue, InsertAtEnd);
  2650. }
  2651. static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *IfFalse,
  2652. Value *Cond, BasicBlock *InsertAtEnd) {
  2653. return new(3) BranchInst(IfTrue, IfFalse, Cond, InsertAtEnd);
  2654. }
  2655. /// Transparently provide more efficient getOperand methods.
  2656. DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
  2657. bool isUnconditional() const { return getNumOperands() == 1; }
  2658. bool isConditional() const { return getNumOperands() == 3; }
  2659. Value *getCondition() const {
  2660. assert(isConditional() && "Cannot get condition of an uncond branch!");
  2661. return Op<-3>();
  2662. }
  2663. void setCondition(Value *V) {
  2664. assert(isConditional() && "Cannot set condition of unconditional branch!");
  2665. Op<-3>() = V;
  2666. }
  2667. unsigned getNumSuccessors() const { return 1+isConditional(); }
  2668. BasicBlock *getSuccessor(unsigned i) const {
  2669. assert(i < getNumSuccessors() && "Successor # out of range for Branch!");
  2670. return cast_or_null<BasicBlock>((&Op<-1>() - i)->get());
  2671. }
  2672. void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
  2673. assert(idx < getNumSuccessors() && "Successor # out of range for Branch!");
  2674. *(&Op<-1>() - idx) = NewSucc;
  2675. }
  2676. /// Swap the successors of this branch instruction.
  2677. ///
  2678. /// Swaps the successors of the branch instruction. This also swaps any
  2679. /// branch weight metadata associated with the instruction so that it
  2680. /// continues to map correctly to each operand.
  2681. void swapSuccessors();
  2682. iterator_range<succ_op_iterator> successors() {
  2683. return make_range(
  2684. succ_op_iterator(std::next(value_op_begin(), isConditional() ? 1 : 0)),
  2685. succ_op_iterator(value_op_end()));
  2686. }
  2687. iterator_range<const_succ_op_iterator> successors() const {
  2688. return make_range(const_succ_op_iterator(
  2689. std::next(value_op_begin(), isConditional() ? 1 : 0)),
  2690. const_succ_op_iterator(value_op_end()));
  2691. }
  2692. // Methods for support type inquiry through isa, cast, and dyn_cast:
  2693. static bool classof(const Instruction *I) {
  2694. return (I->getOpcode() == Instruction::Br);
  2695. }
  2696. static bool classof(const Value *V) {
  2697. return isa<Instruction>(V) && classof(cast<Instruction>(V));
  2698. }
  2699. };
  2700. template <>
  2701. struct OperandTraits<BranchInst> : public VariadicOperandTraits<BranchInst, 1> {
  2702. };
  2703. DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BranchInst, Value)
  2704. //===----------------------------------------------------------------------===//
  2705. // SwitchInst Class
  2706. //===----------------------------------------------------------------------===//
  2707. //===---------------------------------------------------------------------------
  2708. /// Multiway switch
  2709. ///
  2710. class SwitchInst : public Instruction {
  2711. unsigned ReservedSpace;
  2712. // Operand[0] = Value to switch on
  2713. // Operand[1] = Default basic block destination
  2714. // Operand[2n ] = Value to match
  2715. // Operand[2n+1] = BasicBlock to go to on match
  2716. SwitchInst(const SwitchInst &SI);
  2717. /// Create a new switch instruction, specifying a value to switch on and a
  2718. /// default destination. The number of additional cases can be specified here
  2719. /// to make memory allocation more efficient. This constructor can also
  2720. /// auto-insert before another instruction.
  2721. SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
  2722. Instruction *InsertBefore);
  2723. /// Create a new switch instruction, specifying a value to switch on and a
  2724. /// default destination. The number of additional cases can be specified here
  2725. /// to make memory allocation more efficient. This constructor also
  2726. /// auto-inserts at the end of the specified BasicBlock.
  2727. SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
  2728. BasicBlock *InsertAtEnd);
  2729. // allocate space for exactly zero operands
  2730. void *operator new(size_t s) {
  2731. return User::operator new(s);
  2732. }
  2733. void init(Value *Value, BasicBlock *Default, unsigned NumReserved);
  2734. void growOperands();
  2735. protected:
  2736. // Note: Instruction needs to be a friend here to call cloneImpl.
  2737. friend class Instruction;
  2738. SwitchInst *cloneImpl() const;
  2739. public:
  2740. // -2
  2741. static const unsigned DefaultPseudoIndex = static_cast<unsigned>(~0L-1);
  2742. template <typename CaseHandleT> class CaseIteratorImpl;
  2743. /// A handle to a particular switch case. It exposes a convenient interface
  2744. /// to both the case value and the successor block.
  2745. ///
  2746. /// We define this as a template and instantiate it to form both a const and
  2747. /// non-const handle.
  2748. template <typename SwitchInstT, typename ConstantIntT, typename BasicBlockT>
  2749. class CaseHandleImpl {
  2750. // Directly befriend both const and non-const iterators.
  2751. friend class SwitchInst::CaseIteratorImpl<
  2752. CaseHandleImpl<SwitchInstT, ConstantIntT, BasicBlockT>>;
  2753. protected:
  2754. // Expose the switch type we're parameterized with to the iterator.
  2755. using SwitchInstType = SwitchInstT;
  2756. SwitchInstT *SI;
  2757. ptrdiff_t Index;
  2758. CaseHandleImpl() = default;
  2759. CaseHandleImpl(SwitchInstT *SI, ptrdiff_t Index) : SI(SI), Index(Index) {}
  2760. public:
  2761. /// Resolves case value for current case.
  2762. ConstantIntT *getCaseValue() const {
  2763. assert((unsigned)Index < SI->getNumCases() &&
  2764. "Index out the number of cases.");
  2765. return reinterpret_cast<ConstantIntT *>(SI->getOperand(2 + Index * 2));
  2766. }
  2767. /// Resolves successor for current case.
  2768. BasicBlockT *getCaseSuccessor() const {
  2769. assert(((unsigned)Index < SI->getNumCases() ||
  2770. (unsigned)Index == DefaultPseudoIndex) &&
  2771. "Index out the number of cases.");
  2772. return SI->getSuccessor(getSuccessorIndex());
  2773. }
  2774. /// Returns number of current case.
  2775. unsigned getCaseIndex() const { return Index; }
  2776. /// Returns successor index for current case successor.
  2777. unsigned getSuccessorIndex() const {
  2778. assert(((unsigned)Index == DefaultPseudoIndex ||
  2779. (unsigned)Index < SI->getNumCases()) &&
  2780. "Index out the number of cases.");
  2781. return (unsigned)Index != DefaultPseudoIndex ? Index + 1 : 0;
  2782. }
  2783. bool operator==(const CaseHandleImpl &RHS) const {
  2784. assert(SI == RHS.SI && "Incompatible operators.");
  2785. return Index == RHS.Index;
  2786. }
  2787. };
  2788. using ConstCaseHandle =
  2789. CaseHandleImpl<const SwitchInst, const ConstantInt, const BasicBlock>;
  2790. class CaseHandle
  2791. : public CaseHandleImpl<SwitchInst, ConstantInt, BasicBlock> {
  2792. friend class SwitchInst::CaseIteratorImpl<CaseHandle>;
  2793. public:
  2794. CaseHandle(SwitchInst *SI, ptrdiff_t Index) : CaseHandleImpl(SI, Index) {}
  2795. /// Sets the new value for current case.
  2796. void setValue(ConstantInt *V) {
  2797. assert((unsigned)Index < SI->getNumCases() &&
  2798. "Index out the number of cases.");
  2799. SI->setOperand(2 + Index*2, reinterpret_cast<Value*>(V));
  2800. }
  2801. /// Sets the new successor for current case.
  2802. void setSuccessor(BasicBlock *S) {
  2803. SI->setSuccessor(getSuccessorIndex(), S);
  2804. }
  2805. };
  2806. template <typename CaseHandleT>
  2807. class CaseIteratorImpl
  2808. : public iterator_facade_base<CaseIteratorImpl<CaseHandleT>,
  2809. std::random_access_iterator_tag,
  2810. CaseHandleT> {
  2811. using SwitchInstT = typename CaseHandleT::SwitchInstType;
  2812. CaseHandleT Case;
  2813. public:
  2814. /// Default constructed iterator is in an invalid state until assigned to
  2815. /// a case for a particular switch.
  2816. CaseIteratorImpl() = default;
  2817. /// Initializes case iterator for given SwitchInst and for given
  2818. /// case number.
  2819. CaseIteratorImpl(SwitchInstT *SI, unsigned CaseNum) : Case(SI, CaseNum) {}
  2820. /// Initializes case iterator for given SwitchInst and for given
  2821. /// successor index.
  2822. static CaseIteratorImpl fromSuccessorIndex(SwitchInstT *SI,
  2823. unsigned SuccessorIndex) {
  2824. assert(SuccessorIndex < SI->getNumSuccessors() &&
  2825. "Successor index # out of range!");
  2826. return SuccessorIndex != 0 ? CaseIteratorImpl(SI, SuccessorIndex - 1)
  2827. : CaseIteratorImpl(SI, DefaultPseudoIndex);
  2828. }
  2829. /// Support converting to the const variant. This will be a no-op for const
  2830. /// variant.
  2831. operator CaseIteratorImpl<ConstCaseHandle>() const {
  2832. return CaseIteratorImpl<ConstCaseHandle>(Case.SI, Case.Index);
  2833. }
  2834. CaseIteratorImpl &operator+=(ptrdiff_t N) {
  2835. // Check index correctness after addition.
  2836. // Note: Index == getNumCases() means end().
  2837. assert(Case.Index + N >= 0 &&
  2838. (unsigned)(Case.Index + N) <= Case.SI->getNumCases() &&
  2839. "Case.Index out the number of cases.");
  2840. Case.Index += N;
  2841. return *this;
  2842. }
  2843. CaseIteratorImpl &operator-=(ptrdiff_t N) {
  2844. // Check index correctness after subtraction.
  2845. // Note: Case.Index == getNumCases() means end().
  2846. assert(Case.Index - N >= 0 &&
  2847. (unsigned)(Case.Index - N) <= Case.SI->getNumCases() &&
  2848. "Case.Index out the number of cases.");
  2849. Case.Index -= N;
  2850. return *this;
  2851. }
  2852. ptrdiff_t operator-(const CaseIteratorImpl &RHS) const {
  2853. assert(Case.SI == RHS.Case.SI && "Incompatible operators.");
  2854. return Case.Index - RHS.Case.Index;
  2855. }
  2856. bool operator==(const CaseIteratorImpl &RHS) const {
  2857. return Case == RHS.Case;
  2858. }
  2859. bool operator<(const CaseIteratorImpl &RHS) const {
  2860. assert(Case.SI == RHS.Case.SI && "Incompatible operators.");
  2861. return Case.Index < RHS.Case.Index;
  2862. }
  2863. CaseHandleT &operator*() { return Case; }
  2864. const CaseHandleT &operator*() const { return Case; }
  2865. };
  2866. using CaseIt = CaseIteratorImpl<CaseHandle>;
  2867. using ConstCaseIt = CaseIteratorImpl<ConstCaseHandle>;
  2868. static SwitchInst *Create(Value *Value, BasicBlock *Default,
  2869. unsigned NumCases,
  2870. Instruction *InsertBefore = nullptr) {
  2871. return new SwitchInst(Value, Default, NumCases, InsertBefore);
  2872. }
  2873. static SwitchInst *Create(Value *Value, BasicBlock *Default,
  2874. unsigned NumCases, BasicBlock *InsertAtEnd) {
  2875. return new SwitchInst(Value, Default, NumCases, InsertAtEnd);
  2876. }
  2877. /// Provide fast operand accessors
  2878. DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
  2879. // Accessor Methods for Switch stmt
  2880. Value *getCondition() const { return getOperand(0); }
  2881. void setCondition(Value *V) { setOperand(0, V); }
  2882. BasicBlock *getDefaultDest() const {
  2883. return cast<BasicBlock>(getOperand(1));
  2884. }
  2885. void setDefaultDest(BasicBlock *DefaultCase) {
  2886. setOperand(1, reinterpret_cast<Value*>(DefaultCase));
  2887. }
  2888. /// Return the number of 'cases' in this switch instruction, excluding the
  2889. /// default case.
  2890. unsigned getNumCases() const {
  2891. return getNumOperands()/2 - 1;
  2892. }
  2893. /// Returns a read/write iterator that points to the first case in the
  2894. /// SwitchInst.
  2895. CaseIt case_begin() {
  2896. return CaseIt(this, 0);
  2897. }
  2898. /// Returns a read-only iterator that points to the first case in the
  2899. /// SwitchInst.
  2900. ConstCaseIt case_begin() const {
  2901. return ConstCaseIt(this, 0);
  2902. }
  2903. /// Returns a read/write iterator that points one past the last in the
  2904. /// SwitchInst.
  2905. CaseIt case_end() {
  2906. return CaseIt(this, getNumCases());
  2907. }
  2908. /// Returns a read-only iterator that points one past the last in the
  2909. /// SwitchInst.
  2910. ConstCaseIt case_end() const {
  2911. return ConstCaseIt(this, getNumCases());
  2912. }
  2913. /// Iteration adapter for range-for loops.
  2914. iterator_range<CaseIt> cases() {
  2915. return make_range(case_begin(), case_end());
  2916. }
  2917. /// Constant iteration adapter for range-for loops.
  2918. iterator_range<ConstCaseIt> cases() const {
  2919. return make_range(case_begin(), case_end());
  2920. }
  2921. /// Returns an iterator that points to the default case.
  2922. /// Note: this iterator allows to resolve successor only. Attempt
  2923. /// to resolve case value causes an assertion.
  2924. /// Also note, that increment and decrement also causes an assertion and
  2925. /// makes iterator invalid.
  2926. CaseIt case_default() {
  2927. return CaseIt(this, DefaultPseudoIndex);
  2928. }
  2929. ConstCaseIt case_default() const {
  2930. return ConstCaseIt(this, DefaultPseudoIndex);
  2931. }
  2932. /// Search all of the case values for the specified constant. If it is
  2933. /// explicitly handled, return the case iterator of it, otherwise return
  2934. /// default case iterator to indicate that it is handled by the default
  2935. /// handler.
  2936. CaseIt findCaseValue(const ConstantInt *C) {
  2937. CaseIt I = llvm::find_if(
  2938. cases(), [C](CaseHandle &Case) { return Case.getCaseValue() == C; });
  2939. if (I != case_end())
  2940. return I;
  2941. return case_default();
  2942. }
  2943. ConstCaseIt findCaseValue(const ConstantInt *C) const {
  2944. ConstCaseIt I = llvm::find_if(cases(), [C](ConstCaseHandle &Case) {
  2945. return Case.getCaseValue() == C;
  2946. });
  2947. if (I != case_end())
  2948. return I;
  2949. return case_default();
  2950. }
  2951. /// Finds the unique case value for a given successor. Returns null if the
  2952. /// successor is not found, not unique, or is the default case.
  2953. ConstantInt *findCaseDest(BasicBlock *BB) {
  2954. if (BB == getDefaultDest())
  2955. return nullptr;
  2956. ConstantInt *CI = nullptr;
  2957. for (auto Case : cases()) {
  2958. if (Case.getCaseSuccessor() != BB)
  2959. continue;
  2960. if (CI)
  2961. return nullptr; // Multiple cases lead to BB.
  2962. CI = Case.getCaseValue();
  2963. }
  2964. return CI;
  2965. }
  2966. /// Add an entry to the switch instruction.
  2967. /// Note:
  2968. /// This action invalidates case_end(). Old case_end() iterator will
  2969. /// point to the added case.
  2970. void addCase(ConstantInt *OnVal, BasicBlock *Dest);
  2971. /// This method removes the specified case and its successor from the switch
  2972. /// instruction. Note that this operation may reorder the remaining cases at
  2973. /// index idx and above.
  2974. /// Note:
  2975. /// This action invalidates iterators for all cases following the one removed,
  2976. /// including the case_end() iterator. It returns an iterator for the next
  2977. /// case.
  2978. CaseIt removeCase(CaseIt I);
  2979. unsigned getNumSuccessors() const { return getNumOperands()/2; }
  2980. BasicBlock *getSuccessor(unsigned idx) const {
  2981. assert(idx < getNumSuccessors() &&"Successor idx out of range for switch!");
  2982. return cast<BasicBlock>(getOperand(idx*2+1));
  2983. }
  2984. void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
  2985. assert(idx < getNumSuccessors() && "Successor # out of range for switch!");
  2986. setOperand(idx * 2 + 1, NewSucc);
  2987. }
  2988. // Methods for support type inquiry through isa, cast, and dyn_cast:
  2989. static bool classof(const Instruction *I) {
  2990. return I->getOpcode() == Instruction::Switch;
  2991. }
  2992. static bool classof(const Value *V) {
  2993. return isa<Instruction>(V) && classof(cast<Instruction>(V));
  2994. }
  2995. };
  2996. /// A wrapper class to simplify modification of SwitchInst cases along with
  2997. /// their prof branch_weights metadata.
  2998. class SwitchInstProfUpdateWrapper {
  2999. SwitchInst &SI;
  3000. Optional<SmallVector<uint32_t, 8> > Weights = None;
  3001. bool Changed = false;
  3002. protected:
  3003. static MDNode *getProfBranchWeightsMD(const SwitchInst &SI);
  3004. MDNode *buildProfBranchWeightsMD();
  3005. void init();
  3006. public:
  3007. using CaseWeightOpt = Optional<uint32_t>;
  3008. SwitchInst *operator->() { return &SI; }
  3009. SwitchInst &operator*() { return SI; }
  3010. operator SwitchInst *() { return &SI; }
  3011. SwitchInstProfUpdateWrapper(SwitchInst &SI) : SI(SI) { init(); }
  3012. ~SwitchInstProfUpdateWrapper() {
  3013. if (Changed)
  3014. SI.setMetadata(LLVMContext::MD_prof, buildProfBranchWeightsMD());
  3015. }
  3016. /// Delegate the call to the underlying SwitchInst::removeCase() and remove
  3017. /// correspondent branch weight.
  3018. SwitchInst::CaseIt removeCase(SwitchInst::CaseIt I);
  3019. /// Delegate the call to the underlying SwitchInst::addCase() and set the
  3020. /// specified branch weight for the added case.
  3021. void addCase(ConstantInt *OnVal, BasicBlock *Dest, CaseWeightOpt W);
  3022. /// Delegate the call to the underlying SwitchInst::eraseFromParent() and mark
  3023. /// this object to not touch the underlying SwitchInst in destructor.
  3024. SymbolTableList<Instruction>::iterator eraseFromParent();
  3025. void setSuccessorWeight(unsigned idx, CaseWeightOpt W);
  3026. CaseWeightOpt getSuccessorWeight(unsigned idx);
  3027. static CaseWeightOpt getSuccessorWeight(const SwitchInst &SI, unsigned idx);
  3028. };
  3029. template <>
  3030. struct OperandTraits<SwitchInst> : public HungoffOperandTraits<2> {
  3031. };
  3032. DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SwitchInst, Value)
  3033. //===----------------------------------------------------------------------===//
  3034. // IndirectBrInst Class
  3035. //===----------------------------------------------------------------------===//
  3036. //===---------------------------------------------------------------------------
  3037. /// Indirect Branch Instruction.
  3038. ///
  3039. class IndirectBrInst : public Instruction {
  3040. unsigned ReservedSpace;
  3041. // Operand[0] = Address to jump to
  3042. // Operand[n+1] = n-th destination
  3043. IndirectBrInst(const IndirectBrInst &IBI);
  3044. /// Create a new indirectbr instruction, specifying an
  3045. /// Address to jump to. The number of expected destinations can be specified
  3046. /// here to make memory allocation more efficient. This constructor can also
  3047. /// autoinsert before another instruction.
  3048. IndirectBrInst(Value *Address, unsigned NumDests, Instruction *InsertBefore);
  3049. /// Create a new indirectbr instruction, specifying an
  3050. /// Address to jump to. The number of expected destinations can be specified
  3051. /// here to make memory allocation more efficient. This constructor also
  3052. /// autoinserts at the end of the specified BasicBlock.
  3053. IndirectBrInst(Value *Address, unsigned NumDests, BasicBlock *InsertAtEnd);
  3054. // allocate space for exactly zero operands
  3055. void *operator new(size_t s) {
  3056. return User::operator new(s);
  3057. }
  3058. void init(Value *Address, unsigned NumDests);
  3059. void growOperands();
  3060. protected:
  3061. // Note: Instruction needs to be a friend here to call cloneImpl.
  3062. friend class Instruction;
  3063. IndirectBrInst *cloneImpl() const;
  3064. public:
  3065. /// Iterator type that casts an operand to a basic block.
  3066. ///
  3067. /// This only makes sense because the successors are stored as adjacent
  3068. /// operands for indirectbr instructions.
  3069. struct succ_op_iterator
  3070. : iterator_adaptor_base<succ_op_iterator, value_op_iterator,
  3071. std::random_access_iterator_tag, BasicBlock *,
  3072. ptrdiff_t, BasicBlock *, BasicBlock *> {
  3073. explicit succ_op_iterator(value_op_iterator I) : iterator_adaptor_base(I) {}
  3074. BasicBlock *operator*() const { return cast<BasicBlock>(*I); }
  3075. BasicBlock *operator->() const { return operator*(); }
  3076. };
  3077. /// The const version of `succ_op_iterator`.
  3078. struct const_succ_op_iterator
  3079. : iterator_adaptor_base<const_succ_op_iterator, const_value_op_iterator,
  3080. std::random_access_iterator_tag,
  3081. const BasicBlock *, ptrdiff_t, const BasicBlock *,
  3082. const BasicBlock *> {
  3083. explicit const_succ_op_iterator(const_value_op_iterator I)
  3084. : iterator_adaptor_base(I) {}
  3085. const BasicBlock *operator*() const { return cast<BasicBlock>(*I); }
  3086. const BasicBlock *operator->() const { return operator*(); }
  3087. };
  3088. static IndirectBrInst *Create(Value *Address, unsigned NumDests,
  3089. Instruction *InsertBefore = nullptr) {
  3090. return new IndirectBrInst(Address, NumDests, InsertBefore);
  3091. }
  3092. static IndirectBrInst *Create(Value *Address, unsigned NumDests,
  3093. BasicBlock *InsertAtEnd) {
  3094. return new IndirectBrInst(Address, NumDests, InsertAtEnd);
  3095. }
  3096. /// Provide fast operand accessors.
  3097. DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
  3098. // Accessor Methods for IndirectBrInst instruction.
  3099. Value *getAddress() { return getOperand(0); }
  3100. const Value *getAddress() const { return getOperand(0); }
  3101. void setAddress(Value *V) { setOperand(0, V); }
  3102. /// return the number of possible destinations in this
  3103. /// indirectbr instruction.
  3104. unsigned getNumDestinations() const { return getNumOperands()-1; }
  3105. /// Return the specified destination.
  3106. BasicBlock *getDestination(unsigned i) { return getSuccessor(i); }
  3107. const BasicBlock *getDestination(unsigned i) const { return getSuccessor(i); }
  3108. /// Add a destination.
  3109. ///
  3110. void addDestination(BasicBlock *Dest);
  3111. /// This method removes the specified successor from the
  3112. /// indirectbr instruction.
  3113. void removeDestination(unsigned i);
  3114. unsigned getNumSuccessors() const { return getNumOperands()-1; }
  3115. BasicBlock *getSuccessor(unsigned i) const {
  3116. return cast<BasicBlock>(getOperand(i+1));
  3117. }
  3118. void setSuccessor(unsigned i, BasicBlock *NewSucc) {
  3119. setOperand(i + 1, NewSucc);
  3120. }
  3121. iterator_range<succ_op_iterator> successors() {
  3122. return make_range(succ_op_iterator(std::next(value_op_begin())),
  3123. succ_op_iterator(value_op_end()));
  3124. }
  3125. iterator_range<const_succ_op_iterator> successors() const {
  3126. return make_range(const_succ_op_iterator(std::next(value_op_begin())),
  3127. const_succ_op_iterator(value_op_end()));
  3128. }
  3129. // Methods for support type inquiry through isa, cast, and dyn_cast:
  3130. static bool classof(const Instruction *I) {
  3131. return I->getOpcode() == Instruction::IndirectBr;
  3132. }
  3133. static bool classof(const Value *V) {
  3134. return isa<Instruction>(V) && classof(cast<Instruction>(V));
  3135. }
  3136. };
  3137. template <>
  3138. struct OperandTraits<IndirectBrInst> : public HungoffOperandTraits<1> {
  3139. };
  3140. DEFINE_TRANSPARENT_OPERAND_ACCESSORS(IndirectBrInst, Value)
  3141. //===----------------------------------------------------------------------===//
  3142. // InvokeInst Class
  3143. //===----------------------------------------------------------------------===//
  3144. /// Invoke instruction. The SubclassData field is used to hold the
  3145. /// calling convention of the call.
  3146. ///
  3147. class InvokeInst : public CallBase {
  3148. /// The number of operands for this call beyond the called function,
  3149. /// arguments, and operand bundles.
  3150. static constexpr int NumExtraOperands = 2;
  3151. /// The index from the end of the operand array to the normal destination.
  3152. static constexpr int NormalDestOpEndIdx = -3;
  3153. /// The index from the end of the operand array to the unwind destination.
  3154. static constexpr int UnwindDestOpEndIdx = -2;
  3155. InvokeInst(const InvokeInst &BI);
  3156. /// Construct an InvokeInst given a range of arguments.
  3157. ///
  3158. /// Construct an InvokeInst from a range of arguments
  3159. inline InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
  3160. BasicBlock *IfException, ArrayRef<Value *> Args,
  3161. ArrayRef<OperandBundleDef> Bundles, int NumOperands,
  3162. const Twine &NameStr, Instruction *InsertBefore);
  3163. inline InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
  3164. BasicBlock *IfException, ArrayRef<Value *> Args,
  3165. ArrayRef<OperandBundleDef> Bundles, int NumOperands,
  3166. const Twine &NameStr, BasicBlock *InsertAtEnd);
  3167. void init(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
  3168. BasicBlock *IfException, ArrayRef<Value *> Args,
  3169. ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr);
  3170. /// Compute the number of operands to allocate.
  3171. static int ComputeNumOperands(int NumArgs, int NumBundleInputs = 0) {
  3172. // We need one operand for the called function, plus our extra operands and
  3173. // the input operand counts provided.
  3174. return 1 + NumExtraOperands + NumArgs + NumBundleInputs;
  3175. }
  3176. protected:
  3177. // Note: Instruction needs to be a friend here to call cloneImpl.
  3178. friend class Instruction;
  3179. InvokeInst *cloneImpl() const;
  3180. public:
  3181. static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
  3182. BasicBlock *IfException, ArrayRef<Value *> Args,
  3183. const Twine &NameStr,
  3184. Instruction *InsertBefore = nullptr) {
  3185. int NumOperands = ComputeNumOperands(Args.size());
  3186. return new (NumOperands)
  3187. InvokeInst(Ty, Func, IfNormal, IfException, Args, None, NumOperands,
  3188. NameStr, InsertBefore);
  3189. }
  3190. static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
  3191. BasicBlock *IfException, ArrayRef<Value *> Args,
  3192. ArrayRef<OperandBundleDef> Bundles = None,
  3193. const Twine &NameStr = "",
  3194. Instruction *InsertBefore = nullptr) {
  3195. int NumOperands =
  3196. ComputeNumOperands(Args.size(), CountBundleInputs(Bundles));
  3197. unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
  3198. return new (NumOperands, DescriptorBytes)
  3199. InvokeInst(Ty, Func, IfNormal, IfException, Args, Bundles, NumOperands,
  3200. NameStr, InsertBefore);
  3201. }
  3202. static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
  3203. BasicBlock *IfException, ArrayRef<Value *> Args,
  3204. const Twine &NameStr, BasicBlock *InsertAtEnd) {
  3205. int NumOperands = ComputeNumOperands(Args.size());
  3206. return new (NumOperands)
  3207. InvokeInst(Ty, Func, IfNormal, IfException, Args, None, NumOperands,
  3208. NameStr, InsertAtEnd);
  3209. }
  3210. static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
  3211. BasicBlock *IfException, ArrayRef<Value *> Args,
  3212. ArrayRef<OperandBundleDef> Bundles,
  3213. const Twine &NameStr, BasicBlock *InsertAtEnd) {
  3214. int NumOperands =
  3215. ComputeNumOperands(Args.size(), CountBundleInputs(Bundles));
  3216. unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
  3217. return new (NumOperands, DescriptorBytes)
  3218. InvokeInst(Ty, Func, IfNormal, IfException, Args, Bundles, NumOperands,
  3219. NameStr, InsertAtEnd);
  3220. }
  3221. static InvokeInst *Create(FunctionCallee Func, BasicBlock *IfNormal,
  3222. BasicBlock *IfException, ArrayRef<Value *> Args,
  3223. const Twine &NameStr,
  3224. Instruction *InsertBefore = nullptr) {
  3225. return Create(Func.getFunctionType(), Func.getCallee(), IfNormal,
  3226. IfException, Args, None, NameStr, InsertBefore);
  3227. }
  3228. static InvokeInst *Create(FunctionCallee Func, BasicBlock *IfNormal,
  3229. BasicBlock *IfException, ArrayRef<Value *> Args,
  3230. ArrayRef<OperandBundleDef> Bundles = None,
  3231. const Twine &NameStr = "",
  3232. Instruction *InsertBefore = nullptr) {
  3233. return Create(Func.getFunctionType(), Func.getCallee(), IfNormal,
  3234. IfException, Args, Bundles, NameStr, InsertBefore);
  3235. }
  3236. static InvokeInst *Create(FunctionCallee Func, BasicBlock *IfNormal,
  3237. BasicBlock *IfException, ArrayRef<Value *> Args,
  3238. const Twine &NameStr, BasicBlock *InsertAtEnd) {
  3239. return Create(Func.getFunctionType(), Func.getCallee(), IfNormal,
  3240. IfException, Args, NameStr, InsertAtEnd);
  3241. }
  3242. static InvokeInst *Create(FunctionCallee Func, BasicBlock *IfNormal,
  3243. BasicBlock *IfException, ArrayRef<Value *> Args,
  3244. ArrayRef<OperandBundleDef> Bundles,
  3245. const Twine &NameStr, BasicBlock *InsertAtEnd) {
  3246. return Create(Func.getFunctionType(), Func.getCallee(), IfNormal,
  3247. IfException, Args, Bundles, NameStr, InsertAtEnd);
  3248. }
  3249. /// Create a clone of \p II with a different set of operand bundles and
  3250. /// insert it before \p InsertPt.
  3251. ///
  3252. /// The returned invoke instruction is identical to \p II in every way except
  3253. /// that the operand bundles for the new instruction are set to the operand
  3254. /// bundles in \p Bundles.
  3255. static InvokeInst *Create(InvokeInst *II, ArrayRef<OperandBundleDef> Bundles,
  3256. Instruction *InsertPt = nullptr);
  3257. /// Create a clone of \p II with a different set of operand bundles and
  3258. /// insert it before \p InsertPt.
  3259. ///
  3260. /// The returned invoke instruction is identical to \p II in every way except
  3261. /// that the operand bundle for the new instruction is set to the operand
  3262. /// bundle in \p Bundle.
  3263. static InvokeInst *CreateWithReplacedBundle(InvokeInst *II,
  3264. OperandBundleDef Bundles,
  3265. Instruction *InsertPt = nullptr);
  3266. // get*Dest - Return the destination basic blocks...
  3267. BasicBlock *getNormalDest() const {
  3268. return cast<BasicBlock>(Op<NormalDestOpEndIdx>());
  3269. }
  3270. BasicBlock *getUnwindDest() const {
  3271. return cast<BasicBlock>(Op<UnwindDestOpEndIdx>());
  3272. }
  3273. void setNormalDest(BasicBlock *B) {
  3274. Op<NormalDestOpEndIdx>() = reinterpret_cast<Value *>(B);
  3275. }
  3276. void setUnwindDest(BasicBlock *B) {
  3277. Op<UnwindDestOpEndIdx>() = reinterpret_cast<Value *>(B);
  3278. }
  3279. /// Get the landingpad instruction from the landing pad
  3280. /// block (the unwind destination).
  3281. LandingPadInst *getLandingPadInst() const;
  3282. BasicBlock *getSuccessor(unsigned i) const {
  3283. assert(i < 2 && "Successor # out of range for invoke!");
  3284. return i == 0 ? getNormalDest() : getUnwindDest();
  3285. }
  3286. void setSuccessor(unsigned i, BasicBlock *NewSucc) {
  3287. assert(i < 2 && "Successor # out of range for invoke!");
  3288. if (i == 0)
  3289. setNormalDest(NewSucc);
  3290. else
  3291. setUnwindDest(NewSucc);
  3292. }
  3293. unsigned getNumSuccessors() const { return 2; }
  3294. // Methods for support type inquiry through isa, cast, and dyn_cast:
  3295. static bool classof(const Instruction *I) {
  3296. return (I->getOpcode() == Instruction::Invoke);
  3297. }
  3298. static bool classof(const Value *V) {
  3299. return isa<Instruction>(V) && classof(cast<Instruction>(V));
  3300. }
  3301. private:
  3302. // Shadow Instruction::setInstructionSubclassData with a private forwarding
  3303. // method so that subclasses cannot accidentally use it.
  3304. template <typename Bitfield>
  3305. void setSubclassData(typename Bitfield::Type Value) {
  3306. Instruction::setSubclassData<Bitfield>(Value);
  3307. }
  3308. };
  3309. InvokeInst::InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
  3310. BasicBlock *IfException, ArrayRef<Value *> Args,
  3311. ArrayRef<OperandBundleDef> Bundles, int NumOperands,
  3312. const Twine &NameStr, Instruction *InsertBefore)
  3313. : CallBase(Ty->getReturnType(), Instruction::Invoke,
  3314. OperandTraits<CallBase>::op_end(this) - NumOperands, NumOperands,
  3315. InsertBefore) {
  3316. init(Ty, Func, IfNormal, IfException, Args, Bundles, NameStr);
  3317. }
  3318. InvokeInst::InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
  3319. BasicBlock *IfException, ArrayRef<Value *> Args,
  3320. ArrayRef<OperandBundleDef> Bundles, int NumOperands,
  3321. const Twine &NameStr, BasicBlock *InsertAtEnd)
  3322. : CallBase(Ty->getReturnType(), Instruction::Invoke,
  3323. OperandTraits<CallBase>::op_end(this) - NumOperands, NumOperands,
  3324. InsertAtEnd) {
  3325. init(Ty, Func, IfNormal, IfException, Args, Bundles, NameStr);
  3326. }
  3327. //===----------------------------------------------------------------------===//
  3328. // CallBrInst Class
  3329. //===----------------------------------------------------------------------===//
  3330. /// CallBr instruction, tracking function calls that may not return control but
  3331. /// instead transfer it to a third location. The SubclassData field is used to
  3332. /// hold the calling convention of the call.
  3333. ///
  3334. class CallBrInst : public CallBase {
  3335. unsigned NumIndirectDests;
  3336. CallBrInst(const CallBrInst &BI);
  3337. /// Construct a CallBrInst given a range of arguments.
  3338. ///
  3339. /// Construct a CallBrInst from a range of arguments
  3340. inline CallBrInst(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest,
  3341. ArrayRef<BasicBlock *> IndirectDests,
  3342. ArrayRef<Value *> Args,
  3343. ArrayRef<OperandBundleDef> Bundles, int NumOperands,
  3344. const Twine &NameStr, Instruction *InsertBefore);
  3345. inline CallBrInst(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest,
  3346. ArrayRef<BasicBlock *> IndirectDests,
  3347. ArrayRef<Value *> Args,
  3348. ArrayRef<OperandBundleDef> Bundles, int NumOperands,
  3349. const Twine &NameStr, BasicBlock *InsertAtEnd);
  3350. void init(FunctionType *FTy, Value *Func, BasicBlock *DefaultDest,
  3351. ArrayRef<BasicBlock *> IndirectDests, ArrayRef<Value *> Args,
  3352. ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr);
  3353. /// Should the Indirect Destinations change, scan + update the Arg list.
  3354. void updateArgBlockAddresses(unsigned i, BasicBlock *B);
  3355. /// Compute the number of operands to allocate.
  3356. static int ComputeNumOperands(int NumArgs, int NumIndirectDests,
  3357. int NumBundleInputs = 0) {
  3358. // We need one operand for the called function, plus our extra operands and
  3359. // the input operand counts provided.
  3360. return 2 + NumIndirectDests + NumArgs + NumBundleInputs;
  3361. }
  3362. protected:
  3363. // Note: Instruction needs to be a friend here to call cloneImpl.
  3364. friend class Instruction;
  3365. CallBrInst *cloneImpl() const;
  3366. public:
  3367. static CallBrInst *Create(FunctionType *Ty, Value *Func,
  3368. BasicBlock *DefaultDest,
  3369. ArrayRef<BasicBlock *> IndirectDests,
  3370. ArrayRef<Value *> Args, const Twine &NameStr,
  3371. Instruction *InsertBefore = nullptr) {
  3372. int NumOperands = ComputeNumOperands(Args.size(), IndirectDests.size());
  3373. return new (NumOperands)
  3374. CallBrInst(Ty, Func, DefaultDest, IndirectDests, Args, None,
  3375. NumOperands, NameStr, InsertBefore);
  3376. }
  3377. static CallBrInst *Create(FunctionType *Ty, Value *Func,
  3378. BasicBlock *DefaultDest,
  3379. ArrayRef<BasicBlock *> IndirectDests,
  3380. ArrayRef<Value *> Args,
  3381. ArrayRef<OperandBundleDef> Bundles = None,
  3382. const Twine &NameStr = "",
  3383. Instruction *InsertBefore = nullptr) {
  3384. int NumOperands = ComputeNumOperands(Args.size(), IndirectDests.size(),
  3385. CountBundleInputs(Bundles));
  3386. unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
  3387. return new (NumOperands, DescriptorBytes)
  3388. CallBrInst(Ty, Func, DefaultDest, IndirectDests, Args, Bundles,
  3389. NumOperands, NameStr, InsertBefore);
  3390. }
  3391. static CallBrInst *Create(FunctionType *Ty, Value *Func,
  3392. BasicBlock *DefaultDest,
  3393. ArrayRef<BasicBlock *> IndirectDests,
  3394. ArrayRef<Value *> Args, const Twine &NameStr,
  3395. BasicBlock *InsertAtEnd) {
  3396. int NumOperands = ComputeNumOperands(Args.size(), IndirectDests.size());
  3397. return new (NumOperands)
  3398. CallBrInst(Ty, Func, DefaultDest, IndirectDests, Args, None,
  3399. NumOperands, NameStr, InsertAtEnd);
  3400. }
  3401. static CallBrInst *Create(FunctionType *Ty, Value *Func,
  3402. BasicBlock *DefaultDest,
  3403. ArrayRef<BasicBlock *> IndirectDests,
  3404. ArrayRef<Value *> Args,
  3405. ArrayRef<OperandBundleDef> Bundles,
  3406. const Twine &NameStr, BasicBlock *InsertAtEnd) {
  3407. int NumOperands = ComputeNumOperands(Args.size(), IndirectDests.size(),
  3408. CountBundleInputs(Bundles));
  3409. unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
  3410. return new (NumOperands, DescriptorBytes)
  3411. CallBrInst(Ty, Func, DefaultDest, IndirectDests, Args, Bundles,
  3412. NumOperands, NameStr, InsertAtEnd);
  3413. }
  3414. static CallBrInst *Create(FunctionCallee Func, BasicBlock *DefaultDest,
  3415. ArrayRef<BasicBlock *> IndirectDests,
  3416. ArrayRef<Value *> Args, const Twine &NameStr,
  3417. Instruction *InsertBefore = nullptr) {
  3418. return Create(Func.getFunctionType(), Func.getCallee(), DefaultDest,
  3419. IndirectDests, Args, NameStr, InsertBefore);
  3420. }
  3421. static CallBrInst *Create(FunctionCallee Func, BasicBlock *DefaultDest,
  3422. ArrayRef<BasicBlock *> IndirectDests,
  3423. ArrayRef<Value *> Args,
  3424. ArrayRef<OperandBundleDef> Bundles = None,
  3425. const Twine &NameStr = "",
  3426. Instruction *InsertBefore = nullptr) {
  3427. return Create(Func.getFunctionType(), Func.getCallee(), DefaultDest,
  3428. IndirectDests, Args, Bundles, NameStr, InsertBefore);
  3429. }
  3430. static CallBrInst *Create(FunctionCallee Func, BasicBlock *DefaultDest,
  3431. ArrayRef<BasicBlock *> IndirectDests,
  3432. ArrayRef<Value *> Args, const Twine &NameStr,
  3433. BasicBlock *InsertAtEnd) {
  3434. return Create(Func.getFunctionType(), Func.getCallee(), DefaultDest,
  3435. IndirectDests, Args, NameStr, InsertAtEnd);
  3436. }
  3437. static CallBrInst *Create(FunctionCallee Func,
  3438. BasicBlock *DefaultDest,
  3439. ArrayRef<BasicBlock *> IndirectDests,
  3440. ArrayRef<Value *> Args,
  3441. ArrayRef<OperandBundleDef> Bundles,
  3442. const Twine &NameStr, BasicBlock *InsertAtEnd) {
  3443. return Create(Func.getFunctionType(), Func.getCallee(), DefaultDest,
  3444. IndirectDests, Args, Bundles, NameStr, InsertAtEnd);
  3445. }
  3446. /// Create a clone of \p CBI with a different set of operand bundles and
  3447. /// insert it before \p InsertPt.
  3448. ///
  3449. /// The returned callbr instruction is identical to \p CBI in every way
  3450. /// except that the operand bundles for the new instruction are set to the
  3451. /// operand bundles in \p Bundles.
  3452. static CallBrInst *Create(CallBrInst *CBI,
  3453. ArrayRef<OperandBundleDef> Bundles,
  3454. Instruction *InsertPt = nullptr);
  3455. /// Return the number of callbr indirect dest labels.
  3456. ///
  3457. unsigned getNumIndirectDests() const { return NumIndirectDests; }
  3458. /// getIndirectDestLabel - Return the i-th indirect dest label.
  3459. ///
  3460. Value *getIndirectDestLabel(unsigned i) const {
  3461. assert(i < getNumIndirectDests() && "Out of bounds!");
  3462. return getOperand(i + getNumArgOperands() + getNumTotalBundleOperands() +
  3463. 1);
  3464. }
  3465. Value *getIndirectDestLabelUse(unsigned i) const {
  3466. assert(i < getNumIndirectDests() && "Out of bounds!");
  3467. return getOperandUse(i + getNumArgOperands() + getNumTotalBundleOperands() +
  3468. 1);
  3469. }
  3470. // Return the destination basic blocks...
  3471. BasicBlock *getDefaultDest() const {
  3472. return cast<BasicBlock>(*(&Op<-1>() - getNumIndirectDests() - 1));
  3473. }
  3474. BasicBlock *getIndirectDest(unsigned i) const {
  3475. return cast_or_null<BasicBlock>(*(&Op<-1>() - getNumIndirectDests() + i));
  3476. }
  3477. SmallVector<BasicBlock *, 16> getIndirectDests() const {
  3478. SmallVector<BasicBlock *, 16> IndirectDests;
  3479. for (unsigned i = 0, e = getNumIndirectDests(); i < e; ++i)
  3480. IndirectDests.push_back(getIndirectDest(i));
  3481. return IndirectDests;
  3482. }
  3483. void setDefaultDest(BasicBlock *B) {
  3484. *(&Op<-1>() - getNumIndirectDests() - 1) = reinterpret_cast<Value *>(B);
  3485. }
  3486. void setIndirectDest(unsigned i, BasicBlock *B) {
  3487. updateArgBlockAddresses(i, B);
  3488. *(&Op<-1>() - getNumIndirectDests() + i) = reinterpret_cast<Value *>(B);
  3489. }
  3490. BasicBlock *getSuccessor(unsigned i) const {
  3491. assert(i < getNumSuccessors() + 1 &&
  3492. "Successor # out of range for callbr!");
  3493. return i == 0 ? getDefaultDest() : getIndirectDest(i - 1);
  3494. }
  3495. void setSuccessor(unsigned i, BasicBlock *NewSucc) {
  3496. assert(i < getNumIndirectDests() + 1 &&
  3497. "Successor # out of range for callbr!");
  3498. return i == 0 ? setDefaultDest(NewSucc) : setIndirectDest(i - 1, NewSucc);
  3499. }
  3500. unsigned getNumSuccessors() const { return getNumIndirectDests() + 1; }
  3501. // Methods for support type inquiry through isa, cast, and dyn_cast:
  3502. static bool classof(const Instruction *I) {
  3503. return (I->getOpcode() == Instruction::CallBr);
  3504. }
  3505. static bool classof(const Value *V) {
  3506. return isa<Instruction>(V) && classof(cast<Instruction>(V));
  3507. }
  3508. private:
  3509. // Shadow Instruction::setInstructionSubclassData with a private forwarding
  3510. // method so that subclasses cannot accidentally use it.
  3511. template <typename Bitfield>
  3512. void setSubclassData(typename Bitfield::Type Value) {
  3513. Instruction::setSubclassData<Bitfield>(Value);
  3514. }
  3515. };
  3516. CallBrInst::CallBrInst(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest,
  3517. ArrayRef<BasicBlock *> IndirectDests,
  3518. ArrayRef<Value *> Args,
  3519. ArrayRef<OperandBundleDef> Bundles, int NumOperands,
  3520. const Twine &NameStr, Instruction *InsertBefore)
  3521. : CallBase(Ty->getReturnType(), Instruction::CallBr,
  3522. OperandTraits<CallBase>::op_end(this) - NumOperands, NumOperands,
  3523. InsertBefore) {
  3524. init(Ty, Func, DefaultDest, IndirectDests, Args, Bundles, NameStr);
  3525. }
  3526. CallBrInst::CallBrInst(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest,
  3527. ArrayRef<BasicBlock *> IndirectDests,
  3528. ArrayRef<Value *> Args,
  3529. ArrayRef<OperandBundleDef> Bundles, int NumOperands,
  3530. const Twine &NameStr, BasicBlock *InsertAtEnd)
  3531. : CallBase(Ty->getReturnType(), Instruction::CallBr,
  3532. OperandTraits<CallBase>::op_end(this) - NumOperands, NumOperands,
  3533. InsertAtEnd) {
  3534. init(Ty, Func, DefaultDest, IndirectDests, Args, Bundles, NameStr);
  3535. }
  3536. //===----------------------------------------------------------------------===//
  3537. // ResumeInst Class
  3538. //===----------------------------------------------------------------------===//
  3539. //===---------------------------------------------------------------------------
  3540. /// Resume the propagation of an exception.
  3541. ///
  3542. class ResumeInst : public Instruction {
  3543. ResumeInst(const ResumeInst &RI);
  3544. explicit ResumeInst(Value *Exn, Instruction *InsertBefore=nullptr);
  3545. ResumeInst(Value *Exn, BasicBlock *InsertAtEnd);
  3546. protected:
  3547. // Note: Instruction needs to be a friend here to call cloneImpl.
  3548. friend class Instruction;
  3549. ResumeInst *cloneImpl() const;
  3550. public:
  3551. static ResumeInst *Create(Value *Exn, Instruction *InsertBefore = nullptr) {
  3552. return new(1) ResumeInst(Exn, InsertBefore);
  3553. }
  3554. static ResumeInst *Create(Value *Exn, BasicBlock *InsertAtEnd) {
  3555. return new(1) ResumeInst(Exn, InsertAtEnd);
  3556. }
  3557. /// Provide fast operand accessors
  3558. DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
  3559. /// Convenience accessor.
  3560. Value *getValue() const { return Op<0>(); }
  3561. unsigned getNumSuccessors() const { return 0; }
  3562. // Methods for support type inquiry through isa, cast, and dyn_cast:
  3563. static bool classof(const Instruction *I) {
  3564. return I->getOpcode() == Instruction::Resume;
  3565. }
  3566. static bool classof(const Value *V) {
  3567. return isa<Instruction>(V) && classof(cast<Instruction>(V));
  3568. }
  3569. private:
  3570. BasicBlock *getSuccessor(unsigned idx) const {
  3571. llvm_unreachable("ResumeInst has no successors!");
  3572. }
  3573. void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
  3574. llvm_unreachable("ResumeInst has no successors!");
  3575. }
  3576. };
  3577. template <>
  3578. struct OperandTraits<ResumeInst> :
  3579. public FixedNumOperandTraits<ResumeInst, 1> {
  3580. };
  3581. DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ResumeInst, Value)
  3582. //===----------------------------------------------------------------------===//
  3583. // CatchSwitchInst Class
  3584. //===----------------------------------------------------------------------===//
  3585. class CatchSwitchInst : public Instruction {
  3586. using UnwindDestField = BoolBitfieldElementT<0>;
  3587. /// The number of operands actually allocated. NumOperands is
  3588. /// the number actually in use.
  3589. unsigned ReservedSpace;
  3590. // Operand[0] = Outer scope
  3591. // Operand[1] = Unwind block destination
  3592. // Operand[n] = BasicBlock to go to on match
  3593. CatchSwitchInst(const CatchSwitchInst &CSI);
  3594. /// Create a new switch instruction, specifying a
  3595. /// default destination. The number of additional handlers can be specified
  3596. /// here to make memory allocation more efficient.
  3597. /// This constructor can also autoinsert before another instruction.
  3598. CatchSwitchInst(Value *ParentPad, BasicBlock *UnwindDest,
  3599. unsigned NumHandlers, const Twine &NameStr,
  3600. Instruction *InsertBefore);
  3601. /// Create a new switch instruction, specifying a
  3602. /// default destination. The number of additional handlers can be specified
  3603. /// here to make memory allocation more efficient.
  3604. /// This constructor also autoinserts at the end of the specified BasicBlock.
  3605. CatchSwitchInst(Value *ParentPad, BasicBlock *UnwindDest,
  3606. unsigned NumHandlers, const Twine &NameStr,
  3607. BasicBlock *InsertAtEnd);
  3608. // allocate space for exactly zero operands
  3609. void *operator new(size_t s) { return User::operator new(s); }
  3610. void init(Value *ParentPad, BasicBlock *UnwindDest, unsigned NumReserved);
  3611. void growOperands(unsigned Size);
  3612. protected:
  3613. // Note: Instruction needs to be a friend here to call cloneImpl.
  3614. friend class Instruction;
  3615. CatchSwitchInst *cloneImpl() const;
  3616. public:
  3617. static CatchSwitchInst *Create(Value *ParentPad, BasicBlock *UnwindDest,
  3618. unsigned NumHandlers,
  3619. const Twine &NameStr = "",
  3620. Instruction *InsertBefore = nullptr) {
  3621. return new CatchSwitchInst(ParentPad, UnwindDest, NumHandlers, NameStr,
  3622. InsertBefore);
  3623. }
  3624. static CatchSwitchInst *Create(Value *ParentPad, BasicBlock *UnwindDest,
  3625. unsigned NumHandlers, const Twine &NameStr,
  3626. BasicBlock *InsertAtEnd) {
  3627. return new CatchSwitchInst(ParentPad, UnwindDest, NumHandlers, NameStr,
  3628. InsertAtEnd);
  3629. }
  3630. /// Provide fast operand accessors
  3631. DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
  3632. // Accessor Methods for CatchSwitch stmt
  3633. Value *getParentPad() const { return getOperand(0); }
  3634. void setParentPad(Value *ParentPad) { setOperand(0, ParentPad); }
  3635. // Accessor Methods for CatchSwitch stmt
  3636. bool hasUnwindDest() const { return getSubclassData<UnwindDestField>(); }
  3637. bool unwindsToCaller() const { return !hasUnwindDest(); }
  3638. BasicBlock *getUnwindDest() const {
  3639. if (hasUnwindDest())
  3640. return cast<BasicBlock>(getOperand(1));
  3641. return nullptr;
  3642. }
  3643. void setUnwindDest(BasicBlock *UnwindDest) {
  3644. assert(UnwindDest);
  3645. assert(hasUnwindDest());
  3646. setOperand(1, UnwindDest);
  3647. }
  3648. /// return the number of 'handlers' in this catchswitch
  3649. /// instruction, except the default handler
  3650. unsigned getNumHandlers() const {
  3651. if (hasUnwindDest())
  3652. return getNumOperands() - 2;
  3653. return getNumOperands() - 1;
  3654. }
  3655. private:
  3656. static BasicBlock *handler_helper(Value *V) { return cast<BasicBlock>(V); }
  3657. static const BasicBlock *handler_helper(const Value *V) {
  3658. return cast<BasicBlock>(V);
  3659. }
  3660. public:
  3661. using DerefFnTy = BasicBlock *(*)(Value *);
  3662. using handler_iterator = mapped_iterator<op_iterator, DerefFnTy>;
  3663. using handler_range = iterator_range<handler_iterator>;
  3664. using ConstDerefFnTy = const BasicBlock *(*)(const Value *);
  3665. using const_handler_iterator =
  3666. mapped_iterator<const_op_iterator, ConstDerefFnTy>;
  3667. using const_handler_range = iterator_range<const_handler_iterator>;
  3668. /// Returns an iterator that points to the first handler in CatchSwitchInst.
  3669. handler_iterator handler_begin() {
  3670. op_iterator It = op_begin() + 1;
  3671. if (hasUnwindDest())
  3672. ++It;
  3673. return handler_iterator(It, DerefFnTy(handler_helper));
  3674. }
  3675. /// Returns an iterator that points to the first handler in the
  3676. /// CatchSwitchInst.
  3677. const_handler_iterator handler_begin() const {
  3678. const_op_iterator It = op_begin() + 1;
  3679. if (hasUnwindDest())
  3680. ++It;
  3681. return const_handler_iterator(It, ConstDerefFnTy(handler_helper));
  3682. }
  3683. /// Returns a read-only iterator that points one past the last
  3684. /// handler in the CatchSwitchInst.
  3685. handler_iterator handler_end() {
  3686. return handler_iterator(op_end(), DerefFnTy(handler_helper));
  3687. }
  3688. /// Returns an iterator that points one past the last handler in the
  3689. /// CatchSwitchInst.
  3690. const_handler_iterator handler_end() const {
  3691. return const_handler_iterator(op_end(), ConstDerefFnTy(handler_helper));
  3692. }
  3693. /// iteration adapter for range-for loops.
  3694. handler_range handlers() {
  3695. return make_range(handler_begin(), handler_end());
  3696. }
  3697. /// iteration adapter for range-for loops.
  3698. const_handler_range handlers() const {
  3699. return make_range(handler_begin(), handler_end());
  3700. }
  3701. /// Add an entry to the switch instruction...
  3702. /// Note:
  3703. /// This action invalidates handler_end(). Old handler_end() iterator will
  3704. /// point to the added handler.
  3705. void addHandler(BasicBlock *Dest);
  3706. void removeHandler(handler_iterator HI);
  3707. unsigned getNumSuccessors() const { return getNumOperands() - 1; }
  3708. BasicBlock *getSuccessor(unsigned Idx) const {
  3709. assert(Idx < getNumSuccessors() &&
  3710. "Successor # out of range for catchswitch!");
  3711. return cast<BasicBlock>(getOperand(Idx + 1));
  3712. }
  3713. void setSuccessor(unsigned Idx, BasicBlock *NewSucc) {
  3714. assert(Idx < getNumSuccessors() &&
  3715. "Successor # out of range for catchswitch!");
  3716. setOperand(Idx + 1, NewSucc);
  3717. }
  3718. // Methods for support type inquiry through isa, cast, and dyn_cast:
  3719. static bool classof(const Instruction *I) {
  3720. return I->getOpcode() == Instruction::CatchSwitch;
  3721. }
  3722. static bool classof(const Value *V) {
  3723. return isa<Instruction>(V) && classof(cast<Instruction>(V));
  3724. }
  3725. };
  3726. template <>
  3727. struct OperandTraits<CatchSwitchInst> : public HungoffOperandTraits<2> {};
  3728. DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CatchSwitchInst, Value)
  3729. //===----------------------------------------------------------------------===//
  3730. // CleanupPadInst Class
  3731. //===----------------------------------------------------------------------===//
  3732. class CleanupPadInst : public FuncletPadInst {
  3733. private:
  3734. explicit CleanupPadInst(Value *ParentPad, ArrayRef<Value *> Args,
  3735. unsigned Values, const Twine &NameStr,
  3736. Instruction *InsertBefore)
  3737. : FuncletPadInst(Instruction::CleanupPad, ParentPad, Args, Values,
  3738. NameStr, InsertBefore) {}
  3739. explicit CleanupPadInst(Value *ParentPad, ArrayRef<Value *> Args,
  3740. unsigned Values, const Twine &NameStr,
  3741. BasicBlock *InsertAtEnd)
  3742. : FuncletPadInst(Instruction::CleanupPad, ParentPad, Args, Values,
  3743. NameStr, InsertAtEnd) {}
  3744. public:
  3745. static CleanupPadInst *Create(Value *ParentPad, ArrayRef<Value *> Args = None,
  3746. const Twine &NameStr = "",
  3747. Instruction *InsertBefore = nullptr) {
  3748. unsigned Values = 1 + Args.size();
  3749. return new (Values)
  3750. CleanupPadInst(ParentPad, Args, Values, NameStr, InsertBefore);
  3751. }
  3752. static CleanupPadInst *Create(Value *ParentPad, ArrayRef<Value *> Args,
  3753. const Twine &NameStr, BasicBlock *InsertAtEnd) {
  3754. unsigned Values = 1 + Args.size();
  3755. return new (Values)
  3756. CleanupPadInst(ParentPad, Args, Values, NameStr, InsertAtEnd);
  3757. }
  3758. /// Methods for support type inquiry through isa, cast, and dyn_cast:
  3759. static bool classof(const Instruction *I) {
  3760. return I->getOpcode() == Instruction::CleanupPad;
  3761. }
  3762. static bool classof(const Value *V) {
  3763. return isa<Instruction>(V) && classof(cast<Instruction>(V));
  3764. }
  3765. };
  3766. //===----------------------------------------------------------------------===//
  3767. // CatchPadInst Class
  3768. //===----------------------------------------------------------------------===//
  3769. class CatchPadInst : public FuncletPadInst {
  3770. private:
  3771. explicit CatchPadInst(Value *CatchSwitch, ArrayRef<Value *> Args,
  3772. unsigned Values, const Twine &NameStr,
  3773. Instruction *InsertBefore)
  3774. : FuncletPadInst(Instruction::CatchPad, CatchSwitch, Args, Values,
  3775. NameStr, InsertBefore) {}
  3776. explicit CatchPadInst(Value *CatchSwitch, ArrayRef<Value *> Args,
  3777. unsigned Values, const Twine &NameStr,
  3778. BasicBlock *InsertAtEnd)
  3779. : FuncletPadInst(Instruction::CatchPad, CatchSwitch, Args, Values,
  3780. NameStr, InsertAtEnd) {}
  3781. public:
  3782. static CatchPadInst *Create(Value *CatchSwitch, ArrayRef<Value *> Args,
  3783. const Twine &NameStr = "",
  3784. Instruction *InsertBefore = nullptr) {
  3785. unsigned Values = 1 + Args.size();
  3786. return new (Values)
  3787. CatchPadInst(CatchSwitch, Args, Values, NameStr, InsertBefore);
  3788. }
  3789. static CatchPadInst *Create(Value *CatchSwitch, ArrayRef<Value *> Args,
  3790. const Twine &NameStr, BasicBlock *InsertAtEnd) {
  3791. unsigned Values = 1 + Args.size();
  3792. return new (Values)
  3793. CatchPadInst(CatchSwitch, Args, Values, NameStr, InsertAtEnd);
  3794. }
  3795. /// Convenience accessors
  3796. CatchSwitchInst *getCatchSwitch() const {
  3797. return cast<CatchSwitchInst>(Op<-1>());
  3798. }
  3799. void setCatchSwitch(Value *CatchSwitch) {
  3800. assert(CatchSwitch);
  3801. Op<-1>() = CatchSwitch;
  3802. }
  3803. /// Methods for support type inquiry through isa, cast, and dyn_cast:
  3804. static bool classof(const Instruction *I) {
  3805. return I->getOpcode() == Instruction::CatchPad;
  3806. }
  3807. static bool classof(const Value *V) {
  3808. return isa<Instruction>(V) && classof(cast<Instruction>(V));
  3809. }
  3810. };
  3811. //===----------------------------------------------------------------------===//
  3812. // CatchReturnInst Class
  3813. //===----------------------------------------------------------------------===//
  3814. class CatchReturnInst : public Instruction {
  3815. CatchReturnInst(const CatchReturnInst &RI);
  3816. CatchReturnInst(Value *CatchPad, BasicBlock *BB, Instruction *InsertBefore);
  3817. CatchReturnInst(Value *CatchPad, BasicBlock *BB, BasicBlock *InsertAtEnd);
  3818. void init(Value *CatchPad, BasicBlock *BB);
  3819. protected:
  3820. // Note: Instruction needs to be a friend here to call cloneImpl.
  3821. friend class Instruction;
  3822. CatchReturnInst *cloneImpl() const;
  3823. public:
  3824. static CatchReturnInst *Create(Value *CatchPad, BasicBlock *BB,
  3825. Instruction *InsertBefore = nullptr) {
  3826. assert(CatchPad);
  3827. assert(BB);
  3828. return new (2) CatchReturnInst(CatchPad, BB, InsertBefore);
  3829. }
  3830. static CatchReturnInst *Create(Value *CatchPad, BasicBlock *BB,
  3831. BasicBlock *InsertAtEnd) {
  3832. assert(CatchPad);
  3833. assert(BB);
  3834. return new (2) CatchReturnInst(CatchPad, BB, InsertAtEnd);
  3835. }
  3836. /// Provide fast operand accessors
  3837. DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
  3838. /// Convenience accessors.
  3839. CatchPadInst *getCatchPad() const { return cast<CatchPadInst>(Op<0>()); }
  3840. void setCatchPad(CatchPadInst *CatchPad) {
  3841. assert(CatchPad);
  3842. Op<0>() = CatchPad;
  3843. }
  3844. BasicBlock *getSuccessor() const { return cast<BasicBlock>(Op<1>()); }
  3845. void setSuccessor(BasicBlock *NewSucc) {
  3846. assert(NewSucc);
  3847. Op<1>() = NewSucc;
  3848. }
  3849. unsigned getNumSuccessors() const { return 1; }
  3850. /// Get the parentPad of this catchret's catchpad's catchswitch.
  3851. /// The successor block is implicitly a member of this funclet.
  3852. Value *getCatchSwitchParentPad() const {
  3853. return getCatchPad()->getCatchSwitch()->getParentPad();
  3854. }
  3855. // Methods for support type inquiry through isa, cast, and dyn_cast:
  3856. static bool classof(const Instruction *I) {
  3857. return (I->getOpcode() == Instruction::CatchRet);
  3858. }
  3859. static bool classof(const Value *V) {
  3860. return isa<Instruction>(V) && classof(cast<Instruction>(V));
  3861. }
  3862. private:
  3863. BasicBlock *getSuccessor(unsigned Idx) const {
  3864. assert(Idx < getNumSuccessors() && "Successor # out of range for catchret!");
  3865. return getSuccessor();
  3866. }
  3867. void setSuccessor(unsigned Idx, BasicBlock *B) {
  3868. assert(Idx < getNumSuccessors() && "Successor # out of range for catchret!");
  3869. setSuccessor(B);
  3870. }
  3871. };
  3872. template <>
  3873. struct OperandTraits<CatchReturnInst>
  3874. : public FixedNumOperandTraits<CatchReturnInst, 2> {};
  3875. DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CatchReturnInst, Value)
  3876. //===----------------------------------------------------------------------===//
  3877. // CleanupReturnInst Class
  3878. //===----------------------------------------------------------------------===//
  3879. class CleanupReturnInst : public Instruction {
  3880. using UnwindDestField = BoolBitfieldElementT<0>;
  3881. private:
  3882. CleanupReturnInst(const CleanupReturnInst &RI);
  3883. CleanupReturnInst(Value *CleanupPad, BasicBlock *UnwindBB, unsigned Values,
  3884. Instruction *InsertBefore = nullptr);
  3885. CleanupReturnInst(Value *CleanupPad, BasicBlock *UnwindBB, unsigned Values,
  3886. BasicBlock *InsertAtEnd);
  3887. void init(Value *CleanupPad, BasicBlock *UnwindBB);
  3888. protected:
  3889. // Note: Instruction needs to be a friend here to call cloneImpl.
  3890. friend class Instruction;
  3891. CleanupReturnInst *cloneImpl() const;
  3892. public:
  3893. static CleanupReturnInst *Create(Value *CleanupPad,
  3894. BasicBlock *UnwindBB = nullptr,
  3895. Instruction *InsertBefore = nullptr) {
  3896. assert(CleanupPad);
  3897. unsigned Values = 1;
  3898. if (UnwindBB)
  3899. ++Values;
  3900. return new (Values)
  3901. CleanupReturnInst(CleanupPad, UnwindBB, Values, InsertBefore);
  3902. }
  3903. static CleanupReturnInst *Create(Value *CleanupPad, BasicBlock *UnwindBB,
  3904. BasicBlock *InsertAtEnd) {
  3905. assert(CleanupPad);
  3906. unsigned Values = 1;
  3907. if (UnwindBB)
  3908. ++Values;
  3909. return new (Values)
  3910. CleanupReturnInst(CleanupPad, UnwindBB, Values, InsertAtEnd);
  3911. }
  3912. /// Provide fast operand accessors
  3913. DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
  3914. bool hasUnwindDest() const { return getSubclassData<UnwindDestField>(); }
  3915. bool unwindsToCaller() const { return !hasUnwindDest(); }
  3916. /// Convenience accessor.
  3917. CleanupPadInst *getCleanupPad() const {
  3918. return cast<CleanupPadInst>(Op<0>());
  3919. }
  3920. void setCleanupPad(CleanupPadInst *CleanupPad) {
  3921. assert(CleanupPad);
  3922. Op<0>() = CleanupPad;
  3923. }
  3924. unsigned getNumSuccessors() const { return hasUnwindDest() ? 1 : 0; }
  3925. BasicBlock *getUnwindDest() const {
  3926. return hasUnwindDest() ? cast<BasicBlock>(Op<1>()) : nullptr;
  3927. }
  3928. void setUnwindDest(BasicBlock *NewDest) {
  3929. assert(NewDest);
  3930. assert(hasUnwindDest());
  3931. Op<1>() = NewDest;
  3932. }
  3933. // Methods for support type inquiry through isa, cast, and dyn_cast:
  3934. static bool classof(const Instruction *I) {
  3935. return (I->getOpcode() == Instruction::CleanupRet);
  3936. }
  3937. static bool classof(const Value *V) {
  3938. return isa<Instruction>(V) && classof(cast<Instruction>(V));
  3939. }
  3940. private:
  3941. BasicBlock *getSuccessor(unsigned Idx) const {
  3942. assert(Idx == 0);
  3943. return getUnwindDest();
  3944. }
  3945. void setSuccessor(unsigned Idx, BasicBlock *B) {
  3946. assert(Idx == 0);
  3947. setUnwindDest(B);
  3948. }
  3949. // Shadow Instruction::setInstructionSubclassData with a private forwarding
  3950. // method so that subclasses cannot accidentally use it.
  3951. template <typename Bitfield>
  3952. void setSubclassData(typename Bitfield::Type Value) {
  3953. Instruction::setSubclassData<Bitfield>(Value);
  3954. }
  3955. };
  3956. template <>
  3957. struct OperandTraits<CleanupReturnInst>
  3958. : public VariadicOperandTraits<CleanupReturnInst, /*MINARITY=*/1> {};
  3959. DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CleanupReturnInst, Value)
  3960. //===----------------------------------------------------------------------===//
  3961. // UnreachableInst Class
  3962. //===----------------------------------------------------------------------===//
  3963. //===---------------------------------------------------------------------------
  3964. /// This function has undefined behavior. In particular, the
  3965. /// presence of this instruction indicates some higher level knowledge that the
  3966. /// end of the block cannot be reached.
  3967. ///
  3968. class UnreachableInst : public Instruction {
  3969. protected:
  3970. // Note: Instruction needs to be a friend here to call cloneImpl.
  3971. friend class Instruction;
  3972. UnreachableInst *cloneImpl() const;
  3973. public:
  3974. explicit UnreachableInst(LLVMContext &C, Instruction *InsertBefore = nullptr);
  3975. explicit UnreachableInst(LLVMContext &C, BasicBlock *InsertAtEnd);
  3976. // allocate space for exactly zero operands
  3977. void *operator new(size_t s) {
  3978. return User::operator new(s, 0);
  3979. }
  3980. unsigned getNumSuccessors() const { return 0; }
  3981. // Methods for support type inquiry through isa, cast, and dyn_cast:
  3982. static bool classof(const Instruction *I) {
  3983. return I->getOpcode() == Instruction::Unreachable;
  3984. }
  3985. static bool classof(const Value *V) {
  3986. return isa<Instruction>(V) && classof(cast<Instruction>(V));
  3987. }
  3988. private:
  3989. BasicBlock *getSuccessor(unsigned idx) const {
  3990. llvm_unreachable("UnreachableInst has no successors!");
  3991. }
  3992. void setSuccessor(unsigned idx, BasicBlock *B) {
  3993. llvm_unreachable("UnreachableInst has no successors!");
  3994. }
  3995. };
  3996. //===----------------------------------------------------------------------===//
  3997. // TruncInst Class
  3998. //===----------------------------------------------------------------------===//
  3999. /// This class represents a truncation of integer types.
  4000. class TruncInst : public CastInst {
  4001. protected:
  4002. // Note: Instruction needs to be a friend here to call cloneImpl.
  4003. friend class Instruction;
  4004. /// Clone an identical TruncInst
  4005. TruncInst *cloneImpl() const;
  4006. public:
  4007. /// Constructor with insert-before-instruction semantics
  4008. TruncInst(
  4009. Value *S, ///< The value to be truncated
  4010. Type *Ty, ///< The (smaller) type to truncate to
  4011. const Twine &NameStr = "", ///< A name for the new instruction
  4012. Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
  4013. );
  4014. /// Constructor with insert-at-end-of-block semantics
  4015. TruncInst(
  4016. Value *S, ///< The value to be truncated
  4017. Type *Ty, ///< The (smaller) type to truncate to
  4018. const Twine &NameStr, ///< A name for the new instruction
  4019. BasicBlock *InsertAtEnd ///< The block to insert the instruction into
  4020. );
  4021. /// Methods for support type inquiry through isa, cast, and dyn_cast:
  4022. static bool classof(const Instruction *I) {
  4023. return I->getOpcode() == Trunc;
  4024. }
  4025. static bool classof(const Value *V) {
  4026. return isa<Instruction>(V) && classof(cast<Instruction>(V));
  4027. }
  4028. };
  4029. //===----------------------------------------------------------------------===//
  4030. // ZExtInst Class
  4031. //===----------------------------------------------------------------------===//
  4032. /// This class represents zero extension of integer types.
  4033. class ZExtInst : public CastInst {
  4034. protected:
  4035. // Note: Instruction needs to be a friend here to call cloneImpl.
  4036. friend class Instruction;
  4037. /// Clone an identical ZExtInst
  4038. ZExtInst *cloneImpl() const;
  4039. public:
  4040. /// Constructor with insert-before-instruction semantics
  4041. ZExtInst(
  4042. Value *S, ///< The value to be zero extended
  4043. Type *Ty, ///< The type to zero extend to
  4044. const Twine &NameStr = "", ///< A name for the new instruction
  4045. Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
  4046. );
  4047. /// Constructor with insert-at-end semantics.
  4048. ZExtInst(
  4049. Value *S, ///< The value to be zero extended
  4050. Type *Ty, ///< The type to zero extend to
  4051. const Twine &NameStr, ///< A name for the new instruction
  4052. BasicBlock *InsertAtEnd ///< The block to insert the instruction into
  4053. );
  4054. /// Methods for support type inquiry through isa, cast, and dyn_cast:
  4055. static bool classof(const Instruction *I) {
  4056. return I->getOpcode() == ZExt;
  4057. }
  4058. static bool classof(const Value *V) {
  4059. return isa<Instruction>(V) && classof(cast<Instruction>(V));
  4060. }
  4061. };
  4062. //===----------------------------------------------------------------------===//
  4063. // SExtInst Class
  4064. //===----------------------------------------------------------------------===//
  4065. /// This class represents a sign extension of integer types.
  4066. class SExtInst : public CastInst {
  4067. protected:
  4068. // Note: Instruction needs to be a friend here to call cloneImpl.
  4069. friend class Instruction;
  4070. /// Clone an identical SExtInst
  4071. SExtInst *cloneImpl() const;
  4072. public:
  4073. /// Constructor with insert-before-instruction semantics
  4074. SExtInst(
  4075. Value *S, ///< The value to be sign extended
  4076. Type *Ty, ///< The type to sign extend to
  4077. const Twine &NameStr = "", ///< A name for the new instruction
  4078. Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
  4079. );
  4080. /// Constructor with insert-at-end-of-block semantics
  4081. SExtInst(
  4082. Value *S, ///< The value to be sign extended
  4083. Type *Ty, ///< The type to sign extend to
  4084. const Twine &NameStr, ///< A name for the new instruction
  4085. BasicBlock *InsertAtEnd ///< The block to insert the instruction into
  4086. );
  4087. /// Methods for support type inquiry through isa, cast, and dyn_cast:
  4088. static bool classof(const Instruction *I) {
  4089. return I->getOpcode() == SExt;
  4090. }
  4091. static bool classof(const Value *V) {
  4092. return isa<Instruction>(V) && classof(cast<Instruction>(V));
  4093. }
  4094. };
  4095. //===----------------------------------------------------------------------===//
  4096. // FPTruncInst Class
  4097. //===----------------------------------------------------------------------===//
  4098. /// This class represents a truncation of floating point types.
  4099. class FPTruncInst : public CastInst {
  4100. protected:
  4101. // Note: Instruction needs to be a friend here to call cloneImpl.
  4102. friend class Instruction;
  4103. /// Clone an identical FPTruncInst
  4104. FPTruncInst *cloneImpl() const;
  4105. public:
  4106. /// Constructor with insert-before-instruction semantics
  4107. FPTruncInst(
  4108. Value *S, ///< The value to be truncated
  4109. Type *Ty, ///< The type to truncate to
  4110. const Twine &NameStr = "", ///< A name for the new instruction
  4111. Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
  4112. );
  4113. /// Constructor with insert-before-instruction semantics
  4114. FPTruncInst(
  4115. Value *S, ///< The value to be truncated
  4116. Type *Ty, ///< The type to truncate to
  4117. const Twine &NameStr, ///< A name for the new instruction
  4118. BasicBlock *InsertAtEnd ///< The block to insert the instruction into
  4119. );
  4120. /// Methods for support type inquiry through isa, cast, and dyn_cast:
  4121. static bool classof(const Instruction *I) {
  4122. return I->getOpcode() == FPTrunc;
  4123. }
  4124. static bool classof(const Value *V) {
  4125. return isa<Instruction>(V) && classof(cast<Instruction>(V));
  4126. }
  4127. };
  4128. //===----------------------------------------------------------------------===//
  4129. // FPExtInst Class
  4130. //===----------------------------------------------------------------------===//
  4131. /// This class represents an extension of floating point types.
  4132. class FPExtInst : public CastInst {
  4133. protected:
  4134. // Note: Instruction needs to be a friend here to call cloneImpl.
  4135. friend class Instruction;
  4136. /// Clone an identical FPExtInst
  4137. FPExtInst *cloneImpl() const;
  4138. public:
  4139. /// Constructor with insert-before-instruction semantics
  4140. FPExtInst(
  4141. Value *S, ///< The value to be extended
  4142. Type *Ty, ///< The type to extend to
  4143. const Twine &NameStr = "", ///< A name for the new instruction
  4144. Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
  4145. );
  4146. /// Constructor with insert-at-end-of-block semantics
  4147. FPExtInst(
  4148. Value *S, ///< The value to be extended
  4149. Type *Ty, ///< The type to extend to
  4150. const Twine &NameStr, ///< A name for the new instruction
  4151. BasicBlock *InsertAtEnd ///< The block to insert the instruction into
  4152. );
  4153. /// Methods for support type inquiry through isa, cast, and dyn_cast:
  4154. static bool classof(const Instruction *I) {
  4155. return I->getOpcode() == FPExt;
  4156. }
  4157. static bool classof(const Value *V) {
  4158. return isa<Instruction>(V) && classof(cast<Instruction>(V));
  4159. }
  4160. };
  4161. //===----------------------------------------------------------------------===//
  4162. // UIToFPInst Class
  4163. //===----------------------------------------------------------------------===//
  4164. /// This class represents a cast unsigned integer to floating point.
  4165. class UIToFPInst : public CastInst {
  4166. protected:
  4167. // Note: Instruction needs to be a friend here to call cloneImpl.
  4168. friend class Instruction;
  4169. /// Clone an identical UIToFPInst
  4170. UIToFPInst *cloneImpl() const;
  4171. public:
  4172. /// Constructor with insert-before-instruction semantics
  4173. UIToFPInst(
  4174. Value *S, ///< The value to be converted
  4175. Type *Ty, ///< The type to convert to
  4176. const Twine &NameStr = "", ///< A name for the new instruction
  4177. Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
  4178. );
  4179. /// Constructor with insert-at-end-of-block semantics
  4180. UIToFPInst(
  4181. Value *S, ///< The value to be converted
  4182. Type *Ty, ///< The type to convert to
  4183. const Twine &NameStr, ///< A name for the new instruction
  4184. BasicBlock *InsertAtEnd ///< The block to insert the instruction into
  4185. );
  4186. /// Methods for support type inquiry through isa, cast, and dyn_cast:
  4187. static bool classof(const Instruction *I) {
  4188. return I->getOpcode() == UIToFP;
  4189. }
  4190. static bool classof(const Value *V) {
  4191. return isa<Instruction>(V) && classof(cast<Instruction>(V));
  4192. }
  4193. };
  4194. //===----------------------------------------------------------------------===//
  4195. // SIToFPInst Class
  4196. //===----------------------------------------------------------------------===//
  4197. /// This class represents a cast from signed integer to floating point.
  4198. class SIToFPInst : public CastInst {
  4199. protected:
  4200. // Note: Instruction needs to be a friend here to call cloneImpl.
  4201. friend class Instruction;
  4202. /// Clone an identical SIToFPInst
  4203. SIToFPInst *cloneImpl() const;
  4204. public:
  4205. /// Constructor with insert-before-instruction semantics
  4206. SIToFPInst(
  4207. Value *S, ///< The value to be converted
  4208. Type *Ty, ///< The type to convert to
  4209. const Twine &NameStr = "", ///< A name for the new instruction
  4210. Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
  4211. );
  4212. /// Constructor with insert-at-end-of-block semantics
  4213. SIToFPInst(
  4214. Value *S, ///< The value to be converted
  4215. Type *Ty, ///< The type to convert to
  4216. const Twine &NameStr, ///< A name for the new instruction
  4217. BasicBlock *InsertAtEnd ///< The block to insert the instruction into
  4218. );
  4219. /// Methods for support type inquiry through isa, cast, and dyn_cast:
  4220. static bool classof(const Instruction *I) {
  4221. return I->getOpcode() == SIToFP;
  4222. }
  4223. static bool classof(const Value *V) {
  4224. return isa<Instruction>(V) && classof(cast<Instruction>(V));
  4225. }
  4226. };
  4227. //===----------------------------------------------------------------------===//
  4228. // FPToUIInst Class
  4229. //===----------------------------------------------------------------------===//
  4230. /// This class represents a cast from floating point to unsigned integer
  4231. class FPToUIInst : public CastInst {
  4232. protected:
  4233. // Note: Instruction needs to be a friend here to call cloneImpl.
  4234. friend class Instruction;
  4235. /// Clone an identical FPToUIInst
  4236. FPToUIInst *cloneImpl() const;
  4237. public:
  4238. /// Constructor with insert-before-instruction semantics
  4239. FPToUIInst(
  4240. Value *S, ///< The value to be converted
  4241. Type *Ty, ///< The type to convert to
  4242. const Twine &NameStr = "", ///< A name for the new instruction
  4243. Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
  4244. );
  4245. /// Constructor with insert-at-end-of-block semantics
  4246. FPToUIInst(
  4247. Value *S, ///< The value to be converted
  4248. Type *Ty, ///< The type to convert to
  4249. const Twine &NameStr, ///< A name for the new instruction
  4250. BasicBlock *InsertAtEnd ///< Where to insert the new instruction
  4251. );
  4252. /// Methods for support type inquiry through isa, cast, and dyn_cast:
  4253. static bool classof(const Instruction *I) {
  4254. return I->getOpcode() == FPToUI;
  4255. }
  4256. static bool classof(const Value *V) {
  4257. return isa<Instruction>(V) && classof(cast<Instruction>(V));
  4258. }
  4259. };
  4260. //===----------------------------------------------------------------------===//
  4261. // FPToSIInst Class
  4262. //===----------------------------------------------------------------------===//
  4263. /// This class represents a cast from floating point to signed integer.
  4264. class FPToSIInst : public CastInst {
  4265. protected:
  4266. // Note: Instruction needs to be a friend here to call cloneImpl.
  4267. friend class Instruction;
  4268. /// Clone an identical FPToSIInst
  4269. FPToSIInst *cloneImpl() const;
  4270. public:
  4271. /// Constructor with insert-before-instruction semantics
  4272. FPToSIInst(
  4273. Value *S, ///< The value to be converted
  4274. Type *Ty, ///< The type to convert to
  4275. const Twine &NameStr = "", ///< A name for the new instruction
  4276. Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
  4277. );
  4278. /// Constructor with insert-at-end-of-block semantics
  4279. FPToSIInst(
  4280. Value *S, ///< The value to be converted
  4281. Type *Ty, ///< The type to convert to
  4282. const Twine &NameStr, ///< A name for the new instruction
  4283. BasicBlock *InsertAtEnd ///< The block to insert the instruction into
  4284. );
  4285. /// Methods for support type inquiry through isa, cast, and dyn_cast:
  4286. static bool classof(const Instruction *I) {
  4287. return I->getOpcode() == FPToSI;
  4288. }
  4289. static bool classof(const Value *V) {
  4290. return isa<Instruction>(V) && classof(cast<Instruction>(V));
  4291. }
  4292. };
  4293. //===----------------------------------------------------------------------===//
  4294. // IntToPtrInst Class
  4295. //===----------------------------------------------------------------------===//
  4296. /// This class represents a cast from an integer to a pointer.
  4297. class IntToPtrInst : public CastInst {
  4298. public:
  4299. // Note: Instruction needs to be a friend here to call cloneImpl.
  4300. friend class Instruction;
  4301. /// Constructor with insert-before-instruction semantics
  4302. IntToPtrInst(
  4303. Value *S, ///< The value to be converted
  4304. Type *Ty, ///< The type to convert to
  4305. const Twine &NameStr = "", ///< A name for the new instruction
  4306. Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
  4307. );
  4308. /// Constructor with insert-at-end-of-block semantics
  4309. IntToPtrInst(
  4310. Value *S, ///< The value to be converted
  4311. Type *Ty, ///< The type to convert to
  4312. const Twine &NameStr, ///< A name for the new instruction
  4313. BasicBlock *InsertAtEnd ///< The block to insert the instruction into
  4314. );
  4315. /// Clone an identical IntToPtrInst.
  4316. IntToPtrInst *cloneImpl() const;
  4317. /// Returns the address space of this instruction's pointer type.
  4318. unsigned getAddressSpace() const {
  4319. return getType()->getPointerAddressSpace();
  4320. }
  4321. // Methods for support type inquiry through isa, cast, and dyn_cast:
  4322. static bool classof(const Instruction *I) {
  4323. return I->getOpcode() == IntToPtr;
  4324. }
  4325. static bool classof(const Value *V) {
  4326. return isa<Instruction>(V) && classof(cast<Instruction>(V));
  4327. }
  4328. };
  4329. //===----------------------------------------------------------------------===//
  4330. // PtrToIntInst Class
  4331. //===----------------------------------------------------------------------===//
  4332. /// This class represents a cast from a pointer to an integer.
  4333. class PtrToIntInst : public CastInst {
  4334. protected:
  4335. // Note: Instruction needs to be a friend here to call cloneImpl.
  4336. friend class Instruction;
  4337. /// Clone an identical PtrToIntInst.
  4338. PtrToIntInst *cloneImpl() const;
  4339. public:
  4340. /// Constructor with insert-before-instruction semantics
  4341. PtrToIntInst(
  4342. Value *S, ///< The value to be converted
  4343. Type *Ty, ///< The type to convert to
  4344. const Twine &NameStr = "", ///< A name for the new instruction
  4345. Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
  4346. );
  4347. /// Constructor with insert-at-end-of-block semantics
  4348. PtrToIntInst(
  4349. Value *S, ///< The value to be converted
  4350. Type *Ty, ///< The type to convert to
  4351. const Twine &NameStr, ///< A name for the new instruction
  4352. BasicBlock *InsertAtEnd ///< The block to insert the instruction into
  4353. );
  4354. /// Gets the pointer operand.
  4355. Value *getPointerOperand() { return getOperand(0); }
  4356. /// Gets the pointer operand.
  4357. const Value *getPointerOperand() const { return getOperand(0); }
  4358. /// Gets the operand index of the pointer operand.
  4359. static unsigned getPointerOperandIndex() { return 0U; }
  4360. /// Returns the address space of the pointer operand.
  4361. unsigned getPointerAddressSpace() const {
  4362. return getPointerOperand()->getType()->getPointerAddressSpace();
  4363. }
  4364. // Methods for support type inquiry through isa, cast, and dyn_cast:
  4365. static bool classof(const Instruction *I) {
  4366. return I->getOpcode() == PtrToInt;
  4367. }
  4368. static bool classof(const Value *V) {
  4369. return isa<Instruction>(V) && classof(cast<Instruction>(V));
  4370. }
  4371. };
  4372. //===----------------------------------------------------------------------===//
  4373. // BitCastInst Class
  4374. //===----------------------------------------------------------------------===//
  4375. /// This class represents a no-op cast from one type to another.
  4376. class BitCastInst : public CastInst {
  4377. protected:
  4378. // Note: Instruction needs to be a friend here to call cloneImpl.
  4379. friend class Instruction;
  4380. /// Clone an identical BitCastInst.
  4381. BitCastInst *cloneImpl() const;
  4382. public:
  4383. /// Constructor with insert-before-instruction semantics
  4384. BitCastInst(
  4385. Value *S, ///< The value to be casted
  4386. Type *Ty, ///< The type to casted to
  4387. const Twine &NameStr = "", ///< A name for the new instruction
  4388. Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
  4389. );
  4390. /// Constructor with insert-at-end-of-block semantics
  4391. BitCastInst(
  4392. Value *S, ///< The value to be casted
  4393. Type *Ty, ///< The type to casted to
  4394. const Twine &NameStr, ///< A name for the new instruction
  4395. BasicBlock *InsertAtEnd ///< The block to insert the instruction into
  4396. );
  4397. // Methods for support type inquiry through isa, cast, and dyn_cast:
  4398. static bool classof(const Instruction *I) {
  4399. return I->getOpcode() == BitCast;
  4400. }
  4401. static bool classof(const Value *V) {
  4402. return isa<Instruction>(V) && classof(cast<Instruction>(V));
  4403. }
  4404. };
  4405. //===----------------------------------------------------------------------===//
  4406. // AddrSpaceCastInst Class
  4407. //===----------------------------------------------------------------------===//
  4408. /// This class represents a conversion between pointers from one address space
  4409. /// to another.
  4410. class AddrSpaceCastInst : public CastInst {
  4411. protected:
  4412. // Note: Instruction needs to be a friend here to call cloneImpl.
  4413. friend class Instruction;
  4414. /// Clone an identical AddrSpaceCastInst.
  4415. AddrSpaceCastInst *cloneImpl() const;
  4416. public:
  4417. /// Constructor with insert-before-instruction semantics
  4418. AddrSpaceCastInst(
  4419. Value *S, ///< The value to be casted
  4420. Type *Ty, ///< The type to casted to
  4421. const Twine &NameStr = "", ///< A name for the new instruction
  4422. Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
  4423. );
  4424. /// Constructor with insert-at-end-of-block semantics
  4425. AddrSpaceCastInst(
  4426. Value *S, ///< The value to be casted
  4427. Type *Ty, ///< The type to casted to
  4428. const Twine &NameStr, ///< A name for the new instruction
  4429. BasicBlock *InsertAtEnd ///< The block to insert the instruction into
  4430. );
  4431. // Methods for support type inquiry through isa, cast, and dyn_cast:
  4432. static bool classof(const Instruction *I) {
  4433. return I->getOpcode() == AddrSpaceCast;
  4434. }
  4435. static bool classof(const Value *V) {
  4436. return isa<Instruction>(V) && classof(cast<Instruction>(V));
  4437. }
  4438. /// Gets the pointer operand.
  4439. Value *getPointerOperand() {
  4440. return getOperand(0);
  4441. }
  4442. /// Gets the pointer operand.
  4443. const Value *getPointerOperand() const {
  4444. return getOperand(0);
  4445. }
  4446. /// Gets the operand index of the pointer operand.
  4447. static unsigned getPointerOperandIndex() {
  4448. return 0U;
  4449. }
  4450. /// Returns the address space of the pointer operand.
  4451. unsigned getSrcAddressSpace() const {
  4452. return getPointerOperand()->getType()->getPointerAddressSpace();
  4453. }
  4454. /// Returns the address space of the result.
  4455. unsigned getDestAddressSpace() const {
  4456. return getType()->getPointerAddressSpace();
  4457. }
  4458. };
  4459. /// A helper function that returns the pointer operand of a load or store
  4460. /// instruction. Returns nullptr if not load or store.
  4461. inline const Value *getLoadStorePointerOperand(const Value *V) {
  4462. if (auto *Load = dyn_cast<LoadInst>(V))
  4463. return Load->getPointerOperand();
  4464. if (auto *Store = dyn_cast<StoreInst>(V))
  4465. return Store->getPointerOperand();
  4466. return nullptr;
  4467. }
  4468. inline Value *getLoadStorePointerOperand(Value *V) {
  4469. return const_cast<Value *>(
  4470. getLoadStorePointerOperand(static_cast<const Value *>(V)));
  4471. }
  4472. /// A helper function that returns the pointer operand of a load, store
  4473. /// or GEP instruction. Returns nullptr if not load, store, or GEP.
  4474. inline const Value *getPointerOperand(const Value *V) {
  4475. if (auto *Ptr = getLoadStorePointerOperand(V))
  4476. return Ptr;
  4477. if (auto *Gep = dyn_cast<GetElementPtrInst>(V))
  4478. return Gep->getPointerOperand();
  4479. return nullptr;
  4480. }
  4481. inline Value *getPointerOperand(Value *V) {
  4482. return const_cast<Value *>(getPointerOperand(static_cast<const Value *>(V)));
  4483. }
  4484. /// A helper function that returns the alignment of load or store instruction.
  4485. inline Align getLoadStoreAlignment(Value *I) {
  4486. assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&
  4487. "Expected Load or Store instruction");
  4488. if (auto *LI = dyn_cast<LoadInst>(I))
  4489. return LI->getAlign();
  4490. return cast<StoreInst>(I)->getAlign();
  4491. }
  4492. /// A helper function that returns the address space of the pointer operand of
  4493. /// load or store instruction.
  4494. inline unsigned getLoadStoreAddressSpace(Value *I) {
  4495. assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&
  4496. "Expected Load or Store instruction");
  4497. if (auto *LI = dyn_cast<LoadInst>(I))
  4498. return LI->getPointerAddressSpace();
  4499. return cast<StoreInst>(I)->getPointerAddressSpace();
  4500. }
  4501. //===----------------------------------------------------------------------===//
  4502. // FreezeInst Class
  4503. //===----------------------------------------------------------------------===//
  4504. /// This class represents a freeze function that returns random concrete
  4505. /// value if an operand is either a poison value or an undef value
  4506. class FreezeInst : public UnaryInstruction {
  4507. protected:
  4508. // Note: Instruction needs to be a friend here to call cloneImpl.
  4509. friend class Instruction;
  4510. /// Clone an identical FreezeInst
  4511. FreezeInst *cloneImpl() const;
  4512. public:
  4513. explicit FreezeInst(Value *S,
  4514. const Twine &NameStr = "",
  4515. Instruction *InsertBefore = nullptr);
  4516. FreezeInst(Value *S, const Twine &NameStr, BasicBlock *InsertAtEnd);
  4517. // Methods for support type inquiry through isa, cast, and dyn_cast:
  4518. static inline bool classof(const Instruction *I) {
  4519. return I->getOpcode() == Freeze;
  4520. }
  4521. static inline bool classof(const Value *V) {
  4522. return isa<Instruction>(V) && classof(cast<Instruction>(V));
  4523. }
  4524. };
  4525. } // end namespace llvm
  4526. #endif // LLVM_IR_INSTRUCTIONS_H
  4527. #ifdef __GNUC__
  4528. #pragma GCC diagnostic pop
  4529. #endif