FastISel.cpp 85 KB

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