FastISel.cpp 85 KB

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