1 //===-- LegalizeDAG.cpp - Implement SelectionDAG::Legalize ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the SelectionDAG::Legalize method.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Analysis/DebugInfo.h"
15 #include "llvm/CodeGen/Analysis.h"
16 #include "llvm/CodeGen/MachineFunction.h"
17 #include "llvm/CodeGen/MachineFrameInfo.h"
18 #include "llvm/CodeGen/MachineJumpTableInfo.h"
19 #include "llvm/CodeGen/MachineModuleInfo.h"
20 #include "llvm/CodeGen/PseudoSourceValue.h"
21 #include "llvm/CodeGen/SelectionDAG.h"
22 #include "llvm/Target/TargetFrameLowering.h"
23 #include "llvm/Target/TargetLowering.h"
24 #include "llvm/Target/TargetData.h"
25 #include "llvm/Target/TargetMachine.h"
26 #include "llvm/Target/TargetOptions.h"
27 #include "llvm/CallingConv.h"
28 #include "llvm/Constants.h"
29 #include "llvm/DerivedTypes.h"
30 #include "llvm/Function.h"
31 #include "llvm/GlobalVariable.h"
32 #include "llvm/LLVMContext.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/MathExtras.h"
37 #include "llvm/Support/raw_ostream.h"
38 #include "llvm/ADT/DenseMap.h"
39 #include "llvm/ADT/SmallVector.h"
40 #include "llvm/ADT/SmallPtrSet.h"
43 //===----------------------------------------------------------------------===//
44 /// SelectionDAGLegalize - This takes an arbitrary SelectionDAG as input and
45 /// hacks on it until the target machine can handle it. This involves
46 /// eliminating value sizes the machine cannot handle (promoting small sizes to
47 /// large sizes or splitting up large values into small values) as well as
48 /// eliminating operations the machine cannot handle.
50 /// This code also does a small amount of optimization and recognition of idioms
51 /// as part of its processing. For example, if a target does not support a
52 /// 'setcc' instruction efficiently, but does support 'brcc' instruction, this
53 /// will attempt merge setcc and brc instructions into brcc's.
56 class SelectionDAGLegalize {
57 const TargetMachine &TM;
58 const TargetLowering &TLI;
60 CodeGenOpt::Level OptLevel;
62 // Libcall insertion helpers.
64 /// LastCALLSEQ_END - This keeps track of the CALLSEQ_END node that has been
65 /// legalized. We use this to ensure that calls are properly serialized
66 /// against each other, including inserted libcalls.
67 SDValue LastCALLSEQ_END;
70 Legal, // The target natively supports this operation.
71 Promote, // This operation should be executed in a larger type.
72 Expand // Try to expand this to other ops, otherwise use a libcall.
75 /// ValueTypeActions - This is a bitvector that contains two bits for each
76 /// value type, where the two bits correspond to the LegalizeAction enum.
77 /// This can be queried with "getTypeAction(VT)".
78 TargetLowering::ValueTypeActionImpl ValueTypeActions;
80 /// LegalizedNodes - For nodes that are of legal width, and that have more
81 /// than one use, this map indicates what regularized operand to use. This
82 /// allows us to avoid legalizing the same thing more than once.
83 DenseMap<SDValue, SDValue> LegalizedNodes;
85 void AddLegalizedOperand(SDValue From, SDValue To) {
86 LegalizedNodes.insert(std::make_pair(From, To));
87 // If someone requests legalization of the new node, return itself.
89 LegalizedNodes.insert(std::make_pair(To, To));
91 // Transfer SDDbgValues.
92 DAG.TransferDbgValues(From, To);
96 SelectionDAGLegalize(SelectionDAG &DAG, CodeGenOpt::Level ol);
98 /// getTypeAction - Return how we should legalize values of this type, either
99 /// it is already legal or we need to expand it into multiple registers of
100 /// smaller integer type, or we need to promote it to a larger type.
101 LegalizeAction getTypeAction(EVT VT) const {
102 return (LegalizeAction)ValueTypeActions.getTypeAction(VT);
105 /// isTypeLegal - Return true if this type is legal on this target.
107 bool isTypeLegal(EVT VT) const {
108 return getTypeAction(VT) == Legal;
114 /// LegalizeOp - We know that the specified value has a legal type.
115 /// Recursively ensure that the operands have legal types, then return the
117 SDValue LegalizeOp(SDValue O);
119 SDValue OptimizeFloatStore(StoreSDNode *ST);
121 /// PerformInsertVectorEltInMemory - Some target cannot handle a variable
122 /// insertion index for the INSERT_VECTOR_ELT instruction. In this case, it
123 /// is necessary to spill the vector being inserted into to memory, perform
124 /// the insert there, and then read the result back.
125 SDValue PerformInsertVectorEltInMemory(SDValue Vec, SDValue Val,
126 SDValue Idx, DebugLoc dl);
127 SDValue ExpandINSERT_VECTOR_ELT(SDValue Vec, SDValue Val,
128 SDValue Idx, DebugLoc dl);
130 /// ShuffleWithNarrowerEltType - Return a vector shuffle operation which
131 /// performs the same shuffe in terms of order or result bytes, but on a type
132 /// whose vector element type is narrower than the original shuffle type.
133 /// e.g. <v4i32> <0, 1, 0, 1> -> v8i16 <0, 1, 2, 3, 0, 1, 2, 3>
134 SDValue ShuffleWithNarrowerEltType(EVT NVT, EVT VT, DebugLoc dl,
135 SDValue N1, SDValue N2,
136 SmallVectorImpl<int> &Mask) const;
138 bool LegalizeAllNodesNotLeadingTo(SDNode *N, SDNode *Dest,
139 SmallPtrSet<SDNode*, 32> &NodesLeadingTo);
141 void LegalizeSetCCCondCode(EVT VT, SDValue &LHS, SDValue &RHS, SDValue &CC,
144 SDValue ExpandLibCall(RTLIB::Libcall LC, SDNode *Node, bool isSigned);
145 std::pair<SDValue, SDValue> ExpandChainLibCall(RTLIB::Libcall LC,
146 SDNode *Node, bool isSigned);
147 SDValue ExpandFPLibCall(SDNode *Node, RTLIB::Libcall Call_F32,
148 RTLIB::Libcall Call_F64, RTLIB::Libcall Call_F80,
149 RTLIB::Libcall Call_PPCF128);
150 SDValue ExpandIntLibCall(SDNode *Node, bool isSigned,
151 RTLIB::Libcall Call_I8,
152 RTLIB::Libcall Call_I16,
153 RTLIB::Libcall Call_I32,
154 RTLIB::Libcall Call_I64,
155 RTLIB::Libcall Call_I128);
157 SDValue EmitStackConvert(SDValue SrcOp, EVT SlotVT, EVT DestVT, DebugLoc dl);
158 SDValue ExpandBUILD_VECTOR(SDNode *Node);
159 SDValue ExpandSCALAR_TO_VECTOR(SDNode *Node);
160 void ExpandDYNAMIC_STACKALLOC(SDNode *Node,
161 SmallVectorImpl<SDValue> &Results);
162 SDValue ExpandFCOPYSIGN(SDNode *Node);
163 SDValue ExpandLegalINT_TO_FP(bool isSigned, SDValue LegalOp, EVT DestVT,
165 SDValue PromoteLegalINT_TO_FP(SDValue LegalOp, EVT DestVT, bool isSigned,
167 SDValue PromoteLegalFP_TO_INT(SDValue LegalOp, EVT DestVT, bool isSigned,
170 SDValue ExpandBSWAP(SDValue Op, DebugLoc dl);
171 SDValue ExpandBitCount(unsigned Opc, SDValue Op, DebugLoc dl);
173 SDValue ExpandExtractFromVectorThroughStack(SDValue Op);
174 SDValue ExpandVectorBuildThroughStack(SDNode* Node);
176 std::pair<SDValue, SDValue> ExpandAtomic(SDNode *Node);
178 void ExpandNode(SDNode *Node, SmallVectorImpl<SDValue> &Results);
179 void PromoteNode(SDNode *Node, SmallVectorImpl<SDValue> &Results);
183 /// ShuffleWithNarrowerEltType - Return a vector shuffle operation which
184 /// performs the same shuffe in terms of order or result bytes, but on a type
185 /// whose vector element type is narrower than the original shuffle type.
186 /// e.g. <v4i32> <0, 1, 0, 1> -> v8i16 <0, 1, 2, 3, 0, 1, 2, 3>
188 SelectionDAGLegalize::ShuffleWithNarrowerEltType(EVT NVT, EVT VT, DebugLoc dl,
189 SDValue N1, SDValue N2,
190 SmallVectorImpl<int> &Mask) const {
191 unsigned NumMaskElts = VT.getVectorNumElements();
192 unsigned NumDestElts = NVT.getVectorNumElements();
193 unsigned NumEltsGrowth = NumDestElts / NumMaskElts;
195 assert(NumEltsGrowth && "Cannot promote to vector type with fewer elts!");
197 if (NumEltsGrowth == 1)
198 return DAG.getVectorShuffle(NVT, dl, N1, N2, &Mask[0]);
200 SmallVector<int, 8> NewMask;
201 for (unsigned i = 0; i != NumMaskElts; ++i) {
203 for (unsigned j = 0; j != NumEltsGrowth; ++j) {
205 NewMask.push_back(-1);
207 NewMask.push_back(Idx * NumEltsGrowth + j);
210 assert(NewMask.size() == NumDestElts && "Non-integer NumEltsGrowth?");
211 assert(TLI.isShuffleMaskLegal(NewMask, NVT) && "Shuffle not legal?");
212 return DAG.getVectorShuffle(NVT, dl, N1, N2, &NewMask[0]);
215 SelectionDAGLegalize::SelectionDAGLegalize(SelectionDAG &dag,
216 CodeGenOpt::Level ol)
217 : TM(dag.getTarget()), TLI(dag.getTargetLoweringInfo()),
218 DAG(dag), OptLevel(ol),
219 ValueTypeActions(TLI.getValueTypeActions()) {
220 assert(MVT::LAST_VALUETYPE <= MVT::MAX_ALLOWED_VALUETYPE &&
221 "Too many value types for ValueTypeActions to hold!");
224 void SelectionDAGLegalize::LegalizeDAG() {
225 LastCALLSEQ_END = DAG.getEntryNode();
227 // The legalize process is inherently a bottom-up recursive process (users
228 // legalize their uses before themselves). Given infinite stack space, we
229 // could just start legalizing on the root and traverse the whole graph. In
230 // practice however, this causes us to run out of stack space on large basic
231 // blocks. To avoid this problem, compute an ordering of the nodes where each
232 // node is only legalized after all of its operands are legalized.
233 DAG.AssignTopologicalOrder();
234 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
235 E = prior(DAG.allnodes_end()); I != llvm::next(E); ++I)
236 LegalizeOp(SDValue(I, 0));
238 // Finally, it's possible the root changed. Get the new root.
239 SDValue OldRoot = DAG.getRoot();
240 assert(LegalizedNodes.count(OldRoot) && "Root didn't get legalized?");
241 DAG.setRoot(LegalizedNodes[OldRoot]);
243 LegalizedNodes.clear();
245 // Remove dead nodes now.
246 DAG.RemoveDeadNodes();
250 /// FindCallEndFromCallStart - Given a chained node that is part of a call
251 /// sequence, find the CALLSEQ_END node that terminates the call sequence.
252 static SDNode *FindCallEndFromCallStart(SDNode *Node, int depth = 0) {
253 // Nested CALLSEQ_START/END constructs aren't yet legal,
254 // but we can DTRT and handle them correctly here.
255 if (Node->getOpcode() == ISD::CALLSEQ_START)
257 else if (Node->getOpcode() == ISD::CALLSEQ_END) {
262 if (Node->use_empty())
263 return 0; // No CallSeqEnd
265 // The chain is usually at the end.
266 SDValue TheChain(Node, Node->getNumValues()-1);
267 if (TheChain.getValueType() != MVT::Other) {
268 // Sometimes it's at the beginning.
269 TheChain = SDValue(Node, 0);
270 if (TheChain.getValueType() != MVT::Other) {
271 // Otherwise, hunt for it.
272 for (unsigned i = 1, e = Node->getNumValues(); i != e; ++i)
273 if (Node->getValueType(i) == MVT::Other) {
274 TheChain = SDValue(Node, i);
278 // Otherwise, we walked into a node without a chain.
279 if (TheChain.getValueType() != MVT::Other)
284 for (SDNode::use_iterator UI = Node->use_begin(),
285 E = Node->use_end(); UI != E; ++UI) {
287 // Make sure to only follow users of our token chain.
289 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i)
290 if (User->getOperand(i) == TheChain)
291 if (SDNode *Result = FindCallEndFromCallStart(User, depth))
297 /// FindCallStartFromCallEnd - Given a chained node that is part of a call
298 /// sequence, find the CALLSEQ_START node that initiates the call sequence.
299 static SDNode *FindCallStartFromCallEnd(SDNode *Node) {
301 assert(Node && "Didn't find callseq_start for a call??");
302 while (Node->getOpcode() != ISD::CALLSEQ_START || nested) {
303 Node = Node->getOperand(0).getNode();
304 assert(Node->getOperand(0).getValueType() == MVT::Other &&
305 "Node doesn't have a token chain argument!");
306 switch (Node->getOpcode()) {
309 case ISD::CALLSEQ_START:
314 case ISD::CALLSEQ_END:
322 /// LegalizeAllNodesNotLeadingTo - Recursively walk the uses of N, looking to
323 /// see if any uses can reach Dest. If no dest operands can get to dest,
324 /// legalize them, legalize ourself, and return false, otherwise, return true.
326 /// Keep track of the nodes we fine that actually do lead to Dest in
327 /// NodesLeadingTo. This avoids retraversing them exponential number of times.
329 bool SelectionDAGLegalize::LegalizeAllNodesNotLeadingTo(SDNode *N, SDNode *Dest,
330 SmallPtrSet<SDNode*, 32> &NodesLeadingTo) {
331 if (N == Dest) return true; // N certainly leads to Dest :)
333 // If we've already processed this node and it does lead to Dest, there is no
334 // need to reprocess it.
335 if (NodesLeadingTo.count(N)) return true;
337 // If the first result of this node has been already legalized, then it cannot
339 if (LegalizedNodes.count(SDValue(N, 0))) return false;
341 // Okay, this node has not already been legalized. Check and legalize all
342 // operands. If none lead to Dest, then we can legalize this node.
343 bool OperandsLeadToDest = false;
344 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
345 OperandsLeadToDest |= // If an operand leads to Dest, so do we.
346 LegalizeAllNodesNotLeadingTo(N->getOperand(i).getNode(), Dest,
349 if (OperandsLeadToDest) {
350 NodesLeadingTo.insert(N);
354 // Okay, this node looks safe, legalize it and return false.
355 LegalizeOp(SDValue(N, 0));
359 /// ExpandConstantFP - Expands the ConstantFP node to an integer constant or
360 /// a load from the constant pool.
361 static SDValue ExpandConstantFP(ConstantFPSDNode *CFP, bool UseCP,
362 SelectionDAG &DAG, const TargetLowering &TLI) {
364 DebugLoc dl = CFP->getDebugLoc();
366 // If a FP immediate is precise when represented as a float and if the
367 // target can do an extending load from float to double, we put it into
368 // the constant pool as a float, even if it's is statically typed as a
369 // double. This shrinks FP constants and canonicalizes them for targets where
370 // an FP extending load is the same cost as a normal load (such as on the x87
371 // fp stack or PPC FP unit).
372 EVT VT = CFP->getValueType(0);
373 ConstantFP *LLVMC = const_cast<ConstantFP*>(CFP->getConstantFPValue());
375 assert((VT == MVT::f64 || VT == MVT::f32) && "Invalid type expansion");
376 return DAG.getConstant(LLVMC->getValueAPF().bitcastToAPInt(),
377 (VT == MVT::f64) ? MVT::i64 : MVT::i32);
382 while (SVT != MVT::f32) {
383 SVT = (MVT::SimpleValueType)(SVT.getSimpleVT().SimpleTy - 1);
384 if (ConstantFPSDNode::isValueValidForType(SVT, CFP->getValueAPF()) &&
385 // Only do this if the target has a native EXTLOAD instruction from
387 TLI.isLoadExtLegal(ISD::EXTLOAD, SVT) &&
388 TLI.ShouldShrinkFPConstant(OrigVT)) {
389 const Type *SType = SVT.getTypeForEVT(*DAG.getContext());
390 LLVMC = cast<ConstantFP>(ConstantExpr::getFPTrunc(LLVMC, SType));
396 SDValue CPIdx = DAG.getConstantPool(LLVMC, TLI.getPointerTy());
397 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
399 return DAG.getExtLoad(ISD::EXTLOAD, OrigVT, dl,
401 CPIdx, MachinePointerInfo::getConstantPool(),
402 VT, false, false, Alignment);
403 return DAG.getLoad(OrigVT, dl, DAG.getEntryNode(), CPIdx,
404 MachinePointerInfo::getConstantPool(), false, false,
408 /// ExpandUnalignedStore - Expands an unaligned store to 2 half-size stores.
410 SDValue ExpandUnalignedStore(StoreSDNode *ST, SelectionDAG &DAG,
411 const TargetLowering &TLI) {
412 SDValue Chain = ST->getChain();
413 SDValue Ptr = ST->getBasePtr();
414 SDValue Val = ST->getValue();
415 EVT VT = Val.getValueType();
416 int Alignment = ST->getAlignment();
417 DebugLoc dl = ST->getDebugLoc();
418 if (ST->getMemoryVT().isFloatingPoint() ||
419 ST->getMemoryVT().isVector()) {
420 EVT intVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
421 if (TLI.isTypeLegal(intVT)) {
422 // Expand to a bitconvert of the value to the integer type of the
423 // same size, then a (misaligned) int store.
424 // FIXME: Does not handle truncating floating point stores!
425 SDValue Result = DAG.getNode(ISD::BITCAST, dl, intVT, Val);
426 return DAG.getStore(Chain, dl, Result, Ptr, ST->getPointerInfo(),
427 ST->isVolatile(), ST->isNonTemporal(), Alignment);
429 // Do a (aligned) store to a stack slot, then copy from the stack slot
430 // to the final destination using (unaligned) integer loads and stores.
431 EVT StoredVT = ST->getMemoryVT();
433 TLI.getRegisterType(*DAG.getContext(),
434 EVT::getIntegerVT(*DAG.getContext(),
435 StoredVT.getSizeInBits()));
436 unsigned StoredBytes = StoredVT.getSizeInBits() / 8;
437 unsigned RegBytes = RegVT.getSizeInBits() / 8;
438 unsigned NumRegs = (StoredBytes + RegBytes - 1) / RegBytes;
440 // Make sure the stack slot is also aligned for the register type.
441 SDValue StackPtr = DAG.CreateStackTemporary(StoredVT, RegVT);
443 // Perform the original store, only redirected to the stack slot.
444 SDValue Store = DAG.getTruncStore(Chain, dl,
445 Val, StackPtr, MachinePointerInfo(),
446 StoredVT, false, false, 0);
447 SDValue Increment = DAG.getConstant(RegBytes, TLI.getPointerTy());
448 SmallVector<SDValue, 8> Stores;
451 // Do all but one copies using the full register width.
452 for (unsigned i = 1; i < NumRegs; i++) {
453 // Load one integer register's worth from the stack slot.
454 SDValue Load = DAG.getLoad(RegVT, dl, Store, StackPtr,
455 MachinePointerInfo(),
457 // Store it to the final location. Remember the store.
458 Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, Ptr,
459 ST->getPointerInfo().getWithOffset(Offset),
460 ST->isVolatile(), ST->isNonTemporal(),
461 MinAlign(ST->getAlignment(), Offset)));
462 // Increment the pointers.
464 StackPtr = DAG.getNode(ISD::ADD, dl, StackPtr.getValueType(), StackPtr,
466 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
469 // The last store may be partial. Do a truncating store. On big-endian
470 // machines this requires an extending load from the stack slot to ensure
471 // that the bits are in the right place.
472 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(),
473 8 * (StoredBytes - Offset));
475 // Load from the stack slot.
476 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, RegVT, dl, Store, StackPtr,
477 MachinePointerInfo(),
478 MemVT, false, false, 0);
480 Stores.push_back(DAG.getTruncStore(Load.getValue(1), dl, Load, Ptr,
482 .getWithOffset(Offset),
483 MemVT, ST->isVolatile(),
485 MinAlign(ST->getAlignment(), Offset)));
486 // The order of the stores doesn't matter - say it with a TokenFactor.
487 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Stores[0],
491 assert(ST->getMemoryVT().isInteger() &&
492 !ST->getMemoryVT().isVector() &&
493 "Unaligned store of unknown type.");
494 // Get the half-size VT
495 EVT NewStoredVT = ST->getMemoryVT().getHalfSizedIntegerVT(*DAG.getContext());
496 int NumBits = NewStoredVT.getSizeInBits();
497 int IncrementSize = NumBits / 8;
499 // Divide the stored value in two parts.
500 SDValue ShiftAmount = DAG.getConstant(NumBits, TLI.getShiftAmountTy());
502 SDValue Hi = DAG.getNode(ISD::SRL, dl, VT, Val, ShiftAmount);
504 // Store the two parts
505 SDValue Store1, Store2;
506 Store1 = DAG.getTruncStore(Chain, dl, TLI.isLittleEndian()?Lo:Hi, Ptr,
507 ST->getPointerInfo(), NewStoredVT,
508 ST->isVolatile(), ST->isNonTemporal(), Alignment);
509 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
510 DAG.getConstant(IncrementSize, TLI.getPointerTy()));
511 Alignment = MinAlign(Alignment, IncrementSize);
512 Store2 = DAG.getTruncStore(Chain, dl, TLI.isLittleEndian()?Hi:Lo, Ptr,
513 ST->getPointerInfo().getWithOffset(IncrementSize),
514 NewStoredVT, ST->isVolatile(), ST->isNonTemporal(),
517 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Store1, Store2);
520 /// ExpandUnalignedLoad - Expands an unaligned load to 2 half-size loads.
522 SDValue ExpandUnalignedLoad(LoadSDNode *LD, SelectionDAG &DAG,
523 const TargetLowering &TLI) {
524 SDValue Chain = LD->getChain();
525 SDValue Ptr = LD->getBasePtr();
526 EVT VT = LD->getValueType(0);
527 EVT LoadedVT = LD->getMemoryVT();
528 DebugLoc dl = LD->getDebugLoc();
529 if (VT.isFloatingPoint() || VT.isVector()) {
530 EVT intVT = EVT::getIntegerVT(*DAG.getContext(), LoadedVT.getSizeInBits());
531 if (TLI.isTypeLegal(intVT)) {
532 // Expand to a (misaligned) integer load of the same size,
533 // then bitconvert to floating point or vector.
534 SDValue newLoad = DAG.getLoad(intVT, dl, Chain, Ptr, LD->getPointerInfo(),
536 LD->isNonTemporal(), LD->getAlignment());
537 SDValue Result = DAG.getNode(ISD::BITCAST, dl, LoadedVT, newLoad);
538 if (VT.isFloatingPoint() && LoadedVT != VT)
539 Result = DAG.getNode(ISD::FP_EXTEND, dl, VT, Result);
541 SDValue Ops[] = { Result, Chain };
542 return DAG.getMergeValues(Ops, 2, dl);
545 // Copy the value to a (aligned) stack slot using (unaligned) integer
546 // loads and stores, then do a (aligned) load from the stack slot.
547 EVT RegVT = TLI.getRegisterType(*DAG.getContext(), intVT);
548 unsigned LoadedBytes = LoadedVT.getSizeInBits() / 8;
549 unsigned RegBytes = RegVT.getSizeInBits() / 8;
550 unsigned NumRegs = (LoadedBytes + RegBytes - 1) / RegBytes;
552 // Make sure the stack slot is also aligned for the register type.
553 SDValue StackBase = DAG.CreateStackTemporary(LoadedVT, RegVT);
555 SDValue Increment = DAG.getConstant(RegBytes, TLI.getPointerTy());
556 SmallVector<SDValue, 8> Stores;
557 SDValue StackPtr = StackBase;
560 // Do all but one copies using the full register width.
561 for (unsigned i = 1; i < NumRegs; i++) {
562 // Load one integer register's worth from the original location.
563 SDValue Load = DAG.getLoad(RegVT, dl, Chain, Ptr,
564 LD->getPointerInfo().getWithOffset(Offset),
565 LD->isVolatile(), LD->isNonTemporal(),
566 MinAlign(LD->getAlignment(), Offset));
567 // Follow the load with a store to the stack slot. Remember the store.
568 Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, StackPtr,
569 MachinePointerInfo(), false, false, 0));
570 // Increment the pointers.
572 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
573 StackPtr = DAG.getNode(ISD::ADD, dl, StackPtr.getValueType(), StackPtr,
577 // The last copy may be partial. Do an extending load.
578 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(),
579 8 * (LoadedBytes - Offset));
580 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, RegVT, dl, Chain, Ptr,
581 LD->getPointerInfo().getWithOffset(Offset),
582 MemVT, LD->isVolatile(),
584 MinAlign(LD->getAlignment(), Offset));
585 // Follow the load with a store to the stack slot. Remember the store.
586 // On big-endian machines this requires a truncating store to ensure
587 // that the bits end up in the right place.
588 Stores.push_back(DAG.getTruncStore(Load.getValue(1), dl, Load, StackPtr,
589 MachinePointerInfo(), MemVT,
592 // The order of the stores doesn't matter - say it with a TokenFactor.
593 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Stores[0],
596 // Finally, perform the original load only redirected to the stack slot.
597 Load = DAG.getExtLoad(LD->getExtensionType(), VT, dl, TF, StackBase,
598 MachinePointerInfo(), LoadedVT, false, false, 0);
600 // Callers expect a MERGE_VALUES node.
601 SDValue Ops[] = { Load, TF };
602 return DAG.getMergeValues(Ops, 2, dl);
604 assert(LoadedVT.isInteger() && !LoadedVT.isVector() &&
605 "Unaligned load of unsupported type.");
607 // Compute the new VT that is half the size of the old one. This is an
609 unsigned NumBits = LoadedVT.getSizeInBits();
611 NewLoadedVT = EVT::getIntegerVT(*DAG.getContext(), NumBits/2);
614 unsigned Alignment = LD->getAlignment();
615 unsigned IncrementSize = NumBits / 8;
616 ISD::LoadExtType HiExtType = LD->getExtensionType();
618 // If the original load is NON_EXTLOAD, the hi part load must be ZEXTLOAD.
619 if (HiExtType == ISD::NON_EXTLOAD)
620 HiExtType = ISD::ZEXTLOAD;
622 // Load the value in two parts
624 if (TLI.isLittleEndian()) {
625 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, VT, dl, Chain, Ptr, LD->getPointerInfo(),
626 NewLoadedVT, LD->isVolatile(),
627 LD->isNonTemporal(), Alignment);
628 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
629 DAG.getConstant(IncrementSize, TLI.getPointerTy()));
630 Hi = DAG.getExtLoad(HiExtType, VT, dl, Chain, Ptr,
631 LD->getPointerInfo().getWithOffset(IncrementSize),
632 NewLoadedVT, LD->isVolatile(),
633 LD->isNonTemporal(), MinAlign(Alignment,IncrementSize));
635 Hi = DAG.getExtLoad(HiExtType, VT, dl, Chain, Ptr, LD->getPointerInfo(),
636 NewLoadedVT, LD->isVolatile(),
637 LD->isNonTemporal(), Alignment);
638 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
639 DAG.getConstant(IncrementSize, TLI.getPointerTy()));
640 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, VT, dl, Chain, Ptr,
641 LD->getPointerInfo().getWithOffset(IncrementSize),
642 NewLoadedVT, LD->isVolatile(),
643 LD->isNonTemporal(), MinAlign(Alignment,IncrementSize));
646 // aggregate the two parts
647 SDValue ShiftAmount = DAG.getConstant(NumBits, TLI.getShiftAmountTy());
648 SDValue Result = DAG.getNode(ISD::SHL, dl, VT, Hi, ShiftAmount);
649 Result = DAG.getNode(ISD::OR, dl, VT, Result, Lo);
651 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
654 SDValue Ops[] = { Result, TF };
655 return DAG.getMergeValues(Ops, 2, dl);
658 /// PerformInsertVectorEltInMemory - Some target cannot handle a variable
659 /// insertion index for the INSERT_VECTOR_ELT instruction. In this case, it
660 /// is necessary to spill the vector being inserted into to memory, perform
661 /// the insert there, and then read the result back.
662 SDValue SelectionDAGLegalize::
663 PerformInsertVectorEltInMemory(SDValue Vec, SDValue Val, SDValue Idx,
669 // If the target doesn't support this, we have to spill the input vector
670 // to a temporary stack slot, update the element, then reload it. This is
671 // badness. We could also load the value into a vector register (either
672 // with a "move to register" or "extload into register" instruction, then
673 // permute it into place, if the idx is a constant and if the idx is
674 // supported by the target.
675 EVT VT = Tmp1.getValueType();
676 EVT EltVT = VT.getVectorElementType();
677 EVT IdxVT = Tmp3.getValueType();
678 EVT PtrVT = TLI.getPointerTy();
679 SDValue StackPtr = DAG.CreateStackTemporary(VT);
681 int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
684 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, Tmp1, StackPtr,
685 MachinePointerInfo::getFixedStack(SPFI),
688 // Truncate or zero extend offset to target pointer type.
689 unsigned CastOpc = IdxVT.bitsGT(PtrVT) ? ISD::TRUNCATE : ISD::ZERO_EXTEND;
690 Tmp3 = DAG.getNode(CastOpc, dl, PtrVT, Tmp3);
691 // Add the offset to the index.
692 unsigned EltSize = EltVT.getSizeInBits()/8;
693 Tmp3 = DAG.getNode(ISD::MUL, dl, IdxVT, Tmp3,DAG.getConstant(EltSize, IdxVT));
694 SDValue StackPtr2 = DAG.getNode(ISD::ADD, dl, IdxVT, Tmp3, StackPtr);
695 // Store the scalar value.
696 Ch = DAG.getTruncStore(Ch, dl, Tmp2, StackPtr2, MachinePointerInfo(), EltVT,
698 // Load the updated vector.
699 return DAG.getLoad(VT, dl, Ch, StackPtr,
700 MachinePointerInfo::getFixedStack(SPFI), false, false, 0);
704 SDValue SelectionDAGLegalize::
705 ExpandINSERT_VECTOR_ELT(SDValue Vec, SDValue Val, SDValue Idx, DebugLoc dl) {
706 if (ConstantSDNode *InsertPos = dyn_cast<ConstantSDNode>(Idx)) {
707 // SCALAR_TO_VECTOR requires that the type of the value being inserted
708 // match the element type of the vector being created, except for
709 // integers in which case the inserted value can be over width.
710 EVT EltVT = Vec.getValueType().getVectorElementType();
711 if (Val.getValueType() == EltVT ||
712 (EltVT.isInteger() && Val.getValueType().bitsGE(EltVT))) {
713 SDValue ScVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
714 Vec.getValueType(), Val);
716 unsigned NumElts = Vec.getValueType().getVectorNumElements();
717 // We generate a shuffle of InVec and ScVec, so the shuffle mask
718 // should be 0,1,2,3,4,5... with the appropriate element replaced with
720 SmallVector<int, 8> ShufOps;
721 for (unsigned i = 0; i != NumElts; ++i)
722 ShufOps.push_back(i != InsertPos->getZExtValue() ? i : NumElts);
724 return DAG.getVectorShuffle(Vec.getValueType(), dl, Vec, ScVec,
728 return PerformInsertVectorEltInMemory(Vec, Val, Idx, dl);
731 SDValue SelectionDAGLegalize::OptimizeFloatStore(StoreSDNode* ST) {
732 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
733 // FIXME: We shouldn't do this for TargetConstantFP's.
734 // FIXME: move this to the DAG Combiner! Note that we can't regress due
735 // to phase ordering between legalized code and the dag combiner. This
736 // probably means that we need to integrate dag combiner and legalizer
738 // We generally can't do this one for long doubles.
739 SDValue Tmp1 = ST->getChain();
740 SDValue Tmp2 = ST->getBasePtr();
742 unsigned Alignment = ST->getAlignment();
743 bool isVolatile = ST->isVolatile();
744 bool isNonTemporal = ST->isNonTemporal();
745 DebugLoc dl = ST->getDebugLoc();
746 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(ST->getValue())) {
747 if (CFP->getValueType(0) == MVT::f32 &&
748 getTypeAction(MVT::i32) == Legal) {
749 Tmp3 = DAG.getConstant(CFP->getValueAPF().
750 bitcastToAPInt().zextOrTrunc(32),
752 return DAG.getStore(Tmp1, dl, Tmp3, Tmp2, ST->getPointerInfo(),
753 isVolatile, isNonTemporal, Alignment);
756 if (CFP->getValueType(0) == MVT::f64) {
757 // If this target supports 64-bit registers, do a single 64-bit store.
758 if (getTypeAction(MVT::i64) == Legal) {
759 Tmp3 = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
760 zextOrTrunc(64), MVT::i64);
761 return DAG.getStore(Tmp1, dl, Tmp3, Tmp2, ST->getPointerInfo(),
762 isVolatile, isNonTemporal, Alignment);
765 if (getTypeAction(MVT::i32) == Legal && !ST->isVolatile()) {
766 // Otherwise, if the target supports 32-bit registers, use 2 32-bit
767 // stores. If the target supports neither 32- nor 64-bits, this
768 // xform is certainly not worth it.
769 const APInt &IntVal =CFP->getValueAPF().bitcastToAPInt();
770 SDValue Lo = DAG.getConstant(IntVal.trunc(32), MVT::i32);
771 SDValue Hi = DAG.getConstant(IntVal.lshr(32).trunc(32), MVT::i32);
772 if (TLI.isBigEndian()) std::swap(Lo, Hi);
774 Lo = DAG.getStore(Tmp1, dl, Lo, Tmp2, ST->getPointerInfo(), isVolatile,
775 isNonTemporal, Alignment);
776 Tmp2 = DAG.getNode(ISD::ADD, dl, Tmp2.getValueType(), Tmp2,
777 DAG.getIntPtrConstant(4));
778 Hi = DAG.getStore(Tmp1, dl, Hi, Tmp2,
779 ST->getPointerInfo().getWithOffset(4),
780 isVolatile, isNonTemporal, MinAlign(Alignment, 4U));
782 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo, Hi);
789 /// LegalizeOp - We know that the specified value has a legal type, and
790 /// that its operands are legal. Now ensure that the operation itself
791 /// is legal, recursively ensuring that the operands' operations remain
793 SDValue SelectionDAGLegalize::LegalizeOp(SDValue Op) {
794 if (Op.getOpcode() == ISD::TargetConstant) // Allow illegal target nodes.
797 SDNode *Node = Op.getNode();
798 DebugLoc dl = Node->getDebugLoc();
800 for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
801 assert(getTypeAction(Node->getValueType(i)) == Legal &&
802 "Unexpected illegal type!");
804 for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i)
805 assert((isTypeLegal(Node->getOperand(i).getValueType()) ||
806 Node->getOperand(i).getOpcode() == ISD::TargetConstant) &&
807 "Unexpected illegal type!");
809 // Note that LegalizeOp may be reentered even from single-use nodes, which
810 // means that we always must cache transformed nodes.
811 DenseMap<SDValue, SDValue>::iterator I = LegalizedNodes.find(Op);
812 if (I != LegalizedNodes.end()) return I->second;
814 SDValue Tmp1, Tmp2, Tmp3, Tmp4;
816 bool isCustom = false;
818 // Figure out the correct action; the way to query this varies by opcode
819 TargetLowering::LegalizeAction Action;
820 bool SimpleFinishLegalizing = true;
821 switch (Node->getOpcode()) {
822 case ISD::INTRINSIC_W_CHAIN:
823 case ISD::INTRINSIC_WO_CHAIN:
824 case ISD::INTRINSIC_VOID:
827 Action = TLI.getOperationAction(Node->getOpcode(), MVT::Other);
829 case ISD::SINT_TO_FP:
830 case ISD::UINT_TO_FP:
831 case ISD::EXTRACT_VECTOR_ELT:
832 Action = TLI.getOperationAction(Node->getOpcode(),
833 Node->getOperand(0).getValueType());
835 case ISD::FP_ROUND_INREG:
836 case ISD::SIGN_EXTEND_INREG: {
837 EVT InnerType = cast<VTSDNode>(Node->getOperand(1))->getVT();
838 Action = TLI.getOperationAction(Node->getOpcode(), InnerType);
844 unsigned CCOperand = Node->getOpcode() == ISD::SELECT_CC ? 4 :
845 Node->getOpcode() == ISD::SETCC ? 2 : 1;
846 unsigned CompareOperand = Node->getOpcode() == ISD::BR_CC ? 2 : 0;
847 EVT OpVT = Node->getOperand(CompareOperand).getValueType();
848 ISD::CondCode CCCode =
849 cast<CondCodeSDNode>(Node->getOperand(CCOperand))->get();
850 Action = TLI.getCondCodeAction(CCCode, OpVT);
851 if (Action == TargetLowering::Legal) {
852 if (Node->getOpcode() == ISD::SELECT_CC)
853 Action = TLI.getOperationAction(Node->getOpcode(),
854 Node->getValueType(0));
856 Action = TLI.getOperationAction(Node->getOpcode(), OpVT);
862 // FIXME: Model these properly. LOAD and STORE are complicated, and
863 // STORE expects the unlegalized operand in some cases.
864 SimpleFinishLegalizing = false;
866 case ISD::CALLSEQ_START:
867 case ISD::CALLSEQ_END:
868 // FIXME: This shouldn't be necessary. These nodes have special properties
869 // dealing with the recursive nature of legalization. Removing this
870 // special case should be done as part of making LegalizeDAG non-recursive.
871 SimpleFinishLegalizing = false;
873 case ISD::EXTRACT_ELEMENT:
874 case ISD::FLT_ROUNDS_:
882 case ISD::MERGE_VALUES:
884 case ISD::FRAME_TO_ARGS_OFFSET:
885 case ISD::EH_SJLJ_SETJMP:
886 case ISD::EH_SJLJ_LONGJMP:
887 case ISD::EH_SJLJ_DISPATCHSETUP:
888 // These operations lie about being legal: when they claim to be legal,
889 // they should actually be expanded.
890 Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
891 if (Action == TargetLowering::Legal)
892 Action = TargetLowering::Expand;
894 case ISD::TRAMPOLINE:
896 case ISD::RETURNADDR:
897 // These operations lie about being legal: when they claim to be legal,
898 // they should actually be custom-lowered.
899 Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
900 if (Action == TargetLowering::Legal)
901 Action = TargetLowering::Custom;
903 case ISD::BUILD_VECTOR:
904 // A weird case: legalization for BUILD_VECTOR never legalizes the
906 // FIXME: This really sucks... changing it isn't semantically incorrect,
907 // but it massively pessimizes the code for floating-point BUILD_VECTORs
908 // because ConstantFP operands get legalized into constant pool loads
909 // before the BUILD_VECTOR code can see them. It doesn't usually bite,
910 // though, because BUILD_VECTORS usually get lowered into other nodes
911 // which get legalized properly.
912 SimpleFinishLegalizing = false;
915 if (Node->getOpcode() >= ISD::BUILTIN_OP_END) {
916 Action = TargetLowering::Legal;
918 Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
923 if (SimpleFinishLegalizing) {
924 SmallVector<SDValue, 8> Ops, ResultVals;
925 for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i)
926 Ops.push_back(LegalizeOp(Node->getOperand(i)));
927 switch (Node->getOpcode()) {
934 // Branches tweak the chain to include LastCALLSEQ_END
935 Ops[0] = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ops[0],
937 Ops[0] = LegalizeOp(Ops[0]);
938 LastCALLSEQ_END = DAG.getEntryNode();
945 // Legalizing shifts/rotates requires adjusting the shift amount
946 // to the appropriate width.
947 if (!Ops[1].getValueType().isVector())
948 Ops[1] = LegalizeOp(DAG.getShiftAmountOperand(Ops[1]));
953 // Legalizing shifts/rotates requires adjusting the shift amount
954 // to the appropriate width.
955 if (!Ops[2].getValueType().isVector())
956 Ops[2] = LegalizeOp(DAG.getShiftAmountOperand(Ops[2]));
960 Result = SDValue(DAG.UpdateNodeOperands(Result.getNode(), Ops.data(),
963 case TargetLowering::Legal:
964 for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
965 ResultVals.push_back(Result.getValue(i));
967 case TargetLowering::Custom:
968 // FIXME: The handling for custom lowering with multiple results is
970 Tmp1 = TLI.LowerOperation(Result, DAG);
971 if (Tmp1.getNode()) {
972 for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i) {
974 ResultVals.push_back(Tmp1);
976 ResultVals.push_back(Tmp1.getValue(i));
982 case TargetLowering::Expand:
983 ExpandNode(Result.getNode(), ResultVals);
985 case TargetLowering::Promote:
986 PromoteNode(Result.getNode(), ResultVals);
989 if (!ResultVals.empty()) {
990 for (unsigned i = 0, e = ResultVals.size(); i != e; ++i) {
991 if (ResultVals[i] != SDValue(Node, i))
992 ResultVals[i] = LegalizeOp(ResultVals[i]);
993 AddLegalizedOperand(SDValue(Node, i), ResultVals[i]);
995 return ResultVals[Op.getResNo()];
999 switch (Node->getOpcode()) {
1006 assert(0 && "Do not know how to legalize this operator!");
1008 case ISD::BUILD_VECTOR:
1009 switch (TLI.getOperationAction(ISD::BUILD_VECTOR, Node->getValueType(0))) {
1010 default: assert(0 && "This action is not supported yet!");
1011 case TargetLowering::Custom:
1012 Tmp3 = TLI.LowerOperation(Result, DAG);
1013 if (Tmp3.getNode()) {
1018 case TargetLowering::Expand:
1019 Result = ExpandBUILD_VECTOR(Result.getNode());
1023 case ISD::CALLSEQ_START: {
1024 static int depth = 0;
1025 SDNode *CallEnd = FindCallEndFromCallStart(Node);
1027 // Recursively Legalize all of the inputs of the call end that do not lead
1028 // to this call start. This ensures that any libcalls that need be inserted
1029 // are inserted *before* the CALLSEQ_START.
1030 {SmallPtrSet<SDNode*, 32> NodesLeadingTo;
1031 for (unsigned i = 0, e = CallEnd->getNumOperands(); i != e; ++i)
1032 LegalizeAllNodesNotLeadingTo(CallEnd->getOperand(i).getNode(), Node,
1036 // Now that we have legalized all of the inputs (which may have inserted
1037 // libcalls), create the new CALLSEQ_START node.
1038 Tmp1 = LegalizeOp(Node->getOperand(0)); // Legalize the chain.
1040 // Merge in the last call to ensure that this call starts after the last
1042 if (LastCALLSEQ_END.getOpcode() != ISD::EntryToken && depth == 0) {
1043 Tmp1 = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1044 Tmp1, LastCALLSEQ_END);
1045 Tmp1 = LegalizeOp(Tmp1);
1048 // Do not try to legalize the target-specific arguments (#1+).
1049 if (Tmp1 != Node->getOperand(0)) {
1050 SmallVector<SDValue, 8> Ops(Node->op_begin(), Node->op_end());
1052 Result = SDValue(DAG.UpdateNodeOperands(Result.getNode(), &Ops[0],
1053 Ops.size()), Result.getResNo());
1056 // Remember that the CALLSEQ_START is legalized.
1057 AddLegalizedOperand(Op.getValue(0), Result);
1058 if (Node->getNumValues() == 2) // If this has a flag result, remember it.
1059 AddLegalizedOperand(Op.getValue(1), Result.getValue(1));
1061 // Now that the callseq_start and all of the non-call nodes above this call
1062 // sequence have been legalized, legalize the call itself. During this
1063 // process, no libcalls can/will be inserted, guaranteeing that no calls
1066 SDValue Saved_LastCALLSEQ_END = LastCALLSEQ_END ;
1067 // Note that we are selecting this call!
1068 LastCALLSEQ_END = SDValue(CallEnd, 0);
1071 // Legalize the call, starting from the CALLSEQ_END.
1072 LegalizeOp(LastCALLSEQ_END);
1074 assert(depth >= 0 && "Un-matched CALLSEQ_START?");
1076 LastCALLSEQ_END = Saved_LastCALLSEQ_END;
1079 case ISD::CALLSEQ_END:
1080 // If the CALLSEQ_START node hasn't been legalized first, legalize it. This
1081 // will cause this node to be legalized as well as handling libcalls right.
1082 if (LastCALLSEQ_END.getNode() != Node) {
1083 LegalizeOp(SDValue(FindCallStartFromCallEnd(Node), 0));
1084 DenseMap<SDValue, SDValue>::iterator I = LegalizedNodes.find(Op);
1085 assert(I != LegalizedNodes.end() &&
1086 "Legalizing the call start should have legalized this node!");
1090 // Otherwise, the call start has been legalized and everything is going
1091 // according to plan. Just legalize ourselves normally here.
1092 Tmp1 = LegalizeOp(Node->getOperand(0)); // Legalize the chain.
1093 // Do not try to legalize the target-specific arguments (#1+), except for
1094 // an optional flag input.
1095 if (Node->getOperand(Node->getNumOperands()-1).getValueType() != MVT::Glue){
1096 if (Tmp1 != Node->getOperand(0)) {
1097 SmallVector<SDValue, 8> Ops(Node->op_begin(), Node->op_end());
1099 Result = SDValue(DAG.UpdateNodeOperands(Result.getNode(),
1100 &Ops[0], Ops.size()),
1104 Tmp2 = LegalizeOp(Node->getOperand(Node->getNumOperands()-1));
1105 if (Tmp1 != Node->getOperand(0) ||
1106 Tmp2 != Node->getOperand(Node->getNumOperands()-1)) {
1107 SmallVector<SDValue, 8> Ops(Node->op_begin(), Node->op_end());
1110 Result = SDValue(DAG.UpdateNodeOperands(Result.getNode(),
1111 &Ops[0], Ops.size()),
1115 // This finishes up call legalization.
1116 // If the CALLSEQ_END node has a flag, remember that we legalized it.
1117 AddLegalizedOperand(SDValue(Node, 0), Result.getValue(0));
1118 if (Node->getNumValues() == 2)
1119 AddLegalizedOperand(SDValue(Node, 1), Result.getValue(1));
1120 return Result.getValue(Op.getResNo());
1122 LoadSDNode *LD = cast<LoadSDNode>(Node);
1123 Tmp1 = LegalizeOp(LD->getChain()); // Legalize the chain.
1124 Tmp2 = LegalizeOp(LD->getBasePtr()); // Legalize the base pointer.
1126 ISD::LoadExtType ExtType = LD->getExtensionType();
1127 if (ExtType == ISD::NON_EXTLOAD) {
1128 EVT VT = Node->getValueType(0);
1129 Result = SDValue(DAG.UpdateNodeOperands(Result.getNode(),
1130 Tmp1, Tmp2, LD->getOffset()),
1132 Tmp3 = Result.getValue(0);
1133 Tmp4 = Result.getValue(1);
1135 switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
1136 default: assert(0 && "This action is not supported yet!");
1137 case TargetLowering::Legal:
1138 // If this is an unaligned load and the target doesn't support it,
1140 if (!TLI.allowsUnalignedMemoryAccesses(LD->getMemoryVT())) {
1141 const Type *Ty = LD->getMemoryVT().getTypeForEVT(*DAG.getContext());
1142 unsigned ABIAlignment = TLI.getTargetData()->getABITypeAlignment(Ty);
1143 if (LD->getAlignment() < ABIAlignment){
1144 Result = ExpandUnalignedLoad(cast<LoadSDNode>(Result.getNode()),
1146 Tmp3 = Result.getOperand(0);
1147 Tmp4 = Result.getOperand(1);
1148 Tmp3 = LegalizeOp(Tmp3);
1149 Tmp4 = LegalizeOp(Tmp4);
1153 case TargetLowering::Custom:
1154 Tmp1 = TLI.LowerOperation(Tmp3, DAG);
1155 if (Tmp1.getNode()) {
1156 Tmp3 = LegalizeOp(Tmp1);
1157 Tmp4 = LegalizeOp(Tmp1.getValue(1));
1160 case TargetLowering::Promote: {
1161 // Only promote a load of vector type to another.
1162 assert(VT.isVector() && "Cannot promote this load!");
1163 // Change base type to a different vector type.
1164 EVT NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), VT);
1166 Tmp1 = DAG.getLoad(NVT, dl, Tmp1, Tmp2, LD->getPointerInfo(),
1167 LD->isVolatile(), LD->isNonTemporal(),
1168 LD->getAlignment());
1169 Tmp3 = LegalizeOp(DAG.getNode(ISD::BITCAST, dl, VT, Tmp1));
1170 Tmp4 = LegalizeOp(Tmp1.getValue(1));
1174 // Since loads produce two values, make sure to remember that we
1175 // legalized both of them.
1176 AddLegalizedOperand(SDValue(Node, 0), Tmp3);
1177 AddLegalizedOperand(SDValue(Node, 1), Tmp4);
1178 return Op.getResNo() ? Tmp4 : Tmp3;
1181 EVT SrcVT = LD->getMemoryVT();
1182 unsigned SrcWidth = SrcVT.getSizeInBits();
1183 unsigned Alignment = LD->getAlignment();
1184 bool isVolatile = LD->isVolatile();
1185 bool isNonTemporal = LD->isNonTemporal();
1187 if (SrcWidth != SrcVT.getStoreSizeInBits() &&
1188 // Some targets pretend to have an i1 loading operation, and actually
1189 // load an i8. This trick is correct for ZEXTLOAD because the top 7
1190 // bits are guaranteed to be zero; it helps the optimizers understand
1191 // that these bits are zero. It is also useful for EXTLOAD, since it
1192 // tells the optimizers that those bits are undefined. It would be
1193 // nice to have an effective generic way of getting these benefits...
1194 // Until such a way is found, don't insist on promoting i1 here.
1195 (SrcVT != MVT::i1 ||
1196 TLI.getLoadExtAction(ExtType, MVT::i1) == TargetLowering::Promote)) {
1197 // Promote to a byte-sized load if not loading an integral number of
1198 // bytes. For example, promote EXTLOAD:i20 -> EXTLOAD:i24.
1199 unsigned NewWidth = SrcVT.getStoreSizeInBits();
1200 EVT NVT = EVT::getIntegerVT(*DAG.getContext(), NewWidth);
1203 // The extra bits are guaranteed to be zero, since we stored them that
1204 // way. A zext load from NVT thus automatically gives zext from SrcVT.
1206 ISD::LoadExtType NewExtType =
1207 ExtType == ISD::ZEXTLOAD ? ISD::ZEXTLOAD : ISD::EXTLOAD;
1209 Result = DAG.getExtLoad(NewExtType, Node->getValueType(0), dl,
1210 Tmp1, Tmp2, LD->getPointerInfo(),
1211 NVT, isVolatile, isNonTemporal, Alignment);
1213 Ch = Result.getValue(1); // The chain.
1215 if (ExtType == ISD::SEXTLOAD)
1216 // Having the top bits zero doesn't help when sign extending.
1217 Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl,
1218 Result.getValueType(),
1219 Result, DAG.getValueType(SrcVT));
1220 else if (ExtType == ISD::ZEXTLOAD || NVT == Result.getValueType())
1221 // All the top bits are guaranteed to be zero - inform the optimizers.
1222 Result = DAG.getNode(ISD::AssertZext, dl,
1223 Result.getValueType(), Result,
1224 DAG.getValueType(SrcVT));
1226 Tmp1 = LegalizeOp(Result);
1227 Tmp2 = LegalizeOp(Ch);
1228 } else if (SrcWidth & (SrcWidth - 1)) {
1229 // If not loading a power-of-2 number of bits, expand as two loads.
1230 assert(!SrcVT.isVector() && "Unsupported extload!");
1231 unsigned RoundWidth = 1 << Log2_32(SrcWidth);
1232 assert(RoundWidth < SrcWidth);
1233 unsigned ExtraWidth = SrcWidth - RoundWidth;
1234 assert(ExtraWidth < RoundWidth);
1235 assert(!(RoundWidth % 8) && !(ExtraWidth % 8) &&
1236 "Load size not an integral number of bytes!");
1237 EVT RoundVT = EVT::getIntegerVT(*DAG.getContext(), RoundWidth);
1238 EVT ExtraVT = EVT::getIntegerVT(*DAG.getContext(), ExtraWidth);
1240 unsigned IncrementSize;
1242 if (TLI.isLittleEndian()) {
1243 // EXTLOAD:i24 -> ZEXTLOAD:i16 | (shl EXTLOAD@+2:i8, 16)
1244 // Load the bottom RoundWidth bits.
1245 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, Node->getValueType(0), dl,
1247 LD->getPointerInfo(), RoundVT, isVolatile,
1248 isNonTemporal, Alignment);
1250 // Load the remaining ExtraWidth bits.
1251 IncrementSize = RoundWidth / 8;
1252 Tmp2 = DAG.getNode(ISD::ADD, dl, Tmp2.getValueType(), Tmp2,
1253 DAG.getIntPtrConstant(IncrementSize));
1254 Hi = DAG.getExtLoad(ExtType, Node->getValueType(0), dl, Tmp1, Tmp2,
1255 LD->getPointerInfo().getWithOffset(IncrementSize),
1256 ExtraVT, isVolatile, isNonTemporal,
1257 MinAlign(Alignment, IncrementSize));
1259 // Build a factor node to remember that this load is independent of
1261 Ch = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
1264 // Move the top bits to the right place.
1265 Hi = DAG.getNode(ISD::SHL, dl, Hi.getValueType(), Hi,
1266 DAG.getConstant(RoundWidth, TLI.getShiftAmountTy()));
1268 // Join the hi and lo parts.
1269 Result = DAG.getNode(ISD::OR, dl, Node->getValueType(0), Lo, Hi);
1271 // Big endian - avoid unaligned loads.
1272 // EXTLOAD:i24 -> (shl EXTLOAD:i16, 8) | ZEXTLOAD@+2:i8
1273 // Load the top RoundWidth bits.
1274 Hi = DAG.getExtLoad(ExtType, Node->getValueType(0), dl, Tmp1, Tmp2,
1275 LD->getPointerInfo(), RoundVT, isVolatile,
1276 isNonTemporal, Alignment);
1278 // Load the remaining ExtraWidth bits.
1279 IncrementSize = RoundWidth / 8;
1280 Tmp2 = DAG.getNode(ISD::ADD, dl, Tmp2.getValueType(), Tmp2,
1281 DAG.getIntPtrConstant(IncrementSize));
1282 Lo = DAG.getExtLoad(ISD::ZEXTLOAD,
1283 Node->getValueType(0), dl, Tmp1, Tmp2,
1284 LD->getPointerInfo().getWithOffset(IncrementSize),
1285 ExtraVT, isVolatile, isNonTemporal,
1286 MinAlign(Alignment, IncrementSize));
1288 // Build a factor node to remember that this load is independent of
1290 Ch = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
1293 // Move the top bits to the right place.
1294 Hi = DAG.getNode(ISD::SHL, dl, Hi.getValueType(), Hi,
1295 DAG.getConstant(ExtraWidth, TLI.getShiftAmountTy()));
1297 // Join the hi and lo parts.
1298 Result = DAG.getNode(ISD::OR, dl, Node->getValueType(0), Lo, Hi);
1301 Tmp1 = LegalizeOp(Result);
1302 Tmp2 = LegalizeOp(Ch);
1304 switch (TLI.getLoadExtAction(ExtType, SrcVT)) {
1305 default: assert(0 && "This action is not supported yet!");
1306 case TargetLowering::Custom:
1309 case TargetLowering::Legal:
1310 Result = SDValue(DAG.UpdateNodeOperands(Result.getNode(),
1311 Tmp1, Tmp2, LD->getOffset()),
1313 Tmp1 = Result.getValue(0);
1314 Tmp2 = Result.getValue(1);
1317 Tmp3 = TLI.LowerOperation(Result, DAG);
1318 if (Tmp3.getNode()) {
1319 Tmp1 = LegalizeOp(Tmp3);
1320 Tmp2 = LegalizeOp(Tmp3.getValue(1));
1323 // If this is an unaligned load and the target doesn't support it,
1325 if (!TLI.allowsUnalignedMemoryAccesses(LD->getMemoryVT())) {
1327 LD->getMemoryVT().getTypeForEVT(*DAG.getContext());
1328 unsigned ABIAlignment =
1329 TLI.getTargetData()->getABITypeAlignment(Ty);
1330 if (LD->getAlignment() < ABIAlignment){
1331 Result = ExpandUnalignedLoad(cast<LoadSDNode>(Result.getNode()),
1333 Tmp1 = Result.getOperand(0);
1334 Tmp2 = Result.getOperand(1);
1335 Tmp1 = LegalizeOp(Tmp1);
1336 Tmp2 = LegalizeOp(Tmp2);
1341 case TargetLowering::Expand:
1342 if (!TLI.isLoadExtLegal(ISD::EXTLOAD, SrcVT) && isTypeLegal(SrcVT)) {
1343 SDValue Load = DAG.getLoad(SrcVT, dl, Tmp1, Tmp2,
1344 LD->getPointerInfo(),
1345 LD->isVolatile(), LD->isNonTemporal(),
1346 LD->getAlignment());
1350 ExtendOp = (SrcVT.isFloatingPoint() ?
1351 ISD::FP_EXTEND : ISD::ANY_EXTEND);
1353 case ISD::SEXTLOAD: ExtendOp = ISD::SIGN_EXTEND; break;
1354 case ISD::ZEXTLOAD: ExtendOp = ISD::ZERO_EXTEND; break;
1355 default: llvm_unreachable("Unexpected extend load type!");
1357 Result = DAG.getNode(ExtendOp, dl, Node->getValueType(0), Load);
1358 Tmp1 = LegalizeOp(Result); // Relegalize new nodes.
1359 Tmp2 = LegalizeOp(Load.getValue(1));
1362 // FIXME: This does not work for vectors on most targets. Sign- and
1363 // zero-extend operations are currently folded into extending loads,
1364 // whether they are legal or not, and then we end up here without any
1365 // support for legalizing them.
1366 assert(ExtType != ISD::EXTLOAD &&
1367 "EXTLOAD should always be supported!");
1368 // Turn the unsupported load into an EXTLOAD followed by an explicit
1369 // zero/sign extend inreg.
1370 Result = DAG.getExtLoad(ISD::EXTLOAD, Node->getValueType(0), dl,
1371 Tmp1, Tmp2, LD->getPointerInfo(), SrcVT,
1372 LD->isVolatile(), LD->isNonTemporal(),
1373 LD->getAlignment());
1375 if (ExtType == ISD::SEXTLOAD)
1376 ValRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl,
1377 Result.getValueType(),
1378 Result, DAG.getValueType(SrcVT));
1380 ValRes = DAG.getZeroExtendInReg(Result, dl, SrcVT.getScalarType());
1381 Tmp1 = LegalizeOp(ValRes); // Relegalize new nodes.
1382 Tmp2 = LegalizeOp(Result.getValue(1)); // Relegalize new nodes.
1387 // Since loads produce two values, make sure to remember that we legalized
1389 AddLegalizedOperand(SDValue(Node, 0), Tmp1);
1390 AddLegalizedOperand(SDValue(Node, 1), Tmp2);
1391 return Op.getResNo() ? Tmp2 : Tmp1;
1394 StoreSDNode *ST = cast<StoreSDNode>(Node);
1395 Tmp1 = LegalizeOp(ST->getChain()); // Legalize the chain.
1396 Tmp2 = LegalizeOp(ST->getBasePtr()); // Legalize the pointer.
1397 unsigned Alignment = ST->getAlignment();
1398 bool isVolatile = ST->isVolatile();
1399 bool isNonTemporal = ST->isNonTemporal();
1401 if (!ST->isTruncatingStore()) {
1402 if (SDNode *OptStore = OptimizeFloatStore(ST).getNode()) {
1403 Result = SDValue(OptStore, 0);
1408 Tmp3 = LegalizeOp(ST->getValue());
1409 Result = SDValue(DAG.UpdateNodeOperands(Result.getNode(),
1414 EVT VT = Tmp3.getValueType();
1415 switch (TLI.getOperationAction(ISD::STORE, VT)) {
1416 default: assert(0 && "This action is not supported yet!");
1417 case TargetLowering::Legal:
1418 // If this is an unaligned store and the target doesn't support it,
1420 if (!TLI.allowsUnalignedMemoryAccesses(ST->getMemoryVT())) {
1421 const Type *Ty = ST->getMemoryVT().getTypeForEVT(*DAG.getContext());
1422 unsigned ABIAlignment= TLI.getTargetData()->getABITypeAlignment(Ty);
1423 if (ST->getAlignment() < ABIAlignment)
1424 Result = ExpandUnalignedStore(cast<StoreSDNode>(Result.getNode()),
1428 case TargetLowering::Custom:
1429 Tmp1 = TLI.LowerOperation(Result, DAG);
1430 if (Tmp1.getNode()) Result = Tmp1;
1432 case TargetLowering::Promote:
1433 assert(VT.isVector() && "Unknown legal promote case!");
1434 Tmp3 = DAG.getNode(ISD::BITCAST, dl,
1435 TLI.getTypeToPromoteTo(ISD::STORE, VT), Tmp3);
1436 Result = DAG.getStore(Tmp1, dl, Tmp3, Tmp2,
1437 ST->getPointerInfo(), isVolatile,
1438 isNonTemporal, Alignment);
1444 Tmp3 = LegalizeOp(ST->getValue());
1446 EVT StVT = ST->getMemoryVT();
1447 unsigned StWidth = StVT.getSizeInBits();
1449 if (StWidth != StVT.getStoreSizeInBits()) {
1450 // Promote to a byte-sized store with upper bits zero if not
1451 // storing an integral number of bytes. For example, promote
1452 // TRUNCSTORE:i1 X -> TRUNCSTORE:i8 (and X, 1)
1453 EVT NVT = EVT::getIntegerVT(*DAG.getContext(),
1454 StVT.getStoreSizeInBits());
1455 Tmp3 = DAG.getZeroExtendInReg(Tmp3, dl, StVT);
1456 Result = DAG.getTruncStore(Tmp1, dl, Tmp3, Tmp2, ST->getPointerInfo(),
1457 NVT, isVolatile, isNonTemporal, Alignment);
1458 } else if (StWidth & (StWidth - 1)) {
1459 // If not storing a power-of-2 number of bits, expand as two stores.
1460 assert(!StVT.isVector() && "Unsupported truncstore!");
1461 unsigned RoundWidth = 1 << Log2_32(StWidth);
1462 assert(RoundWidth < StWidth);
1463 unsigned ExtraWidth = StWidth - RoundWidth;
1464 assert(ExtraWidth < RoundWidth);
1465 assert(!(RoundWidth % 8) && !(ExtraWidth % 8) &&
1466 "Store size not an integral number of bytes!");
1467 EVT RoundVT = EVT::getIntegerVT(*DAG.getContext(), RoundWidth);
1468 EVT ExtraVT = EVT::getIntegerVT(*DAG.getContext(), ExtraWidth);
1470 unsigned IncrementSize;
1472 if (TLI.isLittleEndian()) {
1473 // TRUNCSTORE:i24 X -> TRUNCSTORE:i16 X, TRUNCSTORE@+2:i8 (srl X, 16)
1474 // Store the bottom RoundWidth bits.
1475 Lo = DAG.getTruncStore(Tmp1, dl, Tmp3, Tmp2, ST->getPointerInfo(),
1477 isVolatile, isNonTemporal, Alignment);
1479 // Store the remaining ExtraWidth bits.
1480 IncrementSize = RoundWidth / 8;
1481 Tmp2 = DAG.getNode(ISD::ADD, dl, Tmp2.getValueType(), Tmp2,
1482 DAG.getIntPtrConstant(IncrementSize));
1483 Hi = DAG.getNode(ISD::SRL, dl, Tmp3.getValueType(), Tmp3,
1484 DAG.getConstant(RoundWidth, TLI.getShiftAmountTy()));
1485 Hi = DAG.getTruncStore(Tmp1, dl, Hi, Tmp2,
1486 ST->getPointerInfo().getWithOffset(IncrementSize),
1487 ExtraVT, isVolatile, isNonTemporal,
1488 MinAlign(Alignment, IncrementSize));
1490 // Big endian - avoid unaligned stores.
1491 // TRUNCSTORE:i24 X -> TRUNCSTORE:i16 (srl X, 8), TRUNCSTORE@+2:i8 X
1492 // Store the top RoundWidth bits.
1493 Hi = DAG.getNode(ISD::SRL, dl, Tmp3.getValueType(), Tmp3,
1494 DAG.getConstant(ExtraWidth, TLI.getShiftAmountTy()));
1495 Hi = DAG.getTruncStore(Tmp1, dl, Hi, Tmp2, ST->getPointerInfo(),
1496 RoundVT, isVolatile, isNonTemporal, Alignment);
1498 // Store the remaining ExtraWidth bits.
1499 IncrementSize = RoundWidth / 8;
1500 Tmp2 = DAG.getNode(ISD::ADD, dl, Tmp2.getValueType(), Tmp2,
1501 DAG.getIntPtrConstant(IncrementSize));
1502 Lo = DAG.getTruncStore(Tmp1, dl, Tmp3, Tmp2,
1503 ST->getPointerInfo().getWithOffset(IncrementSize),
1504 ExtraVT, isVolatile, isNonTemporal,
1505 MinAlign(Alignment, IncrementSize));
1508 // The order of the stores doesn't matter.
1509 Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo, Hi);
1511 if (Tmp1 != ST->getChain() || Tmp3 != ST->getValue() ||
1512 Tmp2 != ST->getBasePtr())
1513 Result = SDValue(DAG.UpdateNodeOperands(Result.getNode(),
1518 switch (TLI.getTruncStoreAction(ST->getValue().getValueType(), StVT)) {
1519 default: assert(0 && "This action is not supported yet!");
1520 case TargetLowering::Legal:
1521 // If this is an unaligned store and the target doesn't support it,
1523 if (!TLI.allowsUnalignedMemoryAccesses(ST->getMemoryVT())) {
1524 const Type *Ty = ST->getMemoryVT().getTypeForEVT(*DAG.getContext());
1525 unsigned ABIAlignment= TLI.getTargetData()->getABITypeAlignment(Ty);
1526 if (ST->getAlignment() < ABIAlignment)
1527 Result = ExpandUnalignedStore(cast<StoreSDNode>(Result.getNode()),
1531 case TargetLowering::Custom:
1532 Result = TLI.LowerOperation(Result, DAG);
1535 // TRUNCSTORE:i16 i32 -> STORE i16
1536 assert(isTypeLegal(StVT) && "Do not know how to expand this store!");
1537 Tmp3 = DAG.getNode(ISD::TRUNCATE, dl, StVT, Tmp3);
1538 Result = DAG.getStore(Tmp1, dl, Tmp3, Tmp2, ST->getPointerInfo(),
1539 isVolatile, isNonTemporal, Alignment);
1547 assert(Result.getValueType() == Op.getValueType() &&
1548 "Bad legalization!");
1550 // Make sure that the generated code is itself legal.
1552 Result = LegalizeOp(Result);
1554 // Note that LegalizeOp may be reentered even from single-use nodes, which
1555 // means that we always must cache transformed nodes.
1556 AddLegalizedOperand(Op, Result);
1560 SDValue SelectionDAGLegalize::ExpandExtractFromVectorThroughStack(SDValue Op) {
1561 SDValue Vec = Op.getOperand(0);
1562 SDValue Idx = Op.getOperand(1);
1563 DebugLoc dl = Op.getDebugLoc();
1564 // Store the value to a temporary stack slot, then LOAD the returned part.
1565 SDValue StackPtr = DAG.CreateStackTemporary(Vec.getValueType());
1566 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, Vec, StackPtr,
1567 MachinePointerInfo(), false, false, 0);
1569 // Add the offset to the index.
1571 Vec.getValueType().getVectorElementType().getSizeInBits()/8;
1572 Idx = DAG.getNode(ISD::MUL, dl, Idx.getValueType(), Idx,
1573 DAG.getConstant(EltSize, Idx.getValueType()));
1575 if (Idx.getValueType().bitsGT(TLI.getPointerTy()))
1576 Idx = DAG.getNode(ISD::TRUNCATE, dl, TLI.getPointerTy(), Idx);
1578 Idx = DAG.getNode(ISD::ZERO_EXTEND, dl, TLI.getPointerTy(), Idx);
1580 StackPtr = DAG.getNode(ISD::ADD, dl, Idx.getValueType(), Idx, StackPtr);
1582 if (Op.getValueType().isVector())
1583 return DAG.getLoad(Op.getValueType(), dl, Ch, StackPtr,MachinePointerInfo(),
1585 return DAG.getExtLoad(ISD::EXTLOAD, Op.getValueType(), dl, Ch, StackPtr,
1586 MachinePointerInfo(),
1587 Vec.getValueType().getVectorElementType(),
1591 SDValue SelectionDAGLegalize::ExpandVectorBuildThroughStack(SDNode* Node) {
1592 // We can't handle this case efficiently. Allocate a sufficiently
1593 // aligned object on the stack, store each element into it, then load
1594 // the result as a vector.
1595 // Create the stack frame object.
1596 EVT VT = Node->getValueType(0);
1597 EVT EltVT = VT.getVectorElementType();
1598 DebugLoc dl = Node->getDebugLoc();
1599 SDValue FIPtr = DAG.CreateStackTemporary(VT);
1600 int FI = cast<FrameIndexSDNode>(FIPtr.getNode())->getIndex();
1601 MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(FI);
1603 // Emit a store of each element to the stack slot.
1604 SmallVector<SDValue, 8> Stores;
1605 unsigned TypeByteSize = EltVT.getSizeInBits() / 8;
1606 // Store (in the right endianness) the elements to memory.
1607 for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
1608 // Ignore undef elements.
1609 if (Node->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1611 unsigned Offset = TypeByteSize*i;
1613 SDValue Idx = DAG.getConstant(Offset, FIPtr.getValueType());
1614 Idx = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr, Idx);
1616 // If the destination vector element type is narrower than the source
1617 // element type, only store the bits necessary.
1618 if (EltVT.bitsLT(Node->getOperand(i).getValueType().getScalarType())) {
1619 Stores.push_back(DAG.getTruncStore(DAG.getEntryNode(), dl,
1620 Node->getOperand(i), Idx,
1621 PtrInfo.getWithOffset(Offset),
1622 EltVT, false, false, 0));
1624 Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl,
1625 Node->getOperand(i), Idx,
1626 PtrInfo.getWithOffset(Offset),
1631 if (!Stores.empty()) // Not all undef elements?
1632 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1633 &Stores[0], Stores.size());
1635 StoreChain = DAG.getEntryNode();
1637 // Result is a load from the stack slot.
1638 return DAG.getLoad(VT, dl, StoreChain, FIPtr, PtrInfo, false, false, 0);
1641 SDValue SelectionDAGLegalize::ExpandFCOPYSIGN(SDNode* Node) {
1642 DebugLoc dl = Node->getDebugLoc();
1643 SDValue Tmp1 = Node->getOperand(0);
1644 SDValue Tmp2 = Node->getOperand(1);
1646 // Get the sign bit of the RHS. First obtain a value that has the same
1647 // sign as the sign bit, i.e. negative if and only if the sign bit is 1.
1649 EVT FloatVT = Tmp2.getValueType();
1650 EVT IVT = EVT::getIntegerVT(*DAG.getContext(), FloatVT.getSizeInBits());
1651 if (isTypeLegal(IVT)) {
1652 // Convert to an integer with the same sign bit.
1653 SignBit = DAG.getNode(ISD::BITCAST, dl, IVT, Tmp2);
1655 // Store the float to memory, then load the sign part out as an integer.
1656 MVT LoadTy = TLI.getPointerTy();
1657 // First create a temporary that is aligned for both the load and store.
1658 SDValue StackPtr = DAG.CreateStackTemporary(FloatVT, LoadTy);
1659 // Then store the float to it.
1661 DAG.getStore(DAG.getEntryNode(), dl, Tmp2, StackPtr, MachinePointerInfo(),
1663 if (TLI.isBigEndian()) {
1664 assert(FloatVT.isByteSized() && "Unsupported floating point type!");
1665 // Load out a legal integer with the same sign bit as the float.
1666 SignBit = DAG.getLoad(LoadTy, dl, Ch, StackPtr, MachinePointerInfo(),
1668 } else { // Little endian
1669 SDValue LoadPtr = StackPtr;
1670 // The float may be wider than the integer we are going to load. Advance
1671 // the pointer so that the loaded integer will contain the sign bit.
1672 unsigned Strides = (FloatVT.getSizeInBits()-1)/LoadTy.getSizeInBits();
1673 unsigned ByteOffset = (Strides * LoadTy.getSizeInBits()) / 8;
1674 LoadPtr = DAG.getNode(ISD::ADD, dl, LoadPtr.getValueType(),
1675 LoadPtr, DAG.getIntPtrConstant(ByteOffset));
1676 // Load a legal integer containing the sign bit.
1677 SignBit = DAG.getLoad(LoadTy, dl, Ch, LoadPtr, MachinePointerInfo(),
1679 // Move the sign bit to the top bit of the loaded integer.
1680 unsigned BitShift = LoadTy.getSizeInBits() -
1681 (FloatVT.getSizeInBits() - 8 * ByteOffset);
1682 assert(BitShift < LoadTy.getSizeInBits() && "Pointer advanced wrong?");
1684 SignBit = DAG.getNode(ISD::SHL, dl, LoadTy, SignBit,
1685 DAG.getConstant(BitShift,TLI.getShiftAmountTy()));
1688 // Now get the sign bit proper, by seeing whether the value is negative.
1689 SignBit = DAG.getSetCC(dl, TLI.getSetCCResultType(SignBit.getValueType()),
1690 SignBit, DAG.getConstant(0, SignBit.getValueType()),
1692 // Get the absolute value of the result.
1693 SDValue AbsVal = DAG.getNode(ISD::FABS, dl, Tmp1.getValueType(), Tmp1);
1694 // Select between the nabs and abs value based on the sign bit of
1696 return DAG.getNode(ISD::SELECT, dl, AbsVal.getValueType(), SignBit,
1697 DAG.getNode(ISD::FNEG, dl, AbsVal.getValueType(), AbsVal),
1701 void SelectionDAGLegalize::ExpandDYNAMIC_STACKALLOC(SDNode* Node,
1702 SmallVectorImpl<SDValue> &Results) {
1703 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
1704 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
1705 " not tell us which reg is the stack pointer!");
1706 DebugLoc dl = Node->getDebugLoc();
1707 EVT VT = Node->getValueType(0);
1708 SDValue Tmp1 = SDValue(Node, 0);
1709 SDValue Tmp2 = SDValue(Node, 1);
1710 SDValue Tmp3 = Node->getOperand(2);
1711 SDValue Chain = Tmp1.getOperand(0);
1713 // Chain the dynamic stack allocation so that it doesn't modify the stack
1714 // pointer when other instructions are using the stack.
1715 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true));
1717 SDValue Size = Tmp2.getOperand(1);
1718 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
1719 Chain = SP.getValue(1);
1720 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
1721 unsigned StackAlign = TM.getFrameLowering()->getStackAlignment();
1722 if (Align > StackAlign)
1723 SP = DAG.getNode(ISD::AND, dl, VT, SP,
1724 DAG.getConstant(-(uint64_t)Align, VT));
1725 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
1726 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
1728 Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
1729 DAG.getIntPtrConstant(0, true), SDValue());
1731 Results.push_back(Tmp1);
1732 Results.push_back(Tmp2);
1735 /// LegalizeSetCCCondCode - Legalize a SETCC with given LHS and RHS and
1736 /// condition code CC on the current target. This routine expands SETCC with
1737 /// illegal condition code into AND / OR of multiple SETCC values.
1738 void SelectionDAGLegalize::LegalizeSetCCCondCode(EVT VT,
1739 SDValue &LHS, SDValue &RHS,
1742 EVT OpVT = LHS.getValueType();
1743 ISD::CondCode CCCode = cast<CondCodeSDNode>(CC)->get();
1744 switch (TLI.getCondCodeAction(CCCode, OpVT)) {
1745 default: assert(0 && "Unknown condition code action!");
1746 case TargetLowering::Legal:
1749 case TargetLowering::Expand: {
1750 ISD::CondCode CC1 = ISD::SETCC_INVALID, CC2 = ISD::SETCC_INVALID;
1753 default: assert(0 && "Don't know how to expand this condition!");
1754 case ISD::SETOEQ: CC1 = ISD::SETEQ; CC2 = ISD::SETO; Opc = ISD::AND; break;
1755 case ISD::SETOGT: CC1 = ISD::SETGT; CC2 = ISD::SETO; Opc = ISD::AND; break;
1756 case ISD::SETOGE: CC1 = ISD::SETGE; CC2 = ISD::SETO; Opc = ISD::AND; break;
1757 case ISD::SETOLT: CC1 = ISD::SETLT; CC2 = ISD::SETO; Opc = ISD::AND; break;
1758 case ISD::SETOLE: CC1 = ISD::SETLE; CC2 = ISD::SETO; Opc = ISD::AND; break;
1759 case ISD::SETONE: CC1 = ISD::SETNE; CC2 = ISD::SETO; Opc = ISD::AND; break;
1760 case ISD::SETUEQ: CC1 = ISD::SETEQ; CC2 = ISD::SETUO; Opc = ISD::OR; break;
1761 case ISD::SETUGT: CC1 = ISD::SETGT; CC2 = ISD::SETUO; Opc = ISD::OR; break;
1762 case ISD::SETUGE: CC1 = ISD::SETGE; CC2 = ISD::SETUO; Opc = ISD::OR; break;
1763 case ISD::SETULT: CC1 = ISD::SETLT; CC2 = ISD::SETUO; Opc = ISD::OR; break;
1764 case ISD::SETULE: CC1 = ISD::SETLE; CC2 = ISD::SETUO; Opc = ISD::OR; break;
1765 case ISD::SETUNE: CC1 = ISD::SETNE; CC2 = ISD::SETUO; Opc = ISD::OR; break;
1766 // FIXME: Implement more expansions.
1769 SDValue SetCC1 = DAG.getSetCC(dl, VT, LHS, RHS, CC1);
1770 SDValue SetCC2 = DAG.getSetCC(dl, VT, LHS, RHS, CC2);
1771 LHS = DAG.getNode(Opc, dl, VT, SetCC1, SetCC2);
1779 /// EmitStackConvert - Emit a store/load combination to the stack. This stores
1780 /// SrcOp to a stack slot of type SlotVT, truncating it if needed. It then does
1781 /// a load from the stack slot to DestVT, extending it if needed.
1782 /// The resultant code need not be legal.
1783 SDValue SelectionDAGLegalize::EmitStackConvert(SDValue SrcOp,
1787 // Create the stack frame object.
1789 TLI.getTargetData()->getPrefTypeAlignment(SrcOp.getValueType().
1790 getTypeForEVT(*DAG.getContext()));
1791 SDValue FIPtr = DAG.CreateStackTemporary(SlotVT, SrcAlign);
1793 FrameIndexSDNode *StackPtrFI = cast<FrameIndexSDNode>(FIPtr);
1794 int SPFI = StackPtrFI->getIndex();
1795 MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(SPFI);
1797 unsigned SrcSize = SrcOp.getValueType().getSizeInBits();
1798 unsigned SlotSize = SlotVT.getSizeInBits();
1799 unsigned DestSize = DestVT.getSizeInBits();
1800 const Type *DestType = DestVT.getTypeForEVT(*DAG.getContext());
1801 unsigned DestAlign = TLI.getTargetData()->getPrefTypeAlignment(DestType);
1803 // Emit a store to the stack slot. Use a truncstore if the input value is
1804 // later than DestVT.
1807 if (SrcSize > SlotSize)
1808 Store = DAG.getTruncStore(DAG.getEntryNode(), dl, SrcOp, FIPtr,
1809 PtrInfo, SlotVT, false, false, SrcAlign);
1811 assert(SrcSize == SlotSize && "Invalid store");
1812 Store = DAG.getStore(DAG.getEntryNode(), dl, SrcOp, FIPtr,
1813 PtrInfo, false, false, SrcAlign);
1816 // Result is a load from the stack slot.
1817 if (SlotSize == DestSize)
1818 return DAG.getLoad(DestVT, dl, Store, FIPtr, PtrInfo,
1819 false, false, DestAlign);
1821 assert(SlotSize < DestSize && "Unknown extension!");
1822 return DAG.getExtLoad(ISD::EXTLOAD, DestVT, dl, Store, FIPtr,
1823 PtrInfo, SlotVT, false, false, DestAlign);
1826 SDValue SelectionDAGLegalize::ExpandSCALAR_TO_VECTOR(SDNode *Node) {
1827 DebugLoc dl = Node->getDebugLoc();
1828 // Create a vector sized/aligned stack slot, store the value to element #0,
1829 // then load the whole vector back out.
1830 SDValue StackPtr = DAG.CreateStackTemporary(Node->getValueType(0));
1832 FrameIndexSDNode *StackPtrFI = cast<FrameIndexSDNode>(StackPtr);
1833 int SPFI = StackPtrFI->getIndex();
1835 SDValue Ch = DAG.getTruncStore(DAG.getEntryNode(), dl, Node->getOperand(0),
1837 MachinePointerInfo::getFixedStack(SPFI),
1838 Node->getValueType(0).getVectorElementType(),
1840 return DAG.getLoad(Node->getValueType(0), dl, Ch, StackPtr,
1841 MachinePointerInfo::getFixedStack(SPFI),
1846 /// ExpandBUILD_VECTOR - Expand a BUILD_VECTOR node on targets that don't
1847 /// support the operation, but do support the resultant vector type.
1848 SDValue SelectionDAGLegalize::ExpandBUILD_VECTOR(SDNode *Node) {
1849 unsigned NumElems = Node->getNumOperands();
1850 SDValue Value1, Value2;
1851 DebugLoc dl = Node->getDebugLoc();
1852 EVT VT = Node->getValueType(0);
1853 EVT OpVT = Node->getOperand(0).getValueType();
1854 EVT EltVT = VT.getVectorElementType();
1856 // If the only non-undef value is the low element, turn this into a
1857 // SCALAR_TO_VECTOR node. If this is { X, X, X, X }, determine X.
1858 bool isOnlyLowElement = true;
1859 bool MoreThanTwoValues = false;
1860 bool isConstant = true;
1861 for (unsigned i = 0; i < NumElems; ++i) {
1862 SDValue V = Node->getOperand(i);
1863 if (V.getOpcode() == ISD::UNDEF)
1866 isOnlyLowElement = false;
1867 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
1870 if (!Value1.getNode()) {
1872 } else if (!Value2.getNode()) {
1875 } else if (V != Value1 && V != Value2) {
1876 MoreThanTwoValues = true;
1880 if (!Value1.getNode())
1881 return DAG.getUNDEF(VT);
1883 if (isOnlyLowElement)
1884 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Node->getOperand(0));
1886 // If all elements are constants, create a load from the constant pool.
1888 std::vector<Constant*> CV;
1889 for (unsigned i = 0, e = NumElems; i != e; ++i) {
1890 if (ConstantFPSDNode *V =
1891 dyn_cast<ConstantFPSDNode>(Node->getOperand(i))) {
1892 CV.push_back(const_cast<ConstantFP *>(V->getConstantFPValue()));
1893 } else if (ConstantSDNode *V =
1894 dyn_cast<ConstantSDNode>(Node->getOperand(i))) {
1896 CV.push_back(const_cast<ConstantInt *>(V->getConstantIntValue()));
1898 // If OpVT and EltVT don't match, EltVT is not legal and the
1899 // element values have been promoted/truncated earlier. Undo this;
1900 // we don't want a v16i8 to become a v16i32 for example.
1901 const ConstantInt *CI = V->getConstantIntValue();
1902 CV.push_back(ConstantInt::get(EltVT.getTypeForEVT(*DAG.getContext()),
1903 CI->getZExtValue()));
1906 assert(Node->getOperand(i).getOpcode() == ISD::UNDEF);
1907 const Type *OpNTy = EltVT.getTypeForEVT(*DAG.getContext());
1908 CV.push_back(UndefValue::get(OpNTy));
1911 Constant *CP = ConstantVector::get(CV);
1912 SDValue CPIdx = DAG.getConstantPool(CP, TLI.getPointerTy());
1913 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
1914 return DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
1915 MachinePointerInfo::getConstantPool(),
1916 false, false, Alignment);
1919 if (!MoreThanTwoValues) {
1920 SmallVector<int, 8> ShuffleVec(NumElems, -1);
1921 for (unsigned i = 0; i < NumElems; ++i) {
1922 SDValue V = Node->getOperand(i);
1923 if (V.getOpcode() == ISD::UNDEF)
1925 ShuffleVec[i] = V == Value1 ? 0 : NumElems;
1927 if (TLI.isShuffleMaskLegal(ShuffleVec, Node->getValueType(0))) {
1928 // Get the splatted value into the low element of a vector register.
1929 SDValue Vec1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value1);
1931 if (Value2.getNode())
1932 Vec2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value2);
1934 Vec2 = DAG.getUNDEF(VT);
1936 // Return shuffle(LowValVec, undef, <0,0,0,0>)
1937 return DAG.getVectorShuffle(VT, dl, Vec1, Vec2, ShuffleVec.data());
1941 // Otherwise, we can't handle this case efficiently.
1942 return ExpandVectorBuildThroughStack(Node);
1945 // ExpandLibCall - Expand a node into a call to a libcall. If the result value
1946 // does not fit into a register, return the lo part and set the hi part to the
1947 // by-reg argument. If it does fit into a single register, return the result
1948 // and leave the Hi part unset.
1949 SDValue SelectionDAGLegalize::ExpandLibCall(RTLIB::Libcall LC, SDNode *Node,
1951 // The input chain to this libcall is the entry node of the function.
1952 // Legalizing the call will automatically add the previous call to the
1954 SDValue InChain = DAG.getEntryNode();
1956 TargetLowering::ArgListTy Args;
1957 TargetLowering::ArgListEntry Entry;
1958 for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
1959 EVT ArgVT = Node->getOperand(i).getValueType();
1960 const Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
1961 Entry.Node = Node->getOperand(i); Entry.Ty = ArgTy;
1962 Entry.isSExt = isSigned;
1963 Entry.isZExt = !isSigned;
1964 Args.push_back(Entry);
1966 SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC),
1967 TLI.getPointerTy());
1969 // Splice the libcall in wherever FindInputOutputChains tells us to.
1970 const Type *RetTy = Node->getValueType(0).getTypeForEVT(*DAG.getContext());
1972 // isTailCall may be true since the callee does not reference caller stack
1973 // frame. Check if it's in the right position.
1974 bool isTailCall = isInTailCallPosition(DAG, Node, TLI);
1975 std::pair<SDValue, SDValue> CallInfo =
1976 TLI.LowerCallTo(InChain, RetTy, isSigned, !isSigned, false, false,
1977 0, TLI.getLibcallCallingConv(LC), isTailCall,
1978 /*isReturnValueUsed=*/true,
1979 Callee, Args, DAG, Node->getDebugLoc());
1981 if (!CallInfo.second.getNode())
1982 // It's a tailcall, return the chain (which is the DAG root).
1983 return DAG.getRoot();
1985 // Legalize the call sequence, starting with the chain. This will advance
1986 // the LastCALLSEQ_END to the legalized version of the CALLSEQ_END node that
1987 // was added by LowerCallTo (guaranteeing proper serialization of calls).
1988 LegalizeOp(CallInfo.second);
1989 return CallInfo.first;
1992 // ExpandChainLibCall - Expand a node into a call to a libcall. Similar to
1993 // ExpandLibCall except that the first operand is the in-chain.
1994 std::pair<SDValue, SDValue>
1995 SelectionDAGLegalize::ExpandChainLibCall(RTLIB::Libcall LC,
1998 SDValue InChain = Node->getOperand(0);
2000 TargetLowering::ArgListTy Args;
2001 TargetLowering::ArgListEntry Entry;
2002 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i) {
2003 EVT ArgVT = Node->getOperand(i).getValueType();
2004 const Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2005 Entry.Node = Node->getOperand(i);
2007 Entry.isSExt = isSigned;
2008 Entry.isZExt = !isSigned;
2009 Args.push_back(Entry);
2011 SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC),
2012 TLI.getPointerTy());
2014 // Splice the libcall in wherever FindInputOutputChains tells us to.
2015 const Type *RetTy = Node->getValueType(0).getTypeForEVT(*DAG.getContext());
2016 std::pair<SDValue, SDValue> CallInfo =
2017 TLI.LowerCallTo(InChain, RetTy, isSigned, !isSigned, false, false,
2018 0, TLI.getLibcallCallingConv(LC), /*isTailCall=*/false,
2019 /*isReturnValueUsed=*/true,
2020 Callee, Args, DAG, Node->getDebugLoc());
2022 // Legalize the call sequence, starting with the chain. This will advance
2023 // the LastCALLSEQ_END to the legalized version of the CALLSEQ_END node that
2024 // was added by LowerCallTo (guaranteeing proper serialization of calls).
2025 LegalizeOp(CallInfo.second);
2029 SDValue SelectionDAGLegalize::ExpandFPLibCall(SDNode* Node,
2030 RTLIB::Libcall Call_F32,
2031 RTLIB::Libcall Call_F64,
2032 RTLIB::Libcall Call_F80,
2033 RTLIB::Libcall Call_PPCF128) {
2035 switch (Node->getValueType(0).getSimpleVT().SimpleTy) {
2036 default: assert(0 && "Unexpected request for libcall!");
2037 case MVT::f32: LC = Call_F32; break;
2038 case MVT::f64: LC = Call_F64; break;
2039 case MVT::f80: LC = Call_F80; break;
2040 case MVT::ppcf128: LC = Call_PPCF128; break;
2042 return ExpandLibCall(LC, Node, false);
2045 SDValue SelectionDAGLegalize::ExpandIntLibCall(SDNode* Node, bool isSigned,
2046 RTLIB::Libcall Call_I8,
2047 RTLIB::Libcall Call_I16,
2048 RTLIB::Libcall Call_I32,
2049 RTLIB::Libcall Call_I64,
2050 RTLIB::Libcall Call_I128) {
2052 switch (Node->getValueType(0).getSimpleVT().SimpleTy) {
2053 default: assert(0 && "Unexpected request for libcall!");
2054 case MVT::i8: LC = Call_I8; break;
2055 case MVT::i16: LC = Call_I16; break;
2056 case MVT::i32: LC = Call_I32; break;
2057 case MVT::i64: LC = Call_I64; break;
2058 case MVT::i128: LC = Call_I128; break;
2060 return ExpandLibCall(LC, Node, isSigned);
2063 /// ExpandLegalINT_TO_FP - This function is responsible for legalizing a
2064 /// INT_TO_FP operation of the specified operand when the target requests that
2065 /// we expand it. At this point, we know that the result and operand types are
2066 /// legal for the target.
2067 SDValue SelectionDAGLegalize::ExpandLegalINT_TO_FP(bool isSigned,
2071 if (Op0.getValueType() == MVT::i32) {
2072 // simple 32-bit [signed|unsigned] integer to float/double expansion
2074 // Get the stack frame index of a 8 byte buffer.
2075 SDValue StackSlot = DAG.CreateStackTemporary(MVT::f64);
2077 // word offset constant for Hi/Lo address computation
2078 SDValue WordOff = DAG.getConstant(sizeof(int), TLI.getPointerTy());
2079 // set up Hi and Lo (into buffer) address based on endian
2080 SDValue Hi = StackSlot;
2081 SDValue Lo = DAG.getNode(ISD::ADD, dl,
2082 TLI.getPointerTy(), StackSlot, WordOff);
2083 if (TLI.isLittleEndian())
2086 // if signed map to unsigned space
2089 // constant used to invert sign bit (signed to unsigned mapping)
2090 SDValue SignBit = DAG.getConstant(0x80000000u, MVT::i32);
2091 Op0Mapped = DAG.getNode(ISD::XOR, dl, MVT::i32, Op0, SignBit);
2095 // store the lo of the constructed double - based on integer input
2096 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl,
2097 Op0Mapped, Lo, MachinePointerInfo(),
2099 // initial hi portion of constructed double
2100 SDValue InitialHi = DAG.getConstant(0x43300000u, MVT::i32);
2101 // store the hi of the constructed double - biased exponent
2102 SDValue Store2 = DAG.getStore(Store1, dl, InitialHi, Hi,
2103 MachinePointerInfo(),
2105 // load the constructed double
2106 SDValue Load = DAG.getLoad(MVT::f64, dl, Store2, StackSlot,
2107 MachinePointerInfo(), false, false, 0);
2108 // FP constant to bias correct the final result
2109 SDValue Bias = DAG.getConstantFP(isSigned ?
2110 BitsToDouble(0x4330000080000000ULL) :
2111 BitsToDouble(0x4330000000000000ULL),
2113 // subtract the bias
2114 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Load, Bias);
2117 // handle final rounding
2118 if (DestVT == MVT::f64) {
2121 } else if (DestVT.bitsLT(MVT::f64)) {
2122 Result = DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
2123 DAG.getIntPtrConstant(0));
2124 } else if (DestVT.bitsGT(MVT::f64)) {
2125 Result = DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
2129 assert(!isSigned && "Legalize cannot Expand SINT_TO_FP for i64 yet");
2130 // Code below here assumes !isSigned without checking again.
2132 // Implementation of unsigned i64 to f64 following the algorithm in
2133 // __floatundidf in compiler_rt. This implementation has the advantage
2134 // of performing rounding correctly, both in the default rounding mode
2135 // and in all alternate rounding modes.
2136 // TODO: Generalize this for use with other types.
2137 if (Op0.getValueType() == MVT::i64 && DestVT == MVT::f64) {
2139 DAG.getConstant(UINT64_C(0x4330000000000000), MVT::i64);
2140 SDValue TwoP84PlusTwoP52 =
2141 DAG.getConstantFP(BitsToDouble(UINT64_C(0x4530000000100000)), MVT::f64);
2143 DAG.getConstant(UINT64_C(0x4530000000000000), MVT::i64);
2145 SDValue Lo = DAG.getZeroExtendInReg(Op0, dl, MVT::i32);
2146 SDValue Hi = DAG.getNode(ISD::SRL, dl, MVT::i64, Op0,
2147 DAG.getConstant(32, MVT::i64));
2148 SDValue LoOr = DAG.getNode(ISD::OR, dl, MVT::i64, Lo, TwoP52);
2149 SDValue HiOr = DAG.getNode(ISD::OR, dl, MVT::i64, Hi, TwoP84);
2150 SDValue LoFlt = DAG.getNode(ISD::BITCAST, dl, MVT::f64, LoOr);
2151 SDValue HiFlt = DAG.getNode(ISD::BITCAST, dl, MVT::f64, HiOr);
2152 SDValue HiSub = DAG.getNode(ISD::FSUB, dl, MVT::f64, HiFlt,
2154 return DAG.getNode(ISD::FADD, dl, MVT::f64, LoFlt, HiSub);
2157 // Implementation of unsigned i64 to f32.
2158 // TODO: Generalize this for use with other types.
2159 if (Op0.getValueType() == MVT::i64 && DestVT == MVT::f32) {
2160 // For unsigned conversions, convert them to signed conversions using the
2161 // algorithm from the x86_64 __floatundidf in compiler_rt.
2163 SDValue Fast = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, Op0);
2165 SDValue ShiftConst = DAG.getConstant(1, TLI.getShiftAmountTy());
2166 SDValue Shr = DAG.getNode(ISD::SRL, dl, MVT::i64, Op0, ShiftConst);
2167 SDValue AndConst = DAG.getConstant(1, MVT::i64);
2168 SDValue And = DAG.getNode(ISD::AND, dl, MVT::i64, Op0, AndConst);
2169 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::i64, And, Shr);
2171 SDValue SignCvt = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, Or);
2172 SDValue Slow = DAG.getNode(ISD::FADD, dl, MVT::f32, SignCvt, SignCvt);
2174 // TODO: This really should be implemented using a branch rather than a
2175 // select. We happen to get lucky and machinesink does the right
2176 // thing most of the time. This would be a good candidate for a
2177 //pseudo-op, or, even better, for whole-function isel.
2178 SDValue SignBitTest = DAG.getSetCC(dl, TLI.getSetCCResultType(MVT::i64),
2179 Op0, DAG.getConstant(0, MVT::i64), ISD::SETLT);
2180 return DAG.getNode(ISD::SELECT, dl, MVT::f32, SignBitTest, Slow, Fast);
2183 // Otherwise, implement the fully general conversion.
2184 EVT SHVT = TLI.getShiftAmountTy();
2186 SDValue And = DAG.getNode(ISD::AND, dl, MVT::i64, Op0,
2187 DAG.getConstant(UINT64_C(0xfffffffffffff800), MVT::i64));
2188 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::i64, And,
2189 DAG.getConstant(UINT64_C(0x800), MVT::i64));
2190 SDValue And2 = DAG.getNode(ISD::AND, dl, MVT::i64, Op0,
2191 DAG.getConstant(UINT64_C(0x7ff), MVT::i64));
2192 SDValue Ne = DAG.getSetCC(dl, TLI.getSetCCResultType(MVT::i64),
2193 And2, DAG.getConstant(UINT64_C(0), MVT::i64), ISD::SETNE);
2194 SDValue Sel = DAG.getNode(ISD::SELECT, dl, MVT::i64, Ne, Or, Op0);
2195 SDValue Ge = DAG.getSetCC(dl, TLI.getSetCCResultType(MVT::i64),
2196 Op0, DAG.getConstant(UINT64_C(0x0020000000000000), MVT::i64),
2198 SDValue Sel2 = DAG.getNode(ISD::SELECT, dl, MVT::i64, Ge, Sel, Op0);
2200 SDValue Sh = DAG.getNode(ISD::SRL, dl, MVT::i64, Sel2,
2201 DAG.getConstant(32, SHVT));
2202 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Sh);
2203 SDValue Fcvt = DAG.getNode(ISD::UINT_TO_FP, dl, MVT::f64, Trunc);
2205 DAG.getConstantFP(BitsToDouble(UINT64_C(0x41f0000000000000)), MVT::f64);
2206 SDValue Fmul = DAG.getNode(ISD::FMUL, dl, MVT::f64, TwoP32, Fcvt);
2207 SDValue Lo = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Sel2);
2208 SDValue Fcvt2 = DAG.getNode(ISD::UINT_TO_FP, dl, MVT::f64, Lo);
2209 SDValue Fadd = DAG.getNode(ISD::FADD, dl, MVT::f64, Fmul, Fcvt2);
2210 return DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, Fadd,
2211 DAG.getIntPtrConstant(0));
2214 SDValue Tmp1 = DAG.getNode(ISD::SINT_TO_FP, dl, DestVT, Op0);
2216 SDValue SignSet = DAG.getSetCC(dl, TLI.getSetCCResultType(Op0.getValueType()),
2217 Op0, DAG.getConstant(0, Op0.getValueType()),
2219 SDValue Zero = DAG.getIntPtrConstant(0), Four = DAG.getIntPtrConstant(4);
2220 SDValue CstOffset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(),
2221 SignSet, Four, Zero);
2223 // If the sign bit of the integer is set, the large number will be treated
2224 // as a negative number. To counteract this, the dynamic code adds an
2225 // offset depending on the data type.
2227 switch (Op0.getValueType().getSimpleVT().SimpleTy) {
2228 default: assert(0 && "Unsupported integer type!");
2229 case MVT::i8 : FF = 0x43800000ULL; break; // 2^8 (as a float)
2230 case MVT::i16: FF = 0x47800000ULL; break; // 2^16 (as a float)
2231 case MVT::i32: FF = 0x4F800000ULL; break; // 2^32 (as a float)
2232 case MVT::i64: FF = 0x5F800000ULL; break; // 2^64 (as a float)
2234 if (TLI.isLittleEndian()) FF <<= 32;
2235 Constant *FudgeFactor = ConstantInt::get(
2236 Type::getInt64Ty(*DAG.getContext()), FF);
2238 SDValue CPIdx = DAG.getConstantPool(FudgeFactor, TLI.getPointerTy());
2239 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
2240 CPIdx = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(), CPIdx, CstOffset);
2241 Alignment = std::min(Alignment, 4u);
2243 if (DestVT == MVT::f32)
2244 FudgeInReg = DAG.getLoad(MVT::f32, dl, DAG.getEntryNode(), CPIdx,
2245 MachinePointerInfo::getConstantPool(),
2246 false, false, Alignment);
2249 LegalizeOp(DAG.getExtLoad(ISD::EXTLOAD, DestVT, dl,
2250 DAG.getEntryNode(), CPIdx,
2251 MachinePointerInfo::getConstantPool(),
2252 MVT::f32, false, false, Alignment));
2255 return DAG.getNode(ISD::FADD, dl, DestVT, Tmp1, FudgeInReg);
2258 /// PromoteLegalINT_TO_FP - This function is responsible for legalizing a
2259 /// *INT_TO_FP operation of the specified operand when the target requests that
2260 /// we promote it. At this point, we know that the result and operand types are
2261 /// legal for the target, and that there is a legal UINT_TO_FP or SINT_TO_FP
2262 /// operation that takes a larger input.
2263 SDValue SelectionDAGLegalize::PromoteLegalINT_TO_FP(SDValue LegalOp,
2267 // First step, figure out the appropriate *INT_TO_FP operation to use.
2268 EVT NewInTy = LegalOp.getValueType();
2270 unsigned OpToUse = 0;
2272 // Scan for the appropriate larger type to use.
2274 NewInTy = (MVT::SimpleValueType)(NewInTy.getSimpleVT().SimpleTy+1);
2275 assert(NewInTy.isInteger() && "Ran out of possibilities!");
2277 // If the target supports SINT_TO_FP of this type, use it.
2278 if (TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, NewInTy)) {
2279 OpToUse = ISD::SINT_TO_FP;
2282 if (isSigned) continue;
2284 // If the target supports UINT_TO_FP of this type, use it.
2285 if (TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, NewInTy)) {
2286 OpToUse = ISD::UINT_TO_FP;
2290 // Otherwise, try a larger type.
2293 // Okay, we found the operation and type to use. Zero extend our input to the
2294 // desired type then run the operation on it.
2295 return DAG.getNode(OpToUse, dl, DestVT,
2296 DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
2297 dl, NewInTy, LegalOp));
2300 /// PromoteLegalFP_TO_INT - This function is responsible for legalizing a
2301 /// FP_TO_*INT operation of the specified operand when the target requests that
2302 /// we promote it. At this point, we know that the result and operand types are
2303 /// legal for the target, and that there is a legal FP_TO_UINT or FP_TO_SINT
2304 /// operation that returns a larger result.
2305 SDValue SelectionDAGLegalize::PromoteLegalFP_TO_INT(SDValue LegalOp,
2309 // First step, figure out the appropriate FP_TO*INT operation to use.
2310 EVT NewOutTy = DestVT;
2312 unsigned OpToUse = 0;
2314 // Scan for the appropriate larger type to use.
2316 NewOutTy = (MVT::SimpleValueType)(NewOutTy.getSimpleVT().SimpleTy+1);
2317 assert(NewOutTy.isInteger() && "Ran out of possibilities!");
2319 if (TLI.isOperationLegalOrCustom(ISD::FP_TO_SINT, NewOutTy)) {
2320 OpToUse = ISD::FP_TO_SINT;
2324 if (TLI.isOperationLegalOrCustom(ISD::FP_TO_UINT, NewOutTy)) {
2325 OpToUse = ISD::FP_TO_UINT;
2329 // Otherwise, try a larger type.
2333 // Okay, we found the operation and type to use.
2334 SDValue Operation = DAG.getNode(OpToUse, dl, NewOutTy, LegalOp);
2336 // Truncate the result of the extended FP_TO_*INT operation to the desired
2338 return DAG.getNode(ISD::TRUNCATE, dl, DestVT, Operation);
2341 /// ExpandBSWAP - Open code the operations for BSWAP of the specified operation.
2343 SDValue SelectionDAGLegalize::ExpandBSWAP(SDValue Op, DebugLoc dl) {
2344 EVT VT = Op.getValueType();
2345 EVT SHVT = TLI.getShiftAmountTy();
2346 SDValue Tmp1, Tmp2, Tmp3, Tmp4, Tmp5, Tmp6, Tmp7, Tmp8;
2347 switch (VT.getSimpleVT().SimpleTy) {
2348 default: assert(0 && "Unhandled Expand type in BSWAP!");
2350 Tmp2 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, SHVT));
2351 Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, SHVT));
2352 return DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
2354 Tmp4 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, SHVT));
2355 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, SHVT));
2356 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, SHVT));
2357 Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, SHVT));
2358 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3, DAG.getConstant(0xFF0000, VT));
2359 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(0xFF00, VT));
2360 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3);
2361 Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1);
2362 return DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2);
2364 Tmp8 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(56, SHVT));
2365 Tmp7 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(40, SHVT));
2366 Tmp6 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, SHVT));
2367 Tmp5 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, SHVT));
2368 Tmp4 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, SHVT));
2369 Tmp3 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, SHVT));
2370 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(40, SHVT));
2371 Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(56, SHVT));
2372 Tmp7 = DAG.getNode(ISD::AND, dl, VT, Tmp7, DAG.getConstant(255ULL<<48, VT));
2373 Tmp6 = DAG.getNode(ISD::AND, dl, VT, Tmp6, DAG.getConstant(255ULL<<40, VT));
2374 Tmp5 = DAG.getNode(ISD::AND, dl, VT, Tmp5, DAG.getConstant(255ULL<<32, VT));
2375 Tmp4 = DAG.getNode(ISD::AND, dl, VT, Tmp4, DAG.getConstant(255ULL<<24, VT));
2376 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3, DAG.getConstant(255ULL<<16, VT));
2377 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(255ULL<<8 , VT));
2378 Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp7);
2379 Tmp6 = DAG.getNode(ISD::OR, dl, VT, Tmp6, Tmp5);
2380 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3);
2381 Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1);
2382 Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp6);
2383 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2);
2384 return DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp4);
2388 /// SplatByte - Distribute ByteVal over NumBits bits.
2389 // FIXME: Move this helper to a common place.
2390 static APInt SplatByte(unsigned NumBits, uint8_t ByteVal) {
2391 APInt Val = APInt(NumBits, ByteVal);
2393 for (unsigned i = NumBits; i > 8; i >>= 1) {
2394 Val = (Val << Shift) | Val;
2400 /// ExpandBitCount - Expand the specified bitcount instruction into operations.
2402 SDValue SelectionDAGLegalize::ExpandBitCount(unsigned Opc, SDValue Op,
2405 default: assert(0 && "Cannot expand this yet!");
2407 EVT VT = Op.getValueType();
2408 EVT ShVT = TLI.getShiftAmountTy();
2409 unsigned Len = VT.getSizeInBits();
2411 assert(VT.isInteger() && Len <= 128 && Len % 8 == 0 &&
2412 "CTPOP not implemented for this type.");
2414 // This is the "best" algorithm from
2415 // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
2417 SDValue Mask55 = DAG.getConstant(SplatByte(Len, 0x55), VT);
2418 SDValue Mask33 = DAG.getConstant(SplatByte(Len, 0x33), VT);
2419 SDValue Mask0F = DAG.getConstant(SplatByte(Len, 0x0F), VT);
2420 SDValue Mask01 = DAG.getConstant(SplatByte(Len, 0x01), VT);
2422 // v = v - ((v >> 1) & 0x55555555...)
2423 Op = DAG.getNode(ISD::SUB, dl, VT, Op,
2424 DAG.getNode(ISD::AND, dl, VT,
2425 DAG.getNode(ISD::SRL, dl, VT, Op,
2426 DAG.getConstant(1, ShVT)),
2428 // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
2429 Op = DAG.getNode(ISD::ADD, dl, VT,
2430 DAG.getNode(ISD::AND, dl, VT, Op, Mask33),
2431 DAG.getNode(ISD::AND, dl, VT,
2432 DAG.getNode(ISD::SRL, dl, VT, Op,
2433 DAG.getConstant(2, ShVT)),
2435 // v = (v + (v >> 4)) & 0x0F0F0F0F...
2436 Op = DAG.getNode(ISD::AND, dl, VT,
2437 DAG.getNode(ISD::ADD, dl, VT, Op,
2438 DAG.getNode(ISD::SRL, dl, VT, Op,
2439 DAG.getConstant(4, ShVT))),
2441 // v = (v * 0x01010101...) >> (Len - 8)
2442 Op = DAG.getNode(ISD::SRL, dl, VT,
2443 DAG.getNode(ISD::MUL, dl, VT, Op, Mask01),
2444 DAG.getConstant(Len - 8, ShVT));
2449 // for now, we do this:
2450 // x = x | (x >> 1);
2451 // x = x | (x >> 2);
2453 // x = x | (x >>16);
2454 // x = x | (x >>32); // for 64-bit input
2455 // return popcount(~x);
2457 // but see also: http://www.hackersdelight.org/HDcode/nlz.cc
2458 EVT VT = Op.getValueType();
2459 EVT ShVT = TLI.getShiftAmountTy();
2460 unsigned len = VT.getSizeInBits();
2461 for (unsigned i = 0; (1U << i) <= (len / 2); ++i) {
2462 SDValue Tmp3 = DAG.getConstant(1ULL << i, ShVT);
2463 Op = DAG.getNode(ISD::OR, dl, VT, Op,
2464 DAG.getNode(ISD::SRL, dl, VT, Op, Tmp3));
2466 Op = DAG.getNOT(dl, Op, VT);
2467 return DAG.getNode(ISD::CTPOP, dl, VT, Op);
2470 // for now, we use: { return popcount(~x & (x - 1)); }
2471 // unless the target has ctlz but not ctpop, in which case we use:
2472 // { return 32 - nlz(~x & (x-1)); }
2473 // see also http://www.hackersdelight.org/HDcode/ntz.cc
2474 EVT VT = Op.getValueType();
2475 SDValue Tmp3 = DAG.getNode(ISD::AND, dl, VT,
2476 DAG.getNOT(dl, Op, VT),
2477 DAG.getNode(ISD::SUB, dl, VT, Op,
2478 DAG.getConstant(1, VT)));
2479 // If ISD::CTLZ is legal and CTPOP isn't, then do that instead.
2480 if (!TLI.isOperationLegalOrCustom(ISD::CTPOP, VT) &&
2481 TLI.isOperationLegalOrCustom(ISD::CTLZ, VT))
2482 return DAG.getNode(ISD::SUB, dl, VT,
2483 DAG.getConstant(VT.getSizeInBits(), VT),
2484 DAG.getNode(ISD::CTLZ, dl, VT, Tmp3));
2485 return DAG.getNode(ISD::CTPOP, dl, VT, Tmp3);
2490 std::pair <SDValue, SDValue> SelectionDAGLegalize::ExpandAtomic(SDNode *Node) {
2491 unsigned Opc = Node->getOpcode();
2492 MVT VT = cast<AtomicSDNode>(Node)->getMemoryVT().getSimpleVT();
2497 llvm_unreachable("Unhandled atomic intrinsic Expand!");
2499 case ISD::ATOMIC_SWAP:
2500 switch (VT.SimpleTy) {
2501 default: llvm_unreachable("Unexpected value type for atomic!");
2502 case MVT::i8: LC = RTLIB::SYNC_LOCK_TEST_AND_SET_1; break;
2503 case MVT::i16: LC = RTLIB::SYNC_LOCK_TEST_AND_SET_2; break;
2504 case MVT::i32: LC = RTLIB::SYNC_LOCK_TEST_AND_SET_4; break;
2505 case MVT::i64: LC = RTLIB::SYNC_LOCK_TEST_AND_SET_8; break;
2508 case ISD::ATOMIC_CMP_SWAP:
2509 switch (VT.SimpleTy) {
2510 default: llvm_unreachable("Unexpected value type for atomic!");
2511 case MVT::i8: LC = RTLIB::SYNC_VAL_COMPARE_AND_SWAP_1; break;
2512 case MVT::i16: LC = RTLIB::SYNC_VAL_COMPARE_AND_SWAP_2; break;
2513 case MVT::i32: LC = RTLIB::SYNC_VAL_COMPARE_AND_SWAP_4; break;
2514 case MVT::i64: LC = RTLIB::SYNC_VAL_COMPARE_AND_SWAP_8; break;
2517 case ISD::ATOMIC_LOAD_ADD:
2518 switch (VT.SimpleTy) {
2519 default: llvm_unreachable("Unexpected value type for atomic!");
2520 case MVT::i8: LC = RTLIB::SYNC_FETCH_AND_ADD_1; break;
2521 case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_ADD_2; break;
2522 case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_ADD_4; break;
2523 case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_ADD_8; break;
2526 case ISD::ATOMIC_LOAD_SUB:
2527 switch (VT.SimpleTy) {
2528 default: llvm_unreachable("Unexpected value type for atomic!");
2529 case MVT::i8: LC = RTLIB::SYNC_FETCH_AND_SUB_1; break;
2530 case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_SUB_2; break;
2531 case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_SUB_4; break;
2532 case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_SUB_8; break;
2535 case ISD::ATOMIC_LOAD_AND:
2536 switch (VT.SimpleTy) {
2537 default: llvm_unreachable("Unexpected value type for atomic!");
2538 case MVT::i8: LC = RTLIB::SYNC_FETCH_AND_AND_1; break;
2539 case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_AND_2; break;
2540 case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_AND_4; break;
2541 case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_AND_8; break;
2544 case ISD::ATOMIC_LOAD_OR:
2545 switch (VT.SimpleTy) {
2546 default: llvm_unreachable("Unexpected value type for atomic!");
2547 case MVT::i8: LC = RTLIB::SYNC_FETCH_AND_OR_1; break;
2548 case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_OR_2; break;
2549 case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_OR_4; break;
2550 case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_OR_8; break;
2553 case ISD::ATOMIC_LOAD_XOR:
2554 switch (VT.SimpleTy) {
2555 default: llvm_unreachable("Unexpected value type for atomic!");
2556 case MVT::i8: LC = RTLIB::SYNC_FETCH_AND_XOR_1; break;
2557 case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_XOR_2; break;
2558 case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_XOR_4; break;
2559 case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_XOR_8; break;
2562 case ISD::ATOMIC_LOAD_NAND:
2563 switch (VT.SimpleTy) {
2564 default: llvm_unreachable("Unexpected value type for atomic!");
2565 case MVT::i8: LC = RTLIB::SYNC_FETCH_AND_NAND_1; break;
2566 case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_NAND_2; break;
2567 case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_NAND_4; break;
2568 case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_NAND_8; break;
2573 return ExpandChainLibCall(LC, Node, false);
2576 void SelectionDAGLegalize::ExpandNode(SDNode *Node,
2577 SmallVectorImpl<SDValue> &Results) {
2578 DebugLoc dl = Node->getDebugLoc();
2579 SDValue Tmp1, Tmp2, Tmp3, Tmp4;
2580 switch (Node->getOpcode()) {
2584 Tmp1 = ExpandBitCount(Node->getOpcode(), Node->getOperand(0), dl);
2585 Results.push_back(Tmp1);
2588 Results.push_back(ExpandBSWAP(Node->getOperand(0), dl));
2590 case ISD::FRAMEADDR:
2591 case ISD::RETURNADDR:
2592 case ISD::FRAME_TO_ARGS_OFFSET:
2593 Results.push_back(DAG.getConstant(0, Node->getValueType(0)));
2595 case ISD::FLT_ROUNDS_:
2596 Results.push_back(DAG.getConstant(1, Node->getValueType(0)));
2598 case ISD::EH_RETURN:
2602 case ISD::EH_SJLJ_LONGJMP:
2603 case ISD::EH_SJLJ_DISPATCHSETUP:
2604 // If the target didn't expand these, there's nothing to do, so just
2605 // preserve the chain and be done.
2606 Results.push_back(Node->getOperand(0));
2608 case ISD::EH_SJLJ_SETJMP:
2609 // If the target didn't expand this, just return 'zero' and preserve the
2611 Results.push_back(DAG.getConstant(0, MVT::i32));
2612 Results.push_back(Node->getOperand(0));
2614 case ISD::MEMBARRIER: {
2615 // If the target didn't lower this, lower it to '__sync_synchronize()' call
2616 TargetLowering::ArgListTy Args;
2617 std::pair<SDValue, SDValue> CallResult =
2618 TLI.LowerCallTo(Node->getOperand(0), Type::getVoidTy(*DAG.getContext()),
2619 false, false, false, false, 0, CallingConv::C,
2620 /*isTailCall=*/false,
2621 /*isReturnValueUsed=*/true,
2622 DAG.getExternalSymbol("__sync_synchronize",
2623 TLI.getPointerTy()),
2625 Results.push_back(CallResult.second);
2628 // By default, atomic intrinsics are marked Legal and lowered. Targets
2629 // which don't support them directly, however, may want libcalls, in which
2630 // case they mark them Expand, and we get here.
2631 case ISD::ATOMIC_SWAP:
2632 case ISD::ATOMIC_LOAD_ADD:
2633 case ISD::ATOMIC_LOAD_SUB:
2634 case ISD::ATOMIC_LOAD_AND:
2635 case ISD::ATOMIC_LOAD_OR:
2636 case ISD::ATOMIC_LOAD_XOR:
2637 case ISD::ATOMIC_LOAD_NAND:
2638 case ISD::ATOMIC_LOAD_MIN:
2639 case ISD::ATOMIC_LOAD_MAX:
2640 case ISD::ATOMIC_LOAD_UMIN:
2641 case ISD::ATOMIC_LOAD_UMAX:
2642 case ISD::ATOMIC_CMP_SWAP: {
2643 std::pair<SDValue, SDValue> Tmp = ExpandAtomic(Node);
2644 Results.push_back(Tmp.first);
2645 Results.push_back(Tmp.second);
2648 case ISD::DYNAMIC_STACKALLOC:
2649 ExpandDYNAMIC_STACKALLOC(Node, Results);
2651 case ISD::MERGE_VALUES:
2652 for (unsigned i = 0; i < Node->getNumValues(); i++)
2653 Results.push_back(Node->getOperand(i));
2656 EVT VT = Node->getValueType(0);
2658 Results.push_back(DAG.getConstant(0, VT));
2660 assert(VT.isFloatingPoint() && "Unknown value type!");
2661 Results.push_back(DAG.getConstantFP(0, VT));
2666 // If this operation is not supported, lower it to 'abort()' call
2667 TargetLowering::ArgListTy Args;
2668 std::pair<SDValue, SDValue> CallResult =
2669 TLI.LowerCallTo(Node->getOperand(0), Type::getVoidTy(*DAG.getContext()),
2670 false, false, false, false, 0, CallingConv::C,
2671 /*isTailCall=*/false,
2672 /*isReturnValueUsed=*/true,
2673 DAG.getExternalSymbol("abort", TLI.getPointerTy()),
2675 Results.push_back(CallResult.second);
2680 Tmp1 = EmitStackConvert(Node->getOperand(0), Node->getValueType(0),
2681 Node->getValueType(0), dl);
2682 Results.push_back(Tmp1);
2684 case ISD::FP_EXTEND:
2685 Tmp1 = EmitStackConvert(Node->getOperand(0),
2686 Node->getOperand(0).getValueType(),
2687 Node->getValueType(0), dl);
2688 Results.push_back(Tmp1);
2690 case ISD::SIGN_EXTEND_INREG: {
2691 // NOTE: we could fall back on load/store here too for targets without
2692 // SAR. However, it is doubtful that any exist.
2693 EVT ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
2694 EVT VT = Node->getValueType(0);
2695 EVT ShiftAmountTy = TLI.getShiftAmountTy();
2698 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
2699 ExtraVT.getScalarType().getSizeInBits();
2700 SDValue ShiftCst = DAG.getConstant(BitsDiff, ShiftAmountTy);
2701 Tmp1 = DAG.getNode(ISD::SHL, dl, Node->getValueType(0),
2702 Node->getOperand(0), ShiftCst);
2703 Tmp1 = DAG.getNode(ISD::SRA, dl, Node->getValueType(0), Tmp1, ShiftCst);
2704 Results.push_back(Tmp1);
2707 case ISD::FP_ROUND_INREG: {
2708 // The only way we can lower this is to turn it into a TRUNCSTORE,
2709 // EXTLOAD pair, targetting a temporary location (a stack slot).
2711 // NOTE: there is a choice here between constantly creating new stack
2712 // slots and always reusing the same one. We currently always create
2713 // new ones, as reuse may inhibit scheduling.
2714 EVT ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
2715 Tmp1 = EmitStackConvert(Node->getOperand(0), ExtraVT,
2716 Node->getValueType(0), dl);
2717 Results.push_back(Tmp1);
2720 case ISD::SINT_TO_FP:
2721 case ISD::UINT_TO_FP:
2722 Tmp1 = ExpandLegalINT_TO_FP(Node->getOpcode() == ISD::SINT_TO_FP,
2723 Node->getOperand(0), Node->getValueType(0), dl);
2724 Results.push_back(Tmp1);
2726 case ISD::FP_TO_UINT: {
2727 SDValue True, False;
2728 EVT VT = Node->getOperand(0).getValueType();
2729 EVT NVT = Node->getValueType(0);
2730 APFloat apf(APInt::getNullValue(VT.getSizeInBits()));
2731 APInt x = APInt::getSignBit(NVT.getSizeInBits());
2732 (void)apf.convertFromAPInt(x, false, APFloat::rmNearestTiesToEven);
2733 Tmp1 = DAG.getConstantFP(apf, VT);
2734 Tmp2 = DAG.getSetCC(dl, TLI.getSetCCResultType(VT),
2735 Node->getOperand(0),
2737 True = DAG.getNode(ISD::FP_TO_SINT, dl, NVT, Node->getOperand(0));
2738 False = DAG.getNode(ISD::FP_TO_SINT, dl, NVT,
2739 DAG.getNode(ISD::FSUB, dl, VT,
2740 Node->getOperand(0), Tmp1));
2741 False = DAG.getNode(ISD::XOR, dl, NVT, False,
2742 DAG.getConstant(x, NVT));
2743 Tmp1 = DAG.getNode(ISD::SELECT, dl, NVT, Tmp2, True, False);
2744 Results.push_back(Tmp1);
2748 const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2749 EVT VT = Node->getValueType(0);
2750 Tmp1 = Node->getOperand(0);
2751 Tmp2 = Node->getOperand(1);
2752 unsigned Align = Node->getConstantOperandVal(3);
2754 SDValue VAListLoad = DAG.getLoad(TLI.getPointerTy(), dl, Tmp1, Tmp2,
2755 MachinePointerInfo(V), false, false, 0);
2756 SDValue VAList = VAListLoad;
2758 if (Align > TLI.getMinStackArgumentAlignment()) {
2759 assert(((Align & (Align-1)) == 0) && "Expected Align to be a power of 2");
2761 VAList = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(), VAList,
2762 DAG.getConstant(Align - 1,
2763 TLI.getPointerTy()));
2765 VAList = DAG.getNode(ISD::AND, dl, TLI.getPointerTy(), VAList,
2766 DAG.getConstant(-(int64_t)Align,
2767 TLI.getPointerTy()));
2770 // Increment the pointer, VAList, to the next vaarg
2771 Tmp3 = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(), VAList,
2772 DAG.getConstant(TLI.getTargetData()->
2773 getTypeAllocSize(VT.getTypeForEVT(*DAG.getContext())),
2774 TLI.getPointerTy()));
2775 // Store the incremented VAList to the legalized pointer
2776 Tmp3 = DAG.getStore(VAListLoad.getValue(1), dl, Tmp3, Tmp2,
2777 MachinePointerInfo(V), false, false, 0);
2778 // Load the actual argument out of the pointer VAList
2779 Results.push_back(DAG.getLoad(VT, dl, Tmp3, VAList, MachinePointerInfo(),
2781 Results.push_back(Results[0].getValue(1));
2785 // This defaults to loading a pointer from the input and storing it to the
2786 // output, returning the chain.
2787 const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue();
2788 const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue();
2789 Tmp1 = DAG.getLoad(TLI.getPointerTy(), dl, Node->getOperand(0),
2790 Node->getOperand(2), MachinePointerInfo(VS),
2792 Tmp1 = DAG.getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1),
2793 MachinePointerInfo(VD), false, false, 0);
2794 Results.push_back(Tmp1);
2797 case ISD::EXTRACT_VECTOR_ELT:
2798 if (Node->getOperand(0).getValueType().getVectorNumElements() == 1)
2799 // This must be an access of the only element. Return it.
2800 Tmp1 = DAG.getNode(ISD::BITCAST, dl, Node->getValueType(0),
2801 Node->getOperand(0));
2803 Tmp1 = ExpandExtractFromVectorThroughStack(SDValue(Node, 0));
2804 Results.push_back(Tmp1);
2806 case ISD::EXTRACT_SUBVECTOR:
2807 Results.push_back(ExpandExtractFromVectorThroughStack(SDValue(Node, 0)));
2809 case ISD::CONCAT_VECTORS: {
2810 Results.push_back(ExpandVectorBuildThroughStack(Node));
2813 case ISD::SCALAR_TO_VECTOR:
2814 Results.push_back(ExpandSCALAR_TO_VECTOR(Node));
2816 case ISD::INSERT_VECTOR_ELT:
2817 Results.push_back(ExpandINSERT_VECTOR_ELT(Node->getOperand(0),
2818 Node->getOperand(1),
2819 Node->getOperand(2), dl));
2821 case ISD::VECTOR_SHUFFLE: {
2822 SmallVector<int, 8> Mask;
2823 cast<ShuffleVectorSDNode>(Node)->getMask(Mask);
2825 EVT VT = Node->getValueType(0);
2826 EVT EltVT = VT.getVectorElementType();
2827 if (getTypeAction(EltVT) == Promote)
2828 EltVT = TLI.getTypeToTransformTo(*DAG.getContext(), EltVT);
2829 unsigned NumElems = VT.getVectorNumElements();
2830 SmallVector<SDValue, 8> Ops;
2831 for (unsigned i = 0; i != NumElems; ++i) {
2833 Ops.push_back(DAG.getUNDEF(EltVT));
2836 unsigned Idx = Mask[i];
2838 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
2839 Node->getOperand(0),
2840 DAG.getIntPtrConstant(Idx)));
2842 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
2843 Node->getOperand(1),
2844 DAG.getIntPtrConstant(Idx - NumElems)));
2846 Tmp1 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Ops[0], Ops.size());
2847 Results.push_back(Tmp1);
2850 case ISD::EXTRACT_ELEMENT: {
2851 EVT OpTy = Node->getOperand(0).getValueType();
2852 if (cast<ConstantSDNode>(Node->getOperand(1))->getZExtValue()) {
2854 Tmp1 = DAG.getNode(ISD::SRL, dl, OpTy, Node->getOperand(0),
2855 DAG.getConstant(OpTy.getSizeInBits()/2,
2856 TLI.getShiftAmountTy()));
2857 Tmp1 = DAG.getNode(ISD::TRUNCATE, dl, Node->getValueType(0), Tmp1);
2860 Tmp1 = DAG.getNode(ISD::TRUNCATE, dl, Node->getValueType(0),
2861 Node->getOperand(0));
2863 Results.push_back(Tmp1);
2866 case ISD::STACKSAVE:
2867 // Expand to CopyFromReg if the target set
2868 // StackPointerRegisterToSaveRestore.
2869 if (unsigned SP = TLI.getStackPointerRegisterToSaveRestore()) {
2870 Results.push_back(DAG.getCopyFromReg(Node->getOperand(0), dl, SP,
2871 Node->getValueType(0)));
2872 Results.push_back(Results[0].getValue(1));
2874 Results.push_back(DAG.getUNDEF(Node->getValueType(0)));
2875 Results.push_back(Node->getOperand(0));
2878 case ISD::STACKRESTORE:
2879 // Expand to CopyToReg if the target set
2880 // StackPointerRegisterToSaveRestore.
2881 if (unsigned SP = TLI.getStackPointerRegisterToSaveRestore()) {
2882 Results.push_back(DAG.getCopyToReg(Node->getOperand(0), dl, SP,
2883 Node->getOperand(1)));
2885 Results.push_back(Node->getOperand(0));
2888 case ISD::FCOPYSIGN:
2889 Results.push_back(ExpandFCOPYSIGN(Node));
2892 // Expand Y = FNEG(X) -> Y = SUB -0.0, X
2893 Tmp1 = DAG.getConstantFP(-0.0, Node->getValueType(0));
2894 Tmp1 = DAG.getNode(ISD::FSUB, dl, Node->getValueType(0), Tmp1,
2895 Node->getOperand(0));
2896 Results.push_back(Tmp1);
2899 // Expand Y = FABS(X) -> Y = (X >u 0.0) ? X : fneg(X).
2900 EVT VT = Node->getValueType(0);
2901 Tmp1 = Node->getOperand(0);
2902 Tmp2 = DAG.getConstantFP(0.0, VT);
2903 Tmp2 = DAG.getSetCC(dl, TLI.getSetCCResultType(Tmp1.getValueType()),
2904 Tmp1, Tmp2, ISD::SETUGT);
2905 Tmp3 = DAG.getNode(ISD::FNEG, dl, VT, Tmp1);
2906 Tmp1 = DAG.getNode(ISD::SELECT, dl, VT, Tmp2, Tmp1, Tmp3);
2907 Results.push_back(Tmp1);
2911 Results.push_back(ExpandFPLibCall(Node, RTLIB::SQRT_F32, RTLIB::SQRT_F64,
2912 RTLIB::SQRT_F80, RTLIB::SQRT_PPCF128));
2915 Results.push_back(ExpandFPLibCall(Node, RTLIB::SIN_F32, RTLIB::SIN_F64,
2916 RTLIB::SIN_F80, RTLIB::SIN_PPCF128));
2919 Results.push_back(ExpandFPLibCall(Node, RTLIB::COS_F32, RTLIB::COS_F64,
2920 RTLIB::COS_F80, RTLIB::COS_PPCF128));
2923 Results.push_back(ExpandFPLibCall(Node, RTLIB::LOG_F32, RTLIB::LOG_F64,
2924 RTLIB::LOG_F80, RTLIB::LOG_PPCF128));
2927 Results.push_back(ExpandFPLibCall(Node, RTLIB::LOG2_F32, RTLIB::LOG2_F64,
2928 RTLIB::LOG2_F80, RTLIB::LOG2_PPCF128));
2931 Results.push_back(ExpandFPLibCall(Node, RTLIB::LOG10_F32, RTLIB::LOG10_F64,
2932 RTLIB::LOG10_F80, RTLIB::LOG10_PPCF128));
2935 Results.push_back(ExpandFPLibCall(Node, RTLIB::EXP_F32, RTLIB::EXP_F64,
2936 RTLIB::EXP_F80, RTLIB::EXP_PPCF128));
2939 Results.push_back(ExpandFPLibCall(Node, RTLIB::EXP2_F32, RTLIB::EXP2_F64,
2940 RTLIB::EXP2_F80, RTLIB::EXP2_PPCF128));
2943 Results.push_back(ExpandFPLibCall(Node, RTLIB::TRUNC_F32, RTLIB::TRUNC_F64,
2944 RTLIB::TRUNC_F80, RTLIB::TRUNC_PPCF128));
2947 Results.push_back(ExpandFPLibCall(Node, RTLIB::FLOOR_F32, RTLIB::FLOOR_F64,
2948 RTLIB::FLOOR_F80, RTLIB::FLOOR_PPCF128));
2951 Results.push_back(ExpandFPLibCall(Node, RTLIB::CEIL_F32, RTLIB::CEIL_F64,
2952 RTLIB::CEIL_F80, RTLIB::CEIL_PPCF128));
2955 Results.push_back(ExpandFPLibCall(Node, RTLIB::RINT_F32, RTLIB::RINT_F64,
2956 RTLIB::RINT_F80, RTLIB::RINT_PPCF128));
2958 case ISD::FNEARBYINT:
2959 Results.push_back(ExpandFPLibCall(Node, RTLIB::NEARBYINT_F32,
2960 RTLIB::NEARBYINT_F64,
2961 RTLIB::NEARBYINT_F80,
2962 RTLIB::NEARBYINT_PPCF128));
2965 Results.push_back(ExpandFPLibCall(Node, RTLIB::POWI_F32, RTLIB::POWI_F64,
2966 RTLIB::POWI_F80, RTLIB::POWI_PPCF128));
2969 Results.push_back(ExpandFPLibCall(Node, RTLIB::POW_F32, RTLIB::POW_F64,
2970 RTLIB::POW_F80, RTLIB::POW_PPCF128));
2973 Results.push_back(ExpandFPLibCall(Node, RTLIB::DIV_F32, RTLIB::DIV_F64,
2974 RTLIB::DIV_F80, RTLIB::DIV_PPCF128));
2977 Results.push_back(ExpandFPLibCall(Node, RTLIB::REM_F32, RTLIB::REM_F64,
2978 RTLIB::REM_F80, RTLIB::REM_PPCF128));
2980 case ISD::FP16_TO_FP32:
2981 Results.push_back(ExpandLibCall(RTLIB::FPEXT_F16_F32, Node, false));
2983 case ISD::FP32_TO_FP16:
2984 Results.push_back(ExpandLibCall(RTLIB::FPROUND_F32_F16, Node, false));
2986 case ISD::ConstantFP: {
2987 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Node);
2988 // Check to see if this FP immediate is already legal.
2989 // If this is a legal constant, turn it into a TargetConstantFP node.
2990 if (TLI.isFPImmLegal(CFP->getValueAPF(), Node->getValueType(0)))
2991 Results.push_back(SDValue(Node, 0));
2993 Results.push_back(ExpandConstantFP(CFP, true, DAG, TLI));
2996 case ISD::EHSELECTION: {
2997 unsigned Reg = TLI.getExceptionSelectorRegister();
2998 assert(Reg && "Can't expand to unknown register!");
2999 Results.push_back(DAG.getCopyFromReg(Node->getOperand(1), dl, Reg,
3000 Node->getValueType(0)));
3001 Results.push_back(Results[0].getValue(1));
3004 case ISD::EXCEPTIONADDR: {
3005 unsigned Reg = TLI.getExceptionAddressRegister();
3006 assert(Reg && "Can't expand to unknown register!");
3007 Results.push_back(DAG.getCopyFromReg(Node->getOperand(0), dl, Reg,
3008 Node->getValueType(0)));
3009 Results.push_back(Results[0].getValue(1));
3013 EVT VT = Node->getValueType(0);
3014 assert(TLI.isOperationLegalOrCustom(ISD::ADD, VT) &&
3015 TLI.isOperationLegalOrCustom(ISD::XOR, VT) &&
3016 "Don't know how to expand this subtraction!");
3017 Tmp1 = DAG.getNode(ISD::XOR, dl, VT, Node->getOperand(1),
3018 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT));
3019 Tmp1 = DAG.getNode(ISD::ADD, dl, VT, Tmp2, DAG.getConstant(1, VT));
3020 Results.push_back(DAG.getNode(ISD::ADD, dl, VT, Node->getOperand(0), Tmp1));
3025 EVT VT = Node->getValueType(0);
3026 SDVTList VTs = DAG.getVTList(VT, VT);
3027 bool isSigned = Node->getOpcode() == ISD::SREM;
3028 unsigned DivOpc = isSigned ? ISD::SDIV : ISD::UDIV;
3029 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
3030 Tmp2 = Node->getOperand(0);
3031 Tmp3 = Node->getOperand(1);
3032 if (TLI.isOperationLegalOrCustom(DivRemOpc, VT)) {
3033 Tmp1 = DAG.getNode(DivRemOpc, dl, VTs, Tmp2, Tmp3).getValue(1);
3034 } else if (TLI.isOperationLegalOrCustom(DivOpc, VT)) {
3036 Tmp1 = DAG.getNode(DivOpc, dl, VT, Tmp2, Tmp3);
3037 Tmp1 = DAG.getNode(ISD::MUL, dl, VT, Tmp1, Tmp3);
3038 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, Tmp2, Tmp1);
3039 } else if (isSigned) {
3040 Tmp1 = ExpandIntLibCall(Node, true,
3042 RTLIB::SREM_I16, RTLIB::SREM_I32,
3043 RTLIB::SREM_I64, RTLIB::SREM_I128);
3045 Tmp1 = ExpandIntLibCall(Node, false,
3047 RTLIB::UREM_I16, RTLIB::UREM_I32,
3048 RTLIB::UREM_I64, RTLIB::UREM_I128);
3050 Results.push_back(Tmp1);
3055 bool isSigned = Node->getOpcode() == ISD::SDIV;
3056 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
3057 EVT VT = Node->getValueType(0);
3058 SDVTList VTs = DAG.getVTList(VT, VT);
3059 if (TLI.isOperationLegalOrCustom(DivRemOpc, VT))
3060 Tmp1 = DAG.getNode(DivRemOpc, dl, VTs, Node->getOperand(0),
3061 Node->getOperand(1));
3063 Tmp1 = ExpandIntLibCall(Node, true,
3065 RTLIB::SDIV_I16, RTLIB::SDIV_I32,
3066 RTLIB::SDIV_I64, RTLIB::SDIV_I128);
3068 Tmp1 = ExpandIntLibCall(Node, false,
3070 RTLIB::UDIV_I16, RTLIB::UDIV_I32,
3071 RTLIB::UDIV_I64, RTLIB::UDIV_I128);
3072 Results.push_back(Tmp1);
3077 unsigned ExpandOpcode = Node->getOpcode() == ISD::MULHU ? ISD::UMUL_LOHI :
3079 EVT VT = Node->getValueType(0);
3080 SDVTList VTs = DAG.getVTList(VT, VT);
3081 assert(TLI.isOperationLegalOrCustom(ExpandOpcode, VT) &&
3082 "If this wasn't legal, it shouldn't have been created!");
3083 Tmp1 = DAG.getNode(ExpandOpcode, dl, VTs, Node->getOperand(0),
3084 Node->getOperand(1));
3085 Results.push_back(Tmp1.getValue(1));
3089 EVT VT = Node->getValueType(0);
3090 SDVTList VTs = DAG.getVTList(VT, VT);
3091 // See if multiply or divide can be lowered using two-result operations.
3092 // We just need the low half of the multiply; try both the signed
3093 // and unsigned forms. If the target supports both SMUL_LOHI and
3094 // UMUL_LOHI, form a preference by checking which forms of plain
3095 // MULH it supports.
3096 bool HasSMUL_LOHI = TLI.isOperationLegalOrCustom(ISD::SMUL_LOHI, VT);
3097 bool HasUMUL_LOHI = TLI.isOperationLegalOrCustom(ISD::UMUL_LOHI, VT);
3098 bool HasMULHS = TLI.isOperationLegalOrCustom(ISD::MULHS, VT);
3099 bool HasMULHU = TLI.isOperationLegalOrCustom(ISD::MULHU, VT);
3100 unsigned OpToUse = 0;
3101 if (HasSMUL_LOHI && !HasMULHS) {
3102 OpToUse = ISD::SMUL_LOHI;
3103 } else if (HasUMUL_LOHI && !HasMULHU) {
3104 OpToUse = ISD::UMUL_LOHI;
3105 } else if (HasSMUL_LOHI) {
3106 OpToUse = ISD::SMUL_LOHI;
3107 } else if (HasUMUL_LOHI) {
3108 OpToUse = ISD::UMUL_LOHI;
3111 Results.push_back(DAG.getNode(OpToUse, dl, VTs, Node->getOperand(0),
3112 Node->getOperand(1)));
3115 Tmp1 = ExpandIntLibCall(Node, false,
3117 RTLIB::MUL_I16, RTLIB::MUL_I32,
3118 RTLIB::MUL_I64, RTLIB::MUL_I128);
3119 Results.push_back(Tmp1);
3124 SDValue LHS = Node->getOperand(0);
3125 SDValue RHS = Node->getOperand(1);
3126 SDValue Sum = DAG.getNode(Node->getOpcode() == ISD::SADDO ?
3127 ISD::ADD : ISD::SUB, dl, LHS.getValueType(),
3129 Results.push_back(Sum);
3130 EVT OType = Node->getValueType(1);
3132 SDValue Zero = DAG.getConstant(0, LHS.getValueType());
3134 // LHSSign -> LHS >= 0
3135 // RHSSign -> RHS >= 0
3136 // SumSign -> Sum >= 0
3139 // Overflow -> (LHSSign == RHSSign) && (LHSSign != SumSign)
3141 // Overflow -> (LHSSign != RHSSign) && (LHSSign != SumSign)
3143 SDValue LHSSign = DAG.getSetCC(dl, OType, LHS, Zero, ISD::SETGE);
3144 SDValue RHSSign = DAG.getSetCC(dl, OType, RHS, Zero, ISD::SETGE);
3145 SDValue SignsMatch = DAG.getSetCC(dl, OType, LHSSign, RHSSign,
3146 Node->getOpcode() == ISD::SADDO ?
3147 ISD::SETEQ : ISD::SETNE);
3149 SDValue SumSign = DAG.getSetCC(dl, OType, Sum, Zero, ISD::SETGE);
3150 SDValue SumSignNE = DAG.getSetCC(dl, OType, LHSSign, SumSign, ISD::SETNE);
3152 SDValue Cmp = DAG.getNode(ISD::AND, dl, OType, SignsMatch, SumSignNE);
3153 Results.push_back(Cmp);
3158 SDValue LHS = Node->getOperand(0);
3159 SDValue RHS = Node->getOperand(1);
3160 SDValue Sum = DAG.getNode(Node->getOpcode() == ISD::UADDO ?
3161 ISD::ADD : ISD::SUB, dl, LHS.getValueType(),
3163 Results.push_back(Sum);
3164 Results.push_back(DAG.getSetCC(dl, Node->getValueType(1), Sum, LHS,
3165 Node->getOpcode () == ISD::UADDO ?
3166 ISD::SETULT : ISD::SETUGT));
3171 EVT VT = Node->getValueType(0);
3172 SDValue LHS = Node->getOperand(0);
3173 SDValue RHS = Node->getOperand(1);
3176 static const unsigned Ops[2][3] =
3177 { { ISD::MULHU, ISD::UMUL_LOHI, ISD::ZERO_EXTEND },
3178 { ISD::MULHS, ISD::SMUL_LOHI, ISD::SIGN_EXTEND }};
3179 bool isSigned = Node->getOpcode() == ISD::SMULO;
3180 if (TLI.isOperationLegalOrCustom(Ops[isSigned][0], VT)) {
3181 BottomHalf = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS);
3182 TopHalf = DAG.getNode(Ops[isSigned][0], dl, VT, LHS, RHS);
3183 } else if (TLI.isOperationLegalOrCustom(Ops[isSigned][1], VT)) {
3184 BottomHalf = DAG.getNode(Ops[isSigned][1], dl, DAG.getVTList(VT, VT), LHS,
3186 TopHalf = BottomHalf.getValue(1);
3187 } else if (TLI.isTypeLegal(EVT::getIntegerVT(*DAG.getContext(),
3188 VT.getSizeInBits() * 2))) {
3189 EVT WideVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits() * 2);
3190 LHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, LHS);
3191 RHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, RHS);
3192 Tmp1 = DAG.getNode(ISD::MUL, dl, WideVT, LHS, RHS);
3193 BottomHalf = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VT, Tmp1,
3194 DAG.getIntPtrConstant(0));
3195 TopHalf = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VT, Tmp1,
3196 DAG.getIntPtrConstant(1));
3198 // We can fall back to a libcall with an illegal type for the MUL if we
3199 // have a libcall big enough.
3200 // Also, we can fall back to a division in some cases, but that's a big
3201 // performance hit in the general case.
3202 EVT WideVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits() * 2);
3203 RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
3204 if (WideVT == MVT::i16)
3205 LC = RTLIB::MUL_I16;
3206 else if (WideVT == MVT::i32)
3207 LC = RTLIB::MUL_I32;
3208 else if (WideVT == MVT::i64)
3209 LC = RTLIB::MUL_I64;
3210 else if (WideVT == MVT::i128)
3211 LC = RTLIB::MUL_I128;
3212 assert(LC != RTLIB::UNKNOWN_LIBCALL && "Cannot expand this operation!");
3213 LHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, LHS);
3214 RHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, RHS);
3216 SDValue Ret = ExpandLibCall(LC, Node, isSigned);
3217 BottomHalf = DAG.getNode(ISD::TRUNCATE, dl, VT, Ret);
3218 TopHalf = DAG.getNode(ISD::SRL, dl, Ret.getValueType(), Ret,
3219 DAG.getConstant(VT.getSizeInBits(), TLI.getPointerTy()));
3220 TopHalf = DAG.getNode(ISD::TRUNCATE, dl, VT, TopHalf);
3223 Tmp1 = DAG.getConstant(VT.getSizeInBits() - 1, TLI.getShiftAmountTy());
3224 Tmp1 = DAG.getNode(ISD::SRA, dl, VT, BottomHalf, Tmp1);
3225 TopHalf = DAG.getSetCC(dl, TLI.getSetCCResultType(VT), TopHalf, Tmp1,
3228 TopHalf = DAG.getSetCC(dl, TLI.getSetCCResultType(VT), TopHalf,
3229 DAG.getConstant(0, VT), ISD::SETNE);
3231 Results.push_back(BottomHalf);
3232 Results.push_back(TopHalf);
3235 case ISD::BUILD_PAIR: {
3236 EVT PairTy = Node->getValueType(0);
3237 Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, PairTy, Node->getOperand(0));
3238 Tmp2 = DAG.getNode(ISD::ANY_EXTEND, dl, PairTy, Node->getOperand(1));
3239 Tmp2 = DAG.getNode(ISD::SHL, dl, PairTy, Tmp2,
3240 DAG.getConstant(PairTy.getSizeInBits()/2,
3241 TLI.getShiftAmountTy()));
3242 Results.push_back(DAG.getNode(ISD::OR, dl, PairTy, Tmp1, Tmp2));
3246 Tmp1 = Node->getOperand(0);
3247 Tmp2 = Node->getOperand(1);
3248 Tmp3 = Node->getOperand(2);
3249 if (Tmp1.getOpcode() == ISD::SETCC) {
3250 Tmp1 = DAG.getSelectCC(dl, Tmp1.getOperand(0), Tmp1.getOperand(1),
3252 cast<CondCodeSDNode>(Tmp1.getOperand(2))->get());
3254 Tmp1 = DAG.getSelectCC(dl, Tmp1,
3255 DAG.getConstant(0, Tmp1.getValueType()),
3256 Tmp2, Tmp3, ISD::SETNE);
3258 Results.push_back(Tmp1);
3261 SDValue Chain = Node->getOperand(0);
3262 SDValue Table = Node->getOperand(1);
3263 SDValue Index = Node->getOperand(2);
3265 EVT PTy = TLI.getPointerTy();
3267 const TargetData &TD = *TLI.getTargetData();
3268 unsigned EntrySize =
3269 DAG.getMachineFunction().getJumpTableInfo()->getEntrySize(TD);
3271 Index = DAG.getNode(ISD::MUL, dl, PTy,
3272 Index, DAG.getConstant(EntrySize, PTy));
3273 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3275 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), EntrySize * 8);
3276 SDValue LD = DAG.getExtLoad(ISD::SEXTLOAD, PTy, dl, Chain, Addr,
3277 MachinePointerInfo::getJumpTable(), MemVT,
3280 if (TM.getRelocationModel() == Reloc::PIC_) {
3281 // For PIC, the sequence is:
3282 // BRIND(load(Jumptable + index) + RelocBase)
3283 // RelocBase can be JumpTable, GOT or some sort of global base.
3284 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr,
3285 TLI.getPICJumpTableRelocBase(Table, DAG));
3287 Tmp1 = DAG.getNode(ISD::BRIND, dl, MVT::Other, LD.getValue(1), Addr);
3288 Results.push_back(Tmp1);
3292 // Expand brcond's setcc into its constituent parts and create a BR_CC
3294 Tmp1 = Node->getOperand(0);
3295 Tmp2 = Node->getOperand(1);
3296 if (Tmp2.getOpcode() == ISD::SETCC) {
3297 Tmp1 = DAG.getNode(ISD::BR_CC, dl, MVT::Other,
3298 Tmp1, Tmp2.getOperand(2),
3299 Tmp2.getOperand(0), Tmp2.getOperand(1),
3300 Node->getOperand(2));
3302 Tmp1 = DAG.getNode(ISD::BR_CC, dl, MVT::Other, Tmp1,
3303 DAG.getCondCode(ISD::SETNE), Tmp2,
3304 DAG.getConstant(0, Tmp2.getValueType()),
3305 Node->getOperand(2));
3307 Results.push_back(Tmp1);
3310 Tmp1 = Node->getOperand(0);
3311 Tmp2 = Node->getOperand(1);
3312 Tmp3 = Node->getOperand(2);
3313 LegalizeSetCCCondCode(Node->getValueType(0), Tmp1, Tmp2, Tmp3, dl);
3315 // If we expanded the SETCC into an AND/OR, return the new node
3316 if (Tmp2.getNode() == 0) {
3317 Results.push_back(Tmp1);
3321 // Otherwise, SETCC for the given comparison type must be completely
3322 // illegal; expand it into a SELECT_CC.
3323 EVT VT = Node->getValueType(0);
3324 Tmp1 = DAG.getNode(ISD::SELECT_CC, dl, VT, Tmp1, Tmp2,
3325 DAG.getConstant(1, VT), DAG.getConstant(0, VT), Tmp3);
3326 Results.push_back(Tmp1);
3329 case ISD::SELECT_CC: {
3330 Tmp1 = Node->getOperand(0); // LHS
3331 Tmp2 = Node->getOperand(1); // RHS
3332 Tmp3 = Node->getOperand(2); // True
3333 Tmp4 = Node->getOperand(3); // False
3334 SDValue CC = Node->getOperand(4);
3336 LegalizeSetCCCondCode(TLI.getSetCCResultType(Tmp1.getValueType()),
3337 Tmp1, Tmp2, CC, dl);
3339 assert(!Tmp2.getNode() && "Can't legalize SELECT_CC with legal condition!");
3340 Tmp2 = DAG.getConstant(0, Tmp1.getValueType());
3341 CC = DAG.getCondCode(ISD::SETNE);
3342 Tmp1 = DAG.getNode(ISD::SELECT_CC, dl, Node->getValueType(0), Tmp1, Tmp2,
3344 Results.push_back(Tmp1);
3348 Tmp1 = Node->getOperand(0); // Chain
3349 Tmp2 = Node->getOperand(2); // LHS
3350 Tmp3 = Node->getOperand(3); // RHS
3351 Tmp4 = Node->getOperand(1); // CC
3353 LegalizeSetCCCondCode(TLI.getSetCCResultType(Tmp2.getValueType()),
3354 Tmp2, Tmp3, Tmp4, dl);
3355 LastCALLSEQ_END = DAG.getEntryNode();
3357 assert(!Tmp3.getNode() && "Can't legalize BR_CC with legal condition!");
3358 Tmp3 = DAG.getConstant(0, Tmp2.getValueType());
3359 Tmp4 = DAG.getCondCode(ISD::SETNE);
3360 Tmp1 = DAG.getNode(ISD::BR_CC, dl, Node->getValueType(0), Tmp1, Tmp4, Tmp2,
3361 Tmp3, Node->getOperand(4));
3362 Results.push_back(Tmp1);
3365 case ISD::GLOBAL_OFFSET_TABLE:
3366 case ISD::GlobalAddress:
3367 case ISD::GlobalTLSAddress:
3368 case ISD::ExternalSymbol:
3369 case ISD::ConstantPool:
3370 case ISD::JumpTable:
3371 case ISD::INTRINSIC_W_CHAIN:
3372 case ISD::INTRINSIC_WO_CHAIN:
3373 case ISD::INTRINSIC_VOID:
3374 // FIXME: Custom lowering for these operations shouldn't return null!
3375 for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
3376 Results.push_back(SDValue(Node, i));
3380 void SelectionDAGLegalize::PromoteNode(SDNode *Node,
3381 SmallVectorImpl<SDValue> &Results) {
3382 EVT OVT = Node->getValueType(0);
3383 if (Node->getOpcode() == ISD::UINT_TO_FP ||
3384 Node->getOpcode() == ISD::SINT_TO_FP ||
3385 Node->getOpcode() == ISD::SETCC) {
3386 OVT = Node->getOperand(0).getValueType();
3388 EVT NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), OVT);
3389 DebugLoc dl = Node->getDebugLoc();
3390 SDValue Tmp1, Tmp2, Tmp3;
3391 switch (Node->getOpcode()) {
3395 // Zero extend the argument.
3396 Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, Node->getOperand(0));
3397 // Perform the larger operation.
3398 Tmp1 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1);
3399 if (Node->getOpcode() == ISD::CTTZ) {
3400 //if Tmp1 == sizeinbits(NVT) then Tmp1 = sizeinbits(Old VT)
3401 Tmp2 = DAG.getSetCC(dl, TLI.getSetCCResultType(NVT),
3402 Tmp1, DAG.getConstant(NVT.getSizeInBits(), NVT),
3404 Tmp1 = DAG.getNode(ISD::SELECT, dl, NVT, Tmp2,
3405 DAG.getConstant(OVT.getSizeInBits(), NVT), Tmp1);
3406 } else if (Node->getOpcode() == ISD::CTLZ) {
3407 // Tmp1 = Tmp1 - (sizeinbits(NVT) - sizeinbits(Old VT))
3408 Tmp1 = DAG.getNode(ISD::SUB, dl, NVT, Tmp1,
3409 DAG.getConstant(NVT.getSizeInBits() -
3410 OVT.getSizeInBits(), NVT));
3412 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, OVT, Tmp1));
3415 unsigned DiffBits = NVT.getSizeInBits() - OVT.getSizeInBits();
3416 Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, Node->getOperand(0));
3417 Tmp1 = DAG.getNode(ISD::BSWAP, dl, NVT, Tmp1);
3418 Tmp1 = DAG.getNode(ISD::SRL, dl, NVT, Tmp1,
3419 DAG.getConstant(DiffBits, TLI.getShiftAmountTy()));
3420 Results.push_back(Tmp1);
3423 case ISD::FP_TO_UINT:
3424 case ISD::FP_TO_SINT:
3425 Tmp1 = PromoteLegalFP_TO_INT(Node->getOperand(0), Node->getValueType(0),
3426 Node->getOpcode() == ISD::FP_TO_SINT, dl);
3427 Results.push_back(Tmp1);
3429 case ISD::UINT_TO_FP:
3430 case ISD::SINT_TO_FP:
3431 Tmp1 = PromoteLegalINT_TO_FP(Node->getOperand(0), Node->getValueType(0),
3432 Node->getOpcode() == ISD::SINT_TO_FP, dl);
3433 Results.push_back(Tmp1);
3438 unsigned ExtOp, TruncOp;
3439 if (OVT.isVector()) {
3440 ExtOp = ISD::BITCAST;
3441 TruncOp = ISD::BITCAST;
3443 assert(OVT.isInteger() && "Cannot promote logic operation");
3444 ExtOp = ISD::ANY_EXTEND;
3445 TruncOp = ISD::TRUNCATE;
3447 // Promote each of the values to the new type.
3448 Tmp1 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(0));
3449 Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1));
3450 // Perform the larger operation, then convert back
3451 Tmp1 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2);
3452 Results.push_back(DAG.getNode(TruncOp, dl, OVT, Tmp1));
3456 unsigned ExtOp, TruncOp;
3457 if (Node->getValueType(0).isVector()) {
3458 ExtOp = ISD::BITCAST;
3459 TruncOp = ISD::BITCAST;
3460 } else if (Node->getValueType(0).isInteger()) {
3461 ExtOp = ISD::ANY_EXTEND;
3462 TruncOp = ISD::TRUNCATE;
3464 ExtOp = ISD::FP_EXTEND;
3465 TruncOp = ISD::FP_ROUND;
3467 Tmp1 = Node->getOperand(0);
3468 // Promote each of the values to the new type.
3469 Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1));
3470 Tmp3 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(2));
3471 // Perform the larger operation, then round down.
3472 Tmp1 = DAG.getNode(ISD::SELECT, dl, NVT, Tmp1, Tmp2, Tmp3);
3473 if (TruncOp != ISD::FP_ROUND)
3474 Tmp1 = DAG.getNode(TruncOp, dl, Node->getValueType(0), Tmp1);
3476 Tmp1 = DAG.getNode(TruncOp, dl, Node->getValueType(0), Tmp1,
3477 DAG.getIntPtrConstant(0));
3478 Results.push_back(Tmp1);
3481 case ISD::VECTOR_SHUFFLE: {
3482 SmallVector<int, 8> Mask;
3483 cast<ShuffleVectorSDNode>(Node)->getMask(Mask);
3485 // Cast the two input vectors.
3486 Tmp1 = DAG.getNode(ISD::BITCAST, dl, NVT, Node->getOperand(0));
3487 Tmp2 = DAG.getNode(ISD::BITCAST, dl, NVT, Node->getOperand(1));
3489 // Convert the shuffle mask to the right # elements.
3490 Tmp1 = ShuffleWithNarrowerEltType(NVT, OVT, dl, Tmp1, Tmp2, Mask);
3491 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OVT, Tmp1);
3492 Results.push_back(Tmp1);
3496 unsigned ExtOp = ISD::FP_EXTEND;
3497 if (NVT.isInteger()) {
3498 ISD::CondCode CCCode =
3499 cast<CondCodeSDNode>(Node->getOperand(2))->get();
3500 ExtOp = isSignedIntSetCC(CCCode) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
3502 Tmp1 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(0));
3503 Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1));
3504 Results.push_back(DAG.getNode(ISD::SETCC, dl, Node->getValueType(0),
3505 Tmp1, Tmp2, Node->getOperand(2)));
3511 // SelectionDAG::Legalize - This is the entry point for the file.
3513 void SelectionDAG::Legalize(CodeGenOpt::Level OptLevel) {
3514 /// run - This is the main entry point to this class.
3516 SelectionDAGLegalize(*this, OptLevel).LegalizeDAG();