FastISel.cpp 90 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473
  1. //===- FastISel.cpp - Implementation of the FastISel class ----------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file contains the implementation of the FastISel class.
  10. //
  11. // "Fast" instruction selection is designed to emit very poor code quickly.
  12. // Also, it is not designed to be able to do much lowering, so most illegal
  13. // types (e.g. i64 on 32-bit targets) and operations are not supported. It is
  14. // also not intended to be able to do much optimization, except in a few cases
  15. // where doing optimizations reduces overall compile time. For example, folding
  16. // constants into immediate fields is often done, because it's cheap and it
  17. // reduces the number of instructions later phases have to examine.
  18. //
  19. // "Fast" instruction selection is able to fail gracefully and transfer
  20. // control to the SelectionDAG selector for operations that it doesn't
  21. // support. In many cases, this allows us to avoid duplicating a lot of
  22. // the complicated lowering logic that SelectionDAG currently has.
  23. //
  24. // The intended use for "fast" instruction selection is "-O0" mode
  25. // compilation, where the quality of the generated code is irrelevant when
  26. // weighed against the speed at which the code can be generated. Also,
  27. // at -O0, the LLVM optimizers are not running, and this makes the
  28. // compile time of codegen a much higher portion of the overall compile
  29. // time. Despite its limitations, "fast" instruction selection is able to
  30. // handle enough code on its own to provide noticeable overall speedups
  31. // in -O0 compiles.
  32. //
  33. // Basic operations are supported in a target-independent way, by reading
  34. // the same instruction descriptions that the SelectionDAG selector reads,
  35. // and identifying simple arithmetic operations that can be directly selected
  36. // from simple operators. More complicated operations currently require
  37. // target-specific code.
  38. //
  39. //===----------------------------------------------------------------------===//
  40. #include "llvm/CodeGen/FastISel.h"
  41. #include "llvm/ADT/APFloat.h"
  42. #include "llvm/ADT/APSInt.h"
  43. #include "llvm/ADT/DenseMap.h"
  44. #include "llvm/ADT/Optional.h"
  45. #include "llvm/ADT/SmallPtrSet.h"
  46. #include "llvm/ADT/SmallString.h"
  47. #include "llvm/ADT/SmallVector.h"
  48. #include "llvm/ADT/Statistic.h"
  49. #include "llvm/Analysis/BranchProbabilityInfo.h"
  50. #include "llvm/Analysis/TargetLibraryInfo.h"
  51. #include "llvm/CodeGen/Analysis.h"
  52. #include "llvm/CodeGen/FunctionLoweringInfo.h"
  53. #include "llvm/CodeGen/ISDOpcodes.h"
  54. #include "llvm/CodeGen/MachineBasicBlock.h"
  55. #include "llvm/CodeGen/MachineFrameInfo.h"
  56. #include "llvm/CodeGen/MachineInstr.h"
  57. #include "llvm/CodeGen/MachineInstrBuilder.h"
  58. #include "llvm/CodeGen/MachineMemOperand.h"
  59. #include "llvm/CodeGen/MachineModuleInfo.h"
  60. #include "llvm/CodeGen/MachineOperand.h"
  61. #include "llvm/CodeGen/MachineRegisterInfo.h"
  62. #include "llvm/CodeGen/StackMaps.h"
  63. #include "llvm/CodeGen/TargetInstrInfo.h"
  64. #include "llvm/CodeGen/TargetLowering.h"
  65. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  66. #include "llvm/CodeGen/ValueTypes.h"
  67. #include "llvm/IR/Argument.h"
  68. #include "llvm/IR/Attributes.h"
  69. #include "llvm/IR/BasicBlock.h"
  70. #include "llvm/IR/CallSite.h"
  71. #include "llvm/IR/CallingConv.h"
  72. #include "llvm/IR/Constant.h"
  73. #include "llvm/IR/Constants.h"
  74. #include "llvm/IR/DataLayout.h"
  75. #include "llvm/IR/DebugInfo.h"
  76. #include "llvm/IR/DebugLoc.h"
  77. #include "llvm/IR/DerivedTypes.h"
  78. #include "llvm/IR/Function.h"
  79. #include "llvm/IR/GetElementPtrTypeIterator.h"
  80. #include "llvm/IR/GlobalValue.h"
  81. #include "llvm/IR/InlineAsm.h"
  82. #include "llvm/IR/InstrTypes.h"
  83. #include "llvm/IR/Instruction.h"
  84. #include "llvm/IR/Instructions.h"
  85. #include "llvm/IR/IntrinsicInst.h"
  86. #include "llvm/IR/LLVMContext.h"
  87. #include "llvm/IR/Mangler.h"
  88. #include "llvm/IR/Metadata.h"
  89. #include "llvm/IR/Operator.h"
  90. #include "llvm/IR/PatternMatch.h"
  91. #include "llvm/IR/Type.h"
  92. #include "llvm/IR/User.h"
  93. #include "llvm/IR/Value.h"
  94. #include "llvm/MC/MCContext.h"
  95. #include "llvm/MC/MCInstrDesc.h"
  96. #include "llvm/MC/MCRegisterInfo.h"
  97. #include "llvm/Support/Casting.h"
  98. #include "llvm/Support/Debug.h"
  99. #include "llvm/Support/ErrorHandling.h"
  100. #include "llvm/Support/MachineValueType.h"
  101. #include "llvm/Support/MathExtras.h"
  102. #include "llvm/Support/raw_ostream.h"
  103. #include "llvm/Target/TargetMachine.h"
  104. #include "llvm/Target/TargetOptions.h"
  105. #include <algorithm>
  106. #include <cassert>
  107. #include <cstdint>
  108. #include <iterator>
  109. #include <utility>
  110. using namespace llvm;
  111. using namespace PatternMatch;
  112. #define DEBUG_TYPE "isel"
  113. // FIXME: Remove this after the feature has proven reliable.
  114. static cl::opt<bool> SinkLocalValues("fast-isel-sink-local-values",
  115. cl::init(true), cl::Hidden,
  116. cl::desc("Sink local values in FastISel"));
  117. STATISTIC(NumFastIselSuccessIndependent, "Number of insts selected by "
  118. "target-independent selector");
  119. STATISTIC(NumFastIselSuccessTarget, "Number of insts selected by "
  120. "target-specific selector");
  121. STATISTIC(NumFastIselDead, "Number of dead insts removed on failure");
  122. /// Set the current block to which generated machine instructions will be
  123. /// appended.
  124. void FastISel::startNewBlock() {
  125. assert(LocalValueMap.empty() &&
  126. "local values should be cleared after finishing a BB");
  127. // Instructions are appended to FuncInfo.MBB. If the basic block already
  128. // contains labels or copies, use the last instruction as the last local
  129. // value.
  130. EmitStartPt = nullptr;
  131. if (!FuncInfo.MBB->empty())
  132. EmitStartPt = &FuncInfo.MBB->back();
  133. LastLocalValue = EmitStartPt;
  134. }
  135. /// Flush the local CSE map and sink anything we can.
  136. void FastISel::finishBasicBlock() { flushLocalValueMap(); }
  137. bool FastISel::lowerArguments() {
  138. if (!FuncInfo.CanLowerReturn)
  139. // Fallback to SDISel argument lowering code to deal with sret pointer
  140. // parameter.
  141. return false;
  142. if (!fastLowerArguments())
  143. return false;
  144. // Enter arguments into ValueMap for uses in non-entry BBs.
  145. for (Function::const_arg_iterator I = FuncInfo.Fn->arg_begin(),
  146. E = FuncInfo.Fn->arg_end();
  147. I != E; ++I) {
  148. DenseMap<const Value *, unsigned>::iterator VI = LocalValueMap.find(&*I);
  149. assert(VI != LocalValueMap.end() && "Missed an argument?");
  150. FuncInfo.ValueMap[&*I] = VI->second;
  151. }
  152. return true;
  153. }
  154. /// Return the defined register if this instruction defines exactly one
  155. /// virtual register and uses no other virtual registers. Otherwise return 0.
  156. static unsigned findSinkableLocalRegDef(MachineInstr &MI) {
  157. unsigned RegDef = 0;
  158. for (const MachineOperand &MO : MI.operands()) {
  159. if (!MO.isReg())
  160. continue;
  161. if (MO.isDef()) {
  162. if (RegDef)
  163. return 0;
  164. RegDef = MO.getReg();
  165. } else if (Register::isVirtualRegister(MO.getReg())) {
  166. // This is another use of a vreg. Don't try to sink it.
  167. return 0;
  168. }
  169. }
  170. return RegDef;
  171. }
  172. void FastISel::flushLocalValueMap() {
  173. // Try to sink local values down to their first use so that we can give them a
  174. // better debug location. This has the side effect of shrinking local value
  175. // live ranges, which helps out fast regalloc.
  176. if (SinkLocalValues && LastLocalValue != EmitStartPt) {
  177. // Sink local value materialization instructions between EmitStartPt and
  178. // LastLocalValue. Visit them bottom-up, starting from LastLocalValue, to
  179. // avoid inserting into the range that we're iterating over.
  180. MachineBasicBlock::reverse_iterator RE =
  181. EmitStartPt ? MachineBasicBlock::reverse_iterator(EmitStartPt)
  182. : FuncInfo.MBB->rend();
  183. MachineBasicBlock::reverse_iterator RI(LastLocalValue);
  184. InstOrderMap OrderMap;
  185. for (; RI != RE;) {
  186. MachineInstr &LocalMI = *RI;
  187. ++RI;
  188. bool Store = true;
  189. if (!LocalMI.isSafeToMove(nullptr, Store))
  190. continue;
  191. unsigned DefReg = findSinkableLocalRegDef(LocalMI);
  192. if (DefReg == 0)
  193. continue;
  194. sinkLocalValueMaterialization(LocalMI, DefReg, OrderMap);
  195. }
  196. }
  197. LocalValueMap.clear();
  198. LastLocalValue = EmitStartPt;
  199. recomputeInsertPt();
  200. SavedInsertPt = FuncInfo.InsertPt;
  201. LastFlushPoint = FuncInfo.InsertPt;
  202. }
  203. static bool isRegUsedByPhiNodes(unsigned DefReg,
  204. FunctionLoweringInfo &FuncInfo) {
  205. for (auto &P : FuncInfo.PHINodesToUpdate)
  206. if (P.second == DefReg)
  207. return true;
  208. return false;
  209. }
  210. /// Build a map of instruction orders. Return the first terminator and its
  211. /// order. Consider EH_LABEL instructions to be terminators as well, since local
  212. /// values for phis after invokes must be materialized before the call.
  213. void FastISel::InstOrderMap::initialize(
  214. MachineBasicBlock *MBB, MachineBasicBlock::iterator LastFlushPoint) {
  215. unsigned Order = 0;
  216. for (MachineInstr &I : *MBB) {
  217. if (!FirstTerminator &&
  218. (I.isTerminator() || (I.isEHLabel() && &I != &MBB->front()))) {
  219. FirstTerminator = &I;
  220. FirstTerminatorOrder = Order;
  221. }
  222. Orders[&I] = Order++;
  223. // We don't need to order instructions past the last flush point.
  224. if (I.getIterator() == LastFlushPoint)
  225. break;
  226. }
  227. }
  228. void FastISel::sinkLocalValueMaterialization(MachineInstr &LocalMI,
  229. unsigned DefReg,
  230. InstOrderMap &OrderMap) {
  231. // If this register is used by a register fixup, MRI will not contain all
  232. // the uses until after register fixups, so don't attempt to sink or DCE
  233. // this instruction. Register fixups typically come from no-op cast
  234. // instructions, which replace the cast instruction vreg with the local
  235. // value vreg.
  236. if (FuncInfo.RegsWithFixups.count(DefReg))
  237. return;
  238. // We can DCE this instruction if there are no uses and it wasn't a
  239. // materialized for a successor PHI node.
  240. bool UsedByPHI = isRegUsedByPhiNodes(DefReg, FuncInfo);
  241. if (!UsedByPHI && MRI.use_nodbg_empty(DefReg)) {
  242. if (EmitStartPt == &LocalMI)
  243. EmitStartPt = EmitStartPt->getPrevNode();
  244. LLVM_DEBUG(dbgs() << "removing dead local value materialization "
  245. << LocalMI);
  246. OrderMap.Orders.erase(&LocalMI);
  247. LocalMI.eraseFromParent();
  248. return;
  249. }
  250. // Number the instructions if we haven't yet so we can efficiently find the
  251. // earliest use.
  252. if (OrderMap.Orders.empty())
  253. OrderMap.initialize(FuncInfo.MBB, LastFlushPoint);
  254. // Find the first user in the BB.
  255. MachineInstr *FirstUser = nullptr;
  256. unsigned FirstOrder = std::numeric_limits<unsigned>::max();
  257. for (MachineInstr &UseInst : MRI.use_nodbg_instructions(DefReg)) {
  258. auto I = OrderMap.Orders.find(&UseInst);
  259. assert(I != OrderMap.Orders.end() &&
  260. "local value used by instruction outside local region");
  261. unsigned UseOrder = I->second;
  262. if (UseOrder < FirstOrder) {
  263. FirstOrder = UseOrder;
  264. FirstUser = &UseInst;
  265. }
  266. }
  267. // The insertion point will be the first terminator or the first user,
  268. // whichever came first. If there was no terminator, this must be a
  269. // fallthrough block and the insertion point is the end of the block.
  270. MachineBasicBlock::instr_iterator SinkPos;
  271. if (UsedByPHI && OrderMap.FirstTerminatorOrder < FirstOrder) {
  272. FirstOrder = OrderMap.FirstTerminatorOrder;
  273. SinkPos = OrderMap.FirstTerminator->getIterator();
  274. } else if (FirstUser) {
  275. SinkPos = FirstUser->getIterator();
  276. } else {
  277. assert(UsedByPHI && "must be users if not used by a phi");
  278. SinkPos = FuncInfo.MBB->instr_end();
  279. }
  280. // Collect all DBG_VALUEs before the new insertion position so that we can
  281. // sink them.
  282. SmallVector<MachineInstr *, 1> DbgValues;
  283. for (MachineInstr &DbgVal : MRI.use_instructions(DefReg)) {
  284. if (!DbgVal.isDebugValue())
  285. continue;
  286. unsigned UseOrder = OrderMap.Orders[&DbgVal];
  287. if (UseOrder < FirstOrder)
  288. DbgValues.push_back(&DbgVal);
  289. }
  290. // Sink LocalMI before SinkPos and assign it the same DebugLoc.
  291. LLVM_DEBUG(dbgs() << "sinking local value to first use " << LocalMI);
  292. FuncInfo.MBB->remove(&LocalMI);
  293. FuncInfo.MBB->insert(SinkPos, &LocalMI);
  294. if (SinkPos != FuncInfo.MBB->end())
  295. LocalMI.setDebugLoc(SinkPos->getDebugLoc());
  296. // Sink any debug values that we've collected.
  297. for (MachineInstr *DI : DbgValues) {
  298. FuncInfo.MBB->remove(DI);
  299. FuncInfo.MBB->insert(SinkPos, DI);
  300. }
  301. }
  302. bool FastISel::hasTrivialKill(const Value *V) {
  303. // Don't consider constants or arguments to have trivial kills.
  304. const Instruction *I = dyn_cast<Instruction>(V);
  305. if (!I)
  306. return false;
  307. // No-op casts are trivially coalesced by fast-isel.
  308. if (const auto *Cast = dyn_cast<CastInst>(I))
  309. if (Cast->isNoopCast(DL) && !hasTrivialKill(Cast->getOperand(0)))
  310. return false;
  311. // Even the value might have only one use in the LLVM IR, it is possible that
  312. // FastISel might fold the use into another instruction and now there is more
  313. // than one use at the Machine Instruction level.
  314. unsigned Reg = lookUpRegForValue(V);
  315. if (Reg && !MRI.use_empty(Reg))
  316. return false;
  317. // GEPs with all zero indices are trivially coalesced by fast-isel.
  318. if (const auto *GEP = dyn_cast<GetElementPtrInst>(I))
  319. if (GEP->hasAllZeroIndices() && !hasTrivialKill(GEP->getOperand(0)))
  320. return false;
  321. // Only instructions with a single use in the same basic block are considered
  322. // to have trivial kills.
  323. return I->hasOneUse() &&
  324. !(I->getOpcode() == Instruction::BitCast ||
  325. I->getOpcode() == Instruction::PtrToInt ||
  326. I->getOpcode() == Instruction::IntToPtr) &&
  327. cast<Instruction>(*I->user_begin())->getParent() == I->getParent();
  328. }
  329. unsigned FastISel::getRegForValue(const Value *V) {
  330. EVT RealVT = TLI.getValueType(DL, V->getType(), /*AllowUnknown=*/true);
  331. // Don't handle non-simple values in FastISel.
  332. if (!RealVT.isSimple())
  333. return 0;
  334. // Ignore illegal types. We must do this before looking up the value
  335. // in ValueMap because Arguments are given virtual registers regardless
  336. // of whether FastISel can handle them.
  337. MVT VT = RealVT.getSimpleVT();
  338. if (!TLI.isTypeLegal(VT)) {
  339. // Handle integer promotions, though, because they're common and easy.
  340. if (VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16)
  341. VT = TLI.getTypeToTransformTo(V->getContext(), VT).getSimpleVT();
  342. else
  343. return 0;
  344. }
  345. // Look up the value to see if we already have a register for it.
  346. unsigned Reg = lookUpRegForValue(V);
  347. if (Reg)
  348. return Reg;
  349. // In bottom-up mode, just create the virtual register which will be used
  350. // to hold the value. It will be materialized later.
  351. if (isa<Instruction>(V) &&
  352. (!isa<AllocaInst>(V) ||
  353. !FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(V))))
  354. return FuncInfo.InitializeRegForValue(V);
  355. SavePoint SaveInsertPt = enterLocalValueArea();
  356. // Materialize the value in a register. Emit any instructions in the
  357. // local value area.
  358. Reg = materializeRegForValue(V, VT);
  359. leaveLocalValueArea(SaveInsertPt);
  360. return Reg;
  361. }
  362. unsigned FastISel::materializeConstant(const Value *V, MVT VT) {
  363. unsigned Reg = 0;
  364. if (const auto *CI = dyn_cast<ConstantInt>(V)) {
  365. if (CI->getValue().getActiveBits() <= 64)
  366. Reg = fastEmit_i(VT, VT, ISD::Constant, CI->getZExtValue());
  367. } else if (isa<AllocaInst>(V))
  368. Reg = fastMaterializeAlloca(cast<AllocaInst>(V));
  369. else if (isa<ConstantPointerNull>(V))
  370. // Translate this as an integer zero so that it can be
  371. // local-CSE'd with actual integer zeros.
  372. Reg = getRegForValue(
  373. Constant::getNullValue(DL.getIntPtrType(V->getContext())));
  374. else if (const auto *CF = dyn_cast<ConstantFP>(V)) {
  375. if (CF->isNullValue())
  376. Reg = fastMaterializeFloatZero(CF);
  377. else
  378. // Try to emit the constant directly.
  379. Reg = fastEmit_f(VT, VT, ISD::ConstantFP, CF);
  380. if (!Reg) {
  381. // Try to emit the constant by using an integer constant with a cast.
  382. const APFloat &Flt = CF->getValueAPF();
  383. EVT IntVT = TLI.getPointerTy(DL);
  384. uint32_t IntBitWidth = IntVT.getSizeInBits();
  385. APSInt SIntVal(IntBitWidth, /*isUnsigned=*/false);
  386. bool isExact;
  387. (void)Flt.convertToInteger(SIntVal, APFloat::rmTowardZero, &isExact);
  388. if (isExact) {
  389. unsigned IntegerReg =
  390. getRegForValue(ConstantInt::get(V->getContext(), SIntVal));
  391. if (IntegerReg != 0)
  392. Reg = fastEmit_r(IntVT.getSimpleVT(), VT, ISD::SINT_TO_FP, IntegerReg,
  393. /*Kill=*/false);
  394. }
  395. }
  396. } else if (const auto *Op = dyn_cast<Operator>(V)) {
  397. if (!selectOperator(Op, Op->getOpcode()))
  398. if (!isa<Instruction>(Op) ||
  399. !fastSelectInstruction(cast<Instruction>(Op)))
  400. return 0;
  401. Reg = lookUpRegForValue(Op);
  402. } else if (isa<UndefValue>(V)) {
  403. Reg = createResultReg(TLI.getRegClassFor(VT));
  404. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  405. TII.get(TargetOpcode::IMPLICIT_DEF), Reg);
  406. }
  407. return Reg;
  408. }
  409. /// Helper for getRegForValue. This function is called when the value isn't
  410. /// already available in a register and must be materialized with new
  411. /// instructions.
  412. unsigned FastISel::materializeRegForValue(const Value *V, MVT VT) {
  413. unsigned Reg = 0;
  414. // Give the target-specific code a try first.
  415. if (isa<Constant>(V))
  416. Reg = fastMaterializeConstant(cast<Constant>(V));
  417. // If target-specific code couldn't or didn't want to handle the value, then
  418. // give target-independent code a try.
  419. if (!Reg)
  420. Reg = materializeConstant(V, VT);
  421. // Don't cache constant materializations in the general ValueMap.
  422. // To do so would require tracking what uses they dominate.
  423. if (Reg) {
  424. LocalValueMap[V] = Reg;
  425. LastLocalValue = MRI.getVRegDef(Reg);
  426. }
  427. return Reg;
  428. }
  429. unsigned FastISel::lookUpRegForValue(const Value *V) {
  430. // Look up the value to see if we already have a register for it. We
  431. // cache values defined by Instructions across blocks, and other values
  432. // only locally. This is because Instructions already have the SSA
  433. // def-dominates-use requirement enforced.
  434. DenseMap<const Value *, unsigned>::iterator I = FuncInfo.ValueMap.find(V);
  435. if (I != FuncInfo.ValueMap.end())
  436. return I->second;
  437. return LocalValueMap[V];
  438. }
  439. void FastISel::updateValueMap(const Value *I, unsigned Reg, unsigned NumRegs) {
  440. if (!isa<Instruction>(I)) {
  441. LocalValueMap[I] = Reg;
  442. return;
  443. }
  444. unsigned &AssignedReg = FuncInfo.ValueMap[I];
  445. if (AssignedReg == 0)
  446. // Use the new register.
  447. AssignedReg = Reg;
  448. else if (Reg != AssignedReg) {
  449. // Arrange for uses of AssignedReg to be replaced by uses of Reg.
  450. for (unsigned i = 0; i < NumRegs; i++) {
  451. FuncInfo.RegFixups[AssignedReg + i] = Reg + i;
  452. FuncInfo.RegsWithFixups.insert(Reg + i);
  453. }
  454. AssignedReg = Reg;
  455. }
  456. }
  457. std::pair<unsigned, bool> FastISel::getRegForGEPIndex(const Value *Idx) {
  458. unsigned IdxN = getRegForValue(Idx);
  459. if (IdxN == 0)
  460. // Unhandled operand. Halt "fast" selection and bail.
  461. return std::pair<unsigned, bool>(0, false);
  462. bool IdxNIsKill = hasTrivialKill(Idx);
  463. // If the index is smaller or larger than intptr_t, truncate or extend it.
  464. MVT PtrVT = TLI.getPointerTy(DL);
  465. EVT IdxVT = EVT::getEVT(Idx->getType(), /*HandleUnknown=*/false);
  466. if (IdxVT.bitsLT(PtrVT)) {
  467. IdxN = fastEmit_r(IdxVT.getSimpleVT(), PtrVT, ISD::SIGN_EXTEND, IdxN,
  468. IdxNIsKill);
  469. IdxNIsKill = true;
  470. } else if (IdxVT.bitsGT(PtrVT)) {
  471. IdxN =
  472. fastEmit_r(IdxVT.getSimpleVT(), PtrVT, ISD::TRUNCATE, IdxN, IdxNIsKill);
  473. IdxNIsKill = true;
  474. }
  475. return std::pair<unsigned, bool>(IdxN, IdxNIsKill);
  476. }
  477. void FastISel::recomputeInsertPt() {
  478. if (getLastLocalValue()) {
  479. FuncInfo.InsertPt = getLastLocalValue();
  480. FuncInfo.MBB = FuncInfo.InsertPt->getParent();
  481. ++FuncInfo.InsertPt;
  482. } else
  483. FuncInfo.InsertPt = FuncInfo.MBB->getFirstNonPHI();
  484. // Now skip past any EH_LABELs, which must remain at the beginning.
  485. while (FuncInfo.InsertPt != FuncInfo.MBB->end() &&
  486. FuncInfo.InsertPt->getOpcode() == TargetOpcode::EH_LABEL)
  487. ++FuncInfo.InsertPt;
  488. }
  489. void FastISel::removeDeadCode(MachineBasicBlock::iterator I,
  490. MachineBasicBlock::iterator E) {
  491. assert(I.isValid() && E.isValid() && std::distance(I, E) > 0 &&
  492. "Invalid iterator!");
  493. while (I != E) {
  494. if (LastFlushPoint == I)
  495. LastFlushPoint = E;
  496. if (SavedInsertPt == I)
  497. SavedInsertPt = E;
  498. if (EmitStartPt == I)
  499. EmitStartPt = E.isValid() ? &*E : nullptr;
  500. if (LastLocalValue == I)
  501. LastLocalValue = E.isValid() ? &*E : nullptr;
  502. MachineInstr *Dead = &*I;
  503. ++I;
  504. Dead->eraseFromParent();
  505. ++NumFastIselDead;
  506. }
  507. recomputeInsertPt();
  508. }
  509. FastISel::SavePoint FastISel::enterLocalValueArea() {
  510. MachineBasicBlock::iterator OldInsertPt = FuncInfo.InsertPt;
  511. DebugLoc OldDL = DbgLoc;
  512. recomputeInsertPt();
  513. DbgLoc = DebugLoc();
  514. SavePoint SP = {OldInsertPt, OldDL};
  515. return SP;
  516. }
  517. void FastISel::leaveLocalValueArea(SavePoint OldInsertPt) {
  518. if (FuncInfo.InsertPt != FuncInfo.MBB->begin())
  519. LastLocalValue = &*std::prev(FuncInfo.InsertPt);
  520. // Restore the previous insert position.
  521. FuncInfo.InsertPt = OldInsertPt.InsertPt;
  522. DbgLoc = OldInsertPt.DL;
  523. }
  524. bool FastISel::selectBinaryOp(const User *I, unsigned ISDOpcode) {
  525. EVT VT = EVT::getEVT(I->getType(), /*HandleUnknown=*/true);
  526. if (VT == MVT::Other || !VT.isSimple())
  527. // Unhandled type. Halt "fast" selection and bail.
  528. return false;
  529. // We only handle legal types. For example, on x86-32 the instruction
  530. // selector contains all of the 64-bit instructions from x86-64,
  531. // under the assumption that i64 won't be used if the target doesn't
  532. // support it.
  533. if (!TLI.isTypeLegal(VT)) {
  534. // MVT::i1 is special. Allow AND, OR, or XOR because they
  535. // don't require additional zeroing, which makes them easy.
  536. if (VT == MVT::i1 && (ISDOpcode == ISD::AND || ISDOpcode == ISD::OR ||
  537. ISDOpcode == ISD::XOR))
  538. VT = TLI.getTypeToTransformTo(I->getContext(), VT);
  539. else
  540. return false;
  541. }
  542. // Check if the first operand is a constant, and handle it as "ri". At -O0,
  543. // we don't have anything that canonicalizes operand order.
  544. if (const auto *CI = dyn_cast<ConstantInt>(I->getOperand(0)))
  545. if (isa<Instruction>(I) && cast<Instruction>(I)->isCommutative()) {
  546. unsigned Op1 = getRegForValue(I->getOperand(1));
  547. if (!Op1)
  548. return false;
  549. bool Op1IsKill = hasTrivialKill(I->getOperand(1));
  550. unsigned ResultReg =
  551. fastEmit_ri_(VT.getSimpleVT(), ISDOpcode, Op1, Op1IsKill,
  552. CI->getZExtValue(), VT.getSimpleVT());
  553. if (!ResultReg)
  554. return false;
  555. // We successfully emitted code for the given LLVM Instruction.
  556. updateValueMap(I, ResultReg);
  557. return true;
  558. }
  559. unsigned Op0 = getRegForValue(I->getOperand(0));
  560. if (!Op0) // Unhandled operand. Halt "fast" selection and bail.
  561. return false;
  562. bool Op0IsKill = hasTrivialKill(I->getOperand(0));
  563. // Check if the second operand is a constant and handle it appropriately.
  564. if (const auto *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
  565. uint64_t Imm = CI->getSExtValue();
  566. // Transform "sdiv exact X, 8" -> "sra X, 3".
  567. if (ISDOpcode == ISD::SDIV && isa<BinaryOperator>(I) &&
  568. cast<BinaryOperator>(I)->isExact() && isPowerOf2_64(Imm)) {
  569. Imm = Log2_64(Imm);
  570. ISDOpcode = ISD::SRA;
  571. }
  572. // Transform "urem x, pow2" -> "and x, pow2-1".
  573. if (ISDOpcode == ISD::UREM && isa<BinaryOperator>(I) &&
  574. isPowerOf2_64(Imm)) {
  575. --Imm;
  576. ISDOpcode = ISD::AND;
  577. }
  578. unsigned ResultReg = fastEmit_ri_(VT.getSimpleVT(), ISDOpcode, Op0,
  579. Op0IsKill, Imm, VT.getSimpleVT());
  580. if (!ResultReg)
  581. return false;
  582. // We successfully emitted code for the given LLVM Instruction.
  583. updateValueMap(I, ResultReg);
  584. return true;
  585. }
  586. unsigned Op1 = getRegForValue(I->getOperand(1));
  587. if (!Op1) // Unhandled operand. Halt "fast" selection and bail.
  588. return false;
  589. bool Op1IsKill = hasTrivialKill(I->getOperand(1));
  590. // Now we have both operands in registers. Emit the instruction.
  591. unsigned ResultReg = fastEmit_rr(VT.getSimpleVT(), VT.getSimpleVT(),
  592. ISDOpcode, Op0, Op0IsKill, Op1, Op1IsKill);
  593. if (!ResultReg)
  594. // Target-specific code wasn't able to find a machine opcode for
  595. // the given ISD opcode and type. Halt "fast" selection and bail.
  596. return false;
  597. // We successfully emitted code for the given LLVM Instruction.
  598. updateValueMap(I, ResultReg);
  599. return true;
  600. }
  601. bool FastISel::selectGetElementPtr(const User *I) {
  602. unsigned N = getRegForValue(I->getOperand(0));
  603. if (!N) // Unhandled operand. Halt "fast" selection and bail.
  604. return false;
  605. bool NIsKill = hasTrivialKill(I->getOperand(0));
  606. // Keep a running tab of the total offset to coalesce multiple N = N + Offset
  607. // into a single N = N + TotalOffset.
  608. uint64_t TotalOffs = 0;
  609. // FIXME: What's a good SWAG number for MaxOffs?
  610. uint64_t MaxOffs = 2048;
  611. MVT VT = TLI.getPointerTy(DL);
  612. for (gep_type_iterator GTI = gep_type_begin(I), E = gep_type_end(I);
  613. GTI != E; ++GTI) {
  614. const Value *Idx = GTI.getOperand();
  615. if (StructType *StTy = GTI.getStructTypeOrNull()) {
  616. uint64_t Field = cast<ConstantInt>(Idx)->getZExtValue();
  617. if (Field) {
  618. // N = N + Offset
  619. TotalOffs += DL.getStructLayout(StTy)->getElementOffset(Field);
  620. if (TotalOffs >= MaxOffs) {
  621. N = fastEmit_ri_(VT, ISD::ADD, N, NIsKill, TotalOffs, VT);
  622. if (!N) // Unhandled operand. Halt "fast" selection and bail.
  623. return false;
  624. NIsKill = true;
  625. TotalOffs = 0;
  626. }
  627. }
  628. } else {
  629. Type *Ty = GTI.getIndexedType();
  630. // If this is a constant subscript, handle it quickly.
  631. if (const auto *CI = dyn_cast<ConstantInt>(Idx)) {
  632. if (CI->isZero())
  633. continue;
  634. // N = N + Offset
  635. uint64_t IdxN = CI->getValue().sextOrTrunc(64).getSExtValue();
  636. TotalOffs += DL.getTypeAllocSize(Ty) * IdxN;
  637. if (TotalOffs >= MaxOffs) {
  638. N = fastEmit_ri_(VT, ISD::ADD, N, NIsKill, TotalOffs, VT);
  639. if (!N) // Unhandled operand. Halt "fast" selection and bail.
  640. return false;
  641. NIsKill = true;
  642. TotalOffs = 0;
  643. }
  644. continue;
  645. }
  646. if (TotalOffs) {
  647. N = fastEmit_ri_(VT, ISD::ADD, N, NIsKill, TotalOffs, VT);
  648. if (!N) // Unhandled operand. Halt "fast" selection and bail.
  649. return false;
  650. NIsKill = true;
  651. TotalOffs = 0;
  652. }
  653. // N = N + Idx * ElementSize;
  654. uint64_t ElementSize = DL.getTypeAllocSize(Ty);
  655. std::pair<unsigned, bool> Pair = getRegForGEPIndex(Idx);
  656. unsigned IdxN = Pair.first;
  657. bool IdxNIsKill = Pair.second;
  658. if (!IdxN) // Unhandled operand. Halt "fast" selection and bail.
  659. return false;
  660. if (ElementSize != 1) {
  661. IdxN = fastEmit_ri_(VT, ISD::MUL, IdxN, IdxNIsKill, ElementSize, VT);
  662. if (!IdxN) // Unhandled operand. Halt "fast" selection and bail.
  663. return false;
  664. IdxNIsKill = true;
  665. }
  666. N = fastEmit_rr(VT, VT, ISD::ADD, N, NIsKill, IdxN, IdxNIsKill);
  667. if (!N) // Unhandled operand. Halt "fast" selection and bail.
  668. return false;
  669. }
  670. }
  671. if (TotalOffs) {
  672. N = fastEmit_ri_(VT, ISD::ADD, N, NIsKill, TotalOffs, VT);
  673. if (!N) // Unhandled operand. Halt "fast" selection and bail.
  674. return false;
  675. }
  676. // We successfully emitted code for the given LLVM Instruction.
  677. updateValueMap(I, N);
  678. return true;
  679. }
  680. bool FastISel::addStackMapLiveVars(SmallVectorImpl<MachineOperand> &Ops,
  681. const CallInst *CI, unsigned StartIdx) {
  682. for (unsigned i = StartIdx, e = CI->getNumArgOperands(); i != e; ++i) {
  683. Value *Val = CI->getArgOperand(i);
  684. // Check for constants and encode them with a StackMaps::ConstantOp prefix.
  685. if (const auto *C = dyn_cast<ConstantInt>(Val)) {
  686. Ops.push_back(MachineOperand::CreateImm(StackMaps::ConstantOp));
  687. Ops.push_back(MachineOperand::CreateImm(C->getSExtValue()));
  688. } else if (isa<ConstantPointerNull>(Val)) {
  689. Ops.push_back(MachineOperand::CreateImm(StackMaps::ConstantOp));
  690. Ops.push_back(MachineOperand::CreateImm(0));
  691. } else if (auto *AI = dyn_cast<AllocaInst>(Val)) {
  692. // Values coming from a stack location also require a special encoding,
  693. // but that is added later on by the target specific frame index
  694. // elimination implementation.
  695. auto SI = FuncInfo.StaticAllocaMap.find(AI);
  696. if (SI != FuncInfo.StaticAllocaMap.end())
  697. Ops.push_back(MachineOperand::CreateFI(SI->second));
  698. else
  699. return false;
  700. } else {
  701. unsigned Reg = getRegForValue(Val);
  702. if (!Reg)
  703. return false;
  704. Ops.push_back(MachineOperand::CreateReg(Reg, /*isDef=*/false));
  705. }
  706. }
  707. return true;
  708. }
  709. bool FastISel::selectStackmap(const CallInst *I) {
  710. // void @llvm.experimental.stackmap(i64 <id>, i32 <numShadowBytes>,
  711. // [live variables...])
  712. assert(I->getCalledFunction()->getReturnType()->isVoidTy() &&
  713. "Stackmap cannot return a value.");
  714. // The stackmap intrinsic only records the live variables (the arguments
  715. // passed to it) and emits NOPS (if requested). Unlike the patchpoint
  716. // intrinsic, this won't be lowered to a function call. This means we don't
  717. // have to worry about calling conventions and target-specific lowering code.
  718. // Instead we perform the call lowering right here.
  719. //
  720. // CALLSEQ_START(0, 0...)
  721. // STACKMAP(id, nbytes, ...)
  722. // CALLSEQ_END(0, 0)
  723. //
  724. SmallVector<MachineOperand, 32> Ops;
  725. // Add the <id> and <numBytes> constants.
  726. assert(isa<ConstantInt>(I->getOperand(PatchPointOpers::IDPos)) &&
  727. "Expected a constant integer.");
  728. const auto *ID = cast<ConstantInt>(I->getOperand(PatchPointOpers::IDPos));
  729. Ops.push_back(MachineOperand::CreateImm(ID->getZExtValue()));
  730. assert(isa<ConstantInt>(I->getOperand(PatchPointOpers::NBytesPos)) &&
  731. "Expected a constant integer.");
  732. const auto *NumBytes =
  733. cast<ConstantInt>(I->getOperand(PatchPointOpers::NBytesPos));
  734. Ops.push_back(MachineOperand::CreateImm(NumBytes->getZExtValue()));
  735. // Push live variables for the stack map (skipping the first two arguments
  736. // <id> and <numBytes>).
  737. if (!addStackMapLiveVars(Ops, I, 2))
  738. return false;
  739. // We are not adding any register mask info here, because the stackmap doesn't
  740. // clobber anything.
  741. // Add scratch registers as implicit def and early clobber.
  742. CallingConv::ID CC = I->getCallingConv();
  743. const MCPhysReg *ScratchRegs = TLI.getScratchRegisters(CC);
  744. for (unsigned i = 0; ScratchRegs[i]; ++i)
  745. Ops.push_back(MachineOperand::CreateReg(
  746. ScratchRegs[i], /*isDef=*/true, /*isImp=*/true, /*isKill=*/false,
  747. /*isDead=*/false, /*isUndef=*/false, /*isEarlyClobber=*/true));
  748. // Issue CALLSEQ_START
  749. unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
  750. auto Builder =
  751. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackDown));
  752. const MCInstrDesc &MCID = Builder.getInstr()->getDesc();
  753. for (unsigned I = 0, E = MCID.getNumOperands(); I < E; ++I)
  754. Builder.addImm(0);
  755. // Issue STACKMAP.
  756. MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  757. TII.get(TargetOpcode::STACKMAP));
  758. for (auto const &MO : Ops)
  759. MIB.add(MO);
  760. // Issue CALLSEQ_END
  761. unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
  762. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackUp))
  763. .addImm(0)
  764. .addImm(0);
  765. // Inform the Frame Information that we have a stackmap in this function.
  766. FuncInfo.MF->getFrameInfo().setHasStackMap();
  767. return true;
  768. }
  769. /// Lower an argument list according to the target calling convention.
  770. ///
  771. /// This is a helper for lowering intrinsics that follow a target calling
  772. /// convention or require stack pointer adjustment. Only a subset of the
  773. /// intrinsic's operands need to participate in the calling convention.
  774. bool FastISel::lowerCallOperands(const CallInst *CI, unsigned ArgIdx,
  775. unsigned NumArgs, const Value *Callee,
  776. bool ForceRetVoidTy, CallLoweringInfo &CLI) {
  777. ArgListTy Args;
  778. Args.reserve(NumArgs);
  779. // Populate the argument list.
  780. ImmutableCallSite CS(CI);
  781. for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs; ArgI != ArgE; ++ArgI) {
  782. Value *V = CI->getOperand(ArgI);
  783. assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
  784. ArgListEntry Entry;
  785. Entry.Val = V;
  786. Entry.Ty = V->getType();
  787. Entry.setAttributes(&CS, ArgI);
  788. Args.push_back(Entry);
  789. }
  790. Type *RetTy = ForceRetVoidTy ? Type::getVoidTy(CI->getType()->getContext())
  791. : CI->getType();
  792. CLI.setCallee(CI->getCallingConv(), RetTy, Callee, std::move(Args), NumArgs);
  793. return lowerCallTo(CLI);
  794. }
  795. FastISel::CallLoweringInfo &FastISel::CallLoweringInfo::setCallee(
  796. const DataLayout &DL, MCContext &Ctx, CallingConv::ID CC, Type *ResultTy,
  797. StringRef Target, ArgListTy &&ArgsList, unsigned FixedArgs) {
  798. SmallString<32> MangledName;
  799. Mangler::getNameWithPrefix(MangledName, Target, DL);
  800. MCSymbol *Sym = Ctx.getOrCreateSymbol(MangledName);
  801. return setCallee(CC, ResultTy, Sym, std::move(ArgsList), FixedArgs);
  802. }
  803. bool FastISel::selectPatchpoint(const CallInst *I) {
  804. // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
  805. // i32 <numBytes>,
  806. // i8* <target>,
  807. // i32 <numArgs>,
  808. // [Args...],
  809. // [live variables...])
  810. CallingConv::ID CC = I->getCallingConv();
  811. bool IsAnyRegCC = CC == CallingConv::AnyReg;
  812. bool HasDef = !I->getType()->isVoidTy();
  813. Value *Callee = I->getOperand(PatchPointOpers::TargetPos)->stripPointerCasts();
  814. // Get the real number of arguments participating in the call <numArgs>
  815. assert(isa<ConstantInt>(I->getOperand(PatchPointOpers::NArgPos)) &&
  816. "Expected a constant integer.");
  817. const auto *NumArgsVal =
  818. cast<ConstantInt>(I->getOperand(PatchPointOpers::NArgPos));
  819. unsigned NumArgs = NumArgsVal->getZExtValue();
  820. // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
  821. // This includes all meta-operands up to but not including CC.
  822. unsigned NumMetaOpers = PatchPointOpers::CCPos;
  823. assert(I->getNumArgOperands() >= NumMetaOpers + NumArgs &&
  824. "Not enough arguments provided to the patchpoint intrinsic");
  825. // For AnyRegCC the arguments are lowered later on manually.
  826. unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
  827. CallLoweringInfo CLI;
  828. CLI.setIsPatchPoint();
  829. if (!lowerCallOperands(I, NumMetaOpers, NumCallArgs, Callee, IsAnyRegCC, CLI))
  830. return false;
  831. assert(CLI.Call && "No call instruction specified.");
  832. SmallVector<MachineOperand, 32> Ops;
  833. // Add an explicit result reg if we use the anyreg calling convention.
  834. if (IsAnyRegCC && HasDef) {
  835. assert(CLI.NumResultRegs == 0 && "Unexpected result register.");
  836. CLI.ResultReg = createResultReg(TLI.getRegClassFor(MVT::i64));
  837. CLI.NumResultRegs = 1;
  838. Ops.push_back(MachineOperand::CreateReg(CLI.ResultReg, /*isDef=*/true));
  839. }
  840. // Add the <id> and <numBytes> constants.
  841. assert(isa<ConstantInt>(I->getOperand(PatchPointOpers::IDPos)) &&
  842. "Expected a constant integer.");
  843. const auto *ID = cast<ConstantInt>(I->getOperand(PatchPointOpers::IDPos));
  844. Ops.push_back(MachineOperand::CreateImm(ID->getZExtValue()));
  845. assert(isa<ConstantInt>(I->getOperand(PatchPointOpers::NBytesPos)) &&
  846. "Expected a constant integer.");
  847. const auto *NumBytes =
  848. cast<ConstantInt>(I->getOperand(PatchPointOpers::NBytesPos));
  849. Ops.push_back(MachineOperand::CreateImm(NumBytes->getZExtValue()));
  850. // Add the call target.
  851. if (const auto *C = dyn_cast<IntToPtrInst>(Callee)) {
  852. uint64_t CalleeConstAddr =
  853. cast<ConstantInt>(C->getOperand(0))->getZExtValue();
  854. Ops.push_back(MachineOperand::CreateImm(CalleeConstAddr));
  855. } else if (const auto *C = dyn_cast<ConstantExpr>(Callee)) {
  856. if (C->getOpcode() == Instruction::IntToPtr) {
  857. uint64_t CalleeConstAddr =
  858. cast<ConstantInt>(C->getOperand(0))->getZExtValue();
  859. Ops.push_back(MachineOperand::CreateImm(CalleeConstAddr));
  860. } else
  861. llvm_unreachable("Unsupported ConstantExpr.");
  862. } else if (const auto *GV = dyn_cast<GlobalValue>(Callee)) {
  863. Ops.push_back(MachineOperand::CreateGA(GV, 0));
  864. } else if (isa<ConstantPointerNull>(Callee))
  865. Ops.push_back(MachineOperand::CreateImm(0));
  866. else
  867. llvm_unreachable("Unsupported callee address.");
  868. // Adjust <numArgs> to account for any arguments that have been passed on
  869. // the stack instead.
  870. unsigned NumCallRegArgs = IsAnyRegCC ? NumArgs : CLI.OutRegs.size();
  871. Ops.push_back(MachineOperand::CreateImm(NumCallRegArgs));
  872. // Add the calling convention
  873. Ops.push_back(MachineOperand::CreateImm((unsigned)CC));
  874. // Add the arguments we omitted previously. The register allocator should
  875. // place these in any free register.
  876. if (IsAnyRegCC) {
  877. for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) {
  878. unsigned Reg = getRegForValue(I->getArgOperand(i));
  879. if (!Reg)
  880. return false;
  881. Ops.push_back(MachineOperand::CreateReg(Reg, /*isDef=*/false));
  882. }
  883. }
  884. // Push the arguments from the call instruction.
  885. for (auto Reg : CLI.OutRegs)
  886. Ops.push_back(MachineOperand::CreateReg(Reg, /*isDef=*/false));
  887. // Push live variables for the stack map.
  888. if (!addStackMapLiveVars(Ops, I, NumMetaOpers + NumArgs))
  889. return false;
  890. // Push the register mask info.
  891. Ops.push_back(MachineOperand::CreateRegMask(
  892. TRI.getCallPreservedMask(*FuncInfo.MF, CC)));
  893. // Add scratch registers as implicit def and early clobber.
  894. const MCPhysReg *ScratchRegs = TLI.getScratchRegisters(CC);
  895. for (unsigned i = 0; ScratchRegs[i]; ++i)
  896. Ops.push_back(MachineOperand::CreateReg(
  897. ScratchRegs[i], /*isDef=*/true, /*isImp=*/true, /*isKill=*/false,
  898. /*isDead=*/false, /*isUndef=*/false, /*isEarlyClobber=*/true));
  899. // Add implicit defs (return values).
  900. for (auto Reg : CLI.InRegs)
  901. Ops.push_back(MachineOperand::CreateReg(Reg, /*isDef=*/true,
  902. /*isImp=*/true));
  903. // Insert the patchpoint instruction before the call generated by the target.
  904. MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, CLI.Call, DbgLoc,
  905. TII.get(TargetOpcode::PATCHPOINT));
  906. for (auto &MO : Ops)
  907. MIB.add(MO);
  908. MIB->setPhysRegsDeadExcept(CLI.InRegs, TRI);
  909. // Delete the original call instruction.
  910. CLI.Call->eraseFromParent();
  911. // Inform the Frame Information that we have a patchpoint in this function.
  912. FuncInfo.MF->getFrameInfo().setHasPatchPoint();
  913. if (CLI.NumResultRegs)
  914. updateValueMap(I, CLI.ResultReg, CLI.NumResultRegs);
  915. return true;
  916. }
  917. bool FastISel::selectXRayCustomEvent(const CallInst *I) {
  918. const auto &Triple = TM.getTargetTriple();
  919. if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
  920. return true; // don't do anything to this instruction.
  921. SmallVector<MachineOperand, 8> Ops;
  922. Ops.push_back(MachineOperand::CreateReg(getRegForValue(I->getArgOperand(0)),
  923. /*isDef=*/false));
  924. Ops.push_back(MachineOperand::CreateReg(getRegForValue(I->getArgOperand(1)),
  925. /*isDef=*/false));
  926. MachineInstrBuilder MIB =
  927. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  928. TII.get(TargetOpcode::PATCHABLE_EVENT_CALL));
  929. for (auto &MO : Ops)
  930. MIB.add(MO);
  931. // Insert the Patchable Event Call instruction, that gets lowered properly.
  932. return true;
  933. }
  934. bool FastISel::selectXRayTypedEvent(const CallInst *I) {
  935. const auto &Triple = TM.getTargetTriple();
  936. if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
  937. return true; // don't do anything to this instruction.
  938. SmallVector<MachineOperand, 8> Ops;
  939. Ops.push_back(MachineOperand::CreateReg(getRegForValue(I->getArgOperand(0)),
  940. /*isDef=*/false));
  941. Ops.push_back(MachineOperand::CreateReg(getRegForValue(I->getArgOperand(1)),
  942. /*isDef=*/false));
  943. Ops.push_back(MachineOperand::CreateReg(getRegForValue(I->getArgOperand(2)),
  944. /*isDef=*/false));
  945. MachineInstrBuilder MIB =
  946. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  947. TII.get(TargetOpcode::PATCHABLE_TYPED_EVENT_CALL));
  948. for (auto &MO : Ops)
  949. MIB.add(MO);
  950. // Insert the Patchable Typed Event Call instruction, that gets lowered properly.
  951. return true;
  952. }
  953. /// Returns an AttributeList representing the attributes applied to the return
  954. /// value of the given call.
  955. static AttributeList getReturnAttrs(FastISel::CallLoweringInfo &CLI) {
  956. SmallVector<Attribute::AttrKind, 2> Attrs;
  957. if (CLI.RetSExt)
  958. Attrs.push_back(Attribute::SExt);
  959. if (CLI.RetZExt)
  960. Attrs.push_back(Attribute::ZExt);
  961. if (CLI.IsInReg)
  962. Attrs.push_back(Attribute::InReg);
  963. return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
  964. Attrs);
  965. }
  966. bool FastISel::lowerCallTo(const CallInst *CI, const char *SymName,
  967. unsigned NumArgs) {
  968. MCContext &Ctx = MF->getContext();
  969. SmallString<32> MangledName;
  970. Mangler::getNameWithPrefix(MangledName, SymName, DL);
  971. MCSymbol *Sym = Ctx.getOrCreateSymbol(MangledName);
  972. return lowerCallTo(CI, Sym, NumArgs);
  973. }
  974. bool FastISel::lowerCallTo(const CallInst *CI, MCSymbol *Symbol,
  975. unsigned NumArgs) {
  976. ImmutableCallSite CS(CI);
  977. FunctionType *FTy = CS.getFunctionType();
  978. Type *RetTy = CS.getType();
  979. ArgListTy Args;
  980. Args.reserve(NumArgs);
  981. // Populate the argument list.
  982. // Attributes for args start at offset 1, after the return attribute.
  983. for (unsigned ArgI = 0; ArgI != NumArgs; ++ArgI) {
  984. Value *V = CI->getOperand(ArgI);
  985. assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
  986. ArgListEntry Entry;
  987. Entry.Val = V;
  988. Entry.Ty = V->getType();
  989. Entry.setAttributes(&CS, ArgI);
  990. Args.push_back(Entry);
  991. }
  992. TLI.markLibCallAttributes(MF, CS.getCallingConv(), Args);
  993. CallLoweringInfo CLI;
  994. CLI.setCallee(RetTy, FTy, Symbol, std::move(Args), CS, NumArgs);
  995. return lowerCallTo(CLI);
  996. }
  997. bool FastISel::lowerCallTo(CallLoweringInfo &CLI) {
  998. // Handle the incoming return values from the call.
  999. CLI.clearIns();
  1000. SmallVector<EVT, 4> RetTys;
  1001. ComputeValueVTs(TLI, DL, CLI.RetTy, RetTys);
  1002. SmallVector<ISD::OutputArg, 4> Outs;
  1003. GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, TLI, DL);
  1004. bool CanLowerReturn = TLI.CanLowerReturn(
  1005. CLI.CallConv, *FuncInfo.MF, CLI.IsVarArg, Outs, CLI.RetTy->getContext());
  1006. // FIXME: sret demotion isn't supported yet - bail out.
  1007. if (!CanLowerReturn)
  1008. return false;
  1009. for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
  1010. EVT VT = RetTys[I];
  1011. MVT RegisterVT = TLI.getRegisterType(CLI.RetTy->getContext(), VT);
  1012. unsigned NumRegs = TLI.getNumRegisters(CLI.RetTy->getContext(), VT);
  1013. for (unsigned i = 0; i != NumRegs; ++i) {
  1014. ISD::InputArg MyFlags;
  1015. MyFlags.VT = RegisterVT;
  1016. MyFlags.ArgVT = VT;
  1017. MyFlags.Used = CLI.IsReturnValueUsed;
  1018. if (CLI.RetSExt)
  1019. MyFlags.Flags.setSExt();
  1020. if (CLI.RetZExt)
  1021. MyFlags.Flags.setZExt();
  1022. if (CLI.IsInReg)
  1023. MyFlags.Flags.setInReg();
  1024. CLI.Ins.push_back(MyFlags);
  1025. }
  1026. }
  1027. // Handle all of the outgoing arguments.
  1028. CLI.clearOuts();
  1029. for (auto &Arg : CLI.getArgs()) {
  1030. Type *FinalType = Arg.Ty;
  1031. if (Arg.IsByVal)
  1032. FinalType = cast<PointerType>(Arg.Ty)->getElementType();
  1033. bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
  1034. FinalType, CLI.CallConv, CLI.IsVarArg);
  1035. ISD::ArgFlagsTy Flags;
  1036. if (Arg.IsZExt)
  1037. Flags.setZExt();
  1038. if (Arg.IsSExt)
  1039. Flags.setSExt();
  1040. if (Arg.IsInReg)
  1041. Flags.setInReg();
  1042. if (Arg.IsSRet)
  1043. Flags.setSRet();
  1044. if (Arg.IsSwiftSelf)
  1045. Flags.setSwiftSelf();
  1046. if (Arg.IsSwiftError)
  1047. Flags.setSwiftError();
  1048. if (Arg.IsByVal)
  1049. Flags.setByVal();
  1050. if (Arg.IsInAlloca) {
  1051. Flags.setInAlloca();
  1052. // Set the byval flag for CCAssignFn callbacks that don't know about
  1053. // inalloca. This way we can know how many bytes we should've allocated
  1054. // and how many bytes a callee cleanup function will pop. If we port
  1055. // inalloca to more targets, we'll have to add custom inalloca handling in
  1056. // the various CC lowering callbacks.
  1057. Flags.setByVal();
  1058. }
  1059. if (Arg.IsByVal || Arg.IsInAlloca) {
  1060. PointerType *Ty = cast<PointerType>(Arg.Ty);
  1061. Type *ElementTy = Ty->getElementType();
  1062. unsigned FrameSize =
  1063. DL.getTypeAllocSize(Arg.ByValType ? Arg.ByValType : ElementTy);
  1064. // For ByVal, alignment should come from FE. BE will guess if this info
  1065. // is not there, but there are cases it cannot get right.
  1066. unsigned FrameAlign = Arg.Alignment;
  1067. if (!FrameAlign)
  1068. FrameAlign = TLI.getByValTypeAlignment(ElementTy, DL);
  1069. Flags.setByValSize(FrameSize);
  1070. Flags.setByValAlign(FrameAlign);
  1071. }
  1072. if (Arg.IsNest)
  1073. Flags.setNest();
  1074. if (NeedsRegBlock)
  1075. Flags.setInConsecutiveRegs();
  1076. unsigned OriginalAlignment = DL.getABITypeAlignment(Arg.Ty);
  1077. Flags.setOrigAlign(OriginalAlignment);
  1078. CLI.OutVals.push_back(Arg.Val);
  1079. CLI.OutFlags.push_back(Flags);
  1080. }
  1081. if (!fastLowerCall(CLI))
  1082. return false;
  1083. // Set all unused physreg defs as dead.
  1084. assert(CLI.Call && "No call instruction specified.");
  1085. CLI.Call->setPhysRegsDeadExcept(CLI.InRegs, TRI);
  1086. if (CLI.NumResultRegs && CLI.CS)
  1087. updateValueMap(CLI.CS->getInstruction(), CLI.ResultReg, CLI.NumResultRegs);
  1088. // Set labels for heapallocsite call.
  1089. if (CLI.CS && CLI.CS->getInstruction()->hasMetadata("heapallocsite")) {
  1090. const MDNode *MD = CLI.CS->getInstruction()->getMetadata("heapallocsite");
  1091. MF->addCodeViewHeapAllocSite(CLI.Call, MD);
  1092. }
  1093. return true;
  1094. }
  1095. bool FastISel::lowerCall(const CallInst *CI) {
  1096. ImmutableCallSite CS(CI);
  1097. FunctionType *FuncTy = CS.getFunctionType();
  1098. Type *RetTy = CS.getType();
  1099. ArgListTy Args;
  1100. ArgListEntry Entry;
  1101. Args.reserve(CS.arg_size());
  1102. for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
  1103. i != e; ++i) {
  1104. Value *V = *i;
  1105. // Skip empty types
  1106. if (V->getType()->isEmptyTy())
  1107. continue;
  1108. Entry.Val = V;
  1109. Entry.Ty = V->getType();
  1110. // Skip the first return-type Attribute to get to params.
  1111. Entry.setAttributes(&CS, i - CS.arg_begin());
  1112. Args.push_back(Entry);
  1113. }
  1114. // Check if target-independent constraints permit a tail call here.
  1115. // Target-dependent constraints are checked within fastLowerCall.
  1116. bool IsTailCall = CI->isTailCall();
  1117. if (IsTailCall && !isInTailCallPosition(CS, TM))
  1118. IsTailCall = false;
  1119. CallLoweringInfo CLI;
  1120. CLI.setCallee(RetTy, FuncTy, CI->getCalledValue(), std::move(Args), CS)
  1121. .setTailCall(IsTailCall);
  1122. return lowerCallTo(CLI);
  1123. }
  1124. bool FastISel::selectCall(const User *I) {
  1125. const CallInst *Call = cast<CallInst>(I);
  1126. // Handle simple inline asms.
  1127. if (const InlineAsm *IA = dyn_cast<InlineAsm>(Call->getCalledValue())) {
  1128. // If the inline asm has side effects, then make sure that no local value
  1129. // lives across by flushing the local value map.
  1130. if (IA->hasSideEffects())
  1131. flushLocalValueMap();
  1132. // Don't attempt to handle constraints.
  1133. if (!IA->getConstraintString().empty())
  1134. return false;
  1135. unsigned ExtraInfo = 0;
  1136. if (IA->hasSideEffects())
  1137. ExtraInfo |= InlineAsm::Extra_HasSideEffects;
  1138. if (IA->isAlignStack())
  1139. ExtraInfo |= InlineAsm::Extra_IsAlignStack;
  1140. ExtraInfo |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
  1141. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  1142. TII.get(TargetOpcode::INLINEASM))
  1143. .addExternalSymbol(IA->getAsmString().c_str())
  1144. .addImm(ExtraInfo);
  1145. return true;
  1146. }
  1147. // Handle intrinsic function calls.
  1148. if (const auto *II = dyn_cast<IntrinsicInst>(Call))
  1149. return selectIntrinsicCall(II);
  1150. // Usually, it does not make sense to initialize a value,
  1151. // make an unrelated function call and use the value, because
  1152. // it tends to be spilled on the stack. So, we move the pointer
  1153. // to the last local value to the beginning of the block, so that
  1154. // all the values which have already been materialized,
  1155. // appear after the call. It also makes sense to skip intrinsics
  1156. // since they tend to be inlined.
  1157. flushLocalValueMap();
  1158. return lowerCall(Call);
  1159. }
  1160. bool FastISel::selectIntrinsicCall(const IntrinsicInst *II) {
  1161. switch (II->getIntrinsicID()) {
  1162. default:
  1163. break;
  1164. // At -O0 we don't care about the lifetime intrinsics.
  1165. case Intrinsic::lifetime_start:
  1166. case Intrinsic::lifetime_end:
  1167. // The donothing intrinsic does, well, nothing.
  1168. case Intrinsic::donothing:
  1169. // Neither does the sideeffect intrinsic.
  1170. case Intrinsic::sideeffect:
  1171. // Neither does the assume intrinsic; it's also OK not to codegen its operand.
  1172. case Intrinsic::assume:
  1173. return true;
  1174. case Intrinsic::dbg_declare: {
  1175. const DbgDeclareInst *DI = cast<DbgDeclareInst>(II);
  1176. assert(DI->getVariable() && "Missing variable");
  1177. if (!FuncInfo.MF->getMMI().hasDebugInfo()) {
  1178. LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
  1179. return true;
  1180. }
  1181. const Value *Address = DI->getAddress();
  1182. if (!Address || isa<UndefValue>(Address)) {
  1183. LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
  1184. return true;
  1185. }
  1186. // Byval arguments with frame indices were already handled after argument
  1187. // lowering and before isel.
  1188. const auto *Arg =
  1189. dyn_cast<Argument>(Address->stripInBoundsConstantOffsets());
  1190. if (Arg && FuncInfo.getArgumentFrameIndex(Arg) != INT_MAX)
  1191. return true;
  1192. Optional<MachineOperand> Op;
  1193. if (unsigned Reg = lookUpRegForValue(Address))
  1194. Op = MachineOperand::CreateReg(Reg, false);
  1195. // If we have a VLA that has a "use" in a metadata node that's then used
  1196. // here but it has no other uses, then we have a problem. E.g.,
  1197. //
  1198. // int foo (const int *x) {
  1199. // char a[*x];
  1200. // return 0;
  1201. // }
  1202. //
  1203. // If we assign 'a' a vreg and fast isel later on has to use the selection
  1204. // DAG isel, it will want to copy the value to the vreg. However, there are
  1205. // no uses, which goes counter to what selection DAG isel expects.
  1206. if (!Op && !Address->use_empty() && isa<Instruction>(Address) &&
  1207. (!isa<AllocaInst>(Address) ||
  1208. !FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(Address))))
  1209. Op = MachineOperand::CreateReg(FuncInfo.InitializeRegForValue(Address),
  1210. false);
  1211. if (Op) {
  1212. assert(DI->getVariable()->isValidLocationForIntrinsic(DbgLoc) &&
  1213. "Expected inlined-at fields to agree");
  1214. // A dbg.declare describes the address of a source variable, so lower it
  1215. // into an indirect DBG_VALUE.
  1216. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  1217. TII.get(TargetOpcode::DBG_VALUE), /*IsIndirect*/ true,
  1218. *Op, DI->getVariable(), DI->getExpression());
  1219. } else {
  1220. // We can't yet handle anything else here because it would require
  1221. // generating code, thus altering codegen because of debug info.
  1222. LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
  1223. }
  1224. return true;
  1225. }
  1226. case Intrinsic::dbg_value: {
  1227. // This form of DBG_VALUE is target-independent.
  1228. const DbgValueInst *DI = cast<DbgValueInst>(II);
  1229. const MCInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE);
  1230. const Value *V = DI->getValue();
  1231. assert(DI->getVariable()->isValidLocationForIntrinsic(DbgLoc) &&
  1232. "Expected inlined-at fields to agree");
  1233. if (!V) {
  1234. // Currently the optimizer can produce this; insert an undef to
  1235. // help debugging. Probably the optimizer should not do this.
  1236. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, false, 0U,
  1237. DI->getVariable(), DI->getExpression());
  1238. } else if (const auto *CI = dyn_cast<ConstantInt>(V)) {
  1239. if (CI->getBitWidth() > 64)
  1240. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
  1241. .addCImm(CI)
  1242. .addImm(0U)
  1243. .addMetadata(DI->getVariable())
  1244. .addMetadata(DI->getExpression());
  1245. else
  1246. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
  1247. .addImm(CI->getZExtValue())
  1248. .addImm(0U)
  1249. .addMetadata(DI->getVariable())
  1250. .addMetadata(DI->getExpression());
  1251. } else if (const auto *CF = dyn_cast<ConstantFP>(V)) {
  1252. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
  1253. .addFPImm(CF)
  1254. .addImm(0U)
  1255. .addMetadata(DI->getVariable())
  1256. .addMetadata(DI->getExpression());
  1257. } else if (unsigned Reg = lookUpRegForValue(V)) {
  1258. // FIXME: This does not handle register-indirect values at offset 0.
  1259. bool IsIndirect = false;
  1260. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, IsIndirect, Reg,
  1261. DI->getVariable(), DI->getExpression());
  1262. } else {
  1263. // We can't yet handle anything else here because it would require
  1264. // generating code, thus altering codegen because of debug info.
  1265. LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
  1266. }
  1267. return true;
  1268. }
  1269. case Intrinsic::dbg_label: {
  1270. const DbgLabelInst *DI = cast<DbgLabelInst>(II);
  1271. assert(DI->getLabel() && "Missing label");
  1272. if (!FuncInfo.MF->getMMI().hasDebugInfo()) {
  1273. LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
  1274. return true;
  1275. }
  1276. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  1277. TII.get(TargetOpcode::DBG_LABEL)).addMetadata(DI->getLabel());
  1278. return true;
  1279. }
  1280. case Intrinsic::objectsize:
  1281. llvm_unreachable("llvm.objectsize.* should have been lowered already");
  1282. case Intrinsic::is_constant:
  1283. llvm_unreachable("llvm.is.constant.* should have been lowered already");
  1284. case Intrinsic::launder_invariant_group:
  1285. case Intrinsic::strip_invariant_group:
  1286. case Intrinsic::expect: {
  1287. unsigned ResultReg = getRegForValue(II->getArgOperand(0));
  1288. if (!ResultReg)
  1289. return false;
  1290. updateValueMap(II, ResultReg);
  1291. return true;
  1292. }
  1293. case Intrinsic::experimental_stackmap:
  1294. return selectStackmap(II);
  1295. case Intrinsic::experimental_patchpoint_void:
  1296. case Intrinsic::experimental_patchpoint_i64:
  1297. return selectPatchpoint(II);
  1298. case Intrinsic::xray_customevent:
  1299. return selectXRayCustomEvent(II);
  1300. case Intrinsic::xray_typedevent:
  1301. return selectXRayTypedEvent(II);
  1302. }
  1303. return fastLowerIntrinsicCall(II);
  1304. }
  1305. bool FastISel::selectCast(const User *I, unsigned Opcode) {
  1306. EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType());
  1307. EVT DstVT = TLI.getValueType(DL, I->getType());
  1308. if (SrcVT == MVT::Other || !SrcVT.isSimple() || DstVT == MVT::Other ||
  1309. !DstVT.isSimple())
  1310. // Unhandled type. Halt "fast" selection and bail.
  1311. return false;
  1312. // Check if the destination type is legal.
  1313. if (!TLI.isTypeLegal(DstVT))
  1314. return false;
  1315. // Check if the source operand is legal.
  1316. if (!TLI.isTypeLegal(SrcVT))
  1317. return false;
  1318. unsigned InputReg = getRegForValue(I->getOperand(0));
  1319. if (!InputReg)
  1320. // Unhandled operand. Halt "fast" selection and bail.
  1321. return false;
  1322. bool InputRegIsKill = hasTrivialKill(I->getOperand(0));
  1323. unsigned ResultReg = fastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(),
  1324. Opcode, InputReg, InputRegIsKill);
  1325. if (!ResultReg)
  1326. return false;
  1327. updateValueMap(I, ResultReg);
  1328. return true;
  1329. }
  1330. bool FastISel::selectBitCast(const User *I) {
  1331. // If the bitcast doesn't change the type, just use the operand value.
  1332. if (I->getType() == I->getOperand(0)->getType()) {
  1333. unsigned Reg = getRegForValue(I->getOperand(0));
  1334. if (!Reg)
  1335. return false;
  1336. updateValueMap(I, Reg);
  1337. return true;
  1338. }
  1339. // Bitcasts of other values become reg-reg copies or BITCAST operators.
  1340. EVT SrcEVT = TLI.getValueType(DL, I->getOperand(0)->getType());
  1341. EVT DstEVT = TLI.getValueType(DL, I->getType());
  1342. if (SrcEVT == MVT::Other || DstEVT == MVT::Other ||
  1343. !TLI.isTypeLegal(SrcEVT) || !TLI.isTypeLegal(DstEVT))
  1344. // Unhandled type. Halt "fast" selection and bail.
  1345. return false;
  1346. MVT SrcVT = SrcEVT.getSimpleVT();
  1347. MVT DstVT = DstEVT.getSimpleVT();
  1348. unsigned Op0 = getRegForValue(I->getOperand(0));
  1349. if (!Op0) // Unhandled operand. Halt "fast" selection and bail.
  1350. return false;
  1351. bool Op0IsKill = hasTrivialKill(I->getOperand(0));
  1352. // First, try to perform the bitcast by inserting a reg-reg copy.
  1353. unsigned ResultReg = 0;
  1354. if (SrcVT == DstVT) {
  1355. const TargetRegisterClass *SrcClass = TLI.getRegClassFor(SrcVT);
  1356. const TargetRegisterClass *DstClass = TLI.getRegClassFor(DstVT);
  1357. // Don't attempt a cross-class copy. It will likely fail.
  1358. if (SrcClass == DstClass) {
  1359. ResultReg = createResultReg(DstClass);
  1360. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  1361. TII.get(TargetOpcode::COPY), ResultReg).addReg(Op0);
  1362. }
  1363. }
  1364. // If the reg-reg copy failed, select a BITCAST opcode.
  1365. if (!ResultReg)
  1366. ResultReg = fastEmit_r(SrcVT, DstVT, ISD::BITCAST, Op0, Op0IsKill);
  1367. if (!ResultReg)
  1368. return false;
  1369. updateValueMap(I, ResultReg);
  1370. return true;
  1371. }
  1372. // Remove local value instructions starting from the instruction after
  1373. // SavedLastLocalValue to the current function insert point.
  1374. void FastISel::removeDeadLocalValueCode(MachineInstr *SavedLastLocalValue)
  1375. {
  1376. MachineInstr *CurLastLocalValue = getLastLocalValue();
  1377. if (CurLastLocalValue != SavedLastLocalValue) {
  1378. // Find the first local value instruction to be deleted.
  1379. // This is the instruction after SavedLastLocalValue if it is non-NULL.
  1380. // Otherwise it's the first instruction in the block.
  1381. MachineBasicBlock::iterator FirstDeadInst(SavedLastLocalValue);
  1382. if (SavedLastLocalValue)
  1383. ++FirstDeadInst;
  1384. else
  1385. FirstDeadInst = FuncInfo.MBB->getFirstNonPHI();
  1386. setLastLocalValue(SavedLastLocalValue);
  1387. removeDeadCode(FirstDeadInst, FuncInfo.InsertPt);
  1388. }
  1389. }
  1390. bool FastISel::selectInstruction(const Instruction *I) {
  1391. MachineInstr *SavedLastLocalValue = getLastLocalValue();
  1392. // Just before the terminator instruction, insert instructions to
  1393. // feed PHI nodes in successor blocks.
  1394. if (I->isTerminator()) {
  1395. if (!handlePHINodesInSuccessorBlocks(I->getParent())) {
  1396. // PHI node handling may have generated local value instructions,
  1397. // even though it failed to handle all PHI nodes.
  1398. // We remove these instructions because SelectionDAGISel will generate
  1399. // them again.
  1400. removeDeadLocalValueCode(SavedLastLocalValue);
  1401. return false;
  1402. }
  1403. }
  1404. // FastISel does not handle any operand bundles except OB_funclet.
  1405. if (ImmutableCallSite CS = ImmutableCallSite(I))
  1406. for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i)
  1407. if (CS.getOperandBundleAt(i).getTagID() != LLVMContext::OB_funclet)
  1408. return false;
  1409. DbgLoc = I->getDebugLoc();
  1410. SavedInsertPt = FuncInfo.InsertPt;
  1411. if (const auto *Call = dyn_cast<CallInst>(I)) {
  1412. const Function *F = Call->getCalledFunction();
  1413. LibFunc Func;
  1414. // As a special case, don't handle calls to builtin library functions that
  1415. // may be translated directly to target instructions.
  1416. if (F && !F->hasLocalLinkage() && F->hasName() &&
  1417. LibInfo->getLibFunc(F->getName(), Func) &&
  1418. LibInfo->hasOptimizedCodeGen(Func))
  1419. return false;
  1420. // Don't handle Intrinsic::trap if a trap function is specified.
  1421. if (F && F->getIntrinsicID() == Intrinsic::trap &&
  1422. Call->hasFnAttr("trap-func-name"))
  1423. return false;
  1424. }
  1425. // First, try doing target-independent selection.
  1426. if (!SkipTargetIndependentISel) {
  1427. if (selectOperator(I, I->getOpcode())) {
  1428. ++NumFastIselSuccessIndependent;
  1429. DbgLoc = DebugLoc();
  1430. return true;
  1431. }
  1432. // Remove dead code.
  1433. recomputeInsertPt();
  1434. if (SavedInsertPt != FuncInfo.InsertPt)
  1435. removeDeadCode(FuncInfo.InsertPt, SavedInsertPt);
  1436. SavedInsertPt = FuncInfo.InsertPt;
  1437. }
  1438. // Next, try calling the target to attempt to handle the instruction.
  1439. if (fastSelectInstruction(I)) {
  1440. ++NumFastIselSuccessTarget;
  1441. DbgLoc = DebugLoc();
  1442. return true;
  1443. }
  1444. // Remove dead code.
  1445. recomputeInsertPt();
  1446. if (SavedInsertPt != FuncInfo.InsertPt)
  1447. removeDeadCode(FuncInfo.InsertPt, SavedInsertPt);
  1448. DbgLoc = DebugLoc();
  1449. // Undo phi node updates, because they will be added again by SelectionDAG.
  1450. if (I->isTerminator()) {
  1451. // PHI node handling may have generated local value instructions.
  1452. // We remove them because SelectionDAGISel will generate them again.
  1453. removeDeadLocalValueCode(SavedLastLocalValue);
  1454. FuncInfo.PHINodesToUpdate.resize(FuncInfo.OrigNumPHINodesToUpdate);
  1455. }
  1456. return false;
  1457. }
  1458. /// Emit an unconditional branch to the given block, unless it is the immediate
  1459. /// (fall-through) successor, and update the CFG.
  1460. void FastISel::fastEmitBranch(MachineBasicBlock *MSucc,
  1461. const DebugLoc &DbgLoc) {
  1462. if (FuncInfo.MBB->getBasicBlock()->sizeWithoutDebug() > 1 &&
  1463. FuncInfo.MBB->isLayoutSuccessor(MSucc)) {
  1464. // For more accurate line information if this is the only non-debug
  1465. // instruction in the block then emit it, otherwise we have the
  1466. // unconditional fall-through case, which needs no instructions.
  1467. } else {
  1468. // The unconditional branch case.
  1469. TII.insertBranch(*FuncInfo.MBB, MSucc, nullptr,
  1470. SmallVector<MachineOperand, 0>(), DbgLoc);
  1471. }
  1472. if (FuncInfo.BPI) {
  1473. auto BranchProbability = FuncInfo.BPI->getEdgeProbability(
  1474. FuncInfo.MBB->getBasicBlock(), MSucc->getBasicBlock());
  1475. FuncInfo.MBB->addSuccessor(MSucc, BranchProbability);
  1476. } else
  1477. FuncInfo.MBB->addSuccessorWithoutProb(MSucc);
  1478. }
  1479. void FastISel::finishCondBranch(const BasicBlock *BranchBB,
  1480. MachineBasicBlock *TrueMBB,
  1481. MachineBasicBlock *FalseMBB) {
  1482. // Add TrueMBB as successor unless it is equal to the FalseMBB: This can
  1483. // happen in degenerate IR and MachineIR forbids to have a block twice in the
  1484. // successor/predecessor lists.
  1485. if (TrueMBB != FalseMBB) {
  1486. if (FuncInfo.BPI) {
  1487. auto BranchProbability =
  1488. FuncInfo.BPI->getEdgeProbability(BranchBB, TrueMBB->getBasicBlock());
  1489. FuncInfo.MBB->addSuccessor(TrueMBB, BranchProbability);
  1490. } else
  1491. FuncInfo.MBB->addSuccessorWithoutProb(TrueMBB);
  1492. }
  1493. fastEmitBranch(FalseMBB, DbgLoc);
  1494. }
  1495. /// Emit an FNeg operation.
  1496. bool FastISel::selectFNeg(const User *I, const Value *In) {
  1497. unsigned OpReg = getRegForValue(In);
  1498. if (!OpReg)
  1499. return false;
  1500. bool OpRegIsKill = hasTrivialKill(In);
  1501. // If the target has ISD::FNEG, use it.
  1502. EVT VT = TLI.getValueType(DL, I->getType());
  1503. unsigned ResultReg = fastEmit_r(VT.getSimpleVT(), VT.getSimpleVT(), ISD::FNEG,
  1504. OpReg, OpRegIsKill);
  1505. if (ResultReg) {
  1506. updateValueMap(I, ResultReg);
  1507. return true;
  1508. }
  1509. // Bitcast the value to integer, twiddle the sign bit with xor,
  1510. // and then bitcast it back to floating-point.
  1511. if (VT.getSizeInBits() > 64)
  1512. return false;
  1513. EVT IntVT = EVT::getIntegerVT(I->getContext(), VT.getSizeInBits());
  1514. if (!TLI.isTypeLegal(IntVT))
  1515. return false;
  1516. unsigned IntReg = fastEmit_r(VT.getSimpleVT(), IntVT.getSimpleVT(),
  1517. ISD::BITCAST, OpReg, OpRegIsKill);
  1518. if (!IntReg)
  1519. return false;
  1520. unsigned IntResultReg = fastEmit_ri_(
  1521. IntVT.getSimpleVT(), ISD::XOR, IntReg, /*IsKill=*/true,
  1522. UINT64_C(1) << (VT.getSizeInBits() - 1), IntVT.getSimpleVT());
  1523. if (!IntResultReg)
  1524. return false;
  1525. ResultReg = fastEmit_r(IntVT.getSimpleVT(), VT.getSimpleVT(), ISD::BITCAST,
  1526. IntResultReg, /*IsKill=*/true);
  1527. if (!ResultReg)
  1528. return false;
  1529. updateValueMap(I, ResultReg);
  1530. return true;
  1531. }
  1532. bool FastISel::selectExtractValue(const User *U) {
  1533. const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(U);
  1534. if (!EVI)
  1535. return false;
  1536. // Make sure we only try to handle extracts with a legal result. But also
  1537. // allow i1 because it's easy.
  1538. EVT RealVT = TLI.getValueType(DL, EVI->getType(), /*AllowUnknown=*/true);
  1539. if (!RealVT.isSimple())
  1540. return false;
  1541. MVT VT = RealVT.getSimpleVT();
  1542. if (!TLI.isTypeLegal(VT) && VT != MVT::i1)
  1543. return false;
  1544. const Value *Op0 = EVI->getOperand(0);
  1545. Type *AggTy = Op0->getType();
  1546. // Get the base result register.
  1547. unsigned ResultReg;
  1548. DenseMap<const Value *, unsigned>::iterator I = FuncInfo.ValueMap.find(Op0);
  1549. if (I != FuncInfo.ValueMap.end())
  1550. ResultReg = I->second;
  1551. else if (isa<Instruction>(Op0))
  1552. ResultReg = FuncInfo.InitializeRegForValue(Op0);
  1553. else
  1554. return false; // fast-isel can't handle aggregate constants at the moment
  1555. // Get the actual result register, which is an offset from the base register.
  1556. unsigned VTIndex = ComputeLinearIndex(AggTy, EVI->getIndices());
  1557. SmallVector<EVT, 4> AggValueVTs;
  1558. ComputeValueVTs(TLI, DL, AggTy, AggValueVTs);
  1559. for (unsigned i = 0; i < VTIndex; i++)
  1560. ResultReg += TLI.getNumRegisters(FuncInfo.Fn->getContext(), AggValueVTs[i]);
  1561. updateValueMap(EVI, ResultReg);
  1562. return true;
  1563. }
  1564. bool FastISel::selectOperator(const User *I, unsigned Opcode) {
  1565. switch (Opcode) {
  1566. case Instruction::Add:
  1567. return selectBinaryOp(I, ISD::ADD);
  1568. case Instruction::FAdd:
  1569. return selectBinaryOp(I, ISD::FADD);
  1570. case Instruction::Sub:
  1571. return selectBinaryOp(I, ISD::SUB);
  1572. case Instruction::FSub: {
  1573. // FNeg is currently represented in LLVM IR as a special case of FSub.
  1574. Value *X;
  1575. if (match(I, m_FNeg(m_Value(X))))
  1576. return selectFNeg(I, X);
  1577. return selectBinaryOp(I, ISD::FSUB);
  1578. }
  1579. case Instruction::Mul:
  1580. return selectBinaryOp(I, ISD::MUL);
  1581. case Instruction::FMul:
  1582. return selectBinaryOp(I, ISD::FMUL);
  1583. case Instruction::SDiv:
  1584. return selectBinaryOp(I, ISD::SDIV);
  1585. case Instruction::UDiv:
  1586. return selectBinaryOp(I, ISD::UDIV);
  1587. case Instruction::FDiv:
  1588. return selectBinaryOp(I, ISD::FDIV);
  1589. case Instruction::SRem:
  1590. return selectBinaryOp(I, ISD::SREM);
  1591. case Instruction::URem:
  1592. return selectBinaryOp(I, ISD::UREM);
  1593. case Instruction::FRem:
  1594. return selectBinaryOp(I, ISD::FREM);
  1595. case Instruction::Shl:
  1596. return selectBinaryOp(I, ISD::SHL);
  1597. case Instruction::LShr:
  1598. return selectBinaryOp(I, ISD::SRL);
  1599. case Instruction::AShr:
  1600. return selectBinaryOp(I, ISD::SRA);
  1601. case Instruction::And:
  1602. return selectBinaryOp(I, ISD::AND);
  1603. case Instruction::Or:
  1604. return selectBinaryOp(I, ISD::OR);
  1605. case Instruction::Xor:
  1606. return selectBinaryOp(I, ISD::XOR);
  1607. case Instruction::FNeg:
  1608. return selectFNeg(I, I->getOperand(0));
  1609. case Instruction::GetElementPtr:
  1610. return selectGetElementPtr(I);
  1611. case Instruction::Br: {
  1612. const BranchInst *BI = cast<BranchInst>(I);
  1613. if (BI->isUnconditional()) {
  1614. const BasicBlock *LLVMSucc = BI->getSuccessor(0);
  1615. MachineBasicBlock *MSucc = FuncInfo.MBBMap[LLVMSucc];
  1616. fastEmitBranch(MSucc, BI->getDebugLoc());
  1617. return true;
  1618. }
  1619. // Conditional branches are not handed yet.
  1620. // Halt "fast" selection and bail.
  1621. return false;
  1622. }
  1623. case Instruction::Unreachable:
  1624. if (TM.Options.TrapUnreachable)
  1625. return fastEmit_(MVT::Other, MVT::Other, ISD::TRAP) != 0;
  1626. else
  1627. return true;
  1628. case Instruction::Alloca:
  1629. // FunctionLowering has the static-sized case covered.
  1630. if (FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(I)))
  1631. return true;
  1632. // Dynamic-sized alloca is not handled yet.
  1633. return false;
  1634. case Instruction::Call:
  1635. // On AIX, call lowering uses the DAG-ISEL path currently so that the
  1636. // callee of the direct function call instruction will be mapped to the
  1637. // symbol for the function's entry point, which is distinct from the
  1638. // function descriptor symbol. The latter is the symbol whose XCOFF symbol
  1639. // name is the C-linkage name of the source level function.
  1640. if (TM.getTargetTriple().isOSAIX())
  1641. return false;
  1642. return selectCall(I);
  1643. case Instruction::BitCast:
  1644. return selectBitCast(I);
  1645. case Instruction::FPToSI:
  1646. return selectCast(I, ISD::FP_TO_SINT);
  1647. case Instruction::ZExt:
  1648. return selectCast(I, ISD::ZERO_EXTEND);
  1649. case Instruction::SExt:
  1650. return selectCast(I, ISD::SIGN_EXTEND);
  1651. case Instruction::Trunc:
  1652. return selectCast(I, ISD::TRUNCATE);
  1653. case Instruction::SIToFP:
  1654. return selectCast(I, ISD::SINT_TO_FP);
  1655. case Instruction::IntToPtr: // Deliberate fall-through.
  1656. case Instruction::PtrToInt: {
  1657. EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType());
  1658. EVT DstVT = TLI.getValueType(DL, I->getType());
  1659. if (DstVT.bitsGT(SrcVT))
  1660. return selectCast(I, ISD::ZERO_EXTEND);
  1661. if (DstVT.bitsLT(SrcVT))
  1662. return selectCast(I, ISD::TRUNCATE);
  1663. unsigned Reg = getRegForValue(I->getOperand(0));
  1664. if (!Reg)
  1665. return false;
  1666. updateValueMap(I, Reg);
  1667. return true;
  1668. }
  1669. case Instruction::ExtractValue:
  1670. return selectExtractValue(I);
  1671. case Instruction::PHI:
  1672. llvm_unreachable("FastISel shouldn't visit PHI nodes!");
  1673. default:
  1674. // Unhandled instruction. Halt "fast" selection and bail.
  1675. return false;
  1676. }
  1677. }
  1678. FastISel::FastISel(FunctionLoweringInfo &FuncInfo,
  1679. const TargetLibraryInfo *LibInfo,
  1680. bool SkipTargetIndependentISel)
  1681. : FuncInfo(FuncInfo), MF(FuncInfo.MF), MRI(FuncInfo.MF->getRegInfo()),
  1682. MFI(FuncInfo.MF->getFrameInfo()), MCP(*FuncInfo.MF->getConstantPool()),
  1683. TM(FuncInfo.MF->getTarget()), DL(MF->getDataLayout()),
  1684. TII(*MF->getSubtarget().getInstrInfo()),
  1685. TLI(*MF->getSubtarget().getTargetLowering()),
  1686. TRI(*MF->getSubtarget().getRegisterInfo()), LibInfo(LibInfo),
  1687. SkipTargetIndependentISel(SkipTargetIndependentISel) {}
  1688. FastISel::~FastISel() = default;
  1689. bool FastISel::fastLowerArguments() { return false; }
  1690. bool FastISel::fastLowerCall(CallLoweringInfo & /*CLI*/) { return false; }
  1691. bool FastISel::fastLowerIntrinsicCall(const IntrinsicInst * /*II*/) {
  1692. return false;
  1693. }
  1694. unsigned FastISel::fastEmit_(MVT, MVT, unsigned) { return 0; }
  1695. unsigned FastISel::fastEmit_r(MVT, MVT, unsigned, unsigned /*Op0*/,
  1696. bool /*Op0IsKill*/) {
  1697. return 0;
  1698. }
  1699. unsigned FastISel::fastEmit_rr(MVT, MVT, unsigned, unsigned /*Op0*/,
  1700. bool /*Op0IsKill*/, unsigned /*Op1*/,
  1701. bool /*Op1IsKill*/) {
  1702. return 0;
  1703. }
  1704. unsigned FastISel::fastEmit_i(MVT, MVT, unsigned, uint64_t /*Imm*/) {
  1705. return 0;
  1706. }
  1707. unsigned FastISel::fastEmit_f(MVT, MVT, unsigned,
  1708. const ConstantFP * /*FPImm*/) {
  1709. return 0;
  1710. }
  1711. unsigned FastISel::fastEmit_ri(MVT, MVT, unsigned, unsigned /*Op0*/,
  1712. bool /*Op0IsKill*/, uint64_t /*Imm*/) {
  1713. return 0;
  1714. }
  1715. /// This method is a wrapper of fastEmit_ri. It first tries to emit an
  1716. /// instruction with an immediate operand using fastEmit_ri.
  1717. /// If that fails, it materializes the immediate into a register and try
  1718. /// fastEmit_rr instead.
  1719. unsigned FastISel::fastEmit_ri_(MVT VT, unsigned Opcode, unsigned Op0,
  1720. bool Op0IsKill, uint64_t Imm, MVT ImmType) {
  1721. // If this is a multiply by a power of two, emit this as a shift left.
  1722. if (Opcode == ISD::MUL && isPowerOf2_64(Imm)) {
  1723. Opcode = ISD::SHL;
  1724. Imm = Log2_64(Imm);
  1725. } else if (Opcode == ISD::UDIV && isPowerOf2_64(Imm)) {
  1726. // div x, 8 -> srl x, 3
  1727. Opcode = ISD::SRL;
  1728. Imm = Log2_64(Imm);
  1729. }
  1730. // Horrible hack (to be removed), check to make sure shift amounts are
  1731. // in-range.
  1732. if ((Opcode == ISD::SHL || Opcode == ISD::SRA || Opcode == ISD::SRL) &&
  1733. Imm >= VT.getSizeInBits())
  1734. return 0;
  1735. // First check if immediate type is legal. If not, we can't use the ri form.
  1736. unsigned ResultReg = fastEmit_ri(VT, VT, Opcode, Op0, Op0IsKill, Imm);
  1737. if (ResultReg)
  1738. return ResultReg;
  1739. unsigned MaterialReg = fastEmit_i(ImmType, ImmType, ISD::Constant, Imm);
  1740. bool IsImmKill = true;
  1741. if (!MaterialReg) {
  1742. // This is a bit ugly/slow, but failing here means falling out of
  1743. // fast-isel, which would be very slow.
  1744. IntegerType *ITy =
  1745. IntegerType::get(FuncInfo.Fn->getContext(), VT.getSizeInBits());
  1746. MaterialReg = getRegForValue(ConstantInt::get(ITy, Imm));
  1747. if (!MaterialReg)
  1748. return 0;
  1749. // FIXME: If the materialized register here has no uses yet then this
  1750. // will be the first use and we should be able to mark it as killed.
  1751. // However, the local value area for materialising constant expressions
  1752. // grows down, not up, which means that any constant expressions we generate
  1753. // later which also use 'Imm' could be after this instruction and therefore
  1754. // after this kill.
  1755. IsImmKill = false;
  1756. }
  1757. return fastEmit_rr(VT, VT, Opcode, Op0, Op0IsKill, MaterialReg, IsImmKill);
  1758. }
  1759. unsigned FastISel::createResultReg(const TargetRegisterClass *RC) {
  1760. return MRI.createVirtualRegister(RC);
  1761. }
  1762. unsigned FastISel::constrainOperandRegClass(const MCInstrDesc &II, unsigned Op,
  1763. unsigned OpNum) {
  1764. if (Register::isVirtualRegister(Op)) {
  1765. const TargetRegisterClass *RegClass =
  1766. TII.getRegClass(II, OpNum, &TRI, *FuncInfo.MF);
  1767. if (!MRI.constrainRegClass(Op, RegClass)) {
  1768. // If it's not legal to COPY between the register classes, something
  1769. // has gone very wrong before we got here.
  1770. unsigned NewOp = createResultReg(RegClass);
  1771. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  1772. TII.get(TargetOpcode::COPY), NewOp).addReg(Op);
  1773. return NewOp;
  1774. }
  1775. }
  1776. return Op;
  1777. }
  1778. unsigned FastISel::fastEmitInst_(unsigned MachineInstOpcode,
  1779. const TargetRegisterClass *RC) {
  1780. unsigned ResultReg = createResultReg(RC);
  1781. const MCInstrDesc &II = TII.get(MachineInstOpcode);
  1782. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg);
  1783. return ResultReg;
  1784. }
  1785. unsigned FastISel::fastEmitInst_r(unsigned MachineInstOpcode,
  1786. const TargetRegisterClass *RC, unsigned Op0,
  1787. bool Op0IsKill) {
  1788. const MCInstrDesc &II = TII.get(MachineInstOpcode);
  1789. unsigned ResultReg = createResultReg(RC);
  1790. Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs());
  1791. if (II.getNumDefs() >= 1)
  1792. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
  1793. .addReg(Op0, getKillRegState(Op0IsKill));
  1794. else {
  1795. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
  1796. .addReg(Op0, getKillRegState(Op0IsKill));
  1797. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  1798. TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
  1799. }
  1800. return ResultReg;
  1801. }
  1802. unsigned FastISel::fastEmitInst_rr(unsigned MachineInstOpcode,
  1803. const TargetRegisterClass *RC, unsigned Op0,
  1804. bool Op0IsKill, unsigned Op1,
  1805. bool Op1IsKill) {
  1806. const MCInstrDesc &II = TII.get(MachineInstOpcode);
  1807. unsigned ResultReg = createResultReg(RC);
  1808. Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs());
  1809. Op1 = constrainOperandRegClass(II, Op1, II.getNumDefs() + 1);
  1810. if (II.getNumDefs() >= 1)
  1811. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
  1812. .addReg(Op0, getKillRegState(Op0IsKill))
  1813. .addReg(Op1, getKillRegState(Op1IsKill));
  1814. else {
  1815. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
  1816. .addReg(Op0, getKillRegState(Op0IsKill))
  1817. .addReg(Op1, getKillRegState(Op1IsKill));
  1818. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  1819. TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
  1820. }
  1821. return ResultReg;
  1822. }
  1823. unsigned FastISel::fastEmitInst_rrr(unsigned MachineInstOpcode,
  1824. const TargetRegisterClass *RC, unsigned Op0,
  1825. bool Op0IsKill, unsigned Op1,
  1826. bool Op1IsKill, unsigned Op2,
  1827. bool Op2IsKill) {
  1828. const MCInstrDesc &II = TII.get(MachineInstOpcode);
  1829. unsigned ResultReg = createResultReg(RC);
  1830. Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs());
  1831. Op1 = constrainOperandRegClass(II, Op1, II.getNumDefs() + 1);
  1832. Op2 = constrainOperandRegClass(II, Op2, II.getNumDefs() + 2);
  1833. if (II.getNumDefs() >= 1)
  1834. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
  1835. .addReg(Op0, getKillRegState(Op0IsKill))
  1836. .addReg(Op1, getKillRegState(Op1IsKill))
  1837. .addReg(Op2, getKillRegState(Op2IsKill));
  1838. else {
  1839. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
  1840. .addReg(Op0, getKillRegState(Op0IsKill))
  1841. .addReg(Op1, getKillRegState(Op1IsKill))
  1842. .addReg(Op2, getKillRegState(Op2IsKill));
  1843. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  1844. TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
  1845. }
  1846. return ResultReg;
  1847. }
  1848. unsigned FastISel::fastEmitInst_ri(unsigned MachineInstOpcode,
  1849. const TargetRegisterClass *RC, unsigned Op0,
  1850. bool Op0IsKill, uint64_t Imm) {
  1851. const MCInstrDesc &II = TII.get(MachineInstOpcode);
  1852. unsigned ResultReg = createResultReg(RC);
  1853. Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs());
  1854. if (II.getNumDefs() >= 1)
  1855. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
  1856. .addReg(Op0, getKillRegState(Op0IsKill))
  1857. .addImm(Imm);
  1858. else {
  1859. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
  1860. .addReg(Op0, getKillRegState(Op0IsKill))
  1861. .addImm(Imm);
  1862. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  1863. TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
  1864. }
  1865. return ResultReg;
  1866. }
  1867. unsigned FastISel::fastEmitInst_rii(unsigned MachineInstOpcode,
  1868. const TargetRegisterClass *RC, unsigned Op0,
  1869. bool Op0IsKill, uint64_t Imm1,
  1870. uint64_t Imm2) {
  1871. const MCInstrDesc &II = TII.get(MachineInstOpcode);
  1872. unsigned ResultReg = createResultReg(RC);
  1873. Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs());
  1874. if (II.getNumDefs() >= 1)
  1875. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
  1876. .addReg(Op0, getKillRegState(Op0IsKill))
  1877. .addImm(Imm1)
  1878. .addImm(Imm2);
  1879. else {
  1880. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
  1881. .addReg(Op0, getKillRegState(Op0IsKill))
  1882. .addImm(Imm1)
  1883. .addImm(Imm2);
  1884. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  1885. TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
  1886. }
  1887. return ResultReg;
  1888. }
  1889. unsigned FastISel::fastEmitInst_f(unsigned MachineInstOpcode,
  1890. const TargetRegisterClass *RC,
  1891. const ConstantFP *FPImm) {
  1892. const MCInstrDesc &II = TII.get(MachineInstOpcode);
  1893. unsigned ResultReg = createResultReg(RC);
  1894. if (II.getNumDefs() >= 1)
  1895. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
  1896. .addFPImm(FPImm);
  1897. else {
  1898. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
  1899. .addFPImm(FPImm);
  1900. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  1901. TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
  1902. }
  1903. return ResultReg;
  1904. }
  1905. unsigned FastISel::fastEmitInst_rri(unsigned MachineInstOpcode,
  1906. const TargetRegisterClass *RC, unsigned Op0,
  1907. bool Op0IsKill, unsigned Op1,
  1908. bool Op1IsKill, uint64_t Imm) {
  1909. const MCInstrDesc &II = TII.get(MachineInstOpcode);
  1910. unsigned ResultReg = createResultReg(RC);
  1911. Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs());
  1912. Op1 = constrainOperandRegClass(II, Op1, II.getNumDefs() + 1);
  1913. if (II.getNumDefs() >= 1)
  1914. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
  1915. .addReg(Op0, getKillRegState(Op0IsKill))
  1916. .addReg(Op1, getKillRegState(Op1IsKill))
  1917. .addImm(Imm);
  1918. else {
  1919. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
  1920. .addReg(Op0, getKillRegState(Op0IsKill))
  1921. .addReg(Op1, getKillRegState(Op1IsKill))
  1922. .addImm(Imm);
  1923. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  1924. TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
  1925. }
  1926. return ResultReg;
  1927. }
  1928. unsigned FastISel::fastEmitInst_i(unsigned MachineInstOpcode,
  1929. const TargetRegisterClass *RC, uint64_t Imm) {
  1930. unsigned ResultReg = createResultReg(RC);
  1931. const MCInstrDesc &II = TII.get(MachineInstOpcode);
  1932. if (II.getNumDefs() >= 1)
  1933. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
  1934. .addImm(Imm);
  1935. else {
  1936. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II).addImm(Imm);
  1937. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  1938. TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
  1939. }
  1940. return ResultReg;
  1941. }
  1942. unsigned FastISel::fastEmitInst_extractsubreg(MVT RetVT, unsigned Op0,
  1943. bool Op0IsKill, uint32_t Idx) {
  1944. unsigned ResultReg = createResultReg(TLI.getRegClassFor(RetVT));
  1945. assert(Register::isVirtualRegister(Op0) &&
  1946. "Cannot yet extract from physregs");
  1947. const TargetRegisterClass *RC = MRI.getRegClass(Op0);
  1948. MRI.constrainRegClass(Op0, TRI.getSubClassWithSubReg(RC, Idx));
  1949. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
  1950. ResultReg).addReg(Op0, getKillRegState(Op0IsKill), Idx);
  1951. return ResultReg;
  1952. }
  1953. /// Emit MachineInstrs to compute the value of Op with all but the least
  1954. /// significant bit set to zero.
  1955. unsigned FastISel::fastEmitZExtFromI1(MVT VT, unsigned Op0, bool Op0IsKill) {
  1956. return fastEmit_ri(VT, VT, ISD::AND, Op0, Op0IsKill, 1);
  1957. }
  1958. /// HandlePHINodesInSuccessorBlocks - Handle PHI nodes in successor blocks.
  1959. /// Emit code to ensure constants are copied into registers when needed.
  1960. /// Remember the virtual registers that need to be added to the Machine PHI
  1961. /// nodes as input. We cannot just directly add them, because expansion
  1962. /// might result in multiple MBB's for one BB. As such, the start of the
  1963. /// BB might correspond to a different MBB than the end.
  1964. bool FastISel::handlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
  1965. const Instruction *TI = LLVMBB->getTerminator();
  1966. SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
  1967. FuncInfo.OrigNumPHINodesToUpdate = FuncInfo.PHINodesToUpdate.size();
  1968. // Check successor nodes' PHI nodes that expect a constant to be available
  1969. // from this block.
  1970. for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
  1971. const BasicBlock *SuccBB = TI->getSuccessor(succ);
  1972. if (!isa<PHINode>(SuccBB->begin()))
  1973. continue;
  1974. MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
  1975. // If this terminator has multiple identical successors (common for
  1976. // switches), only handle each succ once.
  1977. if (!SuccsHandled.insert(SuccMBB).second)
  1978. continue;
  1979. MachineBasicBlock::iterator MBBI = SuccMBB->begin();
  1980. // At this point we know that there is a 1-1 correspondence between LLVM PHI
  1981. // nodes and Machine PHI nodes, but the incoming operands have not been
  1982. // emitted yet.
  1983. for (const PHINode &PN : SuccBB->phis()) {
  1984. // Ignore dead phi's.
  1985. if (PN.use_empty())
  1986. continue;
  1987. // Only handle legal types. Two interesting things to note here. First,
  1988. // by bailing out early, we may leave behind some dead instructions,
  1989. // since SelectionDAG's HandlePHINodesInSuccessorBlocks will insert its
  1990. // own moves. Second, this check is necessary because FastISel doesn't
  1991. // use CreateRegs to create registers, so it always creates
  1992. // exactly one register for each non-void instruction.
  1993. EVT VT = TLI.getValueType(DL, PN.getType(), /*AllowUnknown=*/true);
  1994. if (VT == MVT::Other || !TLI.isTypeLegal(VT)) {
  1995. // Handle integer promotions, though, because they're common and easy.
  1996. if (!(VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16)) {
  1997. FuncInfo.PHINodesToUpdate.resize(FuncInfo.OrigNumPHINodesToUpdate);
  1998. return false;
  1999. }
  2000. }
  2001. const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
  2002. // Set the DebugLoc for the copy. Prefer the location of the operand
  2003. // if there is one; use the location of the PHI otherwise.
  2004. DbgLoc = PN.getDebugLoc();
  2005. if (const auto *Inst = dyn_cast<Instruction>(PHIOp))
  2006. DbgLoc = Inst->getDebugLoc();
  2007. unsigned Reg = getRegForValue(PHIOp);
  2008. if (!Reg) {
  2009. FuncInfo.PHINodesToUpdate.resize(FuncInfo.OrigNumPHINodesToUpdate);
  2010. return false;
  2011. }
  2012. FuncInfo.PHINodesToUpdate.push_back(std::make_pair(&*MBBI++, Reg));
  2013. DbgLoc = DebugLoc();
  2014. }
  2015. }
  2016. return true;
  2017. }
  2018. bool FastISel::tryToFoldLoad(const LoadInst *LI, const Instruction *FoldInst) {
  2019. assert(LI->hasOneUse() &&
  2020. "tryToFoldLoad expected a LoadInst with a single use");
  2021. // We know that the load has a single use, but don't know what it is. If it
  2022. // isn't one of the folded instructions, then we can't succeed here. Handle
  2023. // this by scanning the single-use users of the load until we get to FoldInst.
  2024. unsigned MaxUsers = 6; // Don't scan down huge single-use chains of instrs.
  2025. const Instruction *TheUser = LI->user_back();
  2026. while (TheUser != FoldInst && // Scan up until we find FoldInst.
  2027. // Stay in the right block.
  2028. TheUser->getParent() == FoldInst->getParent() &&
  2029. --MaxUsers) { // Don't scan too far.
  2030. // If there are multiple or no uses of this instruction, then bail out.
  2031. if (!TheUser->hasOneUse())
  2032. return false;
  2033. TheUser = TheUser->user_back();
  2034. }
  2035. // If we didn't find the fold instruction, then we failed to collapse the
  2036. // sequence.
  2037. if (TheUser != FoldInst)
  2038. return false;
  2039. // Don't try to fold volatile loads. Target has to deal with alignment
  2040. // constraints.
  2041. if (LI->isVolatile())
  2042. return false;
  2043. // Figure out which vreg this is going into. If there is no assigned vreg yet
  2044. // then there actually was no reference to it. Perhaps the load is referenced
  2045. // by a dead instruction.
  2046. unsigned LoadReg = getRegForValue(LI);
  2047. if (!LoadReg)
  2048. return false;
  2049. // We can't fold if this vreg has no uses or more than one use. Multiple uses
  2050. // may mean that the instruction got lowered to multiple MIs, or the use of
  2051. // the loaded value ended up being multiple operands of the result.
  2052. if (!MRI.hasOneUse(LoadReg))
  2053. return false;
  2054. MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(LoadReg);
  2055. MachineInstr *User = RI->getParent();
  2056. // Set the insertion point properly. Folding the load can cause generation of
  2057. // other random instructions (like sign extends) for addressing modes; make
  2058. // sure they get inserted in a logical place before the new instruction.
  2059. FuncInfo.InsertPt = User;
  2060. FuncInfo.MBB = User->getParent();
  2061. // Ask the target to try folding the load.
  2062. return tryToFoldLoadIntoMI(User, RI.getOperandNo(), LI);
  2063. }
  2064. bool FastISel::canFoldAddIntoGEP(const User *GEP, const Value *Add) {
  2065. // Must be an add.
  2066. if (!isa<AddOperator>(Add))
  2067. return false;
  2068. // Type size needs to match.
  2069. if (DL.getTypeSizeInBits(GEP->getType()) !=
  2070. DL.getTypeSizeInBits(Add->getType()))
  2071. return false;
  2072. // Must be in the same basic block.
  2073. if (isa<Instruction>(Add) &&
  2074. FuncInfo.MBBMap[cast<Instruction>(Add)->getParent()] != FuncInfo.MBB)
  2075. return false;
  2076. // Must have a constant operand.
  2077. return isa<ConstantInt>(cast<AddOperator>(Add)->getOperand(1));
  2078. }
  2079. MachineMemOperand *
  2080. FastISel::createMachineMemOperandFor(const Instruction *I) const {
  2081. const Value *Ptr;
  2082. Type *ValTy;
  2083. unsigned Alignment;
  2084. MachineMemOperand::Flags Flags;
  2085. bool IsVolatile;
  2086. if (const auto *LI = dyn_cast<LoadInst>(I)) {
  2087. Alignment = LI->getAlignment();
  2088. IsVolatile = LI->isVolatile();
  2089. Flags = MachineMemOperand::MOLoad;
  2090. Ptr = LI->getPointerOperand();
  2091. ValTy = LI->getType();
  2092. } else if (const auto *SI = dyn_cast<StoreInst>(I)) {
  2093. Alignment = SI->getAlignment();
  2094. IsVolatile = SI->isVolatile();
  2095. Flags = MachineMemOperand::MOStore;
  2096. Ptr = SI->getPointerOperand();
  2097. ValTy = SI->getValueOperand()->getType();
  2098. } else
  2099. return nullptr;
  2100. bool IsNonTemporal = I->hasMetadata(LLVMContext::MD_nontemporal);
  2101. bool IsInvariant = I->hasMetadata(LLVMContext::MD_invariant_load);
  2102. bool IsDereferenceable = I->hasMetadata(LLVMContext::MD_dereferenceable);
  2103. const MDNode *Ranges = I->getMetadata(LLVMContext::MD_range);
  2104. AAMDNodes AAInfo;
  2105. I->getAAMetadata(AAInfo);
  2106. if (Alignment == 0) // Ensure that codegen never sees alignment 0.
  2107. Alignment = DL.getABITypeAlignment(ValTy);
  2108. unsigned Size = DL.getTypeStoreSize(ValTy);
  2109. if (IsVolatile)
  2110. Flags |= MachineMemOperand::MOVolatile;
  2111. if (IsNonTemporal)
  2112. Flags |= MachineMemOperand::MONonTemporal;
  2113. if (IsDereferenceable)
  2114. Flags |= MachineMemOperand::MODereferenceable;
  2115. if (IsInvariant)
  2116. Flags |= MachineMemOperand::MOInvariant;
  2117. return FuncInfo.MF->getMachineMemOperand(MachinePointerInfo(Ptr), Flags, Size,
  2118. Alignment, AAInfo, Ranges);
  2119. }
  2120. CmpInst::Predicate FastISel::optimizeCmpPredicate(const CmpInst *CI) const {
  2121. // If both operands are the same, then try to optimize or fold the cmp.
  2122. CmpInst::Predicate Predicate = CI->getPredicate();
  2123. if (CI->getOperand(0) != CI->getOperand(1))
  2124. return Predicate;
  2125. switch (Predicate) {
  2126. default: llvm_unreachable("Invalid predicate!");
  2127. case CmpInst::FCMP_FALSE: Predicate = CmpInst::FCMP_FALSE; break;
  2128. case CmpInst::FCMP_OEQ: Predicate = CmpInst::FCMP_ORD; break;
  2129. case CmpInst::FCMP_OGT: Predicate = CmpInst::FCMP_FALSE; break;
  2130. case CmpInst::FCMP_OGE: Predicate = CmpInst::FCMP_ORD; break;
  2131. case CmpInst::FCMP_OLT: Predicate = CmpInst::FCMP_FALSE; break;
  2132. case CmpInst::FCMP_OLE: Predicate = CmpInst::FCMP_ORD; break;
  2133. case CmpInst::FCMP_ONE: Predicate = CmpInst::FCMP_FALSE; break;
  2134. case CmpInst::FCMP_ORD: Predicate = CmpInst::FCMP_ORD; break;
  2135. case CmpInst::FCMP_UNO: Predicate = CmpInst::FCMP_UNO; break;
  2136. case CmpInst::FCMP_UEQ: Predicate = CmpInst::FCMP_TRUE; break;
  2137. case CmpInst::FCMP_UGT: Predicate = CmpInst::FCMP_UNO; break;
  2138. case CmpInst::FCMP_UGE: Predicate = CmpInst::FCMP_TRUE; break;
  2139. case CmpInst::FCMP_ULT: Predicate = CmpInst::FCMP_UNO; break;
  2140. case CmpInst::FCMP_ULE: Predicate = CmpInst::FCMP_TRUE; break;
  2141. case CmpInst::FCMP_UNE: Predicate = CmpInst::FCMP_UNO; break;
  2142. case CmpInst::FCMP_TRUE: Predicate = CmpInst::FCMP_TRUE; break;
  2143. case CmpInst::ICMP_EQ: Predicate = CmpInst::FCMP_TRUE; break;
  2144. case CmpInst::ICMP_NE: Predicate = CmpInst::FCMP_FALSE; break;
  2145. case CmpInst::ICMP_UGT: Predicate = CmpInst::FCMP_FALSE; break;
  2146. case CmpInst::ICMP_UGE: Predicate = CmpInst::FCMP_TRUE; break;
  2147. case CmpInst::ICMP_ULT: Predicate = CmpInst::FCMP_FALSE; break;
  2148. case CmpInst::ICMP_ULE: Predicate = CmpInst::FCMP_TRUE; break;
  2149. case CmpInst::ICMP_SGT: Predicate = CmpInst::FCMP_FALSE; break;
  2150. case CmpInst::ICMP_SGE: Predicate = CmpInst::FCMP_TRUE; break;
  2151. case CmpInst::ICMP_SLT: Predicate = CmpInst::FCMP_FALSE; break;
  2152. case CmpInst::ICMP_SLE: Predicate = CmpInst::FCMP_TRUE; break;
  2153. }
  2154. return Predicate;
  2155. }