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));
93 SelectionDAGLegalize(SelectionDAG &DAG, CodeGenOpt::Level ol);
95 /// getTypeAction - Return how we should legalize values of this type, either
96 /// it is already legal or we need to expand it into multiple registers of
97 /// smaller integer type, or we need to promote it to a larger type.
98 LegalizeAction getTypeAction(EVT VT) const {
99 return (LegalizeAction)ValueTypeActions.getTypeAction(VT);
102 /// isTypeLegal - Return true if this type is legal on this target.
104 bool isTypeLegal(EVT VT) const {
105 return getTypeAction(VT) == Legal;
111 /// LegalizeOp - We know that the specified value has a legal type.
112 /// Recursively ensure that the operands have legal types, then return the
114 SDValue LegalizeOp(SDValue O);
116 SDValue OptimizeFloatStore(StoreSDNode *ST);
118 /// PerformInsertVectorEltInMemory - Some target cannot handle a variable
119 /// insertion index for the INSERT_VECTOR_ELT instruction. In this case, it
120 /// is necessary to spill the vector being inserted into to memory, perform
121 /// the insert there, and then read the result back.
122 SDValue PerformInsertVectorEltInMemory(SDValue Vec, SDValue Val,
123 SDValue Idx, DebugLoc dl);
124 SDValue ExpandINSERT_VECTOR_ELT(SDValue Vec, SDValue Val,
125 SDValue Idx, DebugLoc dl);
127 /// ShuffleWithNarrowerEltType - Return a vector shuffle operation which
128 /// performs the same shuffe in terms of order or result bytes, but on a type
129 /// whose vector element type is narrower than the original shuffle type.
130 /// e.g. <v4i32> <0, 1, 0, 1> -> v8i16 <0, 1, 2, 3, 0, 1, 2, 3>
131 SDValue ShuffleWithNarrowerEltType(EVT NVT, EVT VT, DebugLoc dl,
132 SDValue N1, SDValue N2,
133 SmallVectorImpl<int> &Mask) const;
135 bool LegalizeAllNodesNotLeadingTo(SDNode *N, SDNode *Dest,
136 SmallPtrSet<SDNode*, 32> &NodesLeadingTo);
138 void LegalizeSetCCCondCode(EVT VT, SDValue &LHS, SDValue &RHS, SDValue &CC,
141 SDValue ExpandLibCall(RTLIB::Libcall LC, SDNode *Node, bool isSigned);
142 std::pair<SDValue, SDValue> ExpandChainLibCall(RTLIB::Libcall LC,
143 SDNode *Node, bool isSigned);
144 SDValue ExpandFPLibCall(SDNode *Node, RTLIB::Libcall Call_F32,
145 RTLIB::Libcall Call_F64, RTLIB::Libcall Call_F80,
146 RTLIB::Libcall Call_PPCF128);
147 SDValue ExpandIntLibCall(SDNode *Node, bool isSigned,
148 RTLIB::Libcall Call_I8,
149 RTLIB::Libcall Call_I16,
150 RTLIB::Libcall Call_I32,
151 RTLIB::Libcall Call_I64,
152 RTLIB::Libcall Call_I128);
154 SDValue EmitStackConvert(SDValue SrcOp, EVT SlotVT, EVT DestVT, DebugLoc dl);
155 SDValue ExpandBUILD_VECTOR(SDNode *Node);
156 SDValue ExpandSCALAR_TO_VECTOR(SDNode *Node);
157 void ExpandDYNAMIC_STACKALLOC(SDNode *Node,
158 SmallVectorImpl<SDValue> &Results);
159 SDValue ExpandFCOPYSIGN(SDNode *Node);
160 SDValue ExpandLegalINT_TO_FP(bool isSigned, SDValue LegalOp, EVT DestVT,
162 SDValue PromoteLegalINT_TO_FP(SDValue LegalOp, EVT DestVT, bool isSigned,
164 SDValue PromoteLegalFP_TO_INT(SDValue LegalOp, EVT DestVT, bool isSigned,
167 SDValue ExpandBSWAP(SDValue Op, DebugLoc dl);
168 SDValue ExpandBitCount(unsigned Opc, SDValue Op, DebugLoc dl);
170 SDValue ExpandExtractFromVectorThroughStack(SDValue Op);
171 SDValue ExpandVectorBuildThroughStack(SDNode* Node);
173 std::pair<SDValue, SDValue> ExpandAtomic(SDNode *Node);
175 void ExpandNode(SDNode *Node, SmallVectorImpl<SDValue> &Results);
176 void PromoteNode(SDNode *Node, SmallVectorImpl<SDValue> &Results);
180 /// ShuffleWithNarrowerEltType - Return a vector shuffle operation which
181 /// performs the same shuffe in terms of order or result bytes, but on a type
182 /// whose vector element type is narrower than the original shuffle type.
183 /// e.g. <v4i32> <0, 1, 0, 1> -> v8i16 <0, 1, 2, 3, 0, 1, 2, 3>
185 SelectionDAGLegalize::ShuffleWithNarrowerEltType(EVT NVT, EVT VT, DebugLoc dl,
186 SDValue N1, SDValue N2,
187 SmallVectorImpl<int> &Mask) const {
188 unsigned NumMaskElts = VT.getVectorNumElements();
189 unsigned NumDestElts = NVT.getVectorNumElements();
190 unsigned NumEltsGrowth = NumDestElts / NumMaskElts;
192 assert(NumEltsGrowth && "Cannot promote to vector type with fewer elts!");
194 if (NumEltsGrowth == 1)
195 return DAG.getVectorShuffle(NVT, dl, N1, N2, &Mask[0]);
197 SmallVector<int, 8> NewMask;
198 for (unsigned i = 0; i != NumMaskElts; ++i) {
200 for (unsigned j = 0; j != NumEltsGrowth; ++j) {
202 NewMask.push_back(-1);
204 NewMask.push_back(Idx * NumEltsGrowth + j);
207 assert(NewMask.size() == NumDestElts && "Non-integer NumEltsGrowth?");
208 assert(TLI.isShuffleMaskLegal(NewMask, NVT) && "Shuffle not legal?");
209 return DAG.getVectorShuffle(NVT, dl, N1, N2, &NewMask[0]);
212 SelectionDAGLegalize::SelectionDAGLegalize(SelectionDAG &dag,
213 CodeGenOpt::Level ol)
214 : TM(dag.getTarget()), TLI(dag.getTargetLoweringInfo()),
215 DAG(dag), OptLevel(ol),
216 ValueTypeActions(TLI.getValueTypeActions()) {
217 assert(MVT::LAST_VALUETYPE <= MVT::MAX_ALLOWED_VALUETYPE &&
218 "Too many value types for ValueTypeActions to hold!");
221 void SelectionDAGLegalize::LegalizeDAG() {
222 LastCALLSEQ_END = DAG.getEntryNode();
224 // The legalize process is inherently a bottom-up recursive process (users
225 // legalize their uses before themselves). Given infinite stack space, we
226 // could just start legalizing on the root and traverse the whole graph. In
227 // practice however, this causes us to run out of stack space on large basic
228 // blocks. To avoid this problem, compute an ordering of the nodes where each
229 // node is only legalized after all of its operands are legalized.
230 DAG.AssignTopologicalOrder();
231 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
232 E = prior(DAG.allnodes_end()); I != llvm::next(E); ++I)
233 LegalizeOp(SDValue(I, 0));
235 // Finally, it's possible the root changed. Get the new root.
236 SDValue OldRoot = DAG.getRoot();
237 assert(LegalizedNodes.count(OldRoot) && "Root didn't get legalized?");
238 DAG.setRoot(LegalizedNodes[OldRoot]);
240 LegalizedNodes.clear();
242 // Remove dead nodes now.
243 DAG.RemoveDeadNodes();
247 /// FindCallEndFromCallStart - Given a chained node that is part of a call
248 /// sequence, find the CALLSEQ_END node that terminates the call sequence.
249 static SDNode *FindCallEndFromCallStart(SDNode *Node, int depth = 0) {
250 // Nested CALLSEQ_START/END constructs aren't yet legal,
251 // but we can DTRT and handle them correctly here.
252 if (Node->getOpcode() == ISD::CALLSEQ_START)
254 else if (Node->getOpcode() == ISD::CALLSEQ_END) {
259 if (Node->use_empty())
260 return 0; // No CallSeqEnd
262 // The chain is usually at the end.
263 SDValue TheChain(Node, Node->getNumValues()-1);
264 if (TheChain.getValueType() != MVT::Other) {
265 // Sometimes it's at the beginning.
266 TheChain = SDValue(Node, 0);
267 if (TheChain.getValueType() != MVT::Other) {
268 // Otherwise, hunt for it.
269 for (unsigned i = 1, e = Node->getNumValues(); i != e; ++i)
270 if (Node->getValueType(i) == MVT::Other) {
271 TheChain = SDValue(Node, i);
275 // Otherwise, we walked into a node without a chain.
276 if (TheChain.getValueType() != MVT::Other)
281 for (SDNode::use_iterator UI = Node->use_begin(),
282 E = Node->use_end(); UI != E; ++UI) {
284 // Make sure to only follow users of our token chain.
286 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i)
287 if (User->getOperand(i) == TheChain)
288 if (SDNode *Result = FindCallEndFromCallStart(User, depth))
294 /// FindCallStartFromCallEnd - Given a chained node that is part of a call
295 /// sequence, find the CALLSEQ_START node that initiates the call sequence.
296 static SDNode *FindCallStartFromCallEnd(SDNode *Node) {
298 assert(Node && "Didn't find callseq_start for a call??");
299 while (Node->getOpcode() != ISD::CALLSEQ_START || nested) {
300 Node = Node->getOperand(0).getNode();
301 assert(Node->getOperand(0).getValueType() == MVT::Other &&
302 "Node doesn't have a token chain argument!");
303 switch (Node->getOpcode()) {
306 case ISD::CALLSEQ_START:
311 case ISD::CALLSEQ_END:
319 /// LegalizeAllNodesNotLeadingTo - Recursively walk the uses of N, looking to
320 /// see if any uses can reach Dest. If no dest operands can get to dest,
321 /// legalize them, legalize ourself, and return false, otherwise, return true.
323 /// Keep track of the nodes we fine that actually do lead to Dest in
324 /// NodesLeadingTo. This avoids retraversing them exponential number of times.
326 bool SelectionDAGLegalize::LegalizeAllNodesNotLeadingTo(SDNode *N, SDNode *Dest,
327 SmallPtrSet<SDNode*, 32> &NodesLeadingTo) {
328 if (N == Dest) return true; // N certainly leads to Dest :)
330 // If we've already processed this node and it does lead to Dest, there is no
331 // need to reprocess it.
332 if (NodesLeadingTo.count(N)) return true;
334 // If the first result of this node has been already legalized, then it cannot
336 if (LegalizedNodes.count(SDValue(N, 0))) return false;
338 // Okay, this node has not already been legalized. Check and legalize all
339 // operands. If none lead to Dest, then we can legalize this node.
340 bool OperandsLeadToDest = false;
341 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
342 OperandsLeadToDest |= // If an operand leads to Dest, so do we.
343 LegalizeAllNodesNotLeadingTo(N->getOperand(i).getNode(), Dest,
346 if (OperandsLeadToDest) {
347 NodesLeadingTo.insert(N);
351 // Okay, this node looks safe, legalize it and return false.
352 LegalizeOp(SDValue(N, 0));
356 /// ExpandConstantFP - Expands the ConstantFP node to an integer constant or
357 /// a load from the constant pool.
358 static SDValue ExpandConstantFP(ConstantFPSDNode *CFP, bool UseCP,
359 SelectionDAG &DAG, const TargetLowering &TLI) {
361 DebugLoc dl = CFP->getDebugLoc();
363 // If a FP immediate is precise when represented as a float and if the
364 // target can do an extending load from float to double, we put it into
365 // the constant pool as a float, even if it's is statically typed as a
366 // double. This shrinks FP constants and canonicalizes them for targets where
367 // an FP extending load is the same cost as a normal load (such as on the x87
368 // fp stack or PPC FP unit).
369 EVT VT = CFP->getValueType(0);
370 ConstantFP *LLVMC = const_cast<ConstantFP*>(CFP->getConstantFPValue());
372 assert((VT == MVT::f64 || VT == MVT::f32) && "Invalid type expansion");
373 return DAG.getConstant(LLVMC->getValueAPF().bitcastToAPInt(),
374 (VT == MVT::f64) ? MVT::i64 : MVT::i32);
379 while (SVT != MVT::f32) {
380 SVT = (MVT::SimpleValueType)(SVT.getSimpleVT().SimpleTy - 1);
381 if (ConstantFPSDNode::isValueValidForType(SVT, CFP->getValueAPF()) &&
382 // Only do this if the target has a native EXTLOAD instruction from
384 TLI.isLoadExtLegal(ISD::EXTLOAD, SVT) &&
385 TLI.ShouldShrinkFPConstant(OrigVT)) {
386 const Type *SType = SVT.getTypeForEVT(*DAG.getContext());
387 LLVMC = cast<ConstantFP>(ConstantExpr::getFPTrunc(LLVMC, SType));
393 SDValue CPIdx = DAG.getConstantPool(LLVMC, TLI.getPointerTy());
394 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
396 return DAG.getExtLoad(ISD::EXTLOAD, OrigVT, dl,
398 CPIdx, MachinePointerInfo::getConstantPool(),
399 VT, false, false, Alignment);
400 return DAG.getLoad(OrigVT, dl, DAG.getEntryNode(), CPIdx,
401 MachinePointerInfo::getConstantPool(), false, false,
405 /// ExpandUnalignedStore - Expands an unaligned store to 2 half-size stores.
407 SDValue ExpandUnalignedStore(StoreSDNode *ST, SelectionDAG &DAG,
408 const TargetLowering &TLI) {
409 SDValue Chain = ST->getChain();
410 SDValue Ptr = ST->getBasePtr();
411 SDValue Val = ST->getValue();
412 EVT VT = Val.getValueType();
413 int Alignment = ST->getAlignment();
414 DebugLoc dl = ST->getDebugLoc();
415 if (ST->getMemoryVT().isFloatingPoint() ||
416 ST->getMemoryVT().isVector()) {
417 EVT intVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
418 if (TLI.isTypeLegal(intVT)) {
419 // Expand to a bitconvert of the value to the integer type of the
420 // same size, then a (misaligned) int store.
421 // FIXME: Does not handle truncating floating point stores!
422 SDValue Result = DAG.getNode(ISD::BITCAST, dl, intVT, Val);
423 return DAG.getStore(Chain, dl, Result, Ptr, ST->getPointerInfo(),
424 ST->isVolatile(), ST->isNonTemporal(), Alignment);
426 // Do a (aligned) store to a stack slot, then copy from the stack slot
427 // to the final destination using (unaligned) integer loads and stores.
428 EVT StoredVT = ST->getMemoryVT();
430 TLI.getRegisterType(*DAG.getContext(),
431 EVT::getIntegerVT(*DAG.getContext(),
432 StoredVT.getSizeInBits()));
433 unsigned StoredBytes = StoredVT.getSizeInBits() / 8;
434 unsigned RegBytes = RegVT.getSizeInBits() / 8;
435 unsigned NumRegs = (StoredBytes + RegBytes - 1) / RegBytes;
437 // Make sure the stack slot is also aligned for the register type.
438 SDValue StackPtr = DAG.CreateStackTemporary(StoredVT, RegVT);
440 // Perform the original store, only redirected to the stack slot.
441 SDValue Store = DAG.getTruncStore(Chain, dl,
442 Val, StackPtr, MachinePointerInfo(),
443 StoredVT, false, false, 0);
444 SDValue Increment = DAG.getConstant(RegBytes, TLI.getPointerTy());
445 SmallVector<SDValue, 8> Stores;
448 // Do all but one copies using the full register width.
449 for (unsigned i = 1; i < NumRegs; i++) {
450 // Load one integer register's worth from the stack slot.
451 SDValue Load = DAG.getLoad(RegVT, dl, Store, StackPtr,
452 MachinePointerInfo(),
454 // Store it to the final location. Remember the store.
455 Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, Ptr,
456 ST->getPointerInfo().getWithOffset(Offset),
457 ST->isVolatile(), ST->isNonTemporal(),
458 MinAlign(ST->getAlignment(), Offset)));
459 // Increment the pointers.
461 StackPtr = DAG.getNode(ISD::ADD, dl, StackPtr.getValueType(), StackPtr,
463 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
466 // The last store may be partial. Do a truncating store. On big-endian
467 // machines this requires an extending load from the stack slot to ensure
468 // that the bits are in the right place.
469 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(),
470 8 * (StoredBytes - Offset));
472 // Load from the stack slot.
473 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, RegVT, dl, Store, StackPtr,
474 MachinePointerInfo(),
475 MemVT, false, false, 0);
477 Stores.push_back(DAG.getTruncStore(Load.getValue(1), dl, Load, Ptr,
479 .getWithOffset(Offset),
480 MemVT, ST->isVolatile(),
482 MinAlign(ST->getAlignment(), Offset)));
483 // The order of the stores doesn't matter - say it with a TokenFactor.
484 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Stores[0],
488 assert(ST->getMemoryVT().isInteger() &&
489 !ST->getMemoryVT().isVector() &&
490 "Unaligned store of unknown type.");
491 // Get the half-size VT
492 EVT NewStoredVT = ST->getMemoryVT().getHalfSizedIntegerVT(*DAG.getContext());
493 int NumBits = NewStoredVT.getSizeInBits();
494 int IncrementSize = NumBits / 8;
496 // Divide the stored value in two parts.
497 SDValue ShiftAmount = DAG.getConstant(NumBits, TLI.getShiftAmountTy());
499 SDValue Hi = DAG.getNode(ISD::SRL, dl, VT, Val, ShiftAmount);
501 // Store the two parts
502 SDValue Store1, Store2;
503 Store1 = DAG.getTruncStore(Chain, dl, TLI.isLittleEndian()?Lo:Hi, Ptr,
504 ST->getPointerInfo(), NewStoredVT,
505 ST->isVolatile(), ST->isNonTemporal(), Alignment);
506 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
507 DAG.getConstant(IncrementSize, TLI.getPointerTy()));
508 Alignment = MinAlign(Alignment, IncrementSize);
509 Store2 = DAG.getTruncStore(Chain, dl, TLI.isLittleEndian()?Hi:Lo, Ptr,
510 ST->getPointerInfo().getWithOffset(IncrementSize),
511 NewStoredVT, ST->isVolatile(), ST->isNonTemporal(),
514 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Store1, Store2);
517 /// ExpandUnalignedLoad - Expands an unaligned load to 2 half-size loads.
519 SDValue ExpandUnalignedLoad(LoadSDNode *LD, SelectionDAG &DAG,
520 const TargetLowering &TLI) {
521 SDValue Chain = LD->getChain();
522 SDValue Ptr = LD->getBasePtr();
523 EVT VT = LD->getValueType(0);
524 EVT LoadedVT = LD->getMemoryVT();
525 DebugLoc dl = LD->getDebugLoc();
526 if (VT.isFloatingPoint() || VT.isVector()) {
527 EVT intVT = EVT::getIntegerVT(*DAG.getContext(), LoadedVT.getSizeInBits());
528 if (TLI.isTypeLegal(intVT)) {
529 // Expand to a (misaligned) integer load of the same size,
530 // then bitconvert to floating point or vector.
531 SDValue newLoad = DAG.getLoad(intVT, dl, Chain, Ptr, LD->getPointerInfo(),
533 LD->isNonTemporal(), LD->getAlignment());
534 SDValue Result = DAG.getNode(ISD::BITCAST, dl, LoadedVT, newLoad);
535 if (VT.isFloatingPoint() && LoadedVT != VT)
536 Result = DAG.getNode(ISD::FP_EXTEND, dl, VT, Result);
538 SDValue Ops[] = { Result, Chain };
539 return DAG.getMergeValues(Ops, 2, dl);
542 // Copy the value to a (aligned) stack slot using (unaligned) integer
543 // loads and stores, then do a (aligned) load from the stack slot.
544 EVT RegVT = TLI.getRegisterType(*DAG.getContext(), intVT);
545 unsigned LoadedBytes = LoadedVT.getSizeInBits() / 8;
546 unsigned RegBytes = RegVT.getSizeInBits() / 8;
547 unsigned NumRegs = (LoadedBytes + RegBytes - 1) / RegBytes;
549 // Make sure the stack slot is also aligned for the register type.
550 SDValue StackBase = DAG.CreateStackTemporary(LoadedVT, RegVT);
552 SDValue Increment = DAG.getConstant(RegBytes, TLI.getPointerTy());
553 SmallVector<SDValue, 8> Stores;
554 SDValue StackPtr = StackBase;
557 // Do all but one copies using the full register width.
558 for (unsigned i = 1; i < NumRegs; i++) {
559 // Load one integer register's worth from the original location.
560 SDValue Load = DAG.getLoad(RegVT, dl, Chain, Ptr,
561 LD->getPointerInfo().getWithOffset(Offset),
562 LD->isVolatile(), LD->isNonTemporal(),
563 MinAlign(LD->getAlignment(), Offset));
564 // Follow the load with a store to the stack slot. Remember the store.
565 Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, StackPtr,
566 MachinePointerInfo(), false, false, 0));
567 // Increment the pointers.
569 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
570 StackPtr = DAG.getNode(ISD::ADD, dl, StackPtr.getValueType(), StackPtr,
574 // The last copy may be partial. Do an extending load.
575 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(),
576 8 * (LoadedBytes - Offset));
577 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, RegVT, dl, Chain, Ptr,
578 LD->getPointerInfo().getWithOffset(Offset),
579 MemVT, LD->isVolatile(),
581 MinAlign(LD->getAlignment(), Offset));
582 // Follow the load with a store to the stack slot. Remember the store.
583 // On big-endian machines this requires a truncating store to ensure
584 // that the bits end up in the right place.
585 Stores.push_back(DAG.getTruncStore(Load.getValue(1), dl, Load, StackPtr,
586 MachinePointerInfo(), MemVT,
589 // The order of the stores doesn't matter - say it with a TokenFactor.
590 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Stores[0],
593 // Finally, perform the original load only redirected to the stack slot.
594 Load = DAG.getExtLoad(LD->getExtensionType(), VT, dl, TF, StackBase,
595 MachinePointerInfo(), LoadedVT, false, false, 0);
597 // Callers expect a MERGE_VALUES node.
598 SDValue Ops[] = { Load, TF };
599 return DAG.getMergeValues(Ops, 2, dl);
601 assert(LoadedVT.isInteger() && !LoadedVT.isVector() &&
602 "Unaligned load of unsupported type.");
604 // Compute the new VT that is half the size of the old one. This is an
606 unsigned NumBits = LoadedVT.getSizeInBits();
608 NewLoadedVT = EVT::getIntegerVT(*DAG.getContext(), NumBits/2);
611 unsigned Alignment = LD->getAlignment();
612 unsigned IncrementSize = NumBits / 8;
613 ISD::LoadExtType HiExtType = LD->getExtensionType();
615 // If the original load is NON_EXTLOAD, the hi part load must be ZEXTLOAD.
616 if (HiExtType == ISD::NON_EXTLOAD)
617 HiExtType = ISD::ZEXTLOAD;
619 // Load the value in two parts
621 if (TLI.isLittleEndian()) {
622 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, VT, dl, Chain, Ptr, LD->getPointerInfo(),
623 NewLoadedVT, LD->isVolatile(),
624 LD->isNonTemporal(), Alignment);
625 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
626 DAG.getConstant(IncrementSize, TLI.getPointerTy()));
627 Hi = DAG.getExtLoad(HiExtType, VT, dl, Chain, Ptr,
628 LD->getPointerInfo().getWithOffset(IncrementSize),
629 NewLoadedVT, LD->isVolatile(),
630 LD->isNonTemporal(), MinAlign(Alignment,IncrementSize));
632 Hi = DAG.getExtLoad(HiExtType, VT, dl, Chain, Ptr, LD->getPointerInfo(),
633 NewLoadedVT, LD->isVolatile(),
634 LD->isNonTemporal(), Alignment);
635 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
636 DAG.getConstant(IncrementSize, TLI.getPointerTy()));
637 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, VT, dl, Chain, Ptr,
638 LD->getPointerInfo().getWithOffset(IncrementSize),
639 NewLoadedVT, LD->isVolatile(),
640 LD->isNonTemporal(), MinAlign(Alignment,IncrementSize));
643 // aggregate the two parts
644 SDValue ShiftAmount = DAG.getConstant(NumBits, TLI.getShiftAmountTy());
645 SDValue Result = DAG.getNode(ISD::SHL, dl, VT, Hi, ShiftAmount);
646 Result = DAG.getNode(ISD::OR, dl, VT, Result, Lo);
648 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
651 SDValue Ops[] = { Result, TF };
652 return DAG.getMergeValues(Ops, 2, dl);
655 /// PerformInsertVectorEltInMemory - Some target cannot handle a variable
656 /// insertion index for the INSERT_VECTOR_ELT instruction. In this case, it
657 /// is necessary to spill the vector being inserted into to memory, perform
658 /// the insert there, and then read the result back.
659 SDValue SelectionDAGLegalize::
660 PerformInsertVectorEltInMemory(SDValue Vec, SDValue Val, SDValue Idx,
666 // If the target doesn't support this, we have to spill the input vector
667 // to a temporary stack slot, update the element, then reload it. This is
668 // badness. We could also load the value into a vector register (either
669 // with a "move to register" or "extload into register" instruction, then
670 // permute it into place, if the idx is a constant and if the idx is
671 // supported by the target.
672 EVT VT = Tmp1.getValueType();
673 EVT EltVT = VT.getVectorElementType();
674 EVT IdxVT = Tmp3.getValueType();
675 EVT PtrVT = TLI.getPointerTy();
676 SDValue StackPtr = DAG.CreateStackTemporary(VT);
678 int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
681 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, Tmp1, StackPtr,
682 MachinePointerInfo::getFixedStack(SPFI),
685 // Truncate or zero extend offset to target pointer type.
686 unsigned CastOpc = IdxVT.bitsGT(PtrVT) ? ISD::TRUNCATE : ISD::ZERO_EXTEND;
687 Tmp3 = DAG.getNode(CastOpc, dl, PtrVT, Tmp3);
688 // Add the offset to the index.
689 unsigned EltSize = EltVT.getSizeInBits()/8;
690 Tmp3 = DAG.getNode(ISD::MUL, dl, IdxVT, Tmp3,DAG.getConstant(EltSize, IdxVT));
691 SDValue StackPtr2 = DAG.getNode(ISD::ADD, dl, IdxVT, Tmp3, StackPtr);
692 // Store the scalar value.
693 Ch = DAG.getTruncStore(Ch, dl, Tmp2, StackPtr2, MachinePointerInfo(), EltVT,
695 // Load the updated vector.
696 return DAG.getLoad(VT, dl, Ch, StackPtr,
697 MachinePointerInfo::getFixedStack(SPFI), false, false, 0);
701 SDValue SelectionDAGLegalize::
702 ExpandINSERT_VECTOR_ELT(SDValue Vec, SDValue Val, SDValue Idx, DebugLoc dl) {
703 if (ConstantSDNode *InsertPos = dyn_cast<ConstantSDNode>(Idx)) {
704 // SCALAR_TO_VECTOR requires that the type of the value being inserted
705 // match the element type of the vector being created, except for
706 // integers in which case the inserted value can be over width.
707 EVT EltVT = Vec.getValueType().getVectorElementType();
708 if (Val.getValueType() == EltVT ||
709 (EltVT.isInteger() && Val.getValueType().bitsGE(EltVT))) {
710 SDValue ScVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
711 Vec.getValueType(), Val);
713 unsigned NumElts = Vec.getValueType().getVectorNumElements();
714 // We generate a shuffle of InVec and ScVec, so the shuffle mask
715 // should be 0,1,2,3,4,5... with the appropriate element replaced with
717 SmallVector<int, 8> ShufOps;
718 for (unsigned i = 0; i != NumElts; ++i)
719 ShufOps.push_back(i != InsertPos->getZExtValue() ? i : NumElts);
721 return DAG.getVectorShuffle(Vec.getValueType(), dl, Vec, ScVec,
725 return PerformInsertVectorEltInMemory(Vec, Val, Idx, dl);
728 SDValue SelectionDAGLegalize::OptimizeFloatStore(StoreSDNode* ST) {
729 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
730 // FIXME: We shouldn't do this for TargetConstantFP's.
731 // FIXME: move this to the DAG Combiner! Note that we can't regress due
732 // to phase ordering between legalized code and the dag combiner. This
733 // probably means that we need to integrate dag combiner and legalizer
735 // We generally can't do this one for long doubles.
736 SDValue Tmp1 = ST->getChain();
737 SDValue Tmp2 = ST->getBasePtr();
739 unsigned Alignment = ST->getAlignment();
740 bool isVolatile = ST->isVolatile();
741 bool isNonTemporal = ST->isNonTemporal();
742 DebugLoc dl = ST->getDebugLoc();
743 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(ST->getValue())) {
744 if (CFP->getValueType(0) == MVT::f32 &&
745 getTypeAction(MVT::i32) == Legal) {
746 Tmp3 = DAG.getConstant(CFP->getValueAPF().
747 bitcastToAPInt().zextOrTrunc(32),
749 return DAG.getStore(Tmp1, dl, Tmp3, Tmp2, ST->getPointerInfo(),
750 isVolatile, isNonTemporal, Alignment);
753 if (CFP->getValueType(0) == MVT::f64) {
754 // If this target supports 64-bit registers, do a single 64-bit store.
755 if (getTypeAction(MVT::i64) == Legal) {
756 Tmp3 = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
757 zextOrTrunc(64), MVT::i64);
758 return DAG.getStore(Tmp1, dl, Tmp3, Tmp2, ST->getPointerInfo(),
759 isVolatile, isNonTemporal, Alignment);
762 if (getTypeAction(MVT::i32) == Legal && !ST->isVolatile()) {
763 // Otherwise, if the target supports 32-bit registers, use 2 32-bit
764 // stores. If the target supports neither 32- nor 64-bits, this
765 // xform is certainly not worth it.
766 const APInt &IntVal =CFP->getValueAPF().bitcastToAPInt();
767 SDValue Lo = DAG.getConstant(IntVal.trunc(32), MVT::i32);
768 SDValue Hi = DAG.getConstant(IntVal.lshr(32).trunc(32), MVT::i32);
769 if (TLI.isBigEndian()) std::swap(Lo, Hi);
771 Lo = DAG.getStore(Tmp1, dl, Lo, Tmp2, ST->getPointerInfo(), isVolatile,
772 isNonTemporal, Alignment);
773 Tmp2 = DAG.getNode(ISD::ADD, dl, Tmp2.getValueType(), Tmp2,
774 DAG.getIntPtrConstant(4));
775 Hi = DAG.getStore(Tmp1, dl, Hi, Tmp2,
776 ST->getPointerInfo().getWithOffset(4),
777 isVolatile, isNonTemporal, MinAlign(Alignment, 4U));
779 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo, Hi);
786 /// LegalizeOp - We know that the specified value has a legal type, and
787 /// that its operands are legal. Now ensure that the operation itself
788 /// is legal, recursively ensuring that the operands' operations remain
790 SDValue SelectionDAGLegalize::LegalizeOp(SDValue Op) {
791 if (Op.getOpcode() == ISD::TargetConstant) // Allow illegal target nodes.
794 SDNode *Node = Op.getNode();
795 DebugLoc dl = Node->getDebugLoc();
797 for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
798 assert(getTypeAction(Node->getValueType(i)) == Legal &&
799 "Unexpected illegal type!");
801 for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i)
802 assert((isTypeLegal(Node->getOperand(i).getValueType()) ||
803 Node->getOperand(i).getOpcode() == ISD::TargetConstant) &&
804 "Unexpected illegal type!");
806 // Note that LegalizeOp may be reentered even from single-use nodes, which
807 // means that we always must cache transformed nodes.
808 DenseMap<SDValue, SDValue>::iterator I = LegalizedNodes.find(Op);
809 if (I != LegalizedNodes.end()) return I->second;
811 SDValue Tmp1, Tmp2, Tmp3, Tmp4;
813 bool isCustom = false;
815 // Figure out the correct action; the way to query this varies by opcode
816 TargetLowering::LegalizeAction Action;
817 bool SimpleFinishLegalizing = true;
818 switch (Node->getOpcode()) {
819 case ISD::INTRINSIC_W_CHAIN:
820 case ISD::INTRINSIC_WO_CHAIN:
821 case ISD::INTRINSIC_VOID:
824 Action = TLI.getOperationAction(Node->getOpcode(), MVT::Other);
826 case ISD::SINT_TO_FP:
827 case ISD::UINT_TO_FP:
828 case ISD::EXTRACT_VECTOR_ELT:
829 Action = TLI.getOperationAction(Node->getOpcode(),
830 Node->getOperand(0).getValueType());
832 case ISD::FP_ROUND_INREG:
833 case ISD::SIGN_EXTEND_INREG: {
834 EVT InnerType = cast<VTSDNode>(Node->getOperand(1))->getVT();
835 Action = TLI.getOperationAction(Node->getOpcode(), InnerType);
841 unsigned CCOperand = Node->getOpcode() == ISD::SELECT_CC ? 4 :
842 Node->getOpcode() == ISD::SETCC ? 2 : 1;
843 unsigned CompareOperand = Node->getOpcode() == ISD::BR_CC ? 2 : 0;
844 EVT OpVT = Node->getOperand(CompareOperand).getValueType();
845 ISD::CondCode CCCode =
846 cast<CondCodeSDNode>(Node->getOperand(CCOperand))->get();
847 Action = TLI.getCondCodeAction(CCCode, OpVT);
848 if (Action == TargetLowering::Legal) {
849 if (Node->getOpcode() == ISD::SELECT_CC)
850 Action = TLI.getOperationAction(Node->getOpcode(),
851 Node->getValueType(0));
853 Action = TLI.getOperationAction(Node->getOpcode(), OpVT);
859 // FIXME: Model these properly. LOAD and STORE are complicated, and
860 // STORE expects the unlegalized operand in some cases.
861 SimpleFinishLegalizing = false;
863 case ISD::CALLSEQ_START:
864 case ISD::CALLSEQ_END:
865 // FIXME: This shouldn't be necessary. These nodes have special properties
866 // dealing with the recursive nature of legalization. Removing this
867 // special case should be done as part of making LegalizeDAG non-recursive.
868 SimpleFinishLegalizing = false;
870 case ISD::EXTRACT_ELEMENT:
871 case ISD::FLT_ROUNDS_:
879 case ISD::MERGE_VALUES:
881 case ISD::FRAME_TO_ARGS_OFFSET:
882 case ISD::EH_SJLJ_SETJMP:
883 case ISD::EH_SJLJ_LONGJMP:
884 case ISD::EH_SJLJ_DISPATCHSETUP:
885 // These operations lie about being legal: when they claim to be legal,
886 // they should actually be expanded.
887 Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
888 if (Action == TargetLowering::Legal)
889 Action = TargetLowering::Expand;
891 case ISD::TRAMPOLINE:
893 case ISD::RETURNADDR:
894 // These operations lie about being legal: when they claim to be legal,
895 // they should actually be custom-lowered.
896 Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
897 if (Action == TargetLowering::Legal)
898 Action = TargetLowering::Custom;
900 case ISD::BUILD_VECTOR:
901 // A weird case: legalization for BUILD_VECTOR never legalizes the
903 // FIXME: This really sucks... changing it isn't semantically incorrect,
904 // but it massively pessimizes the code for floating-point BUILD_VECTORs
905 // because ConstantFP operands get legalized into constant pool loads
906 // before the BUILD_VECTOR code can see them. It doesn't usually bite,
907 // though, because BUILD_VECTORS usually get lowered into other nodes
908 // which get legalized properly.
909 SimpleFinishLegalizing = false;
912 if (Node->getOpcode() >= ISD::BUILTIN_OP_END) {
913 Action = TargetLowering::Legal;
915 Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
920 if (SimpleFinishLegalizing) {
921 SmallVector<SDValue, 8> Ops, ResultVals;
922 for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i)
923 Ops.push_back(LegalizeOp(Node->getOperand(i)));
924 switch (Node->getOpcode()) {
931 // Branches tweak the chain to include LastCALLSEQ_END
932 Ops[0] = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ops[0],
934 Ops[0] = LegalizeOp(Ops[0]);
935 LastCALLSEQ_END = DAG.getEntryNode();
942 // Legalizing shifts/rotates requires adjusting the shift amount
943 // to the appropriate width.
944 if (!Ops[1].getValueType().isVector())
945 Ops[1] = LegalizeOp(DAG.getShiftAmountOperand(Ops[1]));
950 // Legalizing shifts/rotates requires adjusting the shift amount
951 // to the appropriate width.
952 if (!Ops[2].getValueType().isVector())
953 Ops[2] = LegalizeOp(DAG.getShiftAmountOperand(Ops[2]));
957 Result = SDValue(DAG.UpdateNodeOperands(Result.getNode(), Ops.data(),
960 case TargetLowering::Legal:
961 for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
962 ResultVals.push_back(Result.getValue(i));
964 case TargetLowering::Custom:
965 // FIXME: The handling for custom lowering with multiple results is
967 Tmp1 = TLI.LowerOperation(Result, DAG);
968 if (Tmp1.getNode()) {
969 for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i) {
971 ResultVals.push_back(Tmp1);
973 ResultVals.push_back(Tmp1.getValue(i));
979 case TargetLowering::Expand:
980 ExpandNode(Result.getNode(), ResultVals);
982 case TargetLowering::Promote:
983 PromoteNode(Result.getNode(), ResultVals);
986 if (!ResultVals.empty()) {
987 for (unsigned i = 0, e = ResultVals.size(); i != e; ++i) {
988 if (ResultVals[i] != SDValue(Node, i))
989 ResultVals[i] = LegalizeOp(ResultVals[i]);
990 AddLegalizedOperand(SDValue(Node, i), ResultVals[i]);
992 return ResultVals[Op.getResNo()];
996 switch (Node->getOpcode()) {
1003 assert(0 && "Do not know how to legalize this operator!");
1005 case ISD::BUILD_VECTOR:
1006 switch (TLI.getOperationAction(ISD::BUILD_VECTOR, Node->getValueType(0))) {
1007 default: assert(0 && "This action is not supported yet!");
1008 case TargetLowering::Custom:
1009 Tmp3 = TLI.LowerOperation(Result, DAG);
1010 if (Tmp3.getNode()) {
1015 case TargetLowering::Expand:
1016 Result = ExpandBUILD_VECTOR(Result.getNode());
1020 case ISD::CALLSEQ_START: {
1021 static int depth = 0;
1022 SDNode *CallEnd = FindCallEndFromCallStart(Node);
1024 // Recursively Legalize all of the inputs of the call end that do not lead
1025 // to this call start. This ensures that any libcalls that need be inserted
1026 // are inserted *before* the CALLSEQ_START.
1027 {SmallPtrSet<SDNode*, 32> NodesLeadingTo;
1028 for (unsigned i = 0, e = CallEnd->getNumOperands(); i != e; ++i)
1029 LegalizeAllNodesNotLeadingTo(CallEnd->getOperand(i).getNode(), Node,
1033 // Now that we have legalized all of the inputs (which may have inserted
1034 // libcalls), create the new CALLSEQ_START node.
1035 Tmp1 = LegalizeOp(Node->getOperand(0)); // Legalize the chain.
1037 // Merge in the last call to ensure that this call starts after the last
1039 if (LastCALLSEQ_END.getOpcode() != ISD::EntryToken && depth == 0) {
1040 Tmp1 = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1041 Tmp1, LastCALLSEQ_END);
1042 Tmp1 = LegalizeOp(Tmp1);
1045 // Do not try to legalize the target-specific arguments (#1+).
1046 if (Tmp1 != Node->getOperand(0)) {
1047 SmallVector<SDValue, 8> Ops(Node->op_begin(), Node->op_end());
1049 Result = SDValue(DAG.UpdateNodeOperands(Result.getNode(), &Ops[0],
1050 Ops.size()), Result.getResNo());
1053 // Remember that the CALLSEQ_START is legalized.
1054 AddLegalizedOperand(Op.getValue(0), Result);
1055 if (Node->getNumValues() == 2) // If this has a flag result, remember it.
1056 AddLegalizedOperand(Op.getValue(1), Result.getValue(1));
1058 // Now that the callseq_start and all of the non-call nodes above this call
1059 // sequence have been legalized, legalize the call itself. During this
1060 // process, no libcalls can/will be inserted, guaranteeing that no calls
1063 SDValue Saved_LastCALLSEQ_END = LastCALLSEQ_END ;
1064 // Note that we are selecting this call!
1065 LastCALLSEQ_END = SDValue(CallEnd, 0);
1068 // Legalize the call, starting from the CALLSEQ_END.
1069 LegalizeOp(LastCALLSEQ_END);
1071 assert(depth >= 0 && "Un-matched CALLSEQ_START?");
1073 LastCALLSEQ_END = Saved_LastCALLSEQ_END;
1076 case ISD::CALLSEQ_END:
1077 // If the CALLSEQ_START node hasn't been legalized first, legalize it. This
1078 // will cause this node to be legalized as well as handling libcalls right.
1079 if (LastCALLSEQ_END.getNode() != Node) {
1080 LegalizeOp(SDValue(FindCallStartFromCallEnd(Node), 0));
1081 DenseMap<SDValue, SDValue>::iterator I = LegalizedNodes.find(Op);
1082 assert(I != LegalizedNodes.end() &&
1083 "Legalizing the call start should have legalized this node!");
1087 // Otherwise, the call start has been legalized and everything is going
1088 // according to plan. Just legalize ourselves normally here.
1089 Tmp1 = LegalizeOp(Node->getOperand(0)); // Legalize the chain.
1090 // Do not try to legalize the target-specific arguments (#1+), except for
1091 // an optional flag input.
1092 if (Node->getOperand(Node->getNumOperands()-1).getValueType() != MVT::Glue){
1093 if (Tmp1 != Node->getOperand(0)) {
1094 SmallVector<SDValue, 8> Ops(Node->op_begin(), Node->op_end());
1096 Result = SDValue(DAG.UpdateNodeOperands(Result.getNode(),
1097 &Ops[0], Ops.size()),
1101 Tmp2 = LegalizeOp(Node->getOperand(Node->getNumOperands()-1));
1102 if (Tmp1 != Node->getOperand(0) ||
1103 Tmp2 != Node->getOperand(Node->getNumOperands()-1)) {
1104 SmallVector<SDValue, 8> Ops(Node->op_begin(), Node->op_end());
1107 Result = SDValue(DAG.UpdateNodeOperands(Result.getNode(),
1108 &Ops[0], Ops.size()),
1112 // This finishes up call legalization.
1113 // If the CALLSEQ_END node has a flag, remember that we legalized it.
1114 AddLegalizedOperand(SDValue(Node, 0), Result.getValue(0));
1115 if (Node->getNumValues() == 2)
1116 AddLegalizedOperand(SDValue(Node, 1), Result.getValue(1));
1117 return Result.getValue(Op.getResNo());
1119 LoadSDNode *LD = cast<LoadSDNode>(Node);
1120 Tmp1 = LegalizeOp(LD->getChain()); // Legalize the chain.
1121 Tmp2 = LegalizeOp(LD->getBasePtr()); // Legalize the base pointer.
1123 ISD::LoadExtType ExtType = LD->getExtensionType();
1124 if (ExtType == ISD::NON_EXTLOAD) {
1125 EVT VT = Node->getValueType(0);
1126 Result = SDValue(DAG.UpdateNodeOperands(Result.getNode(),
1127 Tmp1, Tmp2, LD->getOffset()),
1129 Tmp3 = Result.getValue(0);
1130 Tmp4 = Result.getValue(1);
1132 switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
1133 default: assert(0 && "This action is not supported yet!");
1134 case TargetLowering::Legal:
1135 // If this is an unaligned load and the target doesn't support it,
1137 if (!TLI.allowsUnalignedMemoryAccesses(LD->getMemoryVT())) {
1138 const Type *Ty = LD->getMemoryVT().getTypeForEVT(*DAG.getContext());
1139 unsigned ABIAlignment = TLI.getTargetData()->getABITypeAlignment(Ty);
1140 if (LD->getAlignment() < ABIAlignment){
1141 Result = ExpandUnalignedLoad(cast<LoadSDNode>(Result.getNode()),
1143 Tmp3 = Result.getOperand(0);
1144 Tmp4 = Result.getOperand(1);
1145 Tmp3 = LegalizeOp(Tmp3);
1146 Tmp4 = LegalizeOp(Tmp4);
1150 case TargetLowering::Custom:
1151 Tmp1 = TLI.LowerOperation(Tmp3, DAG);
1152 if (Tmp1.getNode()) {
1153 Tmp3 = LegalizeOp(Tmp1);
1154 Tmp4 = LegalizeOp(Tmp1.getValue(1));
1157 case TargetLowering::Promote: {
1158 // Only promote a load of vector type to another.
1159 assert(VT.isVector() && "Cannot promote this load!");
1160 // Change base type to a different vector type.
1161 EVT NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), VT);
1163 Tmp1 = DAG.getLoad(NVT, dl, Tmp1, Tmp2, LD->getPointerInfo(),
1164 LD->isVolatile(), LD->isNonTemporal(),
1165 LD->getAlignment());
1166 Tmp3 = LegalizeOp(DAG.getNode(ISD::BITCAST, dl, VT, Tmp1));
1167 Tmp4 = LegalizeOp(Tmp1.getValue(1));
1171 // Since loads produce two values, make sure to remember that we
1172 // legalized both of them.
1173 AddLegalizedOperand(SDValue(Node, 0), Tmp3);
1174 AddLegalizedOperand(SDValue(Node, 1), Tmp4);
1175 return Op.getResNo() ? Tmp4 : Tmp3;
1178 EVT SrcVT = LD->getMemoryVT();
1179 unsigned SrcWidth = SrcVT.getSizeInBits();
1180 unsigned Alignment = LD->getAlignment();
1181 bool isVolatile = LD->isVolatile();
1182 bool isNonTemporal = LD->isNonTemporal();
1184 if (SrcWidth != SrcVT.getStoreSizeInBits() &&
1185 // Some targets pretend to have an i1 loading operation, and actually
1186 // load an i8. This trick is correct for ZEXTLOAD because the top 7
1187 // bits are guaranteed to be zero; it helps the optimizers understand
1188 // that these bits are zero. It is also useful for EXTLOAD, since it
1189 // tells the optimizers that those bits are undefined. It would be
1190 // nice to have an effective generic way of getting these benefits...
1191 // Until such a way is found, don't insist on promoting i1 here.
1192 (SrcVT != MVT::i1 ||
1193 TLI.getLoadExtAction(ExtType, MVT::i1) == TargetLowering::Promote)) {
1194 // Promote to a byte-sized load if not loading an integral number of
1195 // bytes. For example, promote EXTLOAD:i20 -> EXTLOAD:i24.
1196 unsigned NewWidth = SrcVT.getStoreSizeInBits();
1197 EVT NVT = EVT::getIntegerVT(*DAG.getContext(), NewWidth);
1200 // The extra bits are guaranteed to be zero, since we stored them that
1201 // way. A zext load from NVT thus automatically gives zext from SrcVT.
1203 ISD::LoadExtType NewExtType =
1204 ExtType == ISD::ZEXTLOAD ? ISD::ZEXTLOAD : ISD::EXTLOAD;
1206 Result = DAG.getExtLoad(NewExtType, Node->getValueType(0), dl,
1207 Tmp1, Tmp2, LD->getPointerInfo(),
1208 NVT, isVolatile, isNonTemporal, Alignment);
1210 Ch = Result.getValue(1); // The chain.
1212 if (ExtType == ISD::SEXTLOAD)
1213 // Having the top bits zero doesn't help when sign extending.
1214 Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl,
1215 Result.getValueType(),
1216 Result, DAG.getValueType(SrcVT));
1217 else if (ExtType == ISD::ZEXTLOAD || NVT == Result.getValueType())
1218 // All the top bits are guaranteed to be zero - inform the optimizers.
1219 Result = DAG.getNode(ISD::AssertZext, dl,
1220 Result.getValueType(), Result,
1221 DAG.getValueType(SrcVT));
1223 Tmp1 = LegalizeOp(Result);
1224 Tmp2 = LegalizeOp(Ch);
1225 } else if (SrcWidth & (SrcWidth - 1)) {
1226 // If not loading a power-of-2 number of bits, expand as two loads.
1227 assert(!SrcVT.isVector() && "Unsupported extload!");
1228 unsigned RoundWidth = 1 << Log2_32(SrcWidth);
1229 assert(RoundWidth < SrcWidth);
1230 unsigned ExtraWidth = SrcWidth - RoundWidth;
1231 assert(ExtraWidth < RoundWidth);
1232 assert(!(RoundWidth % 8) && !(ExtraWidth % 8) &&
1233 "Load size not an integral number of bytes!");
1234 EVT RoundVT = EVT::getIntegerVT(*DAG.getContext(), RoundWidth);
1235 EVT ExtraVT = EVT::getIntegerVT(*DAG.getContext(), ExtraWidth);
1237 unsigned IncrementSize;
1239 if (TLI.isLittleEndian()) {
1240 // EXTLOAD:i24 -> ZEXTLOAD:i16 | (shl EXTLOAD@+2:i8, 16)
1241 // Load the bottom RoundWidth bits.
1242 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, Node->getValueType(0), dl,
1244 LD->getPointerInfo(), RoundVT, isVolatile,
1245 isNonTemporal, Alignment);
1247 // Load the remaining ExtraWidth bits.
1248 IncrementSize = RoundWidth / 8;
1249 Tmp2 = DAG.getNode(ISD::ADD, dl, Tmp2.getValueType(), Tmp2,
1250 DAG.getIntPtrConstant(IncrementSize));
1251 Hi = DAG.getExtLoad(ExtType, Node->getValueType(0), dl, Tmp1, Tmp2,
1252 LD->getPointerInfo().getWithOffset(IncrementSize),
1253 ExtraVT, isVolatile, isNonTemporal,
1254 MinAlign(Alignment, IncrementSize));
1256 // Build a factor node to remember that this load is independent of
1258 Ch = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
1261 // Move the top bits to the right place.
1262 Hi = DAG.getNode(ISD::SHL, dl, Hi.getValueType(), Hi,
1263 DAG.getConstant(RoundWidth, TLI.getShiftAmountTy()));
1265 // Join the hi and lo parts.
1266 Result = DAG.getNode(ISD::OR, dl, Node->getValueType(0), Lo, Hi);
1268 // Big endian - avoid unaligned loads.
1269 // EXTLOAD:i24 -> (shl EXTLOAD:i16, 8) | ZEXTLOAD@+2:i8
1270 // Load the top RoundWidth bits.
1271 Hi = DAG.getExtLoad(ExtType, Node->getValueType(0), dl, Tmp1, Tmp2,
1272 LD->getPointerInfo(), RoundVT, isVolatile,
1273 isNonTemporal, Alignment);
1275 // Load the remaining ExtraWidth bits.
1276 IncrementSize = RoundWidth / 8;
1277 Tmp2 = DAG.getNode(ISD::ADD, dl, Tmp2.getValueType(), Tmp2,
1278 DAG.getIntPtrConstant(IncrementSize));
1279 Lo = DAG.getExtLoad(ISD::ZEXTLOAD,
1280 Node->getValueType(0), dl, Tmp1, Tmp2,
1281 LD->getPointerInfo().getWithOffset(IncrementSize),
1282 ExtraVT, isVolatile, isNonTemporal,
1283 MinAlign(Alignment, IncrementSize));
1285 // Build a factor node to remember that this load is independent of
1287 Ch = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
1290 // Move the top bits to the right place.
1291 Hi = DAG.getNode(ISD::SHL, dl, Hi.getValueType(), Hi,
1292 DAG.getConstant(ExtraWidth, TLI.getShiftAmountTy()));
1294 // Join the hi and lo parts.
1295 Result = DAG.getNode(ISD::OR, dl, Node->getValueType(0), Lo, Hi);
1298 Tmp1 = LegalizeOp(Result);
1299 Tmp2 = LegalizeOp(Ch);
1301 switch (TLI.getLoadExtAction(ExtType, SrcVT)) {
1302 default: assert(0 && "This action is not supported yet!");
1303 case TargetLowering::Custom:
1306 case TargetLowering::Legal:
1307 Result = SDValue(DAG.UpdateNodeOperands(Result.getNode(),
1308 Tmp1, Tmp2, LD->getOffset()),
1310 Tmp1 = Result.getValue(0);
1311 Tmp2 = Result.getValue(1);
1314 Tmp3 = TLI.LowerOperation(Result, DAG);
1315 if (Tmp3.getNode()) {
1316 Tmp1 = LegalizeOp(Tmp3);
1317 Tmp2 = LegalizeOp(Tmp3.getValue(1));
1320 // If this is an unaligned load and the target doesn't support it,
1322 if (!TLI.allowsUnalignedMemoryAccesses(LD->getMemoryVT())) {
1324 LD->getMemoryVT().getTypeForEVT(*DAG.getContext());
1325 unsigned ABIAlignment =
1326 TLI.getTargetData()->getABITypeAlignment(Ty);
1327 if (LD->getAlignment() < ABIAlignment){
1328 Result = ExpandUnalignedLoad(cast<LoadSDNode>(Result.getNode()),
1330 Tmp1 = Result.getOperand(0);
1331 Tmp2 = Result.getOperand(1);
1332 Tmp1 = LegalizeOp(Tmp1);
1333 Tmp2 = LegalizeOp(Tmp2);
1338 case TargetLowering::Expand:
1339 if (!TLI.isLoadExtLegal(ISD::EXTLOAD, SrcVT) && isTypeLegal(SrcVT)) {
1340 SDValue Load = DAG.getLoad(SrcVT, dl, Tmp1, Tmp2,
1341 LD->getPointerInfo(),
1342 LD->isVolatile(), LD->isNonTemporal(),
1343 LD->getAlignment());
1347 ExtendOp = (SrcVT.isFloatingPoint() ?
1348 ISD::FP_EXTEND : ISD::ANY_EXTEND);
1350 case ISD::SEXTLOAD: ExtendOp = ISD::SIGN_EXTEND; break;
1351 case ISD::ZEXTLOAD: ExtendOp = ISD::ZERO_EXTEND; break;
1352 default: llvm_unreachable("Unexpected extend load type!");
1354 Result = DAG.getNode(ExtendOp, dl, Node->getValueType(0), Load);
1355 Tmp1 = LegalizeOp(Result); // Relegalize new nodes.
1356 Tmp2 = LegalizeOp(Load.getValue(1));
1359 // FIXME: This does not work for vectors on most targets. Sign- and
1360 // zero-extend operations are currently folded into extending loads,
1361 // whether they are legal or not, and then we end up here without any
1362 // support for legalizing them.
1363 assert(ExtType != ISD::EXTLOAD &&
1364 "EXTLOAD should always be supported!");
1365 // Turn the unsupported load into an EXTLOAD followed by an explicit
1366 // zero/sign extend inreg.
1367 Result = DAG.getExtLoad(ISD::EXTLOAD, Node->getValueType(0), dl,
1368 Tmp1, Tmp2, LD->getPointerInfo(), SrcVT,
1369 LD->isVolatile(), LD->isNonTemporal(),
1370 LD->getAlignment());
1372 if (ExtType == ISD::SEXTLOAD)
1373 ValRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl,
1374 Result.getValueType(),
1375 Result, DAG.getValueType(SrcVT));
1377 ValRes = DAG.getZeroExtendInReg(Result, dl, SrcVT.getScalarType());
1378 Tmp1 = LegalizeOp(ValRes); // Relegalize new nodes.
1379 Tmp2 = LegalizeOp(Result.getValue(1)); // Relegalize new nodes.
1384 // Since loads produce two values, make sure to remember that we legalized
1386 AddLegalizedOperand(SDValue(Node, 0), Tmp1);
1387 AddLegalizedOperand(SDValue(Node, 1), Tmp2);
1388 return Op.getResNo() ? Tmp2 : Tmp1;
1391 StoreSDNode *ST = cast<StoreSDNode>(Node);
1392 Tmp1 = LegalizeOp(ST->getChain()); // Legalize the chain.
1393 Tmp2 = LegalizeOp(ST->getBasePtr()); // Legalize the pointer.
1394 unsigned Alignment = ST->getAlignment();
1395 bool isVolatile = ST->isVolatile();
1396 bool isNonTemporal = ST->isNonTemporal();
1398 if (!ST->isTruncatingStore()) {
1399 if (SDNode *OptStore = OptimizeFloatStore(ST).getNode()) {
1400 Result = SDValue(OptStore, 0);
1405 Tmp3 = LegalizeOp(ST->getValue());
1406 Result = SDValue(DAG.UpdateNodeOperands(Result.getNode(),
1411 EVT VT = Tmp3.getValueType();
1412 switch (TLI.getOperationAction(ISD::STORE, VT)) {
1413 default: assert(0 && "This action is not supported yet!");
1414 case TargetLowering::Legal:
1415 // If this is an unaligned store and the target doesn't support it,
1417 if (!TLI.allowsUnalignedMemoryAccesses(ST->getMemoryVT())) {
1418 const Type *Ty = ST->getMemoryVT().getTypeForEVT(*DAG.getContext());
1419 unsigned ABIAlignment= TLI.getTargetData()->getABITypeAlignment(Ty);
1420 if (ST->getAlignment() < ABIAlignment)
1421 Result = ExpandUnalignedStore(cast<StoreSDNode>(Result.getNode()),
1425 case TargetLowering::Custom:
1426 Tmp1 = TLI.LowerOperation(Result, DAG);
1427 if (Tmp1.getNode()) Result = Tmp1;
1429 case TargetLowering::Promote:
1430 assert(VT.isVector() && "Unknown legal promote case!");
1431 Tmp3 = DAG.getNode(ISD::BITCAST, dl,
1432 TLI.getTypeToPromoteTo(ISD::STORE, VT), Tmp3);
1433 Result = DAG.getStore(Tmp1, dl, Tmp3, Tmp2,
1434 ST->getPointerInfo(), isVolatile,
1435 isNonTemporal, Alignment);
1441 Tmp3 = LegalizeOp(ST->getValue());
1443 EVT StVT = ST->getMemoryVT();
1444 unsigned StWidth = StVT.getSizeInBits();
1446 if (StWidth != StVT.getStoreSizeInBits()) {
1447 // Promote to a byte-sized store with upper bits zero if not
1448 // storing an integral number of bytes. For example, promote
1449 // TRUNCSTORE:i1 X -> TRUNCSTORE:i8 (and X, 1)
1450 EVT NVT = EVT::getIntegerVT(*DAG.getContext(),
1451 StVT.getStoreSizeInBits());
1452 Tmp3 = DAG.getZeroExtendInReg(Tmp3, dl, StVT);
1453 Result = DAG.getTruncStore(Tmp1, dl, Tmp3, Tmp2, ST->getPointerInfo(),
1454 NVT, isVolatile, isNonTemporal, Alignment);
1455 } else if (StWidth & (StWidth - 1)) {
1456 // If not storing a power-of-2 number of bits, expand as two stores.
1457 assert(!StVT.isVector() && "Unsupported truncstore!");
1458 unsigned RoundWidth = 1 << Log2_32(StWidth);
1459 assert(RoundWidth < StWidth);
1460 unsigned ExtraWidth = StWidth - RoundWidth;
1461 assert(ExtraWidth < RoundWidth);
1462 assert(!(RoundWidth % 8) && !(ExtraWidth % 8) &&
1463 "Store size not an integral number of bytes!");
1464 EVT RoundVT = EVT::getIntegerVT(*DAG.getContext(), RoundWidth);
1465 EVT ExtraVT = EVT::getIntegerVT(*DAG.getContext(), ExtraWidth);
1467 unsigned IncrementSize;
1469 if (TLI.isLittleEndian()) {
1470 // TRUNCSTORE:i24 X -> TRUNCSTORE:i16 X, TRUNCSTORE@+2:i8 (srl X, 16)
1471 // Store the bottom RoundWidth bits.
1472 Lo = DAG.getTruncStore(Tmp1, dl, Tmp3, Tmp2, ST->getPointerInfo(),
1474 isVolatile, isNonTemporal, Alignment);
1476 // Store the remaining ExtraWidth bits.
1477 IncrementSize = RoundWidth / 8;
1478 Tmp2 = DAG.getNode(ISD::ADD, dl, Tmp2.getValueType(), Tmp2,
1479 DAG.getIntPtrConstant(IncrementSize));
1480 Hi = DAG.getNode(ISD::SRL, dl, Tmp3.getValueType(), Tmp3,
1481 DAG.getConstant(RoundWidth, TLI.getShiftAmountTy()));
1482 Hi = DAG.getTruncStore(Tmp1, dl, Hi, Tmp2,
1483 ST->getPointerInfo().getWithOffset(IncrementSize),
1484 ExtraVT, isVolatile, isNonTemporal,
1485 MinAlign(Alignment, IncrementSize));
1487 // Big endian - avoid unaligned stores.
1488 // TRUNCSTORE:i24 X -> TRUNCSTORE:i16 (srl X, 8), TRUNCSTORE@+2:i8 X
1489 // Store the top RoundWidth bits.
1490 Hi = DAG.getNode(ISD::SRL, dl, Tmp3.getValueType(), Tmp3,
1491 DAG.getConstant(ExtraWidth, TLI.getShiftAmountTy()));
1492 Hi = DAG.getTruncStore(Tmp1, dl, Hi, Tmp2, ST->getPointerInfo(),
1493 RoundVT, isVolatile, isNonTemporal, Alignment);
1495 // Store the remaining ExtraWidth bits.
1496 IncrementSize = RoundWidth / 8;
1497 Tmp2 = DAG.getNode(ISD::ADD, dl, Tmp2.getValueType(), Tmp2,
1498 DAG.getIntPtrConstant(IncrementSize));
1499 Lo = DAG.getTruncStore(Tmp1, dl, Tmp3, Tmp2,
1500 ST->getPointerInfo().getWithOffset(IncrementSize),
1501 ExtraVT, isVolatile, isNonTemporal,
1502 MinAlign(Alignment, IncrementSize));
1505 // The order of the stores doesn't matter.
1506 Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo, Hi);
1508 if (Tmp1 != ST->getChain() || Tmp3 != ST->getValue() ||
1509 Tmp2 != ST->getBasePtr())
1510 Result = SDValue(DAG.UpdateNodeOperands(Result.getNode(),
1515 switch (TLI.getTruncStoreAction(ST->getValue().getValueType(), StVT)) {
1516 default: assert(0 && "This action is not supported yet!");
1517 case TargetLowering::Legal:
1518 // If this is an unaligned store and the target doesn't support it,
1520 if (!TLI.allowsUnalignedMemoryAccesses(ST->getMemoryVT())) {
1521 const Type *Ty = ST->getMemoryVT().getTypeForEVT(*DAG.getContext());
1522 unsigned ABIAlignment= TLI.getTargetData()->getABITypeAlignment(Ty);
1523 if (ST->getAlignment() < ABIAlignment)
1524 Result = ExpandUnalignedStore(cast<StoreSDNode>(Result.getNode()),
1528 case TargetLowering::Custom:
1529 Result = TLI.LowerOperation(Result, DAG);
1532 // TRUNCSTORE:i16 i32 -> STORE i16
1533 assert(isTypeLegal(StVT) && "Do not know how to expand this store!");
1534 Tmp3 = DAG.getNode(ISD::TRUNCATE, dl, StVT, Tmp3);
1535 Result = DAG.getStore(Tmp1, dl, Tmp3, Tmp2, ST->getPointerInfo(),
1536 isVolatile, isNonTemporal, Alignment);
1544 assert(Result.getValueType() == Op.getValueType() &&
1545 "Bad legalization!");
1547 // Make sure that the generated code is itself legal.
1549 Result = LegalizeOp(Result);
1551 // Note that LegalizeOp may be reentered even from single-use nodes, which
1552 // means that we always must cache transformed nodes.
1553 AddLegalizedOperand(Op, Result);
1557 SDValue SelectionDAGLegalize::ExpandExtractFromVectorThroughStack(SDValue Op) {
1558 SDValue Vec = Op.getOperand(0);
1559 SDValue Idx = Op.getOperand(1);
1560 DebugLoc dl = Op.getDebugLoc();
1561 // Store the value to a temporary stack slot, then LOAD the returned part.
1562 SDValue StackPtr = DAG.CreateStackTemporary(Vec.getValueType());
1563 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, Vec, StackPtr,
1564 MachinePointerInfo(), false, false, 0);
1566 // Add the offset to the index.
1568 Vec.getValueType().getVectorElementType().getSizeInBits()/8;
1569 Idx = DAG.getNode(ISD::MUL, dl, Idx.getValueType(), Idx,
1570 DAG.getConstant(EltSize, Idx.getValueType()));
1572 if (Idx.getValueType().bitsGT(TLI.getPointerTy()))
1573 Idx = DAG.getNode(ISD::TRUNCATE, dl, TLI.getPointerTy(), Idx);
1575 Idx = DAG.getNode(ISD::ZERO_EXTEND, dl, TLI.getPointerTy(), Idx);
1577 StackPtr = DAG.getNode(ISD::ADD, dl, Idx.getValueType(), Idx, StackPtr);
1579 if (Op.getValueType().isVector())
1580 return DAG.getLoad(Op.getValueType(), dl, Ch, StackPtr,MachinePointerInfo(),
1582 return DAG.getExtLoad(ISD::EXTLOAD, Op.getValueType(), dl, Ch, StackPtr,
1583 MachinePointerInfo(),
1584 Vec.getValueType().getVectorElementType(),
1588 SDValue SelectionDAGLegalize::ExpandVectorBuildThroughStack(SDNode* Node) {
1589 // We can't handle this case efficiently. Allocate a sufficiently
1590 // aligned object on the stack, store each element into it, then load
1591 // the result as a vector.
1592 // Create the stack frame object.
1593 EVT VT = Node->getValueType(0);
1594 EVT EltVT = VT.getVectorElementType();
1595 DebugLoc dl = Node->getDebugLoc();
1596 SDValue FIPtr = DAG.CreateStackTemporary(VT);
1597 int FI = cast<FrameIndexSDNode>(FIPtr.getNode())->getIndex();
1598 MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(FI);
1600 // Emit a store of each element to the stack slot.
1601 SmallVector<SDValue, 8> Stores;
1602 unsigned TypeByteSize = EltVT.getSizeInBits() / 8;
1603 // Store (in the right endianness) the elements to memory.
1604 for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
1605 // Ignore undef elements.
1606 if (Node->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1608 unsigned Offset = TypeByteSize*i;
1610 SDValue Idx = DAG.getConstant(Offset, FIPtr.getValueType());
1611 Idx = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr, Idx);
1613 // If the destination vector element type is narrower than the source
1614 // element type, only store the bits necessary.
1615 if (EltVT.bitsLT(Node->getOperand(i).getValueType().getScalarType())) {
1616 Stores.push_back(DAG.getTruncStore(DAG.getEntryNode(), dl,
1617 Node->getOperand(i), Idx,
1618 PtrInfo.getWithOffset(Offset),
1619 EltVT, false, false, 0));
1621 Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl,
1622 Node->getOperand(i), Idx,
1623 PtrInfo.getWithOffset(Offset),
1628 if (!Stores.empty()) // Not all undef elements?
1629 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1630 &Stores[0], Stores.size());
1632 StoreChain = DAG.getEntryNode();
1634 // Result is a load from the stack slot.
1635 return DAG.getLoad(VT, dl, StoreChain, FIPtr, PtrInfo, false, false, 0);
1638 SDValue SelectionDAGLegalize::ExpandFCOPYSIGN(SDNode* Node) {
1639 DebugLoc dl = Node->getDebugLoc();
1640 SDValue Tmp1 = Node->getOperand(0);
1641 SDValue Tmp2 = Node->getOperand(1);
1643 // Get the sign bit of the RHS. First obtain a value that has the same
1644 // sign as the sign bit, i.e. negative if and only if the sign bit is 1.
1646 EVT FloatVT = Tmp2.getValueType();
1647 EVT IVT = EVT::getIntegerVT(*DAG.getContext(), FloatVT.getSizeInBits());
1648 if (isTypeLegal(IVT)) {
1649 // Convert to an integer with the same sign bit.
1650 SignBit = DAG.getNode(ISD::BITCAST, dl, IVT, Tmp2);
1652 // Store the float to memory, then load the sign part out as an integer.
1653 MVT LoadTy = TLI.getPointerTy();
1654 // First create a temporary that is aligned for both the load and store.
1655 SDValue StackPtr = DAG.CreateStackTemporary(FloatVT, LoadTy);
1656 // Then store the float to it.
1658 DAG.getStore(DAG.getEntryNode(), dl, Tmp2, StackPtr, MachinePointerInfo(),
1660 if (TLI.isBigEndian()) {
1661 assert(FloatVT.isByteSized() && "Unsupported floating point type!");
1662 // Load out a legal integer with the same sign bit as the float.
1663 SignBit = DAG.getLoad(LoadTy, dl, Ch, StackPtr, MachinePointerInfo(),
1665 } else { // Little endian
1666 SDValue LoadPtr = StackPtr;
1667 // The float may be wider than the integer we are going to load. Advance
1668 // the pointer so that the loaded integer will contain the sign bit.
1669 unsigned Strides = (FloatVT.getSizeInBits()-1)/LoadTy.getSizeInBits();
1670 unsigned ByteOffset = (Strides * LoadTy.getSizeInBits()) / 8;
1671 LoadPtr = DAG.getNode(ISD::ADD, dl, LoadPtr.getValueType(),
1672 LoadPtr, DAG.getIntPtrConstant(ByteOffset));
1673 // Load a legal integer containing the sign bit.
1674 SignBit = DAG.getLoad(LoadTy, dl, Ch, LoadPtr, MachinePointerInfo(),
1676 // Move the sign bit to the top bit of the loaded integer.
1677 unsigned BitShift = LoadTy.getSizeInBits() -
1678 (FloatVT.getSizeInBits() - 8 * ByteOffset);
1679 assert(BitShift < LoadTy.getSizeInBits() && "Pointer advanced wrong?");
1681 SignBit = DAG.getNode(ISD::SHL, dl, LoadTy, SignBit,
1682 DAG.getConstant(BitShift,TLI.getShiftAmountTy()));
1685 // Now get the sign bit proper, by seeing whether the value is negative.
1686 SignBit = DAG.getSetCC(dl, TLI.getSetCCResultType(SignBit.getValueType()),
1687 SignBit, DAG.getConstant(0, SignBit.getValueType()),
1689 // Get the absolute value of the result.
1690 SDValue AbsVal = DAG.getNode(ISD::FABS, dl, Tmp1.getValueType(), Tmp1);
1691 // Select between the nabs and abs value based on the sign bit of
1693 return DAG.getNode(ISD::SELECT, dl, AbsVal.getValueType(), SignBit,
1694 DAG.getNode(ISD::FNEG, dl, AbsVal.getValueType(), AbsVal),
1698 void SelectionDAGLegalize::ExpandDYNAMIC_STACKALLOC(SDNode* Node,
1699 SmallVectorImpl<SDValue> &Results) {
1700 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
1701 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
1702 " not tell us which reg is the stack pointer!");
1703 DebugLoc dl = Node->getDebugLoc();
1704 EVT VT = Node->getValueType(0);
1705 SDValue Tmp1 = SDValue(Node, 0);
1706 SDValue Tmp2 = SDValue(Node, 1);
1707 SDValue Tmp3 = Node->getOperand(2);
1708 SDValue Chain = Tmp1.getOperand(0);
1710 // Chain the dynamic stack allocation so that it doesn't modify the stack
1711 // pointer when other instructions are using the stack.
1712 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true));
1714 SDValue Size = Tmp2.getOperand(1);
1715 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
1716 Chain = SP.getValue(1);
1717 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
1718 unsigned StackAlign = TM.getFrameLowering()->getStackAlignment();
1719 if (Align > StackAlign)
1720 SP = DAG.getNode(ISD::AND, dl, VT, SP,
1721 DAG.getConstant(-(uint64_t)Align, VT));
1722 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
1723 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
1725 Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
1726 DAG.getIntPtrConstant(0, true), SDValue());
1728 Results.push_back(Tmp1);
1729 Results.push_back(Tmp2);
1732 /// LegalizeSetCCCondCode - Legalize a SETCC with given LHS and RHS and
1733 /// condition code CC on the current target. This routine expands SETCC with
1734 /// illegal condition code into AND / OR of multiple SETCC values.
1735 void SelectionDAGLegalize::LegalizeSetCCCondCode(EVT VT,
1736 SDValue &LHS, SDValue &RHS,
1739 EVT OpVT = LHS.getValueType();
1740 ISD::CondCode CCCode = cast<CondCodeSDNode>(CC)->get();
1741 switch (TLI.getCondCodeAction(CCCode, OpVT)) {
1742 default: assert(0 && "Unknown condition code action!");
1743 case TargetLowering::Legal:
1746 case TargetLowering::Expand: {
1747 ISD::CondCode CC1 = ISD::SETCC_INVALID, CC2 = ISD::SETCC_INVALID;
1750 default: assert(0 && "Don't know how to expand this condition!");
1751 case ISD::SETOEQ: CC1 = ISD::SETEQ; CC2 = ISD::SETO; Opc = ISD::AND; break;
1752 case ISD::SETOGT: CC1 = ISD::SETGT; CC2 = ISD::SETO; Opc = ISD::AND; break;
1753 case ISD::SETOGE: CC1 = ISD::SETGE; CC2 = ISD::SETO; Opc = ISD::AND; break;
1754 case ISD::SETOLT: CC1 = ISD::SETLT; CC2 = ISD::SETO; Opc = ISD::AND; break;
1755 case ISD::SETOLE: CC1 = ISD::SETLE; CC2 = ISD::SETO; Opc = ISD::AND; break;
1756 case ISD::SETONE: CC1 = ISD::SETNE; CC2 = ISD::SETO; Opc = ISD::AND; break;
1757 case ISD::SETUEQ: CC1 = ISD::SETEQ; CC2 = ISD::SETUO; Opc = ISD::OR; break;
1758 case ISD::SETUGT: CC1 = ISD::SETGT; CC2 = ISD::SETUO; Opc = ISD::OR; break;
1759 case ISD::SETUGE: CC1 = ISD::SETGE; CC2 = ISD::SETUO; Opc = ISD::OR; break;
1760 case ISD::SETULT: CC1 = ISD::SETLT; CC2 = ISD::SETUO; Opc = ISD::OR; break;
1761 case ISD::SETULE: CC1 = ISD::SETLE; CC2 = ISD::SETUO; Opc = ISD::OR; break;
1762 case ISD::SETUNE: CC1 = ISD::SETNE; CC2 = ISD::SETUO; Opc = ISD::OR; break;
1763 // FIXME: Implement more expansions.
1766 SDValue SetCC1 = DAG.getSetCC(dl, VT, LHS, RHS, CC1);
1767 SDValue SetCC2 = DAG.getSetCC(dl, VT, LHS, RHS, CC2);
1768 LHS = DAG.getNode(Opc, dl, VT, SetCC1, SetCC2);
1776 /// EmitStackConvert - Emit a store/load combination to the stack. This stores
1777 /// SrcOp to a stack slot of type SlotVT, truncating it if needed. It then does
1778 /// a load from the stack slot to DestVT, extending it if needed.
1779 /// The resultant code need not be legal.
1780 SDValue SelectionDAGLegalize::EmitStackConvert(SDValue SrcOp,
1784 // Create the stack frame object.
1786 TLI.getTargetData()->getPrefTypeAlignment(SrcOp.getValueType().
1787 getTypeForEVT(*DAG.getContext()));
1788 SDValue FIPtr = DAG.CreateStackTemporary(SlotVT, SrcAlign);
1790 FrameIndexSDNode *StackPtrFI = cast<FrameIndexSDNode>(FIPtr);
1791 int SPFI = StackPtrFI->getIndex();
1792 MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(SPFI);
1794 unsigned SrcSize = SrcOp.getValueType().getSizeInBits();
1795 unsigned SlotSize = SlotVT.getSizeInBits();
1796 unsigned DestSize = DestVT.getSizeInBits();
1797 const Type *DestType = DestVT.getTypeForEVT(*DAG.getContext());
1798 unsigned DestAlign = TLI.getTargetData()->getPrefTypeAlignment(DestType);
1800 // Emit a store to the stack slot. Use a truncstore if the input value is
1801 // later than DestVT.
1804 if (SrcSize > SlotSize)
1805 Store = DAG.getTruncStore(DAG.getEntryNode(), dl, SrcOp, FIPtr,
1806 PtrInfo, SlotVT, false, false, SrcAlign);
1808 assert(SrcSize == SlotSize && "Invalid store");
1809 Store = DAG.getStore(DAG.getEntryNode(), dl, SrcOp, FIPtr,
1810 PtrInfo, false, false, SrcAlign);
1813 // Result is a load from the stack slot.
1814 if (SlotSize == DestSize)
1815 return DAG.getLoad(DestVT, dl, Store, FIPtr, PtrInfo,
1816 false, false, DestAlign);
1818 assert(SlotSize < DestSize && "Unknown extension!");
1819 return DAG.getExtLoad(ISD::EXTLOAD, DestVT, dl, Store, FIPtr,
1820 PtrInfo, SlotVT, false, false, DestAlign);
1823 SDValue SelectionDAGLegalize::ExpandSCALAR_TO_VECTOR(SDNode *Node) {
1824 DebugLoc dl = Node->getDebugLoc();
1825 // Create a vector sized/aligned stack slot, store the value to element #0,
1826 // then load the whole vector back out.
1827 SDValue StackPtr = DAG.CreateStackTemporary(Node->getValueType(0));
1829 FrameIndexSDNode *StackPtrFI = cast<FrameIndexSDNode>(StackPtr);
1830 int SPFI = StackPtrFI->getIndex();
1832 SDValue Ch = DAG.getTruncStore(DAG.getEntryNode(), dl, Node->getOperand(0),
1834 MachinePointerInfo::getFixedStack(SPFI),
1835 Node->getValueType(0).getVectorElementType(),
1837 return DAG.getLoad(Node->getValueType(0), dl, Ch, StackPtr,
1838 MachinePointerInfo::getFixedStack(SPFI),
1843 /// ExpandBUILD_VECTOR - Expand a BUILD_VECTOR node on targets that don't
1844 /// support the operation, but do support the resultant vector type.
1845 SDValue SelectionDAGLegalize::ExpandBUILD_VECTOR(SDNode *Node) {
1846 unsigned NumElems = Node->getNumOperands();
1847 SDValue Value1, Value2;
1848 DebugLoc dl = Node->getDebugLoc();
1849 EVT VT = Node->getValueType(0);
1850 EVT OpVT = Node->getOperand(0).getValueType();
1851 EVT EltVT = VT.getVectorElementType();
1853 // If the only non-undef value is the low element, turn this into a
1854 // SCALAR_TO_VECTOR node. If this is { X, X, X, X }, determine X.
1855 bool isOnlyLowElement = true;
1856 bool MoreThanTwoValues = false;
1857 bool isConstant = true;
1858 for (unsigned i = 0; i < NumElems; ++i) {
1859 SDValue V = Node->getOperand(i);
1860 if (V.getOpcode() == ISD::UNDEF)
1863 isOnlyLowElement = false;
1864 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
1867 if (!Value1.getNode()) {
1869 } else if (!Value2.getNode()) {
1872 } else if (V != Value1 && V != Value2) {
1873 MoreThanTwoValues = true;
1877 if (!Value1.getNode())
1878 return DAG.getUNDEF(VT);
1880 if (isOnlyLowElement)
1881 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Node->getOperand(0));
1883 // If all elements are constants, create a load from the constant pool.
1885 std::vector<Constant*> CV;
1886 for (unsigned i = 0, e = NumElems; i != e; ++i) {
1887 if (ConstantFPSDNode *V =
1888 dyn_cast<ConstantFPSDNode>(Node->getOperand(i))) {
1889 CV.push_back(const_cast<ConstantFP *>(V->getConstantFPValue()));
1890 } else if (ConstantSDNode *V =
1891 dyn_cast<ConstantSDNode>(Node->getOperand(i))) {
1893 CV.push_back(const_cast<ConstantInt *>(V->getConstantIntValue()));
1895 // If OpVT and EltVT don't match, EltVT is not legal and the
1896 // element values have been promoted/truncated earlier. Undo this;
1897 // we don't want a v16i8 to become a v16i32 for example.
1898 const ConstantInt *CI = V->getConstantIntValue();
1899 CV.push_back(ConstantInt::get(EltVT.getTypeForEVT(*DAG.getContext()),
1900 CI->getZExtValue()));
1903 assert(Node->getOperand(i).getOpcode() == ISD::UNDEF);
1904 const Type *OpNTy = EltVT.getTypeForEVT(*DAG.getContext());
1905 CV.push_back(UndefValue::get(OpNTy));
1908 Constant *CP = ConstantVector::get(CV);
1909 SDValue CPIdx = DAG.getConstantPool(CP, TLI.getPointerTy());
1910 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
1911 return DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
1912 MachinePointerInfo::getConstantPool(),
1913 false, false, Alignment);
1916 if (!MoreThanTwoValues) {
1917 SmallVector<int, 8> ShuffleVec(NumElems, -1);
1918 for (unsigned i = 0; i < NumElems; ++i) {
1919 SDValue V = Node->getOperand(i);
1920 if (V.getOpcode() == ISD::UNDEF)
1922 ShuffleVec[i] = V == Value1 ? 0 : NumElems;
1924 if (TLI.isShuffleMaskLegal(ShuffleVec, Node->getValueType(0))) {
1925 // Get the splatted value into the low element of a vector register.
1926 SDValue Vec1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value1);
1928 if (Value2.getNode())
1929 Vec2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value2);
1931 Vec2 = DAG.getUNDEF(VT);
1933 // Return shuffle(LowValVec, undef, <0,0,0,0>)
1934 return DAG.getVectorShuffle(VT, dl, Vec1, Vec2, ShuffleVec.data());
1938 // Otherwise, we can't handle this case efficiently.
1939 return ExpandVectorBuildThroughStack(Node);
1942 // ExpandLibCall - Expand a node into a call to a libcall. If the result value
1943 // does not fit into a register, return the lo part and set the hi part to the
1944 // by-reg argument. If it does fit into a single register, return the result
1945 // and leave the Hi part unset.
1946 SDValue SelectionDAGLegalize::ExpandLibCall(RTLIB::Libcall LC, SDNode *Node,
1948 // The input chain to this libcall is the entry node of the function.
1949 // Legalizing the call will automatically add the previous call to the
1951 SDValue InChain = DAG.getEntryNode();
1953 TargetLowering::ArgListTy Args;
1954 TargetLowering::ArgListEntry Entry;
1955 for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
1956 EVT ArgVT = Node->getOperand(i).getValueType();
1957 const Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
1958 Entry.Node = Node->getOperand(i); Entry.Ty = ArgTy;
1959 Entry.isSExt = isSigned;
1960 Entry.isZExt = !isSigned;
1961 Args.push_back(Entry);
1963 SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC),
1964 TLI.getPointerTy());
1966 // Splice the libcall in wherever FindInputOutputChains tells us to.
1967 const Type *RetTy = Node->getValueType(0).getTypeForEVT(*DAG.getContext());
1969 // isTailCall may be true since the callee does not reference caller stack
1970 // frame. Check if it's in the right position.
1971 bool isTailCall = isInTailCallPosition(DAG, Node, TLI);
1972 std::pair<SDValue, SDValue> CallInfo =
1973 TLI.LowerCallTo(InChain, RetTy, isSigned, !isSigned, false, false,
1974 0, TLI.getLibcallCallingConv(LC), isTailCall,
1975 /*isReturnValueUsed=*/true,
1976 Callee, Args, DAG, Node->getDebugLoc());
1978 if (!CallInfo.second.getNode())
1979 // It's a tailcall, return the chain (which is the DAG root).
1980 return DAG.getRoot();
1982 // Legalize the call sequence, starting with the chain. This will advance
1983 // the LastCALLSEQ_END to the legalized version of the CALLSEQ_END node that
1984 // was added by LowerCallTo (guaranteeing proper serialization of calls).
1985 LegalizeOp(CallInfo.second);
1986 return CallInfo.first;
1989 // ExpandChainLibCall - Expand a node into a call to a libcall. Similar to
1990 // ExpandLibCall except that the first operand is the in-chain.
1991 std::pair<SDValue, SDValue>
1992 SelectionDAGLegalize::ExpandChainLibCall(RTLIB::Libcall LC,
1995 SDValue InChain = Node->getOperand(0);
1997 TargetLowering::ArgListTy Args;
1998 TargetLowering::ArgListEntry Entry;
1999 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i) {
2000 EVT ArgVT = Node->getOperand(i).getValueType();
2001 const Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2002 Entry.Node = Node->getOperand(i);
2004 Entry.isSExt = isSigned;
2005 Entry.isZExt = !isSigned;
2006 Args.push_back(Entry);
2008 SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC),
2009 TLI.getPointerTy());
2011 // Splice the libcall in wherever FindInputOutputChains tells us to.
2012 const Type *RetTy = Node->getValueType(0).getTypeForEVT(*DAG.getContext());
2013 std::pair<SDValue, SDValue> CallInfo =
2014 TLI.LowerCallTo(InChain, RetTy, isSigned, !isSigned, false, false,
2015 0, TLI.getLibcallCallingConv(LC), /*isTailCall=*/false,
2016 /*isReturnValueUsed=*/true,
2017 Callee, Args, DAG, Node->getDebugLoc());
2019 // Legalize the call sequence, starting with the chain. This will advance
2020 // the LastCALLSEQ_END to the legalized version of the CALLSEQ_END node that
2021 // was added by LowerCallTo (guaranteeing proper serialization of calls).
2022 LegalizeOp(CallInfo.second);
2026 SDValue SelectionDAGLegalize::ExpandFPLibCall(SDNode* Node,
2027 RTLIB::Libcall Call_F32,
2028 RTLIB::Libcall Call_F64,
2029 RTLIB::Libcall Call_F80,
2030 RTLIB::Libcall Call_PPCF128) {
2032 switch (Node->getValueType(0).getSimpleVT().SimpleTy) {
2033 default: assert(0 && "Unexpected request for libcall!");
2034 case MVT::f32: LC = Call_F32; break;
2035 case MVT::f64: LC = Call_F64; break;
2036 case MVT::f80: LC = Call_F80; break;
2037 case MVT::ppcf128: LC = Call_PPCF128; break;
2039 return ExpandLibCall(LC, Node, false);
2042 SDValue SelectionDAGLegalize::ExpandIntLibCall(SDNode* Node, bool isSigned,
2043 RTLIB::Libcall Call_I8,
2044 RTLIB::Libcall Call_I16,
2045 RTLIB::Libcall Call_I32,
2046 RTLIB::Libcall Call_I64,
2047 RTLIB::Libcall Call_I128) {
2049 switch (Node->getValueType(0).getSimpleVT().SimpleTy) {
2050 default: assert(0 && "Unexpected request for libcall!");
2051 case MVT::i8: LC = Call_I8; break;
2052 case MVT::i16: LC = Call_I16; break;
2053 case MVT::i32: LC = Call_I32; break;
2054 case MVT::i64: LC = Call_I64; break;
2055 case MVT::i128: LC = Call_I128; break;
2057 return ExpandLibCall(LC, Node, isSigned);
2060 /// ExpandLegalINT_TO_FP - This function is responsible for legalizing a
2061 /// INT_TO_FP operation of the specified operand when the target requests that
2062 /// we expand it. At this point, we know that the result and operand types are
2063 /// legal for the target.
2064 SDValue SelectionDAGLegalize::ExpandLegalINT_TO_FP(bool isSigned,
2068 if (Op0.getValueType() == MVT::i32) {
2069 // simple 32-bit [signed|unsigned] integer to float/double expansion
2071 // Get the stack frame index of a 8 byte buffer.
2072 SDValue StackSlot = DAG.CreateStackTemporary(MVT::f64);
2074 // word offset constant for Hi/Lo address computation
2075 SDValue WordOff = DAG.getConstant(sizeof(int), TLI.getPointerTy());
2076 // set up Hi and Lo (into buffer) address based on endian
2077 SDValue Hi = StackSlot;
2078 SDValue Lo = DAG.getNode(ISD::ADD, dl,
2079 TLI.getPointerTy(), StackSlot, WordOff);
2080 if (TLI.isLittleEndian())
2083 // if signed map to unsigned space
2086 // constant used to invert sign bit (signed to unsigned mapping)
2087 SDValue SignBit = DAG.getConstant(0x80000000u, MVT::i32);
2088 Op0Mapped = DAG.getNode(ISD::XOR, dl, MVT::i32, Op0, SignBit);
2092 // store the lo of the constructed double - based on integer input
2093 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl,
2094 Op0Mapped, Lo, MachinePointerInfo(),
2096 // initial hi portion of constructed double
2097 SDValue InitialHi = DAG.getConstant(0x43300000u, MVT::i32);
2098 // store the hi of the constructed double - biased exponent
2099 SDValue Store2 = DAG.getStore(Store1, dl, InitialHi, Hi,
2100 MachinePointerInfo(),
2102 // load the constructed double
2103 SDValue Load = DAG.getLoad(MVT::f64, dl, Store2, StackSlot,
2104 MachinePointerInfo(), false, false, 0);
2105 // FP constant to bias correct the final result
2106 SDValue Bias = DAG.getConstantFP(isSigned ?
2107 BitsToDouble(0x4330000080000000ULL) :
2108 BitsToDouble(0x4330000000000000ULL),
2110 // subtract the bias
2111 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Load, Bias);
2114 // handle final rounding
2115 if (DestVT == MVT::f64) {
2118 } else if (DestVT.bitsLT(MVT::f64)) {
2119 Result = DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
2120 DAG.getIntPtrConstant(0));
2121 } else if (DestVT.bitsGT(MVT::f64)) {
2122 Result = DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
2126 assert(!isSigned && "Legalize cannot Expand SINT_TO_FP for i64 yet");
2127 // Code below here assumes !isSigned without checking again.
2129 // Implementation of unsigned i64 to f64 following the algorithm in
2130 // __floatundidf in compiler_rt. This implementation has the advantage
2131 // of performing rounding correctly, both in the default rounding mode
2132 // and in all alternate rounding modes.
2133 // TODO: Generalize this for use with other types.
2134 if (Op0.getValueType() == MVT::i64 && DestVT == MVT::f64) {
2136 DAG.getConstant(UINT64_C(0x4330000000000000), MVT::i64);
2137 SDValue TwoP84PlusTwoP52 =
2138 DAG.getConstantFP(BitsToDouble(UINT64_C(0x4530000000100000)), MVT::f64);
2140 DAG.getConstant(UINT64_C(0x4530000000000000), MVT::i64);
2142 SDValue Lo = DAG.getZeroExtendInReg(Op0, dl, MVT::i32);
2143 SDValue Hi = DAG.getNode(ISD::SRL, dl, MVT::i64, Op0,
2144 DAG.getConstant(32, MVT::i64));
2145 SDValue LoOr = DAG.getNode(ISD::OR, dl, MVT::i64, Lo, TwoP52);
2146 SDValue HiOr = DAG.getNode(ISD::OR, dl, MVT::i64, Hi, TwoP84);
2147 SDValue LoFlt = DAG.getNode(ISD::BITCAST, dl, MVT::f64, LoOr);
2148 SDValue HiFlt = DAG.getNode(ISD::BITCAST, dl, MVT::f64, HiOr);
2149 SDValue HiSub = DAG.getNode(ISD::FSUB, dl, MVT::f64, HiFlt,
2151 return DAG.getNode(ISD::FADD, dl, MVT::f64, LoFlt, HiSub);
2154 // Implementation of unsigned i64 to f32.
2155 // TODO: Generalize this for use with other types.
2156 if (Op0.getValueType() == MVT::i64 && DestVT == MVT::f32) {
2157 // For unsigned conversions, convert them to signed conversions using the
2158 // algorithm from the x86_64 __floatundidf in compiler_rt.
2160 SDValue Fast = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, Op0);
2162 SDValue ShiftConst = DAG.getConstant(1, TLI.getShiftAmountTy());
2163 SDValue Shr = DAG.getNode(ISD::SRL, dl, MVT::i64, Op0, ShiftConst);
2164 SDValue AndConst = DAG.getConstant(1, MVT::i64);
2165 SDValue And = DAG.getNode(ISD::AND, dl, MVT::i64, Op0, AndConst);
2166 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::i64, And, Shr);
2168 SDValue SignCvt = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, Or);
2169 SDValue Slow = DAG.getNode(ISD::FADD, dl, MVT::f32, SignCvt, SignCvt);
2171 // TODO: This really should be implemented using a branch rather than a
2172 // select. We happen to get lucky and machinesink does the right
2173 // thing most of the time. This would be a good candidate for a
2174 //pseudo-op, or, even better, for whole-function isel.
2175 SDValue SignBitTest = DAG.getSetCC(dl, TLI.getSetCCResultType(MVT::i64),
2176 Op0, DAG.getConstant(0, MVT::i64), ISD::SETLT);
2177 return DAG.getNode(ISD::SELECT, dl, MVT::f32, SignBitTest, Slow, Fast);
2180 // Otherwise, implement the fully general conversion.
2181 EVT SHVT = TLI.getShiftAmountTy();
2183 SDValue And = DAG.getNode(ISD::AND, dl, MVT::i64, Op0,
2184 DAG.getConstant(UINT64_C(0xfffffffffffff800), MVT::i64));
2185 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::i64, And,
2186 DAG.getConstant(UINT64_C(0x800), MVT::i64));
2187 SDValue And2 = DAG.getNode(ISD::AND, dl, MVT::i64, Op0,
2188 DAG.getConstant(UINT64_C(0x7ff), MVT::i64));
2189 SDValue Ne = DAG.getSetCC(dl, TLI.getSetCCResultType(MVT::i64),
2190 And2, DAG.getConstant(UINT64_C(0), MVT::i64), ISD::SETNE);
2191 SDValue Sel = DAG.getNode(ISD::SELECT, dl, MVT::i64, Ne, Or, Op0);
2192 SDValue Ge = DAG.getSetCC(dl, TLI.getSetCCResultType(MVT::i64),
2193 Op0, DAG.getConstant(UINT64_C(0x0020000000000000), MVT::i64),
2195 SDValue Sel2 = DAG.getNode(ISD::SELECT, dl, MVT::i64, Ge, Sel, Op0);
2197 SDValue Sh = DAG.getNode(ISD::SRL, dl, MVT::i64, Sel2,
2198 DAG.getConstant(32, SHVT));
2199 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Sh);
2200 SDValue Fcvt = DAG.getNode(ISD::UINT_TO_FP, dl, MVT::f64, Trunc);
2202 DAG.getConstantFP(BitsToDouble(UINT64_C(0x41f0000000000000)), MVT::f64);
2203 SDValue Fmul = DAG.getNode(ISD::FMUL, dl, MVT::f64, TwoP32, Fcvt);
2204 SDValue Lo = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Sel2);
2205 SDValue Fcvt2 = DAG.getNode(ISD::UINT_TO_FP, dl, MVT::f64, Lo);
2206 SDValue Fadd = DAG.getNode(ISD::FADD, dl, MVT::f64, Fmul, Fcvt2);
2207 return DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, Fadd,
2208 DAG.getIntPtrConstant(0));
2211 SDValue Tmp1 = DAG.getNode(ISD::SINT_TO_FP, dl, DestVT, Op0);
2213 SDValue SignSet = DAG.getSetCC(dl, TLI.getSetCCResultType(Op0.getValueType()),
2214 Op0, DAG.getConstant(0, Op0.getValueType()),
2216 SDValue Zero = DAG.getIntPtrConstant(0), Four = DAG.getIntPtrConstant(4);
2217 SDValue CstOffset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(),
2218 SignSet, Four, Zero);
2220 // If the sign bit of the integer is set, the large number will be treated
2221 // as a negative number. To counteract this, the dynamic code adds an
2222 // offset depending on the data type.
2224 switch (Op0.getValueType().getSimpleVT().SimpleTy) {
2225 default: assert(0 && "Unsupported integer type!");
2226 case MVT::i8 : FF = 0x43800000ULL; break; // 2^8 (as a float)
2227 case MVT::i16: FF = 0x47800000ULL; break; // 2^16 (as a float)
2228 case MVT::i32: FF = 0x4F800000ULL; break; // 2^32 (as a float)
2229 case MVT::i64: FF = 0x5F800000ULL; break; // 2^64 (as a float)
2231 if (TLI.isLittleEndian()) FF <<= 32;
2232 Constant *FudgeFactor = ConstantInt::get(
2233 Type::getInt64Ty(*DAG.getContext()), FF);
2235 SDValue CPIdx = DAG.getConstantPool(FudgeFactor, TLI.getPointerTy());
2236 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
2237 CPIdx = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(), CPIdx, CstOffset);
2238 Alignment = std::min(Alignment, 4u);
2240 if (DestVT == MVT::f32)
2241 FudgeInReg = DAG.getLoad(MVT::f32, dl, DAG.getEntryNode(), CPIdx,
2242 MachinePointerInfo::getConstantPool(),
2243 false, false, Alignment);
2246 LegalizeOp(DAG.getExtLoad(ISD::EXTLOAD, DestVT, dl,
2247 DAG.getEntryNode(), CPIdx,
2248 MachinePointerInfo::getConstantPool(),
2249 MVT::f32, false, false, Alignment));
2252 return DAG.getNode(ISD::FADD, dl, DestVT, Tmp1, FudgeInReg);
2255 /// PromoteLegalINT_TO_FP - This function is responsible for legalizing a
2256 /// *INT_TO_FP operation of the specified operand when the target requests that
2257 /// we promote it. At this point, we know that the result and operand types are
2258 /// legal for the target, and that there is a legal UINT_TO_FP or SINT_TO_FP
2259 /// operation that takes a larger input.
2260 SDValue SelectionDAGLegalize::PromoteLegalINT_TO_FP(SDValue LegalOp,
2264 // First step, figure out the appropriate *INT_TO_FP operation to use.
2265 EVT NewInTy = LegalOp.getValueType();
2267 unsigned OpToUse = 0;
2269 // Scan for the appropriate larger type to use.
2271 NewInTy = (MVT::SimpleValueType)(NewInTy.getSimpleVT().SimpleTy+1);
2272 assert(NewInTy.isInteger() && "Ran out of possibilities!");
2274 // If the target supports SINT_TO_FP of this type, use it.
2275 if (TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, NewInTy)) {
2276 OpToUse = ISD::SINT_TO_FP;
2279 if (isSigned) continue;
2281 // If the target supports UINT_TO_FP of this type, use it.
2282 if (TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, NewInTy)) {
2283 OpToUse = ISD::UINT_TO_FP;
2287 // Otherwise, try a larger type.
2290 // Okay, we found the operation and type to use. Zero extend our input to the
2291 // desired type then run the operation on it.
2292 return DAG.getNode(OpToUse, dl, DestVT,
2293 DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
2294 dl, NewInTy, LegalOp));
2297 /// PromoteLegalFP_TO_INT - This function is responsible for legalizing a
2298 /// FP_TO_*INT operation of the specified operand when the target requests that
2299 /// we promote it. At this point, we know that the result and operand types are
2300 /// legal for the target, and that there is a legal FP_TO_UINT or FP_TO_SINT
2301 /// operation that returns a larger result.
2302 SDValue SelectionDAGLegalize::PromoteLegalFP_TO_INT(SDValue LegalOp,
2306 // First step, figure out the appropriate FP_TO*INT operation to use.
2307 EVT NewOutTy = DestVT;
2309 unsigned OpToUse = 0;
2311 // Scan for the appropriate larger type to use.
2313 NewOutTy = (MVT::SimpleValueType)(NewOutTy.getSimpleVT().SimpleTy+1);
2314 assert(NewOutTy.isInteger() && "Ran out of possibilities!");
2316 if (TLI.isOperationLegalOrCustom(ISD::FP_TO_SINT, NewOutTy)) {
2317 OpToUse = ISD::FP_TO_SINT;
2321 if (TLI.isOperationLegalOrCustom(ISD::FP_TO_UINT, NewOutTy)) {
2322 OpToUse = ISD::FP_TO_UINT;
2326 // Otherwise, try a larger type.
2330 // Okay, we found the operation and type to use.
2331 SDValue Operation = DAG.getNode(OpToUse, dl, NewOutTy, LegalOp);
2333 // Truncate the result of the extended FP_TO_*INT operation to the desired
2335 return DAG.getNode(ISD::TRUNCATE, dl, DestVT, Operation);
2338 /// ExpandBSWAP - Open code the operations for BSWAP of the specified operation.
2340 SDValue SelectionDAGLegalize::ExpandBSWAP(SDValue Op, DebugLoc dl) {
2341 EVT VT = Op.getValueType();
2342 EVT SHVT = TLI.getShiftAmountTy();
2343 SDValue Tmp1, Tmp2, Tmp3, Tmp4, Tmp5, Tmp6, Tmp7, Tmp8;
2344 switch (VT.getSimpleVT().SimpleTy) {
2345 default: assert(0 && "Unhandled Expand type in BSWAP!");
2347 Tmp2 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, SHVT));
2348 Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, SHVT));
2349 return DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
2351 Tmp4 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, SHVT));
2352 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, SHVT));
2353 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, SHVT));
2354 Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, SHVT));
2355 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3, DAG.getConstant(0xFF0000, VT));
2356 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(0xFF00, VT));
2357 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3);
2358 Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1);
2359 return DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2);
2361 Tmp8 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(56, SHVT));
2362 Tmp7 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(40, SHVT));
2363 Tmp6 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, SHVT));
2364 Tmp5 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, SHVT));
2365 Tmp4 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, SHVT));
2366 Tmp3 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, SHVT));
2367 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(40, SHVT));
2368 Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(56, SHVT));
2369 Tmp7 = DAG.getNode(ISD::AND, dl, VT, Tmp7, DAG.getConstant(255ULL<<48, VT));
2370 Tmp6 = DAG.getNode(ISD::AND, dl, VT, Tmp6, DAG.getConstant(255ULL<<40, VT));
2371 Tmp5 = DAG.getNode(ISD::AND, dl, VT, Tmp5, DAG.getConstant(255ULL<<32, VT));
2372 Tmp4 = DAG.getNode(ISD::AND, dl, VT, Tmp4, DAG.getConstant(255ULL<<24, VT));
2373 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3, DAG.getConstant(255ULL<<16, VT));
2374 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(255ULL<<8 , VT));
2375 Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp7);
2376 Tmp6 = DAG.getNode(ISD::OR, dl, VT, Tmp6, Tmp5);
2377 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3);
2378 Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1);
2379 Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp6);
2380 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2);
2381 return DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp4);
2385 /// SplatByte - Distribute ByteVal over NumBits bits.
2386 // FIXME: Move this helper to a common place.
2387 static APInt SplatByte(unsigned NumBits, uint8_t ByteVal) {
2388 APInt Val = APInt(NumBits, ByteVal);
2390 for (unsigned i = NumBits; i > 8; i >>= 1) {
2391 Val = (Val << Shift) | Val;
2397 /// ExpandBitCount - Expand the specified bitcount instruction into operations.
2399 SDValue SelectionDAGLegalize::ExpandBitCount(unsigned Opc, SDValue Op,
2402 default: assert(0 && "Cannot expand this yet!");
2404 EVT VT = Op.getValueType();
2405 EVT ShVT = TLI.getShiftAmountTy();
2406 unsigned Len = VT.getSizeInBits();
2408 assert(VT.isInteger() && Len <= 128 && Len % 8 == 0 &&
2409 "CTPOP not implemented for this type.");
2411 // This is the "best" algorithm from
2412 // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
2414 SDValue Mask55 = DAG.getConstant(SplatByte(Len, 0x55), VT);
2415 SDValue Mask33 = DAG.getConstant(SplatByte(Len, 0x33), VT);
2416 SDValue Mask0F = DAG.getConstant(SplatByte(Len, 0x0F), VT);
2417 SDValue Mask01 = DAG.getConstant(SplatByte(Len, 0x01), VT);
2419 // v = v - ((v >> 1) & 0x55555555...)
2420 Op = DAG.getNode(ISD::SUB, dl, VT, Op,
2421 DAG.getNode(ISD::AND, dl, VT,
2422 DAG.getNode(ISD::SRL, dl, VT, Op,
2423 DAG.getConstant(1, ShVT)),
2425 // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
2426 Op = DAG.getNode(ISD::ADD, dl, VT,
2427 DAG.getNode(ISD::AND, dl, VT, Op, Mask33),
2428 DAG.getNode(ISD::AND, dl, VT,
2429 DAG.getNode(ISD::SRL, dl, VT, Op,
2430 DAG.getConstant(2, ShVT)),
2432 // v = (v + (v >> 4)) & 0x0F0F0F0F...
2433 Op = DAG.getNode(ISD::AND, dl, VT,
2434 DAG.getNode(ISD::ADD, dl, VT, Op,
2435 DAG.getNode(ISD::SRL, dl, VT, Op,
2436 DAG.getConstant(4, ShVT))),
2438 // v = (v * 0x01010101...) >> (Len - 8)
2439 Op = DAG.getNode(ISD::SRL, dl, VT,
2440 DAG.getNode(ISD::MUL, dl, VT, Op, Mask01),
2441 DAG.getConstant(Len - 8, ShVT));
2446 // for now, we do this:
2447 // x = x | (x >> 1);
2448 // x = x | (x >> 2);
2450 // x = x | (x >>16);
2451 // x = x | (x >>32); // for 64-bit input
2452 // return popcount(~x);
2454 // but see also: http://www.hackersdelight.org/HDcode/nlz.cc
2455 EVT VT = Op.getValueType();
2456 EVT ShVT = TLI.getShiftAmountTy();
2457 unsigned len = VT.getSizeInBits();
2458 for (unsigned i = 0; (1U << i) <= (len / 2); ++i) {
2459 SDValue Tmp3 = DAG.getConstant(1ULL << i, ShVT);
2460 Op = DAG.getNode(ISD::OR, dl, VT, Op,
2461 DAG.getNode(ISD::SRL, dl, VT, Op, Tmp3));
2463 Op = DAG.getNOT(dl, Op, VT);
2464 return DAG.getNode(ISD::CTPOP, dl, VT, Op);
2467 // for now, we use: { return popcount(~x & (x - 1)); }
2468 // unless the target has ctlz but not ctpop, in which case we use:
2469 // { return 32 - nlz(~x & (x-1)); }
2470 // see also http://www.hackersdelight.org/HDcode/ntz.cc
2471 EVT VT = Op.getValueType();
2472 SDValue Tmp3 = DAG.getNode(ISD::AND, dl, VT,
2473 DAG.getNOT(dl, Op, VT),
2474 DAG.getNode(ISD::SUB, dl, VT, Op,
2475 DAG.getConstant(1, VT)));
2476 // If ISD::CTLZ is legal and CTPOP isn't, then do that instead.
2477 if (!TLI.isOperationLegalOrCustom(ISD::CTPOP, VT) &&
2478 TLI.isOperationLegalOrCustom(ISD::CTLZ, VT))
2479 return DAG.getNode(ISD::SUB, dl, VT,
2480 DAG.getConstant(VT.getSizeInBits(), VT),
2481 DAG.getNode(ISD::CTLZ, dl, VT, Tmp3));
2482 return DAG.getNode(ISD::CTPOP, dl, VT, Tmp3);
2487 std::pair <SDValue, SDValue> SelectionDAGLegalize::ExpandAtomic(SDNode *Node) {
2488 unsigned Opc = Node->getOpcode();
2489 MVT VT = cast<AtomicSDNode>(Node)->getMemoryVT().getSimpleVT();
2494 llvm_unreachable("Unhandled atomic intrinsic Expand!");
2496 case ISD::ATOMIC_SWAP:
2497 switch (VT.SimpleTy) {
2498 default: llvm_unreachable("Unexpected value type for atomic!");
2499 case MVT::i8: LC = RTLIB::SYNC_LOCK_TEST_AND_SET_1; break;
2500 case MVT::i16: LC = RTLIB::SYNC_LOCK_TEST_AND_SET_2; break;
2501 case MVT::i32: LC = RTLIB::SYNC_LOCK_TEST_AND_SET_4; break;
2502 case MVT::i64: LC = RTLIB::SYNC_LOCK_TEST_AND_SET_8; break;
2505 case ISD::ATOMIC_CMP_SWAP:
2506 switch (VT.SimpleTy) {
2507 default: llvm_unreachable("Unexpected value type for atomic!");
2508 case MVT::i8: LC = RTLIB::SYNC_VAL_COMPARE_AND_SWAP_1; break;
2509 case MVT::i16: LC = RTLIB::SYNC_VAL_COMPARE_AND_SWAP_2; break;
2510 case MVT::i32: LC = RTLIB::SYNC_VAL_COMPARE_AND_SWAP_4; break;
2511 case MVT::i64: LC = RTLIB::SYNC_VAL_COMPARE_AND_SWAP_8; break;
2514 case ISD::ATOMIC_LOAD_ADD:
2515 switch (VT.SimpleTy) {
2516 default: llvm_unreachable("Unexpected value type for atomic!");
2517 case MVT::i8: LC = RTLIB::SYNC_FETCH_AND_ADD_1; break;
2518 case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_ADD_2; break;
2519 case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_ADD_4; break;
2520 case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_ADD_8; break;
2523 case ISD::ATOMIC_LOAD_SUB:
2524 switch (VT.SimpleTy) {
2525 default: llvm_unreachable("Unexpected value type for atomic!");
2526 case MVT::i8: LC = RTLIB::SYNC_FETCH_AND_SUB_1; break;
2527 case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_SUB_2; break;
2528 case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_SUB_4; break;
2529 case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_SUB_8; break;
2532 case ISD::ATOMIC_LOAD_AND:
2533 switch (VT.SimpleTy) {
2534 default: llvm_unreachable("Unexpected value type for atomic!");
2535 case MVT::i8: LC = RTLIB::SYNC_FETCH_AND_AND_1; break;
2536 case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_AND_2; break;
2537 case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_AND_4; break;
2538 case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_AND_8; break;
2541 case ISD::ATOMIC_LOAD_OR:
2542 switch (VT.SimpleTy) {
2543 default: llvm_unreachable("Unexpected value type for atomic!");
2544 case MVT::i8: LC = RTLIB::SYNC_FETCH_AND_OR_1; break;
2545 case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_OR_2; break;
2546 case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_OR_4; break;
2547 case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_OR_8; break;
2550 case ISD::ATOMIC_LOAD_XOR:
2551 switch (VT.SimpleTy) {
2552 default: llvm_unreachable("Unexpected value type for atomic!");
2553 case MVT::i8: LC = RTLIB::SYNC_FETCH_AND_XOR_1; break;
2554 case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_XOR_2; break;
2555 case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_XOR_4; break;
2556 case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_XOR_8; break;
2559 case ISD::ATOMIC_LOAD_NAND:
2560 switch (VT.SimpleTy) {
2561 default: llvm_unreachable("Unexpected value type for atomic!");
2562 case MVT::i8: LC = RTLIB::SYNC_FETCH_AND_NAND_1; break;
2563 case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_NAND_2; break;
2564 case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_NAND_4; break;
2565 case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_NAND_8; break;
2570 return ExpandChainLibCall(LC, Node, false);
2573 void SelectionDAGLegalize::ExpandNode(SDNode *Node,
2574 SmallVectorImpl<SDValue> &Results) {
2575 DebugLoc dl = Node->getDebugLoc();
2576 SDValue Tmp1, Tmp2, Tmp3, Tmp4;
2577 switch (Node->getOpcode()) {
2581 Tmp1 = ExpandBitCount(Node->getOpcode(), Node->getOperand(0), dl);
2582 Results.push_back(Tmp1);
2585 Results.push_back(ExpandBSWAP(Node->getOperand(0), dl));
2587 case ISD::FRAMEADDR:
2588 case ISD::RETURNADDR:
2589 case ISD::FRAME_TO_ARGS_OFFSET:
2590 Results.push_back(DAG.getConstant(0, Node->getValueType(0)));
2592 case ISD::FLT_ROUNDS_:
2593 Results.push_back(DAG.getConstant(1, Node->getValueType(0)));
2595 case ISD::EH_RETURN:
2599 case ISD::EH_SJLJ_LONGJMP:
2600 case ISD::EH_SJLJ_DISPATCHSETUP:
2601 // If the target didn't expand these, there's nothing to do, so just
2602 // preserve the chain and be done.
2603 Results.push_back(Node->getOperand(0));
2605 case ISD::EH_SJLJ_SETJMP:
2606 // If the target didn't expand this, just return 'zero' and preserve the
2608 Results.push_back(DAG.getConstant(0, MVT::i32));
2609 Results.push_back(Node->getOperand(0));
2611 case ISD::MEMBARRIER: {
2612 // If the target didn't lower this, lower it to '__sync_synchronize()' call
2613 TargetLowering::ArgListTy Args;
2614 std::pair<SDValue, SDValue> CallResult =
2615 TLI.LowerCallTo(Node->getOperand(0), Type::getVoidTy(*DAG.getContext()),
2616 false, false, false, false, 0, CallingConv::C,
2617 /*isTailCall=*/false,
2618 /*isReturnValueUsed=*/true,
2619 DAG.getExternalSymbol("__sync_synchronize",
2620 TLI.getPointerTy()),
2622 Results.push_back(CallResult.second);
2625 // By default, atomic intrinsics are marked Legal and lowered. Targets
2626 // which don't support them directly, however, may want libcalls, in which
2627 // case they mark them Expand, and we get here.
2628 case ISD::ATOMIC_SWAP:
2629 case ISD::ATOMIC_LOAD_ADD:
2630 case ISD::ATOMIC_LOAD_SUB:
2631 case ISD::ATOMIC_LOAD_AND:
2632 case ISD::ATOMIC_LOAD_OR:
2633 case ISD::ATOMIC_LOAD_XOR:
2634 case ISD::ATOMIC_LOAD_NAND:
2635 case ISD::ATOMIC_LOAD_MIN:
2636 case ISD::ATOMIC_LOAD_MAX:
2637 case ISD::ATOMIC_LOAD_UMIN:
2638 case ISD::ATOMIC_LOAD_UMAX:
2639 case ISD::ATOMIC_CMP_SWAP: {
2640 std::pair<SDValue, SDValue> Tmp = ExpandAtomic(Node);
2641 Results.push_back(Tmp.first);
2642 Results.push_back(Tmp.second);
2645 case ISD::DYNAMIC_STACKALLOC:
2646 ExpandDYNAMIC_STACKALLOC(Node, Results);
2648 case ISD::MERGE_VALUES:
2649 for (unsigned i = 0; i < Node->getNumValues(); i++)
2650 Results.push_back(Node->getOperand(i));
2653 EVT VT = Node->getValueType(0);
2655 Results.push_back(DAG.getConstant(0, VT));
2657 assert(VT.isFloatingPoint() && "Unknown value type!");
2658 Results.push_back(DAG.getConstantFP(0, VT));
2663 // If this operation is not supported, lower it to 'abort()' call
2664 TargetLowering::ArgListTy Args;
2665 std::pair<SDValue, SDValue> CallResult =
2666 TLI.LowerCallTo(Node->getOperand(0), Type::getVoidTy(*DAG.getContext()),
2667 false, false, false, false, 0, CallingConv::C,
2668 /*isTailCall=*/false,
2669 /*isReturnValueUsed=*/true,
2670 DAG.getExternalSymbol("abort", TLI.getPointerTy()),
2672 Results.push_back(CallResult.second);
2677 Tmp1 = EmitStackConvert(Node->getOperand(0), Node->getValueType(0),
2678 Node->getValueType(0), dl);
2679 Results.push_back(Tmp1);
2681 case ISD::FP_EXTEND:
2682 Tmp1 = EmitStackConvert(Node->getOperand(0),
2683 Node->getOperand(0).getValueType(),
2684 Node->getValueType(0), dl);
2685 Results.push_back(Tmp1);
2687 case ISD::SIGN_EXTEND_INREG: {
2688 // NOTE: we could fall back on load/store here too for targets without
2689 // SAR. However, it is doubtful that any exist.
2690 EVT ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
2691 EVT VT = Node->getValueType(0);
2692 EVT ShiftAmountTy = TLI.getShiftAmountTy();
2695 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
2696 ExtraVT.getScalarType().getSizeInBits();
2697 SDValue ShiftCst = DAG.getConstant(BitsDiff, ShiftAmountTy);
2698 Tmp1 = DAG.getNode(ISD::SHL, dl, Node->getValueType(0),
2699 Node->getOperand(0), ShiftCst);
2700 Tmp1 = DAG.getNode(ISD::SRA, dl, Node->getValueType(0), Tmp1, ShiftCst);
2701 Results.push_back(Tmp1);
2704 case ISD::FP_ROUND_INREG: {
2705 // The only way we can lower this is to turn it into a TRUNCSTORE,
2706 // EXTLOAD pair, targetting a temporary location (a stack slot).
2708 // NOTE: there is a choice here between constantly creating new stack
2709 // slots and always reusing the same one. We currently always create
2710 // new ones, as reuse may inhibit scheduling.
2711 EVT ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
2712 Tmp1 = EmitStackConvert(Node->getOperand(0), ExtraVT,
2713 Node->getValueType(0), dl);
2714 Results.push_back(Tmp1);
2717 case ISD::SINT_TO_FP:
2718 case ISD::UINT_TO_FP:
2719 Tmp1 = ExpandLegalINT_TO_FP(Node->getOpcode() == ISD::SINT_TO_FP,
2720 Node->getOperand(0), Node->getValueType(0), dl);
2721 Results.push_back(Tmp1);
2723 case ISD::FP_TO_UINT: {
2724 SDValue True, False;
2725 EVT VT = Node->getOperand(0).getValueType();
2726 EVT NVT = Node->getValueType(0);
2727 APFloat apf(APInt::getNullValue(VT.getSizeInBits()));
2728 APInt x = APInt::getSignBit(NVT.getSizeInBits());
2729 (void)apf.convertFromAPInt(x, false, APFloat::rmNearestTiesToEven);
2730 Tmp1 = DAG.getConstantFP(apf, VT);
2731 Tmp2 = DAG.getSetCC(dl, TLI.getSetCCResultType(VT),
2732 Node->getOperand(0),
2734 True = DAG.getNode(ISD::FP_TO_SINT, dl, NVT, Node->getOperand(0));
2735 False = DAG.getNode(ISD::FP_TO_SINT, dl, NVT,
2736 DAG.getNode(ISD::FSUB, dl, VT,
2737 Node->getOperand(0), Tmp1));
2738 False = DAG.getNode(ISD::XOR, dl, NVT, False,
2739 DAG.getConstant(x, NVT));
2740 Tmp1 = DAG.getNode(ISD::SELECT, dl, NVT, Tmp2, True, False);
2741 Results.push_back(Tmp1);
2745 const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2746 EVT VT = Node->getValueType(0);
2747 Tmp1 = Node->getOperand(0);
2748 Tmp2 = Node->getOperand(1);
2749 unsigned Align = Node->getConstantOperandVal(3);
2751 SDValue VAListLoad = DAG.getLoad(TLI.getPointerTy(), dl, Tmp1, Tmp2,
2752 MachinePointerInfo(V), false, false, 0);
2753 SDValue VAList = VAListLoad;
2755 if (Align > TLI.getMinStackArgumentAlignment()) {
2756 assert(((Align & (Align-1)) == 0) && "Expected Align to be a power of 2");
2758 VAList = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(), VAList,
2759 DAG.getConstant(Align - 1,
2760 TLI.getPointerTy()));
2762 VAList = DAG.getNode(ISD::AND, dl, TLI.getPointerTy(), VAList,
2763 DAG.getConstant(-(int64_t)Align,
2764 TLI.getPointerTy()));
2767 // Increment the pointer, VAList, to the next vaarg
2768 Tmp3 = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(), VAList,
2769 DAG.getConstant(TLI.getTargetData()->
2770 getTypeAllocSize(VT.getTypeForEVT(*DAG.getContext())),
2771 TLI.getPointerTy()));
2772 // Store the incremented VAList to the legalized pointer
2773 Tmp3 = DAG.getStore(VAListLoad.getValue(1), dl, Tmp3, Tmp2,
2774 MachinePointerInfo(V), false, false, 0);
2775 // Load the actual argument out of the pointer VAList
2776 Results.push_back(DAG.getLoad(VT, dl, Tmp3, VAList, MachinePointerInfo(),
2778 Results.push_back(Results[0].getValue(1));
2782 // This defaults to loading a pointer from the input and storing it to the
2783 // output, returning the chain.
2784 const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue();
2785 const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue();
2786 Tmp1 = DAG.getLoad(TLI.getPointerTy(), dl, Node->getOperand(0),
2787 Node->getOperand(2), MachinePointerInfo(VS),
2789 Tmp1 = DAG.getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1),
2790 MachinePointerInfo(VD), false, false, 0);
2791 Results.push_back(Tmp1);
2794 case ISD::EXTRACT_VECTOR_ELT:
2795 if (Node->getOperand(0).getValueType().getVectorNumElements() == 1)
2796 // This must be an access of the only element. Return it.
2797 Tmp1 = DAG.getNode(ISD::BITCAST, dl, Node->getValueType(0),
2798 Node->getOperand(0));
2800 Tmp1 = ExpandExtractFromVectorThroughStack(SDValue(Node, 0));
2801 Results.push_back(Tmp1);
2803 case ISD::EXTRACT_SUBVECTOR:
2804 Results.push_back(ExpandExtractFromVectorThroughStack(SDValue(Node, 0)));
2806 case ISD::CONCAT_VECTORS: {
2807 Results.push_back(ExpandVectorBuildThroughStack(Node));
2810 case ISD::SCALAR_TO_VECTOR:
2811 Results.push_back(ExpandSCALAR_TO_VECTOR(Node));
2813 case ISD::INSERT_VECTOR_ELT:
2814 Results.push_back(ExpandINSERT_VECTOR_ELT(Node->getOperand(0),
2815 Node->getOperand(1),
2816 Node->getOperand(2), dl));
2818 case ISD::VECTOR_SHUFFLE: {
2819 SmallVector<int, 8> Mask;
2820 cast<ShuffleVectorSDNode>(Node)->getMask(Mask);
2822 EVT VT = Node->getValueType(0);
2823 EVT EltVT = VT.getVectorElementType();
2824 if (getTypeAction(EltVT) == Promote)
2825 EltVT = TLI.getTypeToTransformTo(*DAG.getContext(), EltVT);
2826 unsigned NumElems = VT.getVectorNumElements();
2827 SmallVector<SDValue, 8> Ops;
2828 for (unsigned i = 0; i != NumElems; ++i) {
2830 Ops.push_back(DAG.getUNDEF(EltVT));
2833 unsigned Idx = Mask[i];
2835 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
2836 Node->getOperand(0),
2837 DAG.getIntPtrConstant(Idx)));
2839 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
2840 Node->getOperand(1),
2841 DAG.getIntPtrConstant(Idx - NumElems)));
2843 Tmp1 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Ops[0], Ops.size());
2844 Results.push_back(Tmp1);
2847 case ISD::EXTRACT_ELEMENT: {
2848 EVT OpTy = Node->getOperand(0).getValueType();
2849 if (cast<ConstantSDNode>(Node->getOperand(1))->getZExtValue()) {
2851 Tmp1 = DAG.getNode(ISD::SRL, dl, OpTy, Node->getOperand(0),
2852 DAG.getConstant(OpTy.getSizeInBits()/2,
2853 TLI.getShiftAmountTy()));
2854 Tmp1 = DAG.getNode(ISD::TRUNCATE, dl, Node->getValueType(0), Tmp1);
2857 Tmp1 = DAG.getNode(ISD::TRUNCATE, dl, Node->getValueType(0),
2858 Node->getOperand(0));
2860 Results.push_back(Tmp1);
2863 case ISD::STACKSAVE:
2864 // Expand to CopyFromReg if the target set
2865 // StackPointerRegisterToSaveRestore.
2866 if (unsigned SP = TLI.getStackPointerRegisterToSaveRestore()) {
2867 Results.push_back(DAG.getCopyFromReg(Node->getOperand(0), dl, SP,
2868 Node->getValueType(0)));
2869 Results.push_back(Results[0].getValue(1));
2871 Results.push_back(DAG.getUNDEF(Node->getValueType(0)));
2872 Results.push_back(Node->getOperand(0));
2875 case ISD::STACKRESTORE:
2876 // Expand to CopyToReg if the target set
2877 // StackPointerRegisterToSaveRestore.
2878 if (unsigned SP = TLI.getStackPointerRegisterToSaveRestore()) {
2879 Results.push_back(DAG.getCopyToReg(Node->getOperand(0), dl, SP,
2880 Node->getOperand(1)));
2882 Results.push_back(Node->getOperand(0));
2885 case ISD::FCOPYSIGN:
2886 Results.push_back(ExpandFCOPYSIGN(Node));
2889 // Expand Y = FNEG(X) -> Y = SUB -0.0, X
2890 Tmp1 = DAG.getConstantFP(-0.0, Node->getValueType(0));
2891 Tmp1 = DAG.getNode(ISD::FSUB, dl, Node->getValueType(0), Tmp1,
2892 Node->getOperand(0));
2893 Results.push_back(Tmp1);
2896 // Expand Y = FABS(X) -> Y = (X >u 0.0) ? X : fneg(X).
2897 EVT VT = Node->getValueType(0);
2898 Tmp1 = Node->getOperand(0);
2899 Tmp2 = DAG.getConstantFP(0.0, VT);
2900 Tmp2 = DAG.getSetCC(dl, TLI.getSetCCResultType(Tmp1.getValueType()),
2901 Tmp1, Tmp2, ISD::SETUGT);
2902 Tmp3 = DAG.getNode(ISD::FNEG, dl, VT, Tmp1);
2903 Tmp1 = DAG.getNode(ISD::SELECT, dl, VT, Tmp2, Tmp1, Tmp3);
2904 Results.push_back(Tmp1);
2908 Results.push_back(ExpandFPLibCall(Node, RTLIB::SQRT_F32, RTLIB::SQRT_F64,
2909 RTLIB::SQRT_F80, RTLIB::SQRT_PPCF128));
2912 Results.push_back(ExpandFPLibCall(Node, RTLIB::SIN_F32, RTLIB::SIN_F64,
2913 RTLIB::SIN_F80, RTLIB::SIN_PPCF128));
2916 Results.push_back(ExpandFPLibCall(Node, RTLIB::COS_F32, RTLIB::COS_F64,
2917 RTLIB::COS_F80, RTLIB::COS_PPCF128));
2920 Results.push_back(ExpandFPLibCall(Node, RTLIB::LOG_F32, RTLIB::LOG_F64,
2921 RTLIB::LOG_F80, RTLIB::LOG_PPCF128));
2924 Results.push_back(ExpandFPLibCall(Node, RTLIB::LOG2_F32, RTLIB::LOG2_F64,
2925 RTLIB::LOG2_F80, RTLIB::LOG2_PPCF128));
2928 Results.push_back(ExpandFPLibCall(Node, RTLIB::LOG10_F32, RTLIB::LOG10_F64,
2929 RTLIB::LOG10_F80, RTLIB::LOG10_PPCF128));
2932 Results.push_back(ExpandFPLibCall(Node, RTLIB::EXP_F32, RTLIB::EXP_F64,
2933 RTLIB::EXP_F80, RTLIB::EXP_PPCF128));
2936 Results.push_back(ExpandFPLibCall(Node, RTLIB::EXP2_F32, RTLIB::EXP2_F64,
2937 RTLIB::EXP2_F80, RTLIB::EXP2_PPCF128));
2940 Results.push_back(ExpandFPLibCall(Node, RTLIB::TRUNC_F32, RTLIB::TRUNC_F64,
2941 RTLIB::TRUNC_F80, RTLIB::TRUNC_PPCF128));
2944 Results.push_back(ExpandFPLibCall(Node, RTLIB::FLOOR_F32, RTLIB::FLOOR_F64,
2945 RTLIB::FLOOR_F80, RTLIB::FLOOR_PPCF128));
2948 Results.push_back(ExpandFPLibCall(Node, RTLIB::CEIL_F32, RTLIB::CEIL_F64,
2949 RTLIB::CEIL_F80, RTLIB::CEIL_PPCF128));
2952 Results.push_back(ExpandFPLibCall(Node, RTLIB::RINT_F32, RTLIB::RINT_F64,
2953 RTLIB::RINT_F80, RTLIB::RINT_PPCF128));
2955 case ISD::FNEARBYINT:
2956 Results.push_back(ExpandFPLibCall(Node, RTLIB::NEARBYINT_F32,
2957 RTLIB::NEARBYINT_F64,
2958 RTLIB::NEARBYINT_F80,
2959 RTLIB::NEARBYINT_PPCF128));
2962 Results.push_back(ExpandFPLibCall(Node, RTLIB::POWI_F32, RTLIB::POWI_F64,
2963 RTLIB::POWI_F80, RTLIB::POWI_PPCF128));
2966 Results.push_back(ExpandFPLibCall(Node, RTLIB::POW_F32, RTLIB::POW_F64,
2967 RTLIB::POW_F80, RTLIB::POW_PPCF128));
2970 Results.push_back(ExpandFPLibCall(Node, RTLIB::DIV_F32, RTLIB::DIV_F64,
2971 RTLIB::DIV_F80, RTLIB::DIV_PPCF128));
2974 Results.push_back(ExpandFPLibCall(Node, RTLIB::REM_F32, RTLIB::REM_F64,
2975 RTLIB::REM_F80, RTLIB::REM_PPCF128));
2977 case ISD::FP16_TO_FP32:
2978 Results.push_back(ExpandLibCall(RTLIB::FPEXT_F16_F32, Node, false));
2980 case ISD::FP32_TO_FP16:
2981 Results.push_back(ExpandLibCall(RTLIB::FPROUND_F32_F16, Node, false));
2983 case ISD::ConstantFP: {
2984 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Node);
2985 // Check to see if this FP immediate is already legal.
2986 // If this is a legal constant, turn it into a TargetConstantFP node.
2987 if (TLI.isFPImmLegal(CFP->getValueAPF(), Node->getValueType(0)))
2988 Results.push_back(SDValue(Node, 0));
2990 Results.push_back(ExpandConstantFP(CFP, true, DAG, TLI));
2993 case ISD::EHSELECTION: {
2994 unsigned Reg = TLI.getExceptionSelectorRegister();
2995 assert(Reg && "Can't expand to unknown register!");
2996 Results.push_back(DAG.getCopyFromReg(Node->getOperand(1), dl, Reg,
2997 Node->getValueType(0)));
2998 Results.push_back(Results[0].getValue(1));
3001 case ISD::EXCEPTIONADDR: {
3002 unsigned Reg = TLI.getExceptionAddressRegister();
3003 assert(Reg && "Can't expand to unknown register!");
3004 Results.push_back(DAG.getCopyFromReg(Node->getOperand(0), dl, Reg,
3005 Node->getValueType(0)));
3006 Results.push_back(Results[0].getValue(1));
3010 EVT VT = Node->getValueType(0);
3011 assert(TLI.isOperationLegalOrCustom(ISD::ADD, VT) &&
3012 TLI.isOperationLegalOrCustom(ISD::XOR, VT) &&
3013 "Don't know how to expand this subtraction!");
3014 Tmp1 = DAG.getNode(ISD::XOR, dl, VT, Node->getOperand(1),
3015 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT));
3016 Tmp1 = DAG.getNode(ISD::ADD, dl, VT, Tmp2, DAG.getConstant(1, VT));
3017 Results.push_back(DAG.getNode(ISD::ADD, dl, VT, Node->getOperand(0), Tmp1));
3022 EVT VT = Node->getValueType(0);
3023 SDVTList VTs = DAG.getVTList(VT, VT);
3024 bool isSigned = Node->getOpcode() == ISD::SREM;
3025 unsigned DivOpc = isSigned ? ISD::SDIV : ISD::UDIV;
3026 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
3027 Tmp2 = Node->getOperand(0);
3028 Tmp3 = Node->getOperand(1);
3029 if (TLI.isOperationLegalOrCustom(DivRemOpc, VT)) {
3030 Tmp1 = DAG.getNode(DivRemOpc, dl, VTs, Tmp2, Tmp3).getValue(1);
3031 } else if (TLI.isOperationLegalOrCustom(DivOpc, VT)) {
3033 Tmp1 = DAG.getNode(DivOpc, dl, VT, Tmp2, Tmp3);
3034 Tmp1 = DAG.getNode(ISD::MUL, dl, VT, Tmp1, Tmp3);
3035 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, Tmp2, Tmp1);
3036 } else if (isSigned) {
3037 Tmp1 = ExpandIntLibCall(Node, true,
3039 RTLIB::SREM_I16, RTLIB::SREM_I32,
3040 RTLIB::SREM_I64, RTLIB::SREM_I128);
3042 Tmp1 = ExpandIntLibCall(Node, false,
3044 RTLIB::UREM_I16, RTLIB::UREM_I32,
3045 RTLIB::UREM_I64, RTLIB::UREM_I128);
3047 Results.push_back(Tmp1);
3052 bool isSigned = Node->getOpcode() == ISD::SDIV;
3053 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
3054 EVT VT = Node->getValueType(0);
3055 SDVTList VTs = DAG.getVTList(VT, VT);
3056 if (TLI.isOperationLegalOrCustom(DivRemOpc, VT))
3057 Tmp1 = DAG.getNode(DivRemOpc, dl, VTs, Node->getOperand(0),
3058 Node->getOperand(1));
3060 Tmp1 = ExpandIntLibCall(Node, true,
3062 RTLIB::SDIV_I16, RTLIB::SDIV_I32,
3063 RTLIB::SDIV_I64, RTLIB::SDIV_I128);
3065 Tmp1 = ExpandIntLibCall(Node, false,
3067 RTLIB::UDIV_I16, RTLIB::UDIV_I32,
3068 RTLIB::UDIV_I64, RTLIB::UDIV_I128);
3069 Results.push_back(Tmp1);
3074 unsigned ExpandOpcode = Node->getOpcode() == ISD::MULHU ? ISD::UMUL_LOHI :
3076 EVT VT = Node->getValueType(0);
3077 SDVTList VTs = DAG.getVTList(VT, VT);
3078 assert(TLI.isOperationLegalOrCustom(ExpandOpcode, VT) &&
3079 "If this wasn't legal, it shouldn't have been created!");
3080 Tmp1 = DAG.getNode(ExpandOpcode, dl, VTs, Node->getOperand(0),
3081 Node->getOperand(1));
3082 Results.push_back(Tmp1.getValue(1));
3086 EVT VT = Node->getValueType(0);
3087 SDVTList VTs = DAG.getVTList(VT, VT);
3088 // See if multiply or divide can be lowered using two-result operations.
3089 // We just need the low half of the multiply; try both the signed
3090 // and unsigned forms. If the target supports both SMUL_LOHI and
3091 // UMUL_LOHI, form a preference by checking which forms of plain
3092 // MULH it supports.
3093 bool HasSMUL_LOHI = TLI.isOperationLegalOrCustom(ISD::SMUL_LOHI, VT);
3094 bool HasUMUL_LOHI = TLI.isOperationLegalOrCustom(ISD::UMUL_LOHI, VT);
3095 bool HasMULHS = TLI.isOperationLegalOrCustom(ISD::MULHS, VT);
3096 bool HasMULHU = TLI.isOperationLegalOrCustom(ISD::MULHU, VT);
3097 unsigned OpToUse = 0;
3098 if (HasSMUL_LOHI && !HasMULHS) {
3099 OpToUse = ISD::SMUL_LOHI;
3100 } else if (HasUMUL_LOHI && !HasMULHU) {
3101 OpToUse = ISD::UMUL_LOHI;
3102 } else if (HasSMUL_LOHI) {
3103 OpToUse = ISD::SMUL_LOHI;
3104 } else if (HasUMUL_LOHI) {
3105 OpToUse = ISD::UMUL_LOHI;
3108 Results.push_back(DAG.getNode(OpToUse, dl, VTs, Node->getOperand(0),
3109 Node->getOperand(1)));
3112 Tmp1 = ExpandIntLibCall(Node, false,
3114 RTLIB::MUL_I16, RTLIB::MUL_I32,
3115 RTLIB::MUL_I64, RTLIB::MUL_I128);
3116 Results.push_back(Tmp1);
3121 SDValue LHS = Node->getOperand(0);
3122 SDValue RHS = Node->getOperand(1);
3123 SDValue Sum = DAG.getNode(Node->getOpcode() == ISD::SADDO ?
3124 ISD::ADD : ISD::SUB, dl, LHS.getValueType(),
3126 Results.push_back(Sum);
3127 EVT OType = Node->getValueType(1);
3129 SDValue Zero = DAG.getConstant(0, LHS.getValueType());
3131 // LHSSign -> LHS >= 0
3132 // RHSSign -> RHS >= 0
3133 // SumSign -> Sum >= 0
3136 // Overflow -> (LHSSign == RHSSign) && (LHSSign != SumSign)
3138 // Overflow -> (LHSSign != RHSSign) && (LHSSign != SumSign)
3140 SDValue LHSSign = DAG.getSetCC(dl, OType, LHS, Zero, ISD::SETGE);
3141 SDValue RHSSign = DAG.getSetCC(dl, OType, RHS, Zero, ISD::SETGE);
3142 SDValue SignsMatch = DAG.getSetCC(dl, OType, LHSSign, RHSSign,
3143 Node->getOpcode() == ISD::SADDO ?
3144 ISD::SETEQ : ISD::SETNE);
3146 SDValue SumSign = DAG.getSetCC(dl, OType, Sum, Zero, ISD::SETGE);
3147 SDValue SumSignNE = DAG.getSetCC(dl, OType, LHSSign, SumSign, ISD::SETNE);
3149 SDValue Cmp = DAG.getNode(ISD::AND, dl, OType, SignsMatch, SumSignNE);
3150 Results.push_back(Cmp);
3155 SDValue LHS = Node->getOperand(0);
3156 SDValue RHS = Node->getOperand(1);
3157 SDValue Sum = DAG.getNode(Node->getOpcode() == ISD::UADDO ?
3158 ISD::ADD : ISD::SUB, dl, LHS.getValueType(),
3160 Results.push_back(Sum);
3161 Results.push_back(DAG.getSetCC(dl, Node->getValueType(1), Sum, LHS,
3162 Node->getOpcode () == ISD::UADDO ?
3163 ISD::SETULT : ISD::SETUGT));
3168 EVT VT = Node->getValueType(0);
3169 SDValue LHS = Node->getOperand(0);
3170 SDValue RHS = Node->getOperand(1);
3173 static const unsigned Ops[2][3] =
3174 { { ISD::MULHU, ISD::UMUL_LOHI, ISD::ZERO_EXTEND },
3175 { ISD::MULHS, ISD::SMUL_LOHI, ISD::SIGN_EXTEND }};
3176 bool isSigned = Node->getOpcode() == ISD::SMULO;
3177 if (TLI.isOperationLegalOrCustom(Ops[isSigned][0], VT)) {
3178 BottomHalf = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS);
3179 TopHalf = DAG.getNode(Ops[isSigned][0], dl, VT, LHS, RHS);
3180 } else if (TLI.isOperationLegalOrCustom(Ops[isSigned][1], VT)) {
3181 BottomHalf = DAG.getNode(Ops[isSigned][1], dl, DAG.getVTList(VT, VT), LHS,
3183 TopHalf = BottomHalf.getValue(1);
3184 } else if (TLI.isTypeLegal(EVT::getIntegerVT(*DAG.getContext(),
3185 VT.getSizeInBits() * 2))) {
3186 EVT WideVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits() * 2);
3187 LHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, LHS);
3188 RHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, RHS);
3189 Tmp1 = DAG.getNode(ISD::MUL, dl, WideVT, LHS, RHS);
3190 BottomHalf = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VT, Tmp1,
3191 DAG.getIntPtrConstant(0));
3192 TopHalf = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VT, Tmp1,
3193 DAG.getIntPtrConstant(1));
3195 // We can fall back to a libcall with an illegal type for the MUL if we
3196 // have a libcall big enough.
3197 // Also, we can fall back to a division in some cases, but that's a big
3198 // performance hit in the general case.
3199 EVT WideVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits() * 2);
3200 RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
3201 if (WideVT == MVT::i16)
3202 LC = RTLIB::MUL_I16;
3203 else if (WideVT == MVT::i32)
3204 LC = RTLIB::MUL_I32;
3205 else if (WideVT == MVT::i64)
3206 LC = RTLIB::MUL_I64;
3207 else if (WideVT == MVT::i128)
3208 LC = RTLIB::MUL_I128;
3209 assert(LC != RTLIB::UNKNOWN_LIBCALL && "Cannot expand this operation!");
3210 LHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, LHS);
3211 RHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, RHS);
3213 SDValue Ops[2] = { LHS, RHS };
3214 SDValue Ret = ExpandLibCall(LC, Node, Ops);
3215 BottomHalf = DAG.getNode(ISD::TRUNCATE, dl, VT, Ret);
3216 TopHalf = DAG.getNode(ISD::SRL, dl, Ret.getValueType(), Ret,
3217 DAG.getConstant(VT.getSizeInBits(), TLI.getPointerTy()));
3218 TopHalf = DAG.getNode(ISD::TRUNCATE, dl, VT, TopHalf);
3221 Tmp1 = DAG.getConstant(VT.getSizeInBits() - 1, TLI.getShiftAmountTy());
3222 Tmp1 = DAG.getNode(ISD::SRA, dl, VT, BottomHalf, Tmp1);
3223 TopHalf = DAG.getSetCC(dl, TLI.getSetCCResultType(VT), TopHalf, Tmp1,
3226 TopHalf = DAG.getSetCC(dl, TLI.getSetCCResultType(VT), TopHalf,
3227 DAG.getConstant(0, VT), ISD::SETNE);
3229 Results.push_back(BottomHalf);
3230 Results.push_back(TopHalf);
3233 case ISD::BUILD_PAIR: {
3234 EVT PairTy = Node->getValueType(0);
3235 Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, PairTy, Node->getOperand(0));
3236 Tmp2 = DAG.getNode(ISD::ANY_EXTEND, dl, PairTy, Node->getOperand(1));
3237 Tmp2 = DAG.getNode(ISD::SHL, dl, PairTy, Tmp2,
3238 DAG.getConstant(PairTy.getSizeInBits()/2,
3239 TLI.getShiftAmountTy()));
3240 Results.push_back(DAG.getNode(ISD::OR, dl, PairTy, Tmp1, Tmp2));
3244 Tmp1 = Node->getOperand(0);
3245 Tmp2 = Node->getOperand(1);
3246 Tmp3 = Node->getOperand(2);
3247 if (Tmp1.getOpcode() == ISD::SETCC) {
3248 Tmp1 = DAG.getSelectCC(dl, Tmp1.getOperand(0), Tmp1.getOperand(1),
3250 cast<CondCodeSDNode>(Tmp1.getOperand(2))->get());
3252 Tmp1 = DAG.getSelectCC(dl, Tmp1,
3253 DAG.getConstant(0, Tmp1.getValueType()),
3254 Tmp2, Tmp3, ISD::SETNE);
3256 Results.push_back(Tmp1);
3259 SDValue Chain = Node->getOperand(0);
3260 SDValue Table = Node->getOperand(1);
3261 SDValue Index = Node->getOperand(2);
3263 EVT PTy = TLI.getPointerTy();
3265 const TargetData &TD = *TLI.getTargetData();
3266 unsigned EntrySize =
3267 DAG.getMachineFunction().getJumpTableInfo()->getEntrySize(TD);
3269 Index = DAG.getNode(ISD::MUL, dl, PTy,
3270 Index, DAG.getConstant(EntrySize, PTy));
3271 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3273 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), EntrySize * 8);
3274 SDValue LD = DAG.getExtLoad(ISD::SEXTLOAD, PTy, dl, Chain, Addr,
3275 MachinePointerInfo::getJumpTable(), MemVT,
3278 if (TM.getRelocationModel() == Reloc::PIC_) {
3279 // For PIC, the sequence is:
3280 // BRIND(load(Jumptable + index) + RelocBase)
3281 // RelocBase can be JumpTable, GOT or some sort of global base.
3282 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr,
3283 TLI.getPICJumpTableRelocBase(Table, DAG));
3285 Tmp1 = DAG.getNode(ISD::BRIND, dl, MVT::Other, LD.getValue(1), Addr);
3286 Results.push_back(Tmp1);
3290 // Expand brcond's setcc into its constituent parts and create a BR_CC
3292 Tmp1 = Node->getOperand(0);
3293 Tmp2 = Node->getOperand(1);
3294 if (Tmp2.getOpcode() == ISD::SETCC) {
3295 Tmp1 = DAG.getNode(ISD::BR_CC, dl, MVT::Other,
3296 Tmp1, Tmp2.getOperand(2),
3297 Tmp2.getOperand(0), Tmp2.getOperand(1),
3298 Node->getOperand(2));
3300 Tmp1 = DAG.getNode(ISD::BR_CC, dl, MVT::Other, Tmp1,
3301 DAG.getCondCode(ISD::SETNE), Tmp2,
3302 DAG.getConstant(0, Tmp2.getValueType()),
3303 Node->getOperand(2));
3305 Results.push_back(Tmp1);
3308 Tmp1 = Node->getOperand(0);
3309 Tmp2 = Node->getOperand(1);
3310 Tmp3 = Node->getOperand(2);
3311 LegalizeSetCCCondCode(Node->getValueType(0), Tmp1, Tmp2, Tmp3, dl);
3313 // If we expanded the SETCC into an AND/OR, return the new node
3314 if (Tmp2.getNode() == 0) {
3315 Results.push_back(Tmp1);
3319 // Otherwise, SETCC for the given comparison type must be completely
3320 // illegal; expand it into a SELECT_CC.
3321 EVT VT = Node->getValueType(0);
3322 Tmp1 = DAG.getNode(ISD::SELECT_CC, dl, VT, Tmp1, Tmp2,
3323 DAG.getConstant(1, VT), DAG.getConstant(0, VT), Tmp3);
3324 Results.push_back(Tmp1);
3327 case ISD::SELECT_CC: {
3328 Tmp1 = Node->getOperand(0); // LHS
3329 Tmp2 = Node->getOperand(1); // RHS
3330 Tmp3 = Node->getOperand(2); // True
3331 Tmp4 = Node->getOperand(3); // False
3332 SDValue CC = Node->getOperand(4);
3334 LegalizeSetCCCondCode(TLI.getSetCCResultType(Tmp1.getValueType()),
3335 Tmp1, Tmp2, CC, dl);
3337 assert(!Tmp2.getNode() && "Can't legalize SELECT_CC with legal condition!");
3338 Tmp2 = DAG.getConstant(0, Tmp1.getValueType());
3339 CC = DAG.getCondCode(ISD::SETNE);
3340 Tmp1 = DAG.getNode(ISD::SELECT_CC, dl, Node->getValueType(0), Tmp1, Tmp2,
3342 Results.push_back(Tmp1);
3346 Tmp1 = Node->getOperand(0); // Chain
3347 Tmp2 = Node->getOperand(2); // LHS
3348 Tmp3 = Node->getOperand(3); // RHS
3349 Tmp4 = Node->getOperand(1); // CC
3351 LegalizeSetCCCondCode(TLI.getSetCCResultType(Tmp2.getValueType()),
3352 Tmp2, Tmp3, Tmp4, dl);
3353 LastCALLSEQ_END = DAG.getEntryNode();
3355 assert(!Tmp3.getNode() && "Can't legalize BR_CC with legal condition!");
3356 Tmp3 = DAG.getConstant(0, Tmp2.getValueType());
3357 Tmp4 = DAG.getCondCode(ISD::SETNE);
3358 Tmp1 = DAG.getNode(ISD::BR_CC, dl, Node->getValueType(0), Tmp1, Tmp4, Tmp2,
3359 Tmp3, Node->getOperand(4));
3360 Results.push_back(Tmp1);
3363 case ISD::GLOBAL_OFFSET_TABLE:
3364 case ISD::GlobalAddress:
3365 case ISD::GlobalTLSAddress:
3366 case ISD::ExternalSymbol:
3367 case ISD::ConstantPool:
3368 case ISD::JumpTable:
3369 case ISD::INTRINSIC_W_CHAIN:
3370 case ISD::INTRINSIC_WO_CHAIN:
3371 case ISD::INTRINSIC_VOID:
3372 // FIXME: Custom lowering for these operations shouldn't return null!
3373 for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
3374 Results.push_back(SDValue(Node, i));
3378 void SelectionDAGLegalize::PromoteNode(SDNode *Node,
3379 SmallVectorImpl<SDValue> &Results) {
3380 EVT OVT = Node->getValueType(0);
3381 if (Node->getOpcode() == ISD::UINT_TO_FP ||
3382 Node->getOpcode() == ISD::SINT_TO_FP ||
3383 Node->getOpcode() == ISD::SETCC) {
3384 OVT = Node->getOperand(0).getValueType();
3386 EVT NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), OVT);
3387 DebugLoc dl = Node->getDebugLoc();
3388 SDValue Tmp1, Tmp2, Tmp3;
3389 switch (Node->getOpcode()) {
3393 // Zero extend the argument.
3394 Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, Node->getOperand(0));
3395 // Perform the larger operation.
3396 Tmp1 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1);
3397 if (Node->getOpcode() == ISD::CTTZ) {
3398 //if Tmp1 == sizeinbits(NVT) then Tmp1 = sizeinbits(Old VT)
3399 Tmp2 = DAG.getSetCC(dl, TLI.getSetCCResultType(NVT),
3400 Tmp1, DAG.getConstant(NVT.getSizeInBits(), NVT),
3402 Tmp1 = DAG.getNode(ISD::SELECT, dl, NVT, Tmp2,
3403 DAG.getConstant(OVT.getSizeInBits(), NVT), Tmp1);
3404 } else if (Node->getOpcode() == ISD::CTLZ) {
3405 // Tmp1 = Tmp1 - (sizeinbits(NVT) - sizeinbits(Old VT))
3406 Tmp1 = DAG.getNode(ISD::SUB, dl, NVT, Tmp1,
3407 DAG.getConstant(NVT.getSizeInBits() -
3408 OVT.getSizeInBits(), NVT));
3410 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, OVT, Tmp1));
3413 unsigned DiffBits = NVT.getSizeInBits() - OVT.getSizeInBits();
3414 Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, Node->getOperand(0));
3415 Tmp1 = DAG.getNode(ISD::BSWAP, dl, NVT, Tmp1);
3416 Tmp1 = DAG.getNode(ISD::SRL, dl, NVT, Tmp1,
3417 DAG.getConstant(DiffBits, TLI.getShiftAmountTy()));
3418 Results.push_back(Tmp1);
3421 case ISD::FP_TO_UINT:
3422 case ISD::FP_TO_SINT:
3423 Tmp1 = PromoteLegalFP_TO_INT(Node->getOperand(0), Node->getValueType(0),
3424 Node->getOpcode() == ISD::FP_TO_SINT, dl);
3425 Results.push_back(Tmp1);
3427 case ISD::UINT_TO_FP:
3428 case ISD::SINT_TO_FP:
3429 Tmp1 = PromoteLegalINT_TO_FP(Node->getOperand(0), Node->getValueType(0),
3430 Node->getOpcode() == ISD::SINT_TO_FP, dl);
3431 Results.push_back(Tmp1);
3436 unsigned ExtOp, TruncOp;
3437 if (OVT.isVector()) {
3438 ExtOp = ISD::BITCAST;
3439 TruncOp = ISD::BITCAST;
3441 assert(OVT.isInteger() && "Cannot promote logic operation");
3442 ExtOp = ISD::ANY_EXTEND;
3443 TruncOp = ISD::TRUNCATE;
3445 // Promote each of the values to the new type.
3446 Tmp1 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(0));
3447 Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1));
3448 // Perform the larger operation, then convert back
3449 Tmp1 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2);
3450 Results.push_back(DAG.getNode(TruncOp, dl, OVT, Tmp1));
3454 unsigned ExtOp, TruncOp;
3455 if (Node->getValueType(0).isVector()) {
3456 ExtOp = ISD::BITCAST;
3457 TruncOp = ISD::BITCAST;
3458 } else if (Node->getValueType(0).isInteger()) {
3459 ExtOp = ISD::ANY_EXTEND;
3460 TruncOp = ISD::TRUNCATE;
3462 ExtOp = ISD::FP_EXTEND;
3463 TruncOp = ISD::FP_ROUND;
3465 Tmp1 = Node->getOperand(0);
3466 // Promote each of the values to the new type.
3467 Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1));
3468 Tmp3 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(2));
3469 // Perform the larger operation, then round down.
3470 Tmp1 = DAG.getNode(ISD::SELECT, dl, NVT, Tmp1, Tmp2, Tmp3);
3471 if (TruncOp != ISD::FP_ROUND)
3472 Tmp1 = DAG.getNode(TruncOp, dl, Node->getValueType(0), Tmp1);
3474 Tmp1 = DAG.getNode(TruncOp, dl, Node->getValueType(0), Tmp1,
3475 DAG.getIntPtrConstant(0));
3476 Results.push_back(Tmp1);
3479 case ISD::VECTOR_SHUFFLE: {
3480 SmallVector<int, 8> Mask;
3481 cast<ShuffleVectorSDNode>(Node)->getMask(Mask);
3483 // Cast the two input vectors.
3484 Tmp1 = DAG.getNode(ISD::BITCAST, dl, NVT, Node->getOperand(0));
3485 Tmp2 = DAG.getNode(ISD::BITCAST, dl, NVT, Node->getOperand(1));
3487 // Convert the shuffle mask to the right # elements.
3488 Tmp1 = ShuffleWithNarrowerEltType(NVT, OVT, dl, Tmp1, Tmp2, Mask);
3489 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OVT, Tmp1);
3490 Results.push_back(Tmp1);
3494 unsigned ExtOp = ISD::FP_EXTEND;
3495 if (NVT.isInteger()) {
3496 ISD::CondCode CCCode =
3497 cast<CondCodeSDNode>(Node->getOperand(2))->get();
3498 ExtOp = isSignedIntSetCC(CCCode) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
3500 Tmp1 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(0));
3501 Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1));
3502 Results.push_back(DAG.getNode(ISD::SETCC, dl, Node->getValueType(0),
3503 Tmp1, Tmp2, Node->getOperand(2)));
3509 // SelectionDAG::Legalize - This is the entry point for the file.
3511 void SelectionDAG::Legalize(CodeGenOpt::Level OptLevel) {
3512 /// run - This is the main entry point to this class.
3514 SelectionDAGLegalize(*this, OptLevel).LegalizeDAG();