blob: c9ed8b624736416207d9c508eb5325a218a87501 [file] [log] [blame]
Chris Lattner7a60d912005-01-07 07:47:53 +00001//===-- SelectionDAGISel.cpp - Implement the SelectionDAGISel class -------===//
Misha Brukman835702a2005-04-21 22:36:52 +00002//
Chris Lattner7a60d912005-01-07 07:47:53 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukman835702a2005-04-21 22:36:52 +00007//
Chris Lattner7a60d912005-01-07 07:47:53 +00008//===----------------------------------------------------------------------===//
9//
10// This implements the SelectionDAGISel class.
11//
12//===----------------------------------------------------------------------===//
13
14#define DEBUG_TYPE "isel"
Anton Korobeynikov915e6172007-04-04 21:14:49 +000015#include "llvm/ADT/BitVector.h"
Jim Laskeydcb2b832006-10-16 20:52:31 +000016#include "llvm/Analysis/AliasAnalysis.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000017#include "llvm/CodeGen/SelectionDAGISel.h"
Evan Cheng739a6a42006-01-21 02:32:06 +000018#include "llvm/CodeGen/ScheduleDAG.h"
Anton Korobeynikov915e6172007-04-04 21:14:49 +000019#include "llvm/Constants.h"
Chris Lattner2e77db62005-05-13 18:50:42 +000020#include "llvm/CallingConv.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000021#include "llvm/DerivedTypes.h"
22#include "llvm/Function.h"
Chris Lattner435b4022005-11-29 06:21:05 +000023#include "llvm/GlobalVariable.h"
Chris Lattner476e67b2006-01-26 22:24:51 +000024#include "llvm/InlineAsm.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000025#include "llvm/Instructions.h"
26#include "llvm/Intrinsics.h"
Jim Laskeya8bdac82006-03-23 18:06:46 +000027#include "llvm/IntrinsicInst.h"
Reid Spencer71b79e32007-04-09 06:17:21 +000028#include "llvm/ParameterAttributes.h"
Jim Laskeyc56315c2007-01-26 21:22:28 +000029#include "llvm/CodeGen/MachineModuleInfo.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000030#include "llvm/CodeGen/MachineFunction.h"
31#include "llvm/CodeGen/MachineFrameInfo.h"
Nate Begeman4ca2ea52006-04-22 18:53:45 +000032#include "llvm/CodeGen/MachineJumpTableInfo.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000033#include "llvm/CodeGen/MachineInstrBuilder.h"
Jim Laskey29e635d2006-08-02 12:30:23 +000034#include "llvm/CodeGen/SchedulerRegistry.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000035#include "llvm/CodeGen/SelectionDAG.h"
36#include "llvm/CodeGen/SSARegMap.h"
Chris Lattnerd4382f02005-09-13 19:30:54 +000037#include "llvm/Target/MRegisterInfo.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000038#include "llvm/Target/TargetData.h"
39#include "llvm/Target/TargetFrameInfo.h"
40#include "llvm/Target/TargetInstrInfo.h"
41#include "llvm/Target/TargetLowering.h"
42#include "llvm/Target/TargetMachine.h"
Vladimir Prusdf1d4392006-05-23 13:43:15 +000043#include "llvm/Target/TargetOptions.h"
Chris Lattner43535a12005-11-09 04:45:33 +000044#include "llvm/Support/MathExtras.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000045#include "llvm/Support/Debug.h"
Chris Lattner3d27be12006-08-27 12:54:02 +000046#include "llvm/Support/Compiler.h"
Jeff Cohen83c22e02006-02-24 02:52:40 +000047#include <algorithm>
Chris Lattner7a60d912005-01-07 07:47:53 +000048using namespace llvm;
49
Chris Lattner975f5c92005-09-01 18:44:10 +000050#ifndef NDEBUG
Chris Lattnere05a4612005-01-12 03:41:21 +000051static cl::opt<bool>
Evan Cheng739a6a42006-01-21 02:32:06 +000052ViewISelDAGs("view-isel-dags", cl::Hidden,
53 cl::desc("Pop up a window to show isel dags as they are selected"));
54static cl::opt<bool>
55ViewSchedDAGs("view-sched-dags", cl::Hidden,
56 cl::desc("Pop up a window to show sched dags as they are processed"));
Chris Lattnere05a4612005-01-12 03:41:21 +000057#else
Chris Lattneref598052006-04-02 03:07:27 +000058static const bool ViewISelDAGs = 0, ViewSchedDAGs = 0;
Chris Lattnere05a4612005-01-12 03:41:21 +000059#endif
60
Jim Laskey29e635d2006-08-02 12:30:23 +000061//===---------------------------------------------------------------------===//
62///
63/// RegisterScheduler class - Track the registration of instruction schedulers.
64///
65//===---------------------------------------------------------------------===//
66MachinePassRegistry RegisterScheduler::Registry;
67
68//===---------------------------------------------------------------------===//
69///
70/// ISHeuristic command line option for instruction schedulers.
71///
72//===---------------------------------------------------------------------===//
Evan Chengc1e1d972006-01-23 07:01:07 +000073namespace {
Jim Laskey29e635d2006-08-02 12:30:23 +000074 cl::opt<RegisterScheduler::FunctionPassCtor, false,
75 RegisterPassParser<RegisterScheduler> >
Jim Laskey95eda5b2006-08-01 14:21:23 +000076 ISHeuristic("sched",
Chris Lattner524c1a22006-08-03 00:18:59 +000077 cl::init(&createDefaultScheduler),
Jim Laskey95eda5b2006-08-01 14:21:23 +000078 cl::desc("Instruction schedulers available:"));
79
Jim Laskey03593f72006-08-01 18:29:48 +000080 static RegisterScheduler
Jim Laskey17c67ef2006-08-01 19:14:14 +000081 defaultListDAGScheduler("default", " Best scheduler for the target",
82 createDefaultScheduler);
Evan Chengc1e1d972006-01-23 07:01:07 +000083} // namespace
84
Chris Lattner4333f8b2007-04-30 17:29:31 +000085namespace { struct AsmOperandInfo; }
86
Chris Lattner6f87d182006-02-22 22:37:12 +000087namespace {
88 /// RegsForValue - This struct represents the physical registers that a
89 /// particular value is assigned and the type information about the value.
90 /// This is needed because values can be promoted into larger registers and
91 /// expanded into multiple smaller registers than the value.
Chris Lattner996795b2006-06-28 23:17:24 +000092 struct VISIBILITY_HIDDEN RegsForValue {
Chris Lattner6f87d182006-02-22 22:37:12 +000093 /// Regs - This list hold the register (for legal and promoted values)
94 /// or register set (for expanded values) that the value should be assigned
95 /// to.
96 std::vector<unsigned> Regs;
97
98 /// RegVT - The value type of each register.
99 ///
100 MVT::ValueType RegVT;
101
102 /// ValueVT - The value type of the LLVM value, which may be promoted from
103 /// RegVT or made from merging the two expanded parts.
104 MVT::ValueType ValueVT;
105
106 RegsForValue() : RegVT(MVT::Other), ValueVT(MVT::Other) {}
107
108 RegsForValue(unsigned Reg, MVT::ValueType regvt, MVT::ValueType valuevt)
109 : RegVT(regvt), ValueVT(valuevt) {
110 Regs.push_back(Reg);
111 }
112 RegsForValue(const std::vector<unsigned> &regs,
113 MVT::ValueType regvt, MVT::ValueType valuevt)
114 : Regs(regs), RegVT(regvt), ValueVT(valuevt) {
115 }
116
117 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
118 /// this value and returns the result as a ValueVT value. This uses
119 /// Chain/Flag as the input and updates them for the output Chain/Flag.
120 SDOperand getCopyFromRegs(SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +0000121 SDOperand &Chain, SDOperand &Flag) const;
Chris Lattner571d9642006-02-23 19:21:04 +0000122
123 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
124 /// specified value into the registers specified by this object. This uses
125 /// Chain/Flag as the input and updates them for the output Chain/Flag.
126 void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Evan Chengef9e07d2006-06-15 08:11:54 +0000127 SDOperand &Chain, SDOperand &Flag,
128 MVT::ValueType PtrVT) const;
Chris Lattner571d9642006-02-23 19:21:04 +0000129
130 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
131 /// operand list. This adds the code marker and includes the number of
132 /// values added into it.
133 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +0000134 std::vector<SDOperand> &Ops) const;
Chris Lattner6f87d182006-02-22 22:37:12 +0000135 };
136}
Evan Chengc1e1d972006-01-23 07:01:07 +0000137
Chris Lattner7a60d912005-01-07 07:47:53 +0000138namespace llvm {
139 //===--------------------------------------------------------------------===//
Jim Laskey17c67ef2006-08-01 19:14:14 +0000140 /// createDefaultScheduler - This creates an instruction scheduler appropriate
141 /// for the target.
142 ScheduleDAG* createDefaultScheduler(SelectionDAGISel *IS,
143 SelectionDAG *DAG,
144 MachineBasicBlock *BB) {
145 TargetLowering &TLI = IS->getTargetLowering();
146
147 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency) {
148 return createTDListDAGScheduler(IS, DAG, BB);
149 } else {
150 assert(TLI.getSchedulingPreference() ==
151 TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
152 return createBURRListDAGScheduler(IS, DAG, BB);
153 }
154 }
155
156
157 //===--------------------------------------------------------------------===//
Chris Lattner7a60d912005-01-07 07:47:53 +0000158 /// FunctionLoweringInfo - This contains information that is global to a
159 /// function that is used when lowering a region of the function.
Chris Lattnerd0061952005-01-08 19:52:31 +0000160 class FunctionLoweringInfo {
161 public:
Chris Lattner7a60d912005-01-07 07:47:53 +0000162 TargetLowering &TLI;
163 Function &Fn;
164 MachineFunction &MF;
165 SSARegMap *RegMap;
166
167 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
168
169 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
170 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
171
172 /// ValueMap - Since we emit code for the function a basic block at a time,
173 /// we must remember which virtual registers hold the values for
174 /// cross-basic-block values.
Chris Lattner289aa442007-02-04 01:35:11 +0000175 DenseMap<const Value*, unsigned> ValueMap;
Chris Lattner7a60d912005-01-07 07:47:53 +0000176
177 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
178 /// the entry block. This allows the allocas to be efficiently referenced
179 /// anywhere in the function.
180 std::map<const AllocaInst*, int> StaticAllocaMap;
181
Duncan Sands92bf2c62007-06-15 19:04:19 +0000182#ifndef NDEBUG
183 SmallSet<Instruction*, 8> CatchInfoLost;
184 SmallSet<Instruction*, 8> CatchInfoFound;
185#endif
186
Chris Lattner7a60d912005-01-07 07:47:53 +0000187 unsigned MakeReg(MVT::ValueType VT) {
188 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
189 }
Chris Lattnered0110b2006-10-27 21:36:01 +0000190
191 /// isExportedInst - Return true if the specified value is an instruction
192 /// exported from its block.
193 bool isExportedInst(const Value *V) {
194 return ValueMap.count(V);
195 }
Misha Brukman835702a2005-04-21 22:36:52 +0000196
Chris Lattner49409cb2006-03-16 19:51:18 +0000197 unsigned CreateRegForValue(const Value *V);
198
Chris Lattner7a60d912005-01-07 07:47:53 +0000199 unsigned InitializeRegForValue(const Value *V) {
200 unsigned &R = ValueMap[V];
201 assert(R == 0 && "Already initialized this value register!");
202 return R = CreateRegForValue(V);
203 }
204 };
205}
206
Duncan Sands92bf2c62007-06-15 19:04:19 +0000207/// isFilterOrSelector - Return true if this instruction is a call to the
208/// eh.filter or the eh.selector intrinsic.
209static bool isFilterOrSelector(Instruction *I) {
210 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
211 return II->getIntrinsicID() == Intrinsic::eh_selector
212 || II->getIntrinsicID() == Intrinsic::eh_filter;
213 return false;
214}
215
Chris Lattner7a60d912005-01-07 07:47:53 +0000216/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
Nate Begemaned728c12006-03-27 01:32:24 +0000217/// PHI nodes or outside of the basic block that defines it, or used by a
218/// switch instruction, which may expand to multiple basic blocks.
Chris Lattner7a60d912005-01-07 07:47:53 +0000219static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
220 if (isa<PHINode>(I)) return true;
221 BasicBlock *BB = I->getParent();
222 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
Nate Begemaned728c12006-03-27 01:32:24 +0000223 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
Chris Lattnered0110b2006-10-27 21:36:01 +0000224 // FIXME: Remove switchinst special case.
Nate Begemaned728c12006-03-27 01:32:24 +0000225 isa<SwitchInst>(*UI))
Chris Lattner7a60d912005-01-07 07:47:53 +0000226 return true;
227 return false;
228}
229
Chris Lattner6871b232005-10-30 19:42:35 +0000230/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
Nate Begemaned728c12006-03-27 01:32:24 +0000231/// entry block, return true. This includes arguments used by switches, since
232/// the switch may expand into multiple basic blocks.
Chris Lattner6871b232005-10-30 19:42:35 +0000233static bool isOnlyUsedInEntryBlock(Argument *A) {
234 BasicBlock *Entry = A->getParent()->begin();
235 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
Nate Begemaned728c12006-03-27 01:32:24 +0000236 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
Chris Lattner6871b232005-10-30 19:42:35 +0000237 return false; // Use not in entry block.
238 return true;
239}
240
Chris Lattner7a60d912005-01-07 07:47:53 +0000241FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
Misha Brukman835702a2005-04-21 22:36:52 +0000242 Function &fn, MachineFunction &mf)
Chris Lattner7a60d912005-01-07 07:47:53 +0000243 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
244
Chris Lattner6871b232005-10-30 19:42:35 +0000245 // Create a vreg for each argument register that is not dead and is used
246 // outside of the entry block for the function.
247 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
248 AI != E; ++AI)
249 if (!isOnlyUsedInEntryBlock(AI))
250 InitializeRegForValue(AI);
251
Chris Lattner7a60d912005-01-07 07:47:53 +0000252 // Initialize the mapping of values to registers. This is only set up for
253 // instruction values that are used outside of the block that defines
254 // them.
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000255 Function::iterator BB = Fn.begin(), EB = Fn.end();
Chris Lattner7a60d912005-01-07 07:47:53 +0000256 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
257 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
Reid Spencere0fc4df2006-10-20 07:07:24 +0000258 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000259 const Type *Ty = AI->getAllocatedType();
Owen Anderson20a631f2006-05-03 01:29:57 +0000260 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
Nate Begeman3ee3e692005-11-06 09:00:38 +0000261 unsigned Align =
Chris Lattner945e4372007-02-14 05:52:17 +0000262 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
Nate Begeman3ee3e692005-11-06 09:00:38 +0000263 AI->getAlignment());
Chris Lattnercbefe722005-05-13 23:14:17 +0000264
Reid Spencere0fc4df2006-10-20 07:07:24 +0000265 TySize *= CUI->getZExtValue(); // Get total allocated size.
Chris Lattner0a71a9a2005-10-18 22:14:06 +0000266 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
Chris Lattner7a60d912005-01-07 07:47:53 +0000267 StaticAllocaMap[AI] =
Chris Lattnercb0ed0c2007-04-25 04:08:28 +0000268 MF.getFrameInfo()->CreateStackObject(TySize, Align);
Chris Lattner7a60d912005-01-07 07:47:53 +0000269 }
270
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000271 for (; BB != EB; ++BB)
272 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner7a60d912005-01-07 07:47:53 +0000273 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
274 if (!isa<AllocaInst>(I) ||
275 !StaticAllocaMap.count(cast<AllocaInst>(I)))
276 InitializeRegForValue(I);
277
278 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
279 // also creates the initial PHI MachineInstrs, though none of the input
280 // operands are populated.
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000281 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000282 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
283 MBBMap[BB] = MBB;
284 MF.getBasicBlockList().push_back(MBB);
285
286 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
287 // appropriate.
288 PHINode *PN;
Chris Lattner84a03502006-10-27 23:50:33 +0000289 for (BasicBlock::iterator I = BB->begin();(PN = dyn_cast<PHINode>(I)); ++I){
290 if (PN->use_empty()) continue;
291
292 MVT::ValueType VT = TLI.getValueType(PN->getType());
293 unsigned NumElements;
294 if (VT != MVT::Vector)
295 NumElements = TLI.getNumElements(VT);
296 else {
297 MVT::ValueType VT1,VT2;
298 NumElements =
Reid Spencerd84d35b2007-02-15 02:26:10 +0000299 TLI.getVectorTypeBreakdown(cast<VectorType>(PN->getType()),
Chris Lattner84a03502006-10-27 23:50:33 +0000300 VT1, VT2);
Chris Lattner8ea875f2005-01-07 21:34:19 +0000301 }
Chris Lattner84a03502006-10-27 23:50:33 +0000302 unsigned PHIReg = ValueMap[PN];
303 assert(PHIReg && "PHI node does not have an assigned virtual register!");
Evan Cheng20350c42006-11-27 23:37:22 +0000304 const TargetInstrInfo *TII = TLI.getTargetMachine().getInstrInfo();
Chris Lattner84a03502006-10-27 23:50:33 +0000305 for (unsigned i = 0; i != NumElements; ++i)
Evan Cheng20350c42006-11-27 23:37:22 +0000306 BuildMI(MBB, TII->get(TargetInstrInfo::PHI), PHIReg+i);
Chris Lattner84a03502006-10-27 23:50:33 +0000307 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000308 }
309}
310
Chris Lattner49409cb2006-03-16 19:51:18 +0000311/// CreateRegForValue - Allocate the appropriate number of virtual registers of
312/// the correctly promoted or expanded types. Assign these registers
313/// consecutive vreg numbers and return the first assigned number.
314unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
315 MVT::ValueType VT = TLI.getValueType(V->getType());
316
317 // The number of multiples of registers that we need, to, e.g., split up
318 // a <2 x int64> -> 4 x i32 registers.
319 unsigned NumVectorRegs = 1;
320
Reid Spencer09575ba2007-02-15 03:39:18 +0000321 // If this is a vector type, figure out what type it will decompose into
Chris Lattner49409cb2006-03-16 19:51:18 +0000322 // and how many of the elements it will use.
323 if (VT == MVT::Vector) {
Reid Spencerd84d35b2007-02-15 02:26:10 +0000324 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner49409cb2006-03-16 19:51:18 +0000325 unsigned NumElts = PTy->getNumElements();
326 MVT::ValueType EltTy = TLI.getValueType(PTy->getElementType());
Dan Gohman1796f1f2007-05-18 17:52:13 +0000327 MVT::ValueType VecTy = MVT::getVectorType(EltTy, NumElts);
Chris Lattner49409cb2006-03-16 19:51:18 +0000328
329 // Divide the input until we get to a supported size. This will always
330 // end with a scalar if the target doesn't support vectors.
Bill Wendling47917b62007-04-24 21:13:23 +0000331 while (NumElts > 1 && !TLI.isTypeLegal(VecTy)) {
Chris Lattner49409cb2006-03-16 19:51:18 +0000332 NumElts >>= 1;
333 NumVectorRegs <<= 1;
Dan Gohman1796f1f2007-05-18 17:52:13 +0000334 VecTy = MVT::getVectorType(EltTy, NumElts);
Chris Lattner49409cb2006-03-16 19:51:18 +0000335 }
Bill Wendling47917b62007-04-24 21:13:23 +0000336
337 // Check that VecTy isn't a 1-element vector.
338 if (NumElts == 1 && VecTy == MVT::Other)
Chris Lattner7ececaa2006-03-16 23:05:19 +0000339 VT = EltTy;
340 else
Bill Wendling47917b62007-04-24 21:13:23 +0000341 VT = VecTy;
Chris Lattner49409cb2006-03-16 19:51:18 +0000342 }
Bill Wendling47917b62007-04-24 21:13:23 +0000343
Chris Lattner49409cb2006-03-16 19:51:18 +0000344 // The common case is that we will only create one register for this
345 // value. If we have that case, create and return the virtual register.
346 unsigned NV = TLI.getNumElements(VT);
347 if (NV == 1) {
348 // If we are promoting this value, pick the next largest supported type.
349 MVT::ValueType PromotedType = TLI.getTypeToTransformTo(VT);
350 unsigned Reg = MakeReg(PromotedType);
351 // If this is a vector of supported or promoted types (e.g. 4 x i16),
352 // create all of the registers.
353 for (unsigned i = 1; i != NumVectorRegs; ++i)
354 MakeReg(PromotedType);
355 return Reg;
356 }
357
358 // If this value is represented with multiple target registers, make sure
359 // to create enough consecutive registers of the right (smaller) type.
Evan Cheng22cf8992006-12-13 20:57:08 +0000360 VT = TLI.getTypeToExpandTo(VT);
361 unsigned R = MakeReg(VT);
Chris Lattner49409cb2006-03-16 19:51:18 +0000362 for (unsigned i = 1; i != NV*NumVectorRegs; ++i)
Evan Cheng22cf8992006-12-13 20:57:08 +0000363 MakeReg(VT);
Chris Lattner49409cb2006-03-16 19:51:18 +0000364 return R;
365}
Chris Lattner7a60d912005-01-07 07:47:53 +0000366
367//===----------------------------------------------------------------------===//
368/// SelectionDAGLowering - This is the common target-independent lowering
369/// implementation that is parameterized by a TargetLowering object.
370/// Also, targets can overload any lowering method.
371///
372namespace llvm {
373class SelectionDAGLowering {
374 MachineBasicBlock *CurMBB;
375
Chris Lattner79084302007-02-04 01:31:47 +0000376 DenseMap<const Value*, SDOperand> NodeMap;
Chris Lattner7a60d912005-01-07 07:47:53 +0000377
Chris Lattner4d9651c2005-01-17 22:19:26 +0000378 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
379 /// them up and then emit token factor nodes when possible. This allows us to
380 /// get simple disambiguation between loads without worrying about alias
381 /// analysis.
382 std::vector<SDOperand> PendingLoads;
383
Anton Korobeynikov915e6172007-04-04 21:14:49 +0000384 /// Case - A struct to record the Value for a switch case, and the
385 /// case's target basic block.
386 struct Case {
387 Constant* Low;
388 Constant* High;
389 MachineBasicBlock* BB;
390
391 Case() : Low(0), High(0), BB(0) { }
392 Case(Constant* low, Constant* high, MachineBasicBlock* bb) :
393 Low(low), High(high), BB(bb) { }
394 uint64_t size() const {
395 uint64_t rHigh = cast<ConstantInt>(High)->getSExtValue();
396 uint64_t rLow = cast<ConstantInt>(Low)->getSExtValue();
397 return (rHigh - rLow + 1ULL);
398 }
399 };
400
Anton Korobeynikov506eaf72007-04-09 12:31:58 +0000401 struct CaseBits {
402 uint64_t Mask;
403 MachineBasicBlock* BB;
404 unsigned Bits;
405
406 CaseBits(uint64_t mask, MachineBasicBlock* bb, unsigned bits):
407 Mask(mask), BB(bb), Bits(bits) { }
408 };
409
Anton Korobeynikov915e6172007-04-04 21:14:49 +0000410 typedef std::vector<Case> CaseVector;
Anton Korobeynikov506eaf72007-04-09 12:31:58 +0000411 typedef std::vector<CaseBits> CaseBitsVector;
Anton Korobeynikov915e6172007-04-04 21:14:49 +0000412 typedef CaseVector::iterator CaseItr;
413 typedef std::pair<CaseItr, CaseItr> CaseRange;
Nate Begemaned728c12006-03-27 01:32:24 +0000414
415 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
416 /// of conditional branches.
417 struct CaseRec {
418 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
419 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
420
421 /// CaseBB - The MBB in which to emit the compare and branch
422 MachineBasicBlock *CaseBB;
423 /// LT, GE - If nonzero, we know the current case value must be less-than or
424 /// greater-than-or-equal-to these Constants.
425 Constant *LT;
426 Constant *GE;
427 /// Range - A pair of iterators representing the range of case values to be
428 /// processed at this point in the binary search tree.
429 CaseRange Range;
430 };
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +0000431
432 typedef std::vector<CaseRec> CaseRecVector;
Anton Korobeynikov915e6172007-04-04 21:14:49 +0000433
434 /// The comparison function for sorting the switch case values in the vector.
435 /// WARNING: Case ranges should be disjoint!
Nate Begemaned728c12006-03-27 01:32:24 +0000436 struct CaseCmp {
Anton Korobeynikov506eaf72007-04-09 12:31:58 +0000437 bool operator () (const Case& C1, const Case& C2) {
Anton Korobeynikov915e6172007-04-04 21:14:49 +0000438 assert(isa<ConstantInt>(C1.Low) && isa<ConstantInt>(C2.High));
439 const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
440 const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
441 return CI1->getValue().slt(CI2->getValue());
Nate Begemaned728c12006-03-27 01:32:24 +0000442 }
443 };
Anton Korobeynikov915e6172007-04-04 21:14:49 +0000444
Anton Korobeynikov506eaf72007-04-09 12:31:58 +0000445 struct CaseBitsCmp {
446 bool operator () (const CaseBits& C1, const CaseBits& C2) {
447 return C1.Bits > C2.Bits;
448 }
449 };
450
Anton Korobeynikov915e6172007-04-04 21:14:49 +0000451 unsigned Clusterify(CaseVector& Cases, const SwitchInst &SI);
Nate Begemaned728c12006-03-27 01:32:24 +0000452
Chris Lattner7a60d912005-01-07 07:47:53 +0000453public:
454 // TLI - This is information that describes the available target features we
455 // need for lowering. This indicates when operations are unavailable,
456 // implemented with a libcall, etc.
457 TargetLowering &TLI;
458 SelectionDAG &DAG;
Owen Anderson20a631f2006-05-03 01:29:57 +0000459 const TargetData *TD;
Chris Lattner7a60d912005-01-07 07:47:53 +0000460
Nate Begemaned728c12006-03-27 01:32:24 +0000461 /// SwitchCases - Vector of CaseBlock structures used to communicate
462 /// SwitchInst code generation information.
463 std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
Anton Korobeynikov70378262007-03-25 15:07:15 +0000464 /// JTCases - Vector of JumpTable structures used to communicate
465 /// SwitchInst code generation information.
466 std::vector<SelectionDAGISel::JumpTableBlock> JTCases;
Anton Korobeynikov506eaf72007-04-09 12:31:58 +0000467 std::vector<SelectionDAGISel::BitTestBlock> BitTestCases;
Nate Begemaned728c12006-03-27 01:32:24 +0000468
Chris Lattner7a60d912005-01-07 07:47:53 +0000469 /// FuncInfo - Information about the function as a whole.
470 ///
471 FunctionLoweringInfo &FuncInfo;
472
473 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Misha Brukman835702a2005-04-21 22:36:52 +0000474 FunctionLoweringInfo &funcinfo)
Chris Lattner7a60d912005-01-07 07:47:53 +0000475 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
Anton Korobeynikov70378262007-03-25 15:07:15 +0000476 FuncInfo(funcinfo) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000477 }
478
Chris Lattner4108bb02005-01-17 19:43:36 +0000479 /// getRoot - Return the current virtual root of the Selection DAG.
480 ///
481 SDOperand getRoot() {
Chris Lattner4d9651c2005-01-17 22:19:26 +0000482 if (PendingLoads.empty())
483 return DAG.getRoot();
Misha Brukman835702a2005-04-21 22:36:52 +0000484
Chris Lattner4d9651c2005-01-17 22:19:26 +0000485 if (PendingLoads.size() == 1) {
486 SDOperand Root = PendingLoads[0];
487 DAG.setRoot(Root);
488 PendingLoads.clear();
489 return Root;
490 }
491
492 // Otherwise, we have to make a token factor node.
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000493 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
494 &PendingLoads[0], PendingLoads.size());
Chris Lattner4d9651c2005-01-17 22:19:26 +0000495 PendingLoads.clear();
496 DAG.setRoot(Root);
497 return Root;
Chris Lattner4108bb02005-01-17 19:43:36 +0000498 }
499
Chris Lattnered0110b2006-10-27 21:36:01 +0000500 SDOperand CopyValueToVirtualRegister(Value *V, unsigned Reg);
501
Chris Lattner7a60d912005-01-07 07:47:53 +0000502 void visit(Instruction &I) { visit(I.getOpcode(), I); }
503
504 void visit(unsigned Opcode, User &I) {
Chris Lattnerd5e604d2006-11-10 04:41:34 +0000505 // Note: this doesn't use InstVisitor, because it has to work with
506 // ConstantExpr's in addition to instructions.
Chris Lattner7a60d912005-01-07 07:47:53 +0000507 switch (Opcode) {
508 default: assert(0 && "Unknown instruction type encountered!");
509 abort();
510 // Build the switch statement using the Instruction.def file.
511#define HANDLE_INST(NUM, OPCODE, CLASS) \
512 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
513#include "llvm/Instruction.def"
514 }
515 }
516
517 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
518
Chris Lattner4024c002006-03-15 22:19:46 +0000519 SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Chenge71fe34d2006-10-09 20:57:25 +0000520 const Value *SV, SDOperand Root,
Christopher Lamb8af6d582007-04-22 23:15:30 +0000521 bool isVolatile, unsigned Alignment);
Chris Lattner7a60d912005-01-07 07:47:53 +0000522
523 SDOperand getIntPtrConstant(uint64_t Val) {
524 return DAG.getConstant(Val, TLI.getPointerTy());
525 }
526
Chris Lattner8471b152006-03-16 19:57:50 +0000527 SDOperand getValue(const Value *V);
Chris Lattner7a60d912005-01-07 07:47:53 +0000528
Chris Lattner79084302007-02-04 01:31:47 +0000529 void setValue(const Value *V, SDOperand NewN) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000530 SDOperand &N = NodeMap[V];
531 assert(N.Val == 0 && "Already set a value for this node!");
Chris Lattner79084302007-02-04 01:31:47 +0000532 N = NewN;
Chris Lattner7a60d912005-01-07 07:47:53 +0000533 }
Chris Lattner1558fc62006-02-01 18:59:47 +0000534
Chris Lattner8cfd33b2007-04-30 21:11:17 +0000535 void GetRegistersForValue(AsmOperandInfo &OpInfo, bool HasEarlyClobber,
536 std::set<unsigned> &OutputRegs,
537 std::set<unsigned> &InputRegs);
Nate Begemaned728c12006-03-27 01:32:24 +0000538
Chris Lattnered0110b2006-10-27 21:36:01 +0000539 void FindMergedConditions(Value *Cond, MachineBasicBlock *TBB,
540 MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
541 unsigned Opc);
Chris Lattner84a03502006-10-27 23:50:33 +0000542 bool isExportableFromCurrentBlock(Value *V, const BasicBlock *FromBB);
Chris Lattnered0110b2006-10-27 21:36:01 +0000543 void ExportFromCurrentBlock(Value *V);
Jim Laskey31fef782007-02-23 21:45:01 +0000544 void LowerCallTo(Instruction &I,
545 const Type *CalledValueTy, unsigned CallingConv,
Anton Korobeynikov3b327822007-05-23 11:08:31 +0000546 bool IsTailCall, SDOperand Callee, unsigned OpIdx,
547 MachineBasicBlock *LandingPad = NULL);
548
Chris Lattner7a60d912005-01-07 07:47:53 +0000549 // Terminator instructions.
550 void visitRet(ReturnInst &I);
551 void visitBr(BranchInst &I);
Nate Begemaned728c12006-03-27 01:32:24 +0000552 void visitSwitch(SwitchInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000553 void visitUnreachable(UnreachableInst &I) { /* noop */ }
554
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +0000555 // Helpers for visitSwitch
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +0000556 bool handleSmallSwitchRange(CaseRec& CR,
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +0000557 CaseRecVector& WorkList,
558 Value* SV,
559 MachineBasicBlock* Default);
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +0000560 bool handleJTSwitchCase(CaseRec& CR,
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +0000561 CaseRecVector& WorkList,
562 Value* SV,
563 MachineBasicBlock* Default);
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +0000564 bool handleBTSplitSwitchCase(CaseRec& CR,
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +0000565 CaseRecVector& WorkList,
566 Value* SV,
567 MachineBasicBlock* Default);
Anton Korobeynikov506eaf72007-04-09 12:31:58 +0000568 bool handleBitTestsSwitchCase(CaseRec& CR,
569 CaseRecVector& WorkList,
570 Value* SV,
571 MachineBasicBlock* Default);
Nate Begemaned728c12006-03-27 01:32:24 +0000572 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
Anton Korobeynikov506eaf72007-04-09 12:31:58 +0000573 void visitBitTestHeader(SelectionDAGISel::BitTestBlock &B);
574 void visitBitTestCase(MachineBasicBlock* NextMBB,
575 unsigned Reg,
576 SelectionDAGISel::BitTestCase &B);
Nate Begeman4ca2ea52006-04-22 18:53:45 +0000577 void visitJumpTable(SelectionDAGISel::JumpTable &JT);
Anton Korobeynikov70378262007-03-25 15:07:15 +0000578 void visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
579 SelectionDAGISel::JumpTableHeader &JTH);
Nate Begemaned728c12006-03-27 01:32:24 +0000580
Chris Lattner7a60d912005-01-07 07:47:53 +0000581 // These all get lowered before this pass.
Jim Laskey4b37a4c2007-02-21 22:53:45 +0000582 void visitInvoke(InvokeInst &I);
583 void visitUnwind(UnwindInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000584
Reid Spencer2eadb532007-01-21 00:29:26 +0000585 void visitScalarBinary(User &I, unsigned OpCode);
586 void visitVectorBinary(User &I, unsigned OpCode);
587 void visitEitherBinary(User &I, unsigned ScalarOp, unsigned VectorOp);
Nate Begeman127321b2005-11-18 07:42:56 +0000588 void visitShift(User &I, unsigned Opcode);
Nate Begemanb2e089c2005-11-19 00:36:38 +0000589 void visitAdd(User &I) {
Reid Spencerd84d35b2007-02-15 02:26:10 +0000590 if (isa<VectorType>(I.getType()))
Reid Spencer2eadb532007-01-21 00:29:26 +0000591 visitVectorBinary(I, ISD::VADD);
592 else if (I.getType()->isFloatingPoint())
593 visitScalarBinary(I, ISD::FADD);
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000594 else
Reid Spencer2eadb532007-01-21 00:29:26 +0000595 visitScalarBinary(I, ISD::ADD);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000596 }
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000597 void visitSub(User &I);
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000598 void visitMul(User &I) {
Reid Spencerd84d35b2007-02-15 02:26:10 +0000599 if (isa<VectorType>(I.getType()))
Reid Spencer2eadb532007-01-21 00:29:26 +0000600 visitVectorBinary(I, ISD::VMUL);
601 else if (I.getType()->isFloatingPoint())
602 visitScalarBinary(I, ISD::FMUL);
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000603 else
Reid Spencer2eadb532007-01-21 00:29:26 +0000604 visitScalarBinary(I, ISD::MUL);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000605 }
Reid Spencer2eadb532007-01-21 00:29:26 +0000606 void visitURem(User &I) { visitScalarBinary(I, ISD::UREM); }
607 void visitSRem(User &I) { visitScalarBinary(I, ISD::SREM); }
608 void visitFRem(User &I) { visitScalarBinary(I, ISD::FREM); }
609 void visitUDiv(User &I) { visitEitherBinary(I, ISD::UDIV, ISD::VUDIV); }
610 void visitSDiv(User &I) { visitEitherBinary(I, ISD::SDIV, ISD::VSDIV); }
611 void visitFDiv(User &I) { visitEitherBinary(I, ISD::FDIV, ISD::VSDIV); }
612 void visitAnd (User &I) { visitEitherBinary(I, ISD::AND, ISD::VAND ); }
613 void visitOr (User &I) { visitEitherBinary(I, ISD::OR, ISD::VOR ); }
614 void visitXor (User &I) { visitEitherBinary(I, ISD::XOR, ISD::VXOR ); }
615 void visitShl (User &I) { visitShift(I, ISD::SHL); }
Reid Spencerfdff9382006-11-08 06:47:33 +0000616 void visitLShr(User &I) { visitShift(I, ISD::SRL); }
617 void visitAShr(User &I) { visitShift(I, ISD::SRA); }
Reid Spencerd9436b62006-11-20 01:22:35 +0000618 void visitICmp(User &I);
619 void visitFCmp(User &I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000620 // Visit the conversion instructions
621 void visitTrunc(User &I);
622 void visitZExt(User &I);
623 void visitSExt(User &I);
624 void visitFPTrunc(User &I);
625 void visitFPExt(User &I);
626 void visitFPToUI(User &I);
627 void visitFPToSI(User &I);
628 void visitUIToFP(User &I);
629 void visitSIToFP(User &I);
630 void visitPtrToInt(User &I);
631 void visitIntToPtr(User &I);
632 void visitBitCast(User &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000633
Chris Lattner67271862006-03-29 00:11:43 +0000634 void visitExtractElement(User &I);
635 void visitInsertElement(User &I);
Chris Lattner098c01e2006-04-08 04:15:24 +0000636 void visitShuffleVector(User &I);
Chris Lattner32206f52006-03-18 01:44:44 +0000637
Chris Lattner7a60d912005-01-07 07:47:53 +0000638 void visitGetElementPtr(User &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000639 void visitSelect(User &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000640
641 void visitMalloc(MallocInst &I);
642 void visitFree(FreeInst &I);
643 void visitAlloca(AllocaInst &I);
644 void visitLoad(LoadInst &I);
645 void visitStore(StoreInst &I);
646 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
647 void visitCall(CallInst &I);
Chris Lattner476e67b2006-01-26 22:24:51 +0000648 void visitInlineAsm(CallInst &I);
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000649 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattnerd96b09a2006-03-24 02:22:33 +0000650 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
Chris Lattner7a60d912005-01-07 07:47:53 +0000651
Chris Lattner7a60d912005-01-07 07:47:53 +0000652 void visitVAStart(CallInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000653 void visitVAArg(VAArgInst &I);
654 void visitVAEnd(CallInst &I);
655 void visitVACopy(CallInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000656
Chris Lattner875def92005-01-11 05:56:49 +0000657 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner7a60d912005-01-07 07:47:53 +0000658
659 void visitUserOp1(Instruction &I) {
660 assert(0 && "UserOp1 should not exist at instruction selection time!");
661 abort();
662 }
663 void visitUserOp2(Instruction &I) {
664 assert(0 && "UserOp2 should not exist at instruction selection time!");
665 abort();
666 }
667};
668} // end namespace llvm
669
Chris Lattner8471b152006-03-16 19:57:50 +0000670SDOperand SelectionDAGLowering::getValue(const Value *V) {
671 SDOperand &N = NodeMap[V];
672 if (N.Val) return N;
673
674 const Type *VTy = V->getType();
675 MVT::ValueType VT = TLI.getValueType(VTy);
676 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
677 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
678 visit(CE->getOpcode(), *CE);
Chris Lattner79084302007-02-04 01:31:47 +0000679 SDOperand N1 = NodeMap[V];
680 assert(N1.Val && "visit didn't populate the ValueMap!");
681 return N1;
Chris Lattner8471b152006-03-16 19:57:50 +0000682 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
683 return N = DAG.getGlobalAddress(GV, VT);
684 } else if (isa<ConstantPointerNull>(C)) {
685 return N = DAG.getConstant(0, TLI.getPointerTy());
686 } else if (isa<UndefValue>(C)) {
Reid Spencerd84d35b2007-02-15 02:26:10 +0000687 if (!isa<VectorType>(VTy))
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000688 return N = DAG.getNode(ISD::UNDEF, VT);
689
Chris Lattnerf4e1a532006-03-19 00:52:58 +0000690 // Create a VBUILD_VECTOR of undef nodes.
Reid Spencerd84d35b2007-02-15 02:26:10 +0000691 const VectorType *PTy = cast<VectorType>(VTy);
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000692 unsigned NumElements = PTy->getNumElements();
693 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
694
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000695 SmallVector<SDOperand, 8> Ops;
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000696 Ops.assign(NumElements, DAG.getNode(ISD::UNDEF, PVT));
697
698 // Create a VConstant node with generic Vector type.
699 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
700 Ops.push_back(DAG.getValueType(PVT));
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000701 return N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector,
702 &Ops[0], Ops.size());
Chris Lattner8471b152006-03-16 19:57:50 +0000703 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
704 return N = DAG.getConstantFP(CFP->getValue(), VT);
Reid Spencerd84d35b2007-02-15 02:26:10 +0000705 } else if (const VectorType *PTy = dyn_cast<VectorType>(VTy)) {
Chris Lattner8471b152006-03-16 19:57:50 +0000706 unsigned NumElements = PTy->getNumElements();
707 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Chris Lattner8471b152006-03-16 19:57:50 +0000708
709 // Now that we know the number and type of the elements, push a
710 // Constant or ConstantFP node onto the ops list for each element of
711 // the packed constant.
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000712 SmallVector<SDOperand, 8> Ops;
Reid Spencerd84d35b2007-02-15 02:26:10 +0000713 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
Chris Lattner67271862006-03-29 00:11:43 +0000714 for (unsigned i = 0; i != NumElements; ++i)
715 Ops.push_back(getValue(CP->getOperand(i)));
Chris Lattner8471b152006-03-16 19:57:50 +0000716 } else {
717 assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
718 SDOperand Op;
719 if (MVT::isFloatingPoint(PVT))
720 Op = DAG.getConstantFP(0, PVT);
721 else
722 Op = DAG.getConstant(0, PVT);
723 Ops.assign(NumElements, Op);
724 }
725
Chris Lattnerf4e1a532006-03-19 00:52:58 +0000726 // Create a VBUILD_VECTOR node with generic Vector type.
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000727 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
728 Ops.push_back(DAG.getValueType(PVT));
Chris Lattner79084302007-02-04 01:31:47 +0000729 return NodeMap[V] = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0],
730 Ops.size());
Chris Lattner8471b152006-03-16 19:57:50 +0000731 } else {
732 // Canonicalize all constant ints to be unsigned.
Zhou Sheng75b871f2007-01-11 12:24:14 +0000733 return N = DAG.getConstant(cast<ConstantInt>(C)->getZExtValue(),VT);
Chris Lattner8471b152006-03-16 19:57:50 +0000734 }
735 }
736
737 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
738 std::map<const AllocaInst*, int>::iterator SI =
739 FuncInfo.StaticAllocaMap.find(AI);
740 if (SI != FuncInfo.StaticAllocaMap.end())
741 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
742 }
743
Chris Lattner8c504cf2007-02-25 18:40:32 +0000744 unsigned InReg = FuncInfo.ValueMap[V];
745 assert(InReg && "Value not in map!");
Chris Lattner8471b152006-03-16 19:57:50 +0000746
747 // If this type is not legal, make it so now.
Chris Lattner5fe1f542006-03-31 02:06:56 +0000748 if (VT != MVT::Vector) {
Evan Cheng22cf8992006-12-13 20:57:08 +0000749 if (TLI.getTypeAction(VT) == TargetLowering::Expand) {
Chris Lattner5fe1f542006-03-31 02:06:56 +0000750 // Source must be expanded. This input value is actually coming from the
Chris Lattner8c504cf2007-02-25 18:40:32 +0000751 // register pair InReg and InReg+1.
Evan Cheng22cf8992006-12-13 20:57:08 +0000752 MVT::ValueType DestVT = TLI.getTypeToExpandTo(VT);
753 unsigned NumVals = TLI.getNumElements(VT);
754 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
755 if (NumVals == 1)
756 N = DAG.getNode(ISD::BIT_CONVERT, VT, N);
757 else {
758 assert(NumVals == 2 && "1 to 4 (and more) expansion not implemented!");
759 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
760 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
761 }
762 } else {
763 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
764 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
765 if (TLI.getTypeAction(VT) == TargetLowering::Promote) // Promotion case
766 N = MVT::isFloatingPoint(VT)
767 ? DAG.getNode(ISD::FP_ROUND, VT, N)
768 : DAG.getNode(ISD::TRUNCATE, VT, N);
Chris Lattner8471b152006-03-16 19:57:50 +0000769 }
Chris Lattner5fe1f542006-03-31 02:06:56 +0000770 } else {
771 // Otherwise, if this is a vector, make it available as a generic vector
772 // here.
773 MVT::ValueType PTyElementVT, PTyLegalElementVT;
Reid Spencerd84d35b2007-02-15 02:26:10 +0000774 const VectorType *PTy = cast<VectorType>(VTy);
775 unsigned NE = TLI.getVectorTypeBreakdown(PTy, PTyElementVT,
Chris Lattner5fe1f542006-03-31 02:06:56 +0000776 PTyLegalElementVT);
777
Dan Gohman26455c42007-06-13 15:12:02 +0000778 // Build a VBUILD_VECTOR or VCONCAT_VECTORS with the input registers.
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000779 SmallVector<SDOperand, 8> Ops;
Chris Lattner5fe1f542006-03-31 02:06:56 +0000780 if (PTyElementVT == PTyLegalElementVT) {
781 // If the value types are legal, just VBUILD the CopyFromReg nodes.
782 for (unsigned i = 0; i != NE; ++i)
783 Ops.push_back(DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
784 PTyElementVT));
785 } else if (PTyElementVT < PTyLegalElementVT) {
Dan Gohman30978072007-05-24 14:36:04 +0000786 // If the register was promoted, use TRUNCATE or FP_ROUND as appropriate.
Chris Lattner5fe1f542006-03-31 02:06:56 +0000787 for (unsigned i = 0; i != NE; ++i) {
788 SDOperand Op = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
Dan Gohmancbd51c82007-06-13 14:55:16 +0000789 PTyLegalElementVT);
Chris Lattner5fe1f542006-03-31 02:06:56 +0000790 if (MVT::isFloatingPoint(PTyElementVT))
791 Op = DAG.getNode(ISD::FP_ROUND, PTyElementVT, Op);
792 else
793 Op = DAG.getNode(ISD::TRUNCATE, PTyElementVT, Op);
794 Ops.push_back(Op);
795 }
796 } else {
797 // If the register was expanded, use BUILD_PAIR.
798 assert((NE & 1) == 0 && "Must expand into a multiple of 2 elements!");
Dan Gohmancbd51c82007-06-13 14:55:16 +0000799 for (unsigned i = 0; i != NE; ++i) {
Chris Lattner5fe1f542006-03-31 02:06:56 +0000800 SDOperand Op0 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
Dan Gohmancbd51c82007-06-13 14:55:16 +0000801 PTyLegalElementVT);
Chris Lattner5fe1f542006-03-31 02:06:56 +0000802 SDOperand Op1 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
Dan Gohmancbd51c82007-06-13 14:55:16 +0000803 PTyLegalElementVT);
804 Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, PTyElementVT, Op0, Op1));
Chris Lattner5fe1f542006-03-31 02:06:56 +0000805 }
806 }
807
Dan Gohman26455c42007-06-13 15:12:02 +0000808 if (MVT::isVector(PTyElementVT)) {
809 Ops.push_back(DAG.getConstant(NE * MVT::getVectorNumElements(PTyElementVT), MVT::i32));
Dan Gohman5c441312007-06-14 22:58:02 +0000810 Ops.push_back(DAG.getValueType(MVT::getVectorElementType(PTyElementVT)));
Dan Gohman26455c42007-06-13 15:12:02 +0000811 N = DAG.getNode(ISD::VCONCAT_VECTORS, MVT::Vector, &Ops[0], Ops.size());
812 } else {
813 Ops.push_back(DAG.getConstant(NE, MVT::i32));
814 Ops.push_back(DAG.getValueType(PTyElementVT));
815 N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0], Ops.size());
816 }
Chris Lattner8471b152006-03-16 19:57:50 +0000817 }
818
819 return N;
820}
821
822
Chris Lattner7a60d912005-01-07 07:47:53 +0000823void SelectionDAGLowering::visitRet(ReturnInst &I) {
824 if (I.getNumOperands() == 0) {
Chris Lattner4108bb02005-01-17 19:43:36 +0000825 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
Chris Lattner7a60d912005-01-07 07:47:53 +0000826 return;
827 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000828 SmallVector<SDOperand, 8> NewValues;
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000829 NewValues.push_back(getRoot());
830 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
831 SDOperand RetOp = getValue(I.getOperand(i));
832
833 // If this is an integer return value, we need to promote it ourselves to
834 // the full width of a register, since LegalizeOp will use ANY_EXTEND rather
835 // than sign/zero.
Evan Chenga2e99532006-05-26 23:09:09 +0000836 // FIXME: C calling convention requires the return type to be promoted to
837 // at least 32-bit. But this is not necessary for non-C calling conventions.
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000838 if (MVT::isInteger(RetOp.getValueType()) &&
839 RetOp.getValueType() < MVT::i64) {
840 MVT::ValueType TmpVT;
841 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
842 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
843 else
844 TmpVT = MVT::i32;
Reid Spencere63b6512006-12-31 05:55:36 +0000845 const FunctionType *FTy = I.getParent()->getParent()->getFunctionType();
Reid Spencer71b79e32007-04-09 06:17:21 +0000846 const ParamAttrsList *Attrs = FTy->getParamAttrs();
Reid Spencere6f81872007-01-03 16:49:33 +0000847 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
Reid Spencera472f662007-04-11 02:44:20 +0000848 if (Attrs && Attrs->paramHasAttr(0, ParamAttr::SExt))
Reid Spencer0917adf2007-01-03 04:25:33 +0000849 ExtendKind = ISD::SIGN_EXTEND;
Reid Spencera472f662007-04-11 02:44:20 +0000850 if (Attrs && Attrs->paramHasAttr(0, ParamAttr::ZExt))
Reid Spencere63b6512006-12-31 05:55:36 +0000851 ExtendKind = ISD::ZERO_EXTEND;
Reid Spencer2a34b912007-01-03 05:03:05 +0000852 RetOp = DAG.getNode(ExtendKind, TmpVT, RetOp);
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000853 }
854 NewValues.push_back(RetOp);
Reid Spencere63b6512006-12-31 05:55:36 +0000855 NewValues.push_back(DAG.getConstant(false, MVT::i32));
Chris Lattner7a60d912005-01-07 07:47:53 +0000856 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000857 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
858 &NewValues[0], NewValues.size()));
Chris Lattner7a60d912005-01-07 07:47:53 +0000859}
860
Chris Lattnered0110b2006-10-27 21:36:01 +0000861/// ExportFromCurrentBlock - If this condition isn't known to be exported from
862/// the current basic block, add it to ValueMap now so that we'll get a
863/// CopyTo/FromReg.
864void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
865 // No need to export constants.
866 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
867
868 // Already exported?
869 if (FuncInfo.isExportedInst(V)) return;
870
871 unsigned Reg = FuncInfo.InitializeRegForValue(V);
872 PendingLoads.push_back(CopyValueToVirtualRegister(V, Reg));
873}
874
Chris Lattner84a03502006-10-27 23:50:33 +0000875bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
876 const BasicBlock *FromBB) {
877 // The operands of the setcc have to be in this block. We don't know
878 // how to export them from some other block.
879 if (Instruction *VI = dyn_cast<Instruction>(V)) {
880 // Can export from current BB.
881 if (VI->getParent() == FromBB)
882 return true;
883
884 // Is already exported, noop.
885 return FuncInfo.isExportedInst(V);
886 }
887
888 // If this is an argument, we can export it if the BB is the entry block or
889 // if it is already exported.
890 if (isa<Argument>(V)) {
891 if (FromBB == &FromBB->getParent()->getEntryBlock())
892 return true;
893
894 // Otherwise, can only export this if it is already exported.
895 return FuncInfo.isExportedInst(V);
896 }
897
898 // Otherwise, constants can always be exported.
899 return true;
900}
901
Chris Lattnere60ae822006-10-29 21:01:20 +0000902static bool InBlock(const Value *V, const BasicBlock *BB) {
903 if (const Instruction *I = dyn_cast<Instruction>(V))
904 return I->getParent() == BB;
905 return true;
906}
907
Chris Lattnered0110b2006-10-27 21:36:01 +0000908/// FindMergedConditions - If Cond is an expression like
909void SelectionDAGLowering::FindMergedConditions(Value *Cond,
910 MachineBasicBlock *TBB,
911 MachineBasicBlock *FBB,
912 MachineBasicBlock *CurBB,
913 unsigned Opc) {
Chris Lattnered0110b2006-10-27 21:36:01 +0000914 // If this node is not part of the or/and tree, emit it as a branch.
Reid Spencer266e42b2006-12-23 06:05:41 +0000915 Instruction *BOp = dyn_cast<Instruction>(Cond);
Chris Lattnered0110b2006-10-27 21:36:01 +0000916
Reid Spencer266e42b2006-12-23 06:05:41 +0000917 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
918 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
Chris Lattnere60ae822006-10-29 21:01:20 +0000919 BOp->getParent() != CurBB->getBasicBlock() ||
920 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
921 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
Chris Lattnered0110b2006-10-27 21:36:01 +0000922 const BasicBlock *BB = CurBB->getBasicBlock();
923
Reid Spencer266e42b2006-12-23 06:05:41 +0000924 // If the leaf of the tree is a comparison, merge the condition into
925 // the caseblock.
926 if ((isa<ICmpInst>(Cond) || isa<FCmpInst>(Cond)) &&
927 // The operands of the cmp have to be in this block. We don't know
Chris Lattnerf31b9ef2006-10-29 18:23:37 +0000928 // how to export them from some other block. If this is the first block
929 // of the sequence, no exporting is needed.
930 (CurBB == CurMBB ||
931 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
932 isExportableFromCurrentBlock(BOp->getOperand(1), BB)))) {
Reid Spencer266e42b2006-12-23 06:05:41 +0000933 BOp = cast<Instruction>(Cond);
934 ISD::CondCode Condition;
935 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
936 switch (IC->getPredicate()) {
937 default: assert(0 && "Unknown icmp predicate opcode!");
938 case ICmpInst::ICMP_EQ: Condition = ISD::SETEQ; break;
939 case ICmpInst::ICMP_NE: Condition = ISD::SETNE; break;
940 case ICmpInst::ICMP_SLE: Condition = ISD::SETLE; break;
941 case ICmpInst::ICMP_ULE: Condition = ISD::SETULE; break;
942 case ICmpInst::ICMP_SGE: Condition = ISD::SETGE; break;
943 case ICmpInst::ICMP_UGE: Condition = ISD::SETUGE; break;
944 case ICmpInst::ICMP_SLT: Condition = ISD::SETLT; break;
945 case ICmpInst::ICMP_ULT: Condition = ISD::SETULT; break;
946 case ICmpInst::ICMP_SGT: Condition = ISD::SETGT; break;
947 case ICmpInst::ICMP_UGT: Condition = ISD::SETUGT; break;
948 }
949 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
950 ISD::CondCode FPC, FOC;
951 switch (FC->getPredicate()) {
952 default: assert(0 && "Unknown fcmp predicate opcode!");
953 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
954 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
955 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
956 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
957 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
958 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
959 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
960 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
961 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
962 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
963 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
964 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
965 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
966 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
967 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
968 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
969 }
970 if (FiniteOnlyFPMath())
971 Condition = FOC;
972 else
973 Condition = FPC;
974 } else {
Chris Lattner79084302007-02-04 01:31:47 +0000975 Condition = ISD::SETEQ; // silence warning.
Reid Spencer266e42b2006-12-23 06:05:41 +0000976 assert(0 && "Unknown compare instruction");
Chris Lattnered0110b2006-10-27 21:36:01 +0000977 }
978
Chris Lattnered0110b2006-10-27 21:36:01 +0000979 SelectionDAGISel::CaseBlock CB(Condition, BOp->getOperand(0),
Anton Korobeynikov915e6172007-04-04 21:14:49 +0000980 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
Chris Lattnered0110b2006-10-27 21:36:01 +0000981 SwitchCases.push_back(CB);
982 return;
983 }
984
985 // Create a CaseBlock record representing this branch.
Zhou Sheng75b871f2007-01-11 12:24:14 +0000986 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
Anton Korobeynikov915e6172007-04-04 21:14:49 +0000987 NULL, TBB, FBB, CurBB);
Chris Lattnered0110b2006-10-27 21:36:01 +0000988 SwitchCases.push_back(CB);
Chris Lattnered0110b2006-10-27 21:36:01 +0000989 return;
990 }
991
Chris Lattnerf1b54fd2006-10-27 21:54:23 +0000992
993 // Create TmpBB after CurBB.
Chris Lattnered0110b2006-10-27 21:36:01 +0000994 MachineFunction::iterator BBI = CurBB;
995 MachineBasicBlock *TmpBB = new MachineBasicBlock(CurBB->getBasicBlock());
996 CurBB->getParent()->getBasicBlockList().insert(++BBI, TmpBB);
997
Chris Lattnerf1b54fd2006-10-27 21:54:23 +0000998 if (Opc == Instruction::Or) {
999 // Codegen X | Y as:
1000 // jmp_if_X TBB
1001 // jmp TmpBB
1002 // TmpBB:
1003 // jmp_if_Y TBB
1004 // jmp FBB
1005 //
Chris Lattnered0110b2006-10-27 21:36:01 +00001006
Chris Lattnerf1b54fd2006-10-27 21:54:23 +00001007 // Emit the LHS condition.
1008 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
1009
1010 // Emit the RHS condition into TmpBB.
1011 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1012 } else {
1013 assert(Opc == Instruction::And && "Unknown merge op!");
1014 // Codegen X & Y as:
1015 // jmp_if_X TmpBB
1016 // jmp FBB
1017 // TmpBB:
1018 // jmp_if_Y TBB
1019 // jmp FBB
1020 //
1021 // This requires creation of TmpBB after CurBB.
1022
1023 // Emit the LHS condition.
1024 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
1025
1026 // Emit the RHS condition into TmpBB.
1027 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1028 }
Chris Lattnered0110b2006-10-27 21:36:01 +00001029}
1030
Chris Lattner427301f2006-10-31 22:37:42 +00001031/// If the set of cases should be emitted as a series of branches, return true.
1032/// If we should emit this as a bunch of and/or'd together conditions, return
1033/// false.
1034static bool
1035ShouldEmitAsBranches(const std::vector<SelectionDAGISel::CaseBlock> &Cases) {
1036 if (Cases.size() != 2) return true;
1037
Chris Lattnerfe43bef2006-10-31 23:06:00 +00001038 // If this is two comparisons of the same values or'd or and'd together, they
1039 // will get folded into a single comparison, so don't emit two blocks.
1040 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1041 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1042 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1043 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1044 return false;
1045 }
1046
Chris Lattner427301f2006-10-31 22:37:42 +00001047 return true;
1048}
1049
Chris Lattner7a60d912005-01-07 07:47:53 +00001050void SelectionDAGLowering::visitBr(BranchInst &I) {
1051 // Update machine-CFG edges.
1052 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner7a60d912005-01-07 07:47:53 +00001053
1054 // Figure out which block is immediately after the current one.
1055 MachineBasicBlock *NextBlock = 0;
1056 MachineFunction::iterator BBI = CurMBB;
1057 if (++BBI != CurMBB->getParent()->end())
1058 NextBlock = BBI;
1059
1060 if (I.isUnconditional()) {
1061 // If this is not a fall-through branch, emit the branch.
1062 if (Succ0MBB != NextBlock)
Chris Lattner4108bb02005-01-17 19:43:36 +00001063 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +00001064 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +00001065
Chris Lattner963ddad2006-10-24 17:57:59 +00001066 // Update machine-CFG edges.
1067 CurMBB->addSuccessor(Succ0MBB);
1068
1069 return;
1070 }
1071
1072 // If this condition is one of the special cases we handle, do special stuff
1073 // now.
1074 Value *CondVal = I.getCondition();
Chris Lattner963ddad2006-10-24 17:57:59 +00001075 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattnered0110b2006-10-27 21:36:01 +00001076
1077 // If this is a series of conditions that are or'd or and'd together, emit
1078 // this as a sequence of branches instead of setcc's with and/or operations.
1079 // For example, instead of something like:
1080 // cmp A, B
1081 // C = seteq
1082 // cmp D, E
1083 // F = setle
1084 // or C, F
1085 // jnz foo
1086 // Emit:
1087 // cmp A, B
1088 // je foo
1089 // cmp D, E
1090 // jle foo
1091 //
1092 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1093 if (BOp->hasOneUse() &&
Chris Lattnerf1b54fd2006-10-27 21:54:23 +00001094 (BOp->getOpcode() == Instruction::And ||
Chris Lattnered0110b2006-10-27 21:36:01 +00001095 BOp->getOpcode() == Instruction::Or)) {
1096 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
Chris Lattnerfe43bef2006-10-31 23:06:00 +00001097 // If the compares in later blocks need to use values not currently
1098 // exported from this block, export them now. This block should always
1099 // be the first entry.
1100 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1101
Chris Lattner427301f2006-10-31 22:37:42 +00001102 // Allow some cases to be rejected.
1103 if (ShouldEmitAsBranches(SwitchCases)) {
Chris Lattner427301f2006-10-31 22:37:42 +00001104 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1105 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1106 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1107 }
1108
1109 // Emit the branch for this block.
1110 visitSwitchCase(SwitchCases[0]);
1111 SwitchCases.erase(SwitchCases.begin());
1112 return;
Chris Lattnerf31b9ef2006-10-29 18:23:37 +00001113 }
1114
Chris Lattnerfe43bef2006-10-31 23:06:00 +00001115 // Okay, we decided not to do this, remove any inserted MBB's and clear
1116 // SwitchCases.
1117 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1118 CurMBB->getParent()->getBasicBlockList().erase(SwitchCases[i].ThisBB);
1119
Chris Lattner427301f2006-10-31 22:37:42 +00001120 SwitchCases.clear();
Chris Lattnered0110b2006-10-27 21:36:01 +00001121 }
1122 }
Chris Lattner61bcf912006-10-24 18:07:37 +00001123
1124 // Create a CaseBlock record representing this branch.
Zhou Sheng75b871f2007-01-11 12:24:14 +00001125 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001126 NULL, Succ0MBB, Succ1MBB, CurMBB);
Chris Lattner61bcf912006-10-24 18:07:37 +00001127 // Use visitSwitchCase to actually insert the fast branch sequence for this
1128 // cond branch.
1129 visitSwitchCase(CB);
Chris Lattner7a60d912005-01-07 07:47:53 +00001130}
1131
Nate Begemaned728c12006-03-27 01:32:24 +00001132/// visitSwitchCase - Emits the necessary code to represent a single node in
1133/// the binary search tree resulting from lowering a switch instruction.
1134void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
Chris Lattner963ddad2006-10-24 17:57:59 +00001135 SDOperand Cond;
1136 SDOperand CondLHS = getValue(CB.CmpLHS);
1137
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001138 // Build the setcc now.
1139 if (CB.CmpMHS == NULL) {
1140 // Fold "(X == true)" to X and "(X == false)" to !X to
1141 // handle common cases produced by branch lowering.
1142 if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
1143 Cond = CondLHS;
1144 else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
1145 SDOperand True = DAG.getConstant(1, CondLHS.getValueType());
1146 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1147 } else
1148 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1149 } else {
1150 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
Anton Korobeynikov70378262007-03-25 15:07:15 +00001151
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001152 uint64_t Low = cast<ConstantInt>(CB.CmpLHS)->getSExtValue();
1153 uint64_t High = cast<ConstantInt>(CB.CmpRHS)->getSExtValue();
1154
1155 SDOperand CmpOp = getValue(CB.CmpMHS);
1156 MVT::ValueType VT = CmpOp.getValueType();
1157
1158 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1159 Cond = DAG.getSetCC(MVT::i1, CmpOp, DAG.getConstant(High, VT), ISD::SETLE);
1160 } else {
1161 SDOperand SUB = DAG.getNode(ISD::SUB, VT, CmpOp, DAG.getConstant(Low, VT));
1162 Cond = DAG.getSetCC(MVT::i1, SUB,
1163 DAG.getConstant(High-Low, VT), ISD::SETULE);
1164 }
1165
1166 }
1167
Nate Begemaned728c12006-03-27 01:32:24 +00001168 // Set NextBlock to be the MBB immediately after the current one, if any.
1169 // This is used to avoid emitting unnecessary branches to the next block.
1170 MachineBasicBlock *NextBlock = 0;
1171 MachineFunction::iterator BBI = CurMBB;
1172 if (++BBI != CurMBB->getParent()->end())
1173 NextBlock = BBI;
1174
1175 // If the lhs block is the next block, invert the condition so that we can
1176 // fall through to the lhs instead of the rhs block.
Chris Lattner963ddad2006-10-24 17:57:59 +00001177 if (CB.TrueBB == NextBlock) {
1178 std::swap(CB.TrueBB, CB.FalseBB);
Nate Begemaned728c12006-03-27 01:32:24 +00001179 SDOperand True = DAG.getConstant(1, Cond.getValueType());
1180 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1181 }
1182 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
Chris Lattner963ddad2006-10-24 17:57:59 +00001183 DAG.getBasicBlock(CB.TrueBB));
1184 if (CB.FalseBB == NextBlock)
Nate Begemaned728c12006-03-27 01:32:24 +00001185 DAG.setRoot(BrCond);
1186 else
1187 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
Chris Lattner963ddad2006-10-24 17:57:59 +00001188 DAG.getBasicBlock(CB.FalseBB)));
Nate Begemaned728c12006-03-27 01:32:24 +00001189 // Update successor info
Chris Lattner963ddad2006-10-24 17:57:59 +00001190 CurMBB->addSuccessor(CB.TrueBB);
1191 CurMBB->addSuccessor(CB.FalseBB);
Nate Begemaned728c12006-03-27 01:32:24 +00001192}
1193
Anton Korobeynikov70378262007-03-25 15:07:15 +00001194/// visitJumpTable - Emit JumpTable node in the current MBB
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001195void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001196 // Emit the code for the jump table
Scott Michel4cfa6162007-04-24 01:24:20 +00001197 assert(JT.Reg != -1U && "Should lower JT Header first!");
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001198 MVT::ValueType PTy = TLI.getPointerTy();
Evan Cheng84a28d42006-10-30 08:00:44 +00001199 SDOperand Index = DAG.getCopyFromReg(getRoot(), JT.Reg, PTy);
1200 SDOperand Table = DAG.getJumpTable(JT.JTI, PTy);
1201 DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1202 Table, Index));
1203 return;
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001204}
1205
Anton Korobeynikov70378262007-03-25 15:07:15 +00001206/// visitJumpTableHeader - This function emits necessary code to produce index
1207/// in the JumpTable from switch case.
1208void SelectionDAGLowering::visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
1209 SelectionDAGISel::JumpTableHeader &JTH) {
1210 // Subtract the lowest switch case value from the value being switched on
1211 // and conditional branch to default mbb if the result is greater than the
1212 // difference between smallest and largest cases.
1213 SDOperand SwitchOp = getValue(JTH.SValue);
1214 MVT::ValueType VT = SwitchOp.getValueType();
1215 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1216 DAG.getConstant(JTH.First, VT));
1217
1218 // The SDNode we just created, which holds the value being switched on
1219 // minus the the smallest case value, needs to be copied to a virtual
1220 // register so it can be used as an index into the jump table in a
1221 // subsequent basic block. This value may be smaller or larger than the
1222 // target's pointer type, and therefore require extension or truncating.
1223 if (VT > TLI.getPointerTy())
1224 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1225 else
1226 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
1227
1228 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1229 SDOperand CopyTo = DAG.getCopyToReg(getRoot(), JumpTableReg, SwitchOp);
1230 JT.Reg = JumpTableReg;
1231
1232 // Emit the range check for the jump table, and branch to the default
1233 // block for the switch statement if the value being switched on exceeds
1234 // the largest case in the switch.
1235 SDOperand CMP = DAG.getSetCC(TLI.getSetCCResultTy(), SUB,
1236 DAG.getConstant(JTH.Last-JTH.First,VT),
1237 ISD::SETUGT);
1238
1239 // Set NextBlock to be the MBB immediately after the current one, if any.
1240 // This is used to avoid emitting unnecessary branches to the next block.
1241 MachineBasicBlock *NextBlock = 0;
1242 MachineFunction::iterator BBI = CurMBB;
1243 if (++BBI != CurMBB->getParent()->end())
1244 NextBlock = BBI;
1245
1246 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
1247 DAG.getBasicBlock(JT.Default));
1248
1249 if (JT.MBB == NextBlock)
1250 DAG.setRoot(BrCond);
1251 else
1252 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001253 DAG.getBasicBlock(JT.MBB)));
1254
1255 return;
Anton Korobeynikov70378262007-03-25 15:07:15 +00001256}
1257
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001258/// visitBitTestHeader - This function emits necessary code to produce value
1259/// suitable for "bit tests"
1260void SelectionDAGLowering::visitBitTestHeader(SelectionDAGISel::BitTestBlock &B) {
1261 // Subtract the minimum value
1262 SDOperand SwitchOp = getValue(B.SValue);
1263 MVT::ValueType VT = SwitchOp.getValueType();
1264 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1265 DAG.getConstant(B.First, VT));
1266
1267 // Check range
1268 SDOperand RangeCmp = DAG.getSetCC(TLI.getSetCCResultTy(), SUB,
1269 DAG.getConstant(B.Range, VT),
1270 ISD::SETUGT);
1271
1272 SDOperand ShiftOp;
1273 if (VT > TLI.getShiftAmountTy())
1274 ShiftOp = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), SUB);
1275 else
1276 ShiftOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getShiftAmountTy(), SUB);
1277
1278 // Make desired shift
1279 SDOperand SwitchVal = DAG.getNode(ISD::SHL, TLI.getPointerTy(),
1280 DAG.getConstant(1, TLI.getPointerTy()),
1281 ShiftOp);
1282
1283 unsigned SwitchReg = FuncInfo.MakeReg(TLI.getPointerTy());
1284 SDOperand CopyTo = DAG.getCopyToReg(getRoot(), SwitchReg, SwitchVal);
1285 B.Reg = SwitchReg;
1286
1287 SDOperand BrRange = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, RangeCmp,
1288 DAG.getBasicBlock(B.Default));
1289
1290 // Set NextBlock to be the MBB immediately after the current one, if any.
1291 // This is used to avoid emitting unnecessary branches to the next block.
1292 MachineBasicBlock *NextBlock = 0;
1293 MachineFunction::iterator BBI = CurMBB;
1294 if (++BBI != CurMBB->getParent()->end())
1295 NextBlock = BBI;
1296
1297 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1298 if (MBB == NextBlock)
1299 DAG.setRoot(BrRange);
1300 else
1301 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, CopyTo,
1302 DAG.getBasicBlock(MBB)));
1303
1304 CurMBB->addSuccessor(B.Default);
1305 CurMBB->addSuccessor(MBB);
1306
1307 return;
1308}
1309
1310/// visitBitTestCase - this function produces one "bit test"
1311void SelectionDAGLowering::visitBitTestCase(MachineBasicBlock* NextMBB,
1312 unsigned Reg,
1313 SelectionDAGISel::BitTestCase &B) {
1314 // Emit bit tests and jumps
1315 SDOperand SwitchVal = DAG.getCopyFromReg(getRoot(), Reg, TLI.getPointerTy());
1316
1317 SDOperand AndOp = DAG.getNode(ISD::AND, TLI.getPointerTy(),
1318 SwitchVal,
1319 DAG.getConstant(B.Mask,
1320 TLI.getPointerTy()));
1321 SDOperand AndCmp = DAG.getSetCC(TLI.getSetCCResultTy(), AndOp,
1322 DAG.getConstant(0, TLI.getPointerTy()),
1323 ISD::SETNE);
1324 SDOperand BrAnd = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
1325 AndCmp, DAG.getBasicBlock(B.TargetBB));
1326
1327 // Set NextBlock to be the MBB immediately after the current one, if any.
1328 // This is used to avoid emitting unnecessary branches to the next block.
1329 MachineBasicBlock *NextBlock = 0;
1330 MachineFunction::iterator BBI = CurMBB;
1331 if (++BBI != CurMBB->getParent()->end())
1332 NextBlock = BBI;
1333
1334 if (NextMBB == NextBlock)
1335 DAG.setRoot(BrAnd);
1336 else
1337 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrAnd,
1338 DAG.getBasicBlock(NextMBB)));
1339
1340 CurMBB->addSuccessor(B.TargetBB);
1341 CurMBB->addSuccessor(NextMBB);
1342
1343 return;
1344}
Anton Korobeynikov70378262007-03-25 15:07:15 +00001345
Jim Laskey4b37a4c2007-02-21 22:53:45 +00001346void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
1347 // Retrieve successors.
1348 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
Duncan Sands97f72362007-06-13 05:51:31 +00001349 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
Duncan Sands61166502007-06-06 10:05:18 +00001350
Duncan Sands97f72362007-06-13 05:51:31 +00001351 LowerCallTo(I, I.getCalledValue()->getType(),
1352 I.getCallingConv(),
1353 false,
1354 getValue(I.getOperand(0)),
1355 3, LandingPad);
Duncan Sands61166502007-06-06 10:05:18 +00001356
Duncan Sands97f72362007-06-13 05:51:31 +00001357 // If the value of the invoke is used outside of its defining block, make it
1358 // available as a virtual register.
1359 if (!I.use_empty()) {
1360 DenseMap<const Value*, unsigned>::iterator VMI = FuncInfo.ValueMap.find(&I);
1361 if (VMI != FuncInfo.ValueMap.end())
1362 DAG.setRoot(CopyValueToVirtualRegister(&I, VMI->second));
Jim Laskey14059d92007-02-25 21:43:59 +00001363 }
Duncan Sands97f72362007-06-13 05:51:31 +00001364
1365 // Drop into normal successor.
1366 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
1367 DAG.getBasicBlock(Return)));
1368
1369 // Update successor info
1370 CurMBB->addSuccessor(Return);
1371 CurMBB->addSuccessor(LandingPad);
Jim Laskey4b37a4c2007-02-21 22:53:45 +00001372}
1373
1374void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1375}
1376
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001377/// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001378/// small case ranges).
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001379bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR,
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001380 CaseRecVector& WorkList,
1381 Value* SV,
1382 MachineBasicBlock* Default) {
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001383 Case& BackCase = *(CR.Range.second-1);
1384
1385 // Size is the number of Cases represented by this range.
1386 unsigned Size = CR.Range.second - CR.Range.first;
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001387 if (Size > 3)
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001388 return false;
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001389
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001390 // Get the MachineFunction which holds the current MBB. This is used when
1391 // inserting any additional MBBs necessary to represent the switch.
1392 MachineFunction *CurMF = CurMBB->getParent();
1393
1394 // Figure out which block is immediately after the current one.
1395 MachineBasicBlock *NextBlock = 0;
1396 MachineFunction::iterator BBI = CR.CaseBB;
1397
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001398 if (++BBI != CurMBB->getParent()->end())
1399 NextBlock = BBI;
1400
1401 // TODO: If any two of the cases has the same destination, and if one value
1402 // is the same as the other, but has one bit unset that the other has set,
1403 // use bit manipulation to do two compares at once. For example:
1404 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1405
1406 // Rearrange the case blocks so that the last one falls through if possible.
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001407 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001408 // The last case block won't fall through into 'NextBlock' if we emit the
1409 // branches in this order. See if rearranging a case value would help.
1410 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001411 if (I->BB == NextBlock) {
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001412 std::swap(*I, BackCase);
1413 break;
1414 }
1415 }
1416 }
1417
1418 // Create a CaseBlock record representing a conditional branch to
1419 // the Case's target mbb if the value being switched on SV is equal
1420 // to C.
1421 MachineBasicBlock *CurBlock = CR.CaseBB;
1422 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1423 MachineBasicBlock *FallThrough;
1424 if (I != E-1) {
1425 FallThrough = new MachineBasicBlock(CurBlock->getBasicBlock());
1426 CurMF->getBasicBlockList().insert(BBI, FallThrough);
1427 } else {
1428 // If the last case doesn't match, go to the default block.
1429 FallThrough = Default;
1430 }
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001431
1432 Value *RHS, *LHS, *MHS;
1433 ISD::CondCode CC;
1434 if (I->High == I->Low) {
1435 // This is just small small case range :) containing exactly 1 case
1436 CC = ISD::SETEQ;
1437 LHS = SV; RHS = I->High; MHS = NULL;
1438 } else {
1439 CC = ISD::SETLE;
1440 LHS = I->Low; MHS = SV; RHS = I->High;
1441 }
1442 SelectionDAGISel::CaseBlock CB(CC, LHS, RHS, MHS,
1443 I->BB, FallThrough, CurBlock);
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001444
1445 // If emitting the first comparison, just call visitSwitchCase to emit the
1446 // code into the current block. Otherwise, push the CaseBlock onto the
1447 // vector to be later processed by SDISel, and insert the node's MBB
1448 // before the next MBB.
1449 if (CurBlock == CurMBB)
1450 visitSwitchCase(CB);
1451 else
1452 SwitchCases.push_back(CB);
1453
1454 CurBlock = FallThrough;
1455 }
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001456
1457 return true;
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001458}
1459
Anton Korobeynikov192d09c2007-05-09 20:07:08 +00001460static inline bool areJTsAllowed(const TargetLowering &TLI) {
1461 return (TLI.isOperationLegal(ISD::BR_JT, MVT::Other) ||
1462 TLI.isOperationLegal(ISD::BRIND, MVT::Other));
1463}
1464
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001465/// handleJTSwitchCase - Emit jumptable for current switch case range
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001466bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR,
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001467 CaseRecVector& WorkList,
1468 Value* SV,
1469 MachineBasicBlock* Default) {
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001470 Case& FrontCase = *CR.Range.first;
1471 Case& BackCase = *(CR.Range.second-1);
1472
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001473 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1474 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
1475
1476 uint64_t TSize = 0;
1477 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1478 I!=E; ++I)
1479 TSize += I->size();
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001480
Anton Korobeynikov192d09c2007-05-09 20:07:08 +00001481 if (!areJTsAllowed(TLI) || TSize <= 3)
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001482 return false;
1483
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001484 double Density = (double)TSize / (double)((Last - First) + 1ULL);
1485 if (Density < 0.4)
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001486 return false;
1487
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001488 DOUT << "Lowering jump table\n"
1489 << "First entry: " << First << ". Last entry: " << Last << "\n"
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001490 << "Size: " << TSize << ". Density: " << Density << "\n\n";
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001491
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001492 // Get the MachineFunction which holds the current MBB. This is used when
1493 // inserting any additional MBBs necessary to represent the switch.
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001494 MachineFunction *CurMF = CurMBB->getParent();
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001495
1496 // Figure out which block is immediately after the current one.
1497 MachineBasicBlock *NextBlock = 0;
1498 MachineFunction::iterator BBI = CR.CaseBB;
1499
1500 if (++BBI != CurMBB->getParent()->end())
1501 NextBlock = BBI;
1502
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001503 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1504
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001505 // Create a new basic block to hold the code for loading the address
1506 // of the jump table, and jumping to it. Update successor information;
1507 // we will either branch to the default case for the switch, or the jump
1508 // table.
1509 MachineBasicBlock *JumpTableBB = new MachineBasicBlock(LLVMBB);
1510 CurMF->getBasicBlockList().insert(BBI, JumpTableBB);
1511 CR.CaseBB->addSuccessor(Default);
1512 CR.CaseBB->addSuccessor(JumpTableBB);
1513
1514 // Build a vector of destination BBs, corresponding to each target
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001515 // of the jump table. If the value of the jump table slot corresponds to
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001516 // a case statement, push the case's BB onto the vector, otherwise, push
1517 // the default BB.
1518 std::vector<MachineBasicBlock*> DestBBs;
1519 int64_t TEI = First;
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001520 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
1521 int64_t Low = cast<ConstantInt>(I->Low)->getSExtValue();
1522 int64_t High = cast<ConstantInt>(I->High)->getSExtValue();
1523
1524 if ((Low <= TEI) && (TEI <= High)) {
1525 DestBBs.push_back(I->BB);
1526 if (TEI==High)
1527 ++I;
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001528 } else {
1529 DestBBs.push_back(Default);
1530 }
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001531 }
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001532
1533 // Update successor info. Add one edge to each unique successor.
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001534 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001535 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
1536 E = DestBBs.end(); I != E; ++I) {
1537 if (!SuccsHandled[(*I)->getNumber()]) {
1538 SuccsHandled[(*I)->getNumber()] = true;
1539 JumpTableBB->addSuccessor(*I);
1540 }
1541 }
1542
1543 // Create a jump table index for this jump table, or return an existing
1544 // one.
1545 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1546
1547 // Set the jump table information so that we can codegen it as a second
1548 // MachineBasicBlock
Scott Michel4cfa6162007-04-24 01:24:20 +00001549 SelectionDAGISel::JumpTable JT(-1U, JTI, JumpTableBB, Default);
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001550 SelectionDAGISel::JumpTableHeader JTH(First, Last, SV, CR.CaseBB,
1551 (CR.CaseBB == CurMBB));
1552 if (CR.CaseBB == CurMBB)
1553 visitJumpTableHeader(JT, JTH);
1554
1555 JTCases.push_back(SelectionDAGISel::JumpTableBlock(JTH, JT));
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001556
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001557 return true;
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001558}
1559
1560/// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1561/// 2 subtrees.
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001562bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR,
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001563 CaseRecVector& WorkList,
1564 Value* SV,
1565 MachineBasicBlock* Default) {
1566 // Get the MachineFunction which holds the current MBB. This is used when
1567 // inserting any additional MBBs necessary to represent the switch.
1568 MachineFunction *CurMF = CurMBB->getParent();
1569
1570 // Figure out which block is immediately after the current one.
1571 MachineBasicBlock *NextBlock = 0;
1572 MachineFunction::iterator BBI = CR.CaseBB;
1573
1574 if (++BBI != CurMBB->getParent()->end())
1575 NextBlock = BBI;
1576
1577 Case& FrontCase = *CR.Range.first;
1578 Case& BackCase = *(CR.Range.second-1);
1579 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1580
1581 // Size is the number of Cases represented by this range.
1582 unsigned Size = CR.Range.second - CR.Range.first;
1583
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001584 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1585 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001586 double FMetric = 0;
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001587 CaseItr Pivot = CR.Range.first + Size/2;
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001588
1589 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
1590 // (heuristically) allow us to emit JumpTable's later.
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001591 uint64_t TSize = 0;
1592 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1593 I!=E; ++I)
1594 TSize += I->size();
1595
1596 uint64_t LSize = FrontCase.size();
1597 uint64_t RSize = TSize-LSize;
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001598 DOUT << "Selecting best pivot: \n"
1599 << "First: " << First << ", Last: " << Last <<"\n"
1600 << "LSize: " << LSize << ", RSize: " << RSize << "\n";
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001601 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001602 J!=E; ++I, ++J) {
1603 int64_t LEnd = cast<ConstantInt>(I->High)->getSExtValue();
1604 int64_t RBegin = cast<ConstantInt>(J->Low)->getSExtValue();
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001605 assert((RBegin-LEnd>=1) && "Invalid case distance");
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001606 double LDensity = (double)LSize / (double)((LEnd - First) + 1ULL);
1607 double RDensity = (double)RSize / (double)((Last - RBegin) + 1ULL);
Anton Korobeynikovda964a22007-04-09 21:57:03 +00001608 double Metric = Log2_64(RBegin-LEnd)*(LDensity+RDensity);
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001609 // Should always split in some non-trivial place
1610 DOUT <<"=>Step\n"
1611 << "LEnd: " << LEnd << ", RBegin: " << RBegin << "\n"
1612 << "LDensity: " << LDensity << ", RDensity: " << RDensity << "\n"
1613 << "Metric: " << Metric << "\n";
1614 if (FMetric < Metric) {
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001615 Pivot = J;
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001616 FMetric = Metric;
1617 DOUT << "Current metric set to: " << FMetric << "\n";
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001618 }
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001619
1620 LSize += J->size();
1621 RSize -= J->size();
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001622 }
Anton Korobeynikov192d09c2007-05-09 20:07:08 +00001623 if (areJTsAllowed(TLI)) {
1624 // If our case is dense we *really* should handle it earlier!
1625 assert((FMetric > 0) && "Should handle dense range earlier!");
1626 } else {
1627 Pivot = CR.Range.first + Size/2;
1628 }
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001629
1630 CaseRange LHSR(CR.Range.first, Pivot);
1631 CaseRange RHSR(Pivot, CR.Range.second);
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001632 Constant *C = Pivot->Low;
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001633 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
1634
1635 // We know that we branch to the LHS if the Value being switched on is
1636 // less than the Pivot value, C. We use this to optimize our binary
1637 // tree a bit, by recognizing that if SV is greater than or equal to the
1638 // LHS's Case Value, and that Case Value is exactly one less than the
1639 // Pivot's Value, then we can branch directly to the LHS's Target,
1640 // rather than creating a leaf node for it.
1641 if ((LHSR.second - LHSR.first) == 1 &&
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001642 LHSR.first->High == CR.GE &&
1643 cast<ConstantInt>(C)->getSExtValue() ==
1644 (cast<ConstantInt>(CR.GE)->getSExtValue() + 1LL)) {
1645 TrueBB = LHSR.first->BB;
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001646 } else {
1647 TrueBB = new MachineBasicBlock(LLVMBB);
1648 CurMF->getBasicBlockList().insert(BBI, TrueBB);
1649 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
1650 }
1651
1652 // Similar to the optimization above, if the Value being switched on is
1653 // known to be less than the Constant CR.LT, and the current Case Value
1654 // is CR.LT - 1, then we can branch directly to the target block for
1655 // the current Case Value, rather than emitting a RHS leaf node for it.
1656 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001657 cast<ConstantInt>(RHSR.first->Low)->getSExtValue() ==
1658 (cast<ConstantInt>(CR.LT)->getSExtValue() - 1LL)) {
1659 FalseBB = RHSR.first->BB;
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001660 } else {
1661 FalseBB = new MachineBasicBlock(LLVMBB);
1662 CurMF->getBasicBlockList().insert(BBI, FalseBB);
1663 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
1664 }
1665
1666 // Create a CaseBlock record representing a conditional branch to
1667 // the LHS node if the value being switched on SV is less than C.
1668 // Otherwise, branch to LHS.
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001669 SelectionDAGISel::CaseBlock CB(ISD::SETLT, SV, C, NULL,
1670 TrueBB, FalseBB, CR.CaseBB);
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001671
1672 if (CR.CaseBB == CurMBB)
1673 visitSwitchCase(CB);
1674 else
1675 SwitchCases.push_back(CB);
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001676
1677 return true;
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001678}
1679
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001680/// handleBitTestsSwitchCase - if current case range has few destination and
1681/// range span less, than machine word bitwidth, encode case range into series
1682/// of masks and emit bit tests with these masks.
1683bool SelectionDAGLowering::handleBitTestsSwitchCase(CaseRec& CR,
1684 CaseRecVector& WorkList,
1685 Value* SV,
Chris Lattner7196f092007-04-14 02:26:56 +00001686 MachineBasicBlock* Default){
Dan Gohman1796f1f2007-05-18 17:52:13 +00001687 unsigned IntPtrBits = MVT::getSizeInBits(TLI.getPointerTy());
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001688
1689 Case& FrontCase = *CR.Range.first;
1690 Case& BackCase = *(CR.Range.second-1);
1691
1692 // Get the MachineFunction which holds the current MBB. This is used when
1693 // inserting any additional MBBs necessary to represent the switch.
1694 MachineFunction *CurMF = CurMBB->getParent();
1695
1696 unsigned numCmps = 0;
1697 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1698 I!=E; ++I) {
1699 // Single case counts one, case range - two.
1700 if (I->Low == I->High)
1701 numCmps +=1;
1702 else
1703 numCmps +=2;
1704 }
1705
1706 // Count unique destinations
1707 SmallSet<MachineBasicBlock*, 4> Dests;
1708 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1709 Dests.insert(I->BB);
1710 if (Dests.size() > 3)
1711 // Don't bother the code below, if there are too much unique destinations
1712 return false;
1713 }
1714 DOUT << "Total number of unique destinations: " << Dests.size() << "\n"
1715 << "Total number of comparisons: " << numCmps << "\n";
1716
1717 // Compute span of values.
1718 Constant* minValue = FrontCase.Low;
1719 Constant* maxValue = BackCase.High;
1720 uint64_t range = cast<ConstantInt>(maxValue)->getSExtValue() -
1721 cast<ConstantInt>(minValue)->getSExtValue();
1722 DOUT << "Compare range: " << range << "\n"
1723 << "Low bound: " << cast<ConstantInt>(minValue)->getSExtValue() << "\n"
1724 << "High bound: " << cast<ConstantInt>(maxValue)->getSExtValue() << "\n";
1725
Anton Korobeynikovd7ae7f12007-04-26 20:44:04 +00001726 if (range>=IntPtrBits ||
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001727 (!(Dests.size() == 1 && numCmps >= 3) &&
1728 !(Dests.size() == 2 && numCmps >= 5) &&
1729 !(Dests.size() >= 3 && numCmps >= 6)))
1730 return false;
1731
1732 DOUT << "Emitting bit tests\n";
1733 int64_t lowBound = 0;
1734
1735 // Optimize the case where all the case values fit in a
1736 // word without having to subtract minValue. In this case,
1737 // we can optimize away the subtraction.
1738 if (cast<ConstantInt>(minValue)->getSExtValue() >= 0 &&
Anton Korobeynikov8a1a84f2007-04-14 13:25:55 +00001739 cast<ConstantInt>(maxValue)->getSExtValue() < IntPtrBits) {
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001740 range = cast<ConstantInt>(maxValue)->getSExtValue();
1741 } else {
1742 lowBound = cast<ConstantInt>(minValue)->getSExtValue();
1743 }
1744
1745 CaseBitsVector CasesBits;
1746 unsigned i, count = 0;
1747
1748 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1749 MachineBasicBlock* Dest = I->BB;
1750 for (i = 0; i < count; ++i)
1751 if (Dest == CasesBits[i].BB)
1752 break;
1753
1754 if (i == count) {
1755 assert((count < 3) && "Too much destinations to test!");
1756 CasesBits.push_back(CaseBits(0, Dest, 0));
1757 count++;
1758 }
1759
1760 uint64_t lo = cast<ConstantInt>(I->Low)->getSExtValue() - lowBound;
1761 uint64_t hi = cast<ConstantInt>(I->High)->getSExtValue() - lowBound;
1762
1763 for (uint64_t j = lo; j <= hi; j++) {
Anton Korobeynikov8a1a84f2007-04-14 13:25:55 +00001764 CasesBits[i].Mask |= 1ULL << j;
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001765 CasesBits[i].Bits++;
1766 }
1767
1768 }
1769 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
1770
1771 SelectionDAGISel::BitTestInfo BTC;
1772
1773 // Figure out which block is immediately after the current one.
1774 MachineFunction::iterator BBI = CR.CaseBB;
1775 ++BBI;
1776
1777 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1778
1779 DOUT << "Cases:\n";
1780 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
1781 DOUT << "Mask: " << CasesBits[i].Mask << ", Bits: " << CasesBits[i].Bits
1782 << ", BB: " << CasesBits[i].BB << "\n";
1783
1784 MachineBasicBlock *CaseBB = new MachineBasicBlock(LLVMBB);
1785 CurMF->getBasicBlockList().insert(BBI, CaseBB);
1786 BTC.push_back(SelectionDAGISel::BitTestCase(CasesBits[i].Mask,
1787 CaseBB,
1788 CasesBits[i].BB));
1789 }
1790
1791 SelectionDAGISel::BitTestBlock BTB(lowBound, range, SV,
Jeff Cohen0475f3b2007-04-09 14:32:59 +00001792 -1U, (CR.CaseBB == CurMBB),
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001793 CR.CaseBB, Default, BTC);
1794
1795 if (CR.CaseBB == CurMBB)
1796 visitBitTestHeader(BTB);
1797
1798 BitTestCases.push_back(BTB);
1799
1800 return true;
1801}
1802
1803
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001804// Clusterify - Transform simple list of Cases into list of CaseRange's
1805unsigned SelectionDAGLowering::Clusterify(CaseVector& Cases,
1806 const SwitchInst& SI) {
1807 unsigned numCmps = 0;
1808
1809 // Start with "simple" cases
1810 for (unsigned i = 1; i < SI.getNumSuccessors(); ++i) {
1811 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
1812 Cases.push_back(Case(SI.getSuccessorValue(i),
1813 SI.getSuccessorValue(i),
1814 SMBB));
1815 }
1816 sort(Cases.begin(), Cases.end(), CaseCmp());
1817
1818 // Merge case into clusters
1819 if (Cases.size()>=2)
1820 for (CaseItr I=Cases.begin(), J=++(Cases.begin()), E=Cases.end(); J!=E; ) {
1821 int64_t nextValue = cast<ConstantInt>(J->Low)->getSExtValue();
1822 int64_t currentValue = cast<ConstantInt>(I->High)->getSExtValue();
1823 MachineBasicBlock* nextBB = J->BB;
1824 MachineBasicBlock* currentBB = I->BB;
1825
1826 // If the two neighboring cases go to the same destination, merge them
1827 // into a single case.
1828 if ((nextValue-currentValue==1) && (currentBB == nextBB)) {
1829 I->High = J->High;
1830 J = Cases.erase(J);
1831 } else {
1832 I = J++;
1833 }
1834 }
1835
1836 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
1837 if (I->Low != I->High)
1838 // A range counts double, since it requires two compares.
1839 ++numCmps;
1840 }
1841
1842 return numCmps;
1843}
1844
1845void SelectionDAGLowering::visitSwitch(SwitchInst &SI) {
Nate Begemaned728c12006-03-27 01:32:24 +00001846 // Figure out which block is immediately after the current one.
1847 MachineBasicBlock *NextBlock = 0;
1848 MachineFunction::iterator BBI = CurMBB;
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001849
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001850 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
Chris Lattner6d6fc262006-10-22 21:36:53 +00001851
Nate Begemaned728c12006-03-27 01:32:24 +00001852 // If there is only the default destination, branch to it if it is not the
1853 // next basic block. Otherwise, just fall through.
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001854 if (SI.getNumOperands() == 2) {
Nate Begemaned728c12006-03-27 01:32:24 +00001855 // Update machine-CFG edges.
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001856
Nate Begemaned728c12006-03-27 01:32:24 +00001857 // If this is not a fall-through branch, emit the branch.
Chris Lattner6d6fc262006-10-22 21:36:53 +00001858 if (Default != NextBlock)
Nate Begemaned728c12006-03-27 01:32:24 +00001859 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Chris Lattner6d6fc262006-10-22 21:36:53 +00001860 DAG.getBasicBlock(Default)));
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001861
Chris Lattner6d6fc262006-10-22 21:36:53 +00001862 CurMBB->addSuccessor(Default);
Nate Begemaned728c12006-03-27 01:32:24 +00001863 return;
1864 }
1865
1866 // If there are any non-default case statements, create a vector of Cases
1867 // representing each one, and sort the vector so that we can efficiently
1868 // create a binary search tree from them.
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001869 CaseVector Cases;
1870 unsigned numCmps = Clusterify(Cases, SI);
1871 DOUT << "Clusterify finished. Total clusters: " << Cases.size()
1872 << ". Total compares: " << numCmps << "\n";
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001873
Nate Begemaned728c12006-03-27 01:32:24 +00001874 // Get the Value to be switched on and default basic blocks, which will be
1875 // inserted into CaseBlock records, representing basic blocks in the binary
1876 // search tree.
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001877 Value *SV = SI.getOperand(0);
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001878
Nate Begemaned728c12006-03-27 01:32:24 +00001879 // Push the initial CaseRec onto the worklist
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001880 CaseRecVector WorkList;
Anton Korobeynikov70378262007-03-25 15:07:15 +00001881 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
1882
1883 while (!WorkList.empty()) {
Nate Begemaned728c12006-03-27 01:32:24 +00001884 // Grab a record representing a case range to process off the worklist
Anton Korobeynikov70378262007-03-25 15:07:15 +00001885 CaseRec CR = WorkList.back();
1886 WorkList.pop_back();
Anton Korobeynikov70378262007-03-25 15:07:15 +00001887
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001888 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
1889 continue;
1890
Anton Korobeynikov70378262007-03-25 15:07:15 +00001891 // If the range has few cases (two or less) emit a series of specific
1892 // tests.
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001893 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
1894 continue;
1895
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001896 // If the switch has more than 5 blocks, and at least 40% dense, and the
Anton Korobeynikov70378262007-03-25 15:07:15 +00001897 // target supports indirect branches, then emit a jump table rather than
1898 // lowering the switch to a binary tree of conditional branches.
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001899 if (handleJTSwitchCase(CR, WorkList, SV, Default))
1900 continue;
1901
1902 // Emit binary tree. We need to pick a pivot, and push left and right ranges
1903 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
1904 handleBTSplitSwitchCase(CR, WorkList, SV, Default);
Nate Begemaned728c12006-03-27 01:32:24 +00001905 }
1906}
1907
Anton Korobeynikov70378262007-03-25 15:07:15 +00001908
Chris Lattnerf68fd0b2005-04-02 05:04:50 +00001909void SelectionDAGLowering::visitSub(User &I) {
1910 // -0.0 - X --> fneg
Reid Spencer2eadb532007-01-21 00:29:26 +00001911 const Type *Ty = I.getType();
Reid Spencerd84d35b2007-02-15 02:26:10 +00001912 if (isa<VectorType>(Ty)) {
Reid Spencer2eadb532007-01-21 00:29:26 +00001913 visitVectorBinary(I, ISD::VSUB);
1914 } else if (Ty->isFloatingPoint()) {
Chris Lattner6f3b5772005-09-28 22:28:18 +00001915 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
1916 if (CFP->isExactlyValue(-0.0)) {
1917 SDOperand Op2 = getValue(I.getOperand(1));
1918 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
1919 return;
1920 }
Reid Spencer2eadb532007-01-21 00:29:26 +00001921 visitScalarBinary(I, ISD::FSUB);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001922 } else
Reid Spencer2eadb532007-01-21 00:29:26 +00001923 visitScalarBinary(I, ISD::SUB);
Chris Lattnerf68fd0b2005-04-02 05:04:50 +00001924}
1925
Reid Spencer2eadb532007-01-21 00:29:26 +00001926void SelectionDAGLowering::visitScalarBinary(User &I, unsigned OpCode) {
Chris Lattner7a60d912005-01-07 07:47:53 +00001927 SDOperand Op1 = getValue(I.getOperand(0));
1928 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencer2eadb532007-01-21 00:29:26 +00001929
1930 setValue(&I, DAG.getNode(OpCode, Op1.getValueType(), Op1, Op2));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001931}
1932
Reid Spencer2eadb532007-01-21 00:29:26 +00001933void
1934SelectionDAGLowering::visitVectorBinary(User &I, unsigned OpCode) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001935 assert(isa<VectorType>(I.getType()));
1936 const VectorType *Ty = cast<VectorType>(I.getType());
Reid Spencer2eadb532007-01-21 00:29:26 +00001937 SDOperand Typ = DAG.getValueType(TLI.getValueType(Ty->getElementType()));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001938
Reid Spencer2eadb532007-01-21 00:29:26 +00001939 setValue(&I, DAG.getNode(OpCode, MVT::Vector,
1940 getValue(I.getOperand(0)),
1941 getValue(I.getOperand(1)),
1942 DAG.getConstant(Ty->getNumElements(), MVT::i32),
1943 Typ));
1944}
1945
1946void SelectionDAGLowering::visitEitherBinary(User &I, unsigned ScalarOp,
1947 unsigned VectorOp) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001948 if (isa<VectorType>(I.getType()))
Reid Spencer2eadb532007-01-21 00:29:26 +00001949 visitVectorBinary(I, VectorOp);
1950 else
1951 visitScalarBinary(I, ScalarOp);
Nate Begeman127321b2005-11-18 07:42:56 +00001952}
Chris Lattner96c26752005-01-19 22:31:21 +00001953
Nate Begeman127321b2005-11-18 07:42:56 +00001954void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
1955 SDOperand Op1 = getValue(I.getOperand(0));
1956 SDOperand Op2 = getValue(I.getOperand(1));
1957
Reid Spencer2341c222007-02-02 02:16:23 +00001958 if (TLI.getShiftAmountTy() < Op2.getValueType())
1959 Op2 = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), Op2);
1960 else if (TLI.getShiftAmountTy() > Op2.getValueType())
1961 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
Nate Begeman127321b2005-11-18 07:42:56 +00001962
Chris Lattner7a60d912005-01-07 07:47:53 +00001963 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
1964}
1965
Reid Spencerd9436b62006-11-20 01:22:35 +00001966void SelectionDAGLowering::visitICmp(User &I) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001967 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
1968 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
1969 predicate = IC->getPredicate();
1970 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
1971 predicate = ICmpInst::Predicate(IC->getPredicate());
1972 SDOperand Op1 = getValue(I.getOperand(0));
1973 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencerd9436b62006-11-20 01:22:35 +00001974 ISD::CondCode Opcode;
Reid Spencer266e42b2006-12-23 06:05:41 +00001975 switch (predicate) {
Reid Spencerd9436b62006-11-20 01:22:35 +00001976 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
1977 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
1978 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
1979 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
1980 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
1981 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
1982 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
1983 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
1984 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
1985 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
1986 default:
1987 assert(!"Invalid ICmp predicate value");
1988 Opcode = ISD::SETEQ;
1989 break;
1990 }
1991 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
1992}
1993
1994void SelectionDAGLowering::visitFCmp(User &I) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001995 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
1996 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
1997 predicate = FC->getPredicate();
1998 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
1999 predicate = FCmpInst::Predicate(FC->getPredicate());
Chris Lattner7a60d912005-01-07 07:47:53 +00002000 SDOperand Op1 = getValue(I.getOperand(0));
2001 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencer266e42b2006-12-23 06:05:41 +00002002 ISD::CondCode Condition, FOC, FPC;
2003 switch (predicate) {
2004 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
2005 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
2006 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
2007 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
2008 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
2009 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
2010 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
2011 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
2012 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
2013 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
2014 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
2015 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
2016 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
2017 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
2018 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
2019 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
2020 default:
2021 assert(!"Invalid FCmp predicate value");
2022 FOC = FPC = ISD::SETFALSE;
2023 break;
2024 }
2025 if (FiniteOnlyFPMath())
2026 Condition = FOC;
2027 else
2028 Condition = FPC;
2029 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Condition));
Chris Lattner7a60d912005-01-07 07:47:53 +00002030}
2031
2032void SelectionDAGLowering::visitSelect(User &I) {
2033 SDOperand Cond = getValue(I.getOperand(0));
2034 SDOperand TrueVal = getValue(I.getOperand(1));
2035 SDOperand FalseVal = getValue(I.getOperand(2));
Reid Spencerd84d35b2007-02-15 02:26:10 +00002036 if (!isa<VectorType>(I.getType())) {
Chris Lattner02274a52006-04-08 22:22:57 +00002037 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
2038 TrueVal, FalseVal));
2039 } else {
2040 setValue(&I, DAG.getNode(ISD::VSELECT, MVT::Vector, Cond, TrueVal, FalseVal,
2041 *(TrueVal.Val->op_end()-2),
2042 *(TrueVal.Val->op_end()-1)));
2043 }
Chris Lattner7a60d912005-01-07 07:47:53 +00002044}
2045
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002046
2047void SelectionDAGLowering::visitTrunc(User &I) {
2048 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2049 SDOperand N = getValue(I.getOperand(0));
2050 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2051 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2052}
2053
2054void SelectionDAGLowering::visitZExt(User &I) {
2055 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2056 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2057 SDOperand N = getValue(I.getOperand(0));
2058 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2059 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2060}
2061
2062void SelectionDAGLowering::visitSExt(User &I) {
2063 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2064 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2065 SDOperand N = getValue(I.getOperand(0));
2066 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2067 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
2068}
2069
2070void SelectionDAGLowering::visitFPTrunc(User &I) {
2071 // FPTrunc is never a no-op cast, no need to check
2072 SDOperand N = getValue(I.getOperand(0));
2073 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2074 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N));
2075}
2076
2077void SelectionDAGLowering::visitFPExt(User &I){
2078 // FPTrunc is never a no-op cast, no need to check
2079 SDOperand N = getValue(I.getOperand(0));
2080 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2081 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
2082}
2083
2084void SelectionDAGLowering::visitFPToUI(User &I) {
2085 // FPToUI is never a no-op cast, no need to check
2086 SDOperand N = getValue(I.getOperand(0));
2087 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2088 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
2089}
2090
2091void SelectionDAGLowering::visitFPToSI(User &I) {
2092 // FPToSI is never a no-op cast, no need to check
2093 SDOperand N = getValue(I.getOperand(0));
2094 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2095 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
2096}
2097
2098void SelectionDAGLowering::visitUIToFP(User &I) {
2099 // UIToFP is never a no-op cast, no need to check
2100 SDOperand N = getValue(I.getOperand(0));
2101 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2102 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
2103}
2104
2105void SelectionDAGLowering::visitSIToFP(User &I){
2106 // UIToFP is never a no-op cast, no need to check
2107 SDOperand N = getValue(I.getOperand(0));
2108 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2109 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
2110}
2111
2112void SelectionDAGLowering::visitPtrToInt(User &I) {
2113 // What to do depends on the size of the integer and the size of the pointer.
2114 // We can either truncate, zero extend, or no-op, accordingly.
Chris Lattner7a60d912005-01-07 07:47:53 +00002115 SDOperand N = getValue(I.getOperand(0));
Chris Lattner2f4119a2006-03-22 20:09:35 +00002116 MVT::ValueType SrcVT = N.getValueType();
Chris Lattner4024c002006-03-15 22:19:46 +00002117 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002118 SDOperand Result;
2119 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
2120 Result = DAG.getNode(ISD::TRUNCATE, DestVT, N);
2121 else
2122 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2123 Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N);
2124 setValue(&I, Result);
2125}
Chris Lattner7a60d912005-01-07 07:47:53 +00002126
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002127void SelectionDAGLowering::visitIntToPtr(User &I) {
2128 // What to do depends on the size of the integer and the size of the pointer.
2129 // We can either truncate, zero extend, or no-op, accordingly.
2130 SDOperand N = getValue(I.getOperand(0));
2131 MVT::ValueType SrcVT = N.getValueType();
2132 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2133 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
2134 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2135 else
2136 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2137 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2138}
2139
2140void SelectionDAGLowering::visitBitCast(User &I) {
2141 SDOperand N = getValue(I.getOperand(0));
2142 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Chris Lattner2f4119a2006-03-22 20:09:35 +00002143 if (DestVT == MVT::Vector) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002144 // This is a cast to a vector from something else.
2145 // Get information about the output vector.
Reid Spencerd84d35b2007-02-15 02:26:10 +00002146 const VectorType *DestTy = cast<VectorType>(I.getType());
Chris Lattner2f4119a2006-03-22 20:09:35 +00002147 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
2148 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N,
2149 DAG.getConstant(DestTy->getNumElements(),MVT::i32),
2150 DAG.getValueType(EltVT)));
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002151 return;
2152 }
2153 MVT::ValueType SrcVT = N.getValueType();
2154 if (SrcVT == MVT::Vector) {
2155 // This is a cast from a vctor to something else.
2156 // Get information about the input vector.
Chris Lattner2f4119a2006-03-22 20:09:35 +00002157 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N));
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002158 return;
Chris Lattner7a60d912005-01-07 07:47:53 +00002159 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002160
2161 // BitCast assures us that source and destination are the same size so this
2162 // is either a BIT_CONVERT or a no-op.
2163 if (DestVT != N.getValueType())
2164 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types
2165 else
2166 setValue(&I, N); // noop cast.
Chris Lattner7a60d912005-01-07 07:47:53 +00002167}
2168
Chris Lattner67271862006-03-29 00:11:43 +00002169void SelectionDAGLowering::visitInsertElement(User &I) {
Chris Lattner32206f52006-03-18 01:44:44 +00002170 SDOperand InVec = getValue(I.getOperand(0));
2171 SDOperand InVal = getValue(I.getOperand(1));
2172 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2173 getValue(I.getOperand(2)));
2174
Chris Lattner29b23012006-03-19 01:17:20 +00002175 SDOperand Num = *(InVec.Val->op_end()-2);
2176 SDOperand Typ = *(InVec.Val->op_end()-1);
2177 setValue(&I, DAG.getNode(ISD::VINSERT_VECTOR_ELT, MVT::Vector,
2178 InVec, InVal, InIdx, Num, Typ));
Chris Lattner32206f52006-03-18 01:44:44 +00002179}
2180
Chris Lattner67271862006-03-29 00:11:43 +00002181void SelectionDAGLowering::visitExtractElement(User &I) {
Chris Lattner7c0cd8c2006-03-21 20:44:12 +00002182 SDOperand InVec = getValue(I.getOperand(0));
2183 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2184 getValue(I.getOperand(1)));
2185 SDOperand Typ = *(InVec.Val->op_end()-1);
2186 setValue(&I, DAG.getNode(ISD::VEXTRACT_VECTOR_ELT,
2187 TLI.getValueType(I.getType()), InVec, InIdx));
2188}
Chris Lattner32206f52006-03-18 01:44:44 +00002189
Chris Lattner098c01e2006-04-08 04:15:24 +00002190void SelectionDAGLowering::visitShuffleVector(User &I) {
2191 SDOperand V1 = getValue(I.getOperand(0));
2192 SDOperand V2 = getValue(I.getOperand(1));
2193 SDOperand Mask = getValue(I.getOperand(2));
2194
2195 SDOperand Num = *(V1.Val->op_end()-2);
2196 SDOperand Typ = *(V2.Val->op_end()-1);
2197 setValue(&I, DAG.getNode(ISD::VVECTOR_SHUFFLE, MVT::Vector,
2198 V1, V2, Mask, Num, Typ));
2199}
2200
2201
Chris Lattner7a60d912005-01-07 07:47:53 +00002202void SelectionDAGLowering::visitGetElementPtr(User &I) {
2203 SDOperand N = getValue(I.getOperand(0));
2204 const Type *Ty = I.getOperand(0)->getType();
Chris Lattner7a60d912005-01-07 07:47:53 +00002205
2206 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2207 OI != E; ++OI) {
2208 Value *Idx = *OI;
Chris Lattner35397782005-12-05 07:10:48 +00002209 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002210 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
Chris Lattner7a60d912005-01-07 07:47:53 +00002211 if (Field) {
2212 // N = N + Offset
Chris Lattnerc473d8e2007-02-10 19:55:17 +00002213 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
Chris Lattner7a60d912005-01-07 07:47:53 +00002214 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Misha Brukman77451162005-04-22 04:01:18 +00002215 getIntPtrConstant(Offset));
Chris Lattner7a60d912005-01-07 07:47:53 +00002216 }
2217 Ty = StTy->getElementType(Field);
2218 } else {
2219 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner19a83992005-01-07 21:56:57 +00002220
Chris Lattner43535a12005-11-09 04:45:33 +00002221 // If this is a constant subscript, handle it quickly.
2222 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002223 if (CI->getZExtValue() == 0) continue;
Reid Spencere63b6512006-12-31 05:55:36 +00002224 uint64_t Offs =
Evan Cheng8ec52832007-01-05 01:46:20 +00002225 TD->getTypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
Chris Lattner43535a12005-11-09 04:45:33 +00002226 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
2227 continue;
Chris Lattner7a60d912005-01-07 07:47:53 +00002228 }
Chris Lattner43535a12005-11-09 04:45:33 +00002229
2230 // N = N + Idx * ElementSize;
Owen Anderson20a631f2006-05-03 01:29:57 +00002231 uint64_t ElementSize = TD->getTypeSize(Ty);
Chris Lattner43535a12005-11-09 04:45:33 +00002232 SDOperand IdxN = getValue(Idx);
2233
2234 // If the index is smaller or larger than intptr_t, truncate or extend
2235 // it.
2236 if (IdxN.getValueType() < N.getValueType()) {
Reid Spencere63b6512006-12-31 05:55:36 +00002237 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
Chris Lattner43535a12005-11-09 04:45:33 +00002238 } else if (IdxN.getValueType() > N.getValueType())
2239 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
2240
2241 // If this is a multiply by a power of two, turn it into a shl
2242 // immediately. This is a very common case.
2243 if (isPowerOf2_64(ElementSize)) {
2244 unsigned Amt = Log2_64(ElementSize);
2245 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner41fd6d52005-11-09 16:50:40 +00002246 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner43535a12005-11-09 04:45:33 +00002247 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
2248 continue;
2249 }
2250
2251 SDOperand Scale = getIntPtrConstant(ElementSize);
2252 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
2253 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner7a60d912005-01-07 07:47:53 +00002254 }
2255 }
2256 setValue(&I, N);
2257}
2258
2259void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
2260 // If this is a fixed sized alloca in the entry block of the function,
2261 // allocate it statically on the stack.
2262 if (FuncInfo.StaticAllocaMap.count(&I))
2263 return; // getValue will auto-populate this.
2264
2265 const Type *Ty = I.getAllocatedType();
Owen Anderson20a631f2006-05-03 01:29:57 +00002266 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
Chris Lattner50ee0e42007-01-20 22:35:55 +00002267 unsigned Align =
Chris Lattner945e4372007-02-14 05:52:17 +00002268 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
Chris Lattner50ee0e42007-01-20 22:35:55 +00002269 I.getAlignment());
Chris Lattner7a60d912005-01-07 07:47:53 +00002270
2271 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattnereccb73d2005-01-22 23:04:37 +00002272 MVT::ValueType IntPtr = TLI.getPointerTy();
2273 if (IntPtr < AllocSize.getValueType())
2274 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
2275 else if (IntPtr > AllocSize.getValueType())
2276 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner7a60d912005-01-07 07:47:53 +00002277
Chris Lattnereccb73d2005-01-22 23:04:37 +00002278 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner7a60d912005-01-07 07:47:53 +00002279 getIntPtrConstant(TySize));
2280
2281 // Handle alignment. If the requested alignment is less than or equal to the
2282 // stack alignment, ignore it and round the size of the allocation up to the
2283 // stack alignment size. If the size is greater than the stack alignment, we
2284 // note this in the DYNAMIC_STACKALLOC node.
2285 unsigned StackAlign =
2286 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
2287 if (Align <= StackAlign) {
2288 Align = 0;
2289 // Add SA-1 to the size.
2290 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
2291 getIntPtrConstant(StackAlign-1));
2292 // Mask out the low bits for alignment purposes.
2293 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
2294 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
2295 }
2296
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002297 SDOperand Ops[] = { getRoot(), AllocSize, getIntPtrConstant(Align) };
Chris Lattnerbd887772006-08-14 23:53:35 +00002298 const MVT::ValueType *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
2299 MVT::Other);
2300 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
Chris Lattner79084302007-02-04 01:31:47 +00002301 setValue(&I, DSA);
2302 DAG.setRoot(DSA.getValue(1));
Chris Lattner7a60d912005-01-07 07:47:53 +00002303
2304 // Inform the Frame Information that we have just allocated a variable-sized
2305 // object.
2306 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
2307}
2308
Chris Lattner7a60d912005-01-07 07:47:53 +00002309void SelectionDAGLowering::visitLoad(LoadInst &I) {
2310 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukman835702a2005-04-21 22:36:52 +00002311
Chris Lattner4d9651c2005-01-17 22:19:26 +00002312 SDOperand Root;
2313 if (I.isVolatile())
2314 Root = getRoot();
2315 else {
2316 // Do not serialize non-volatile loads against each other.
2317 Root = DAG.getRoot();
2318 }
Chris Lattner4024c002006-03-15 22:19:46 +00002319
Evan Chenge71fe34d2006-10-09 20:57:25 +00002320 setValue(&I, getLoadFrom(I.getType(), Ptr, I.getOperand(0),
Christopher Lamb8af6d582007-04-22 23:15:30 +00002321 Root, I.isVolatile(), I.getAlignment()));
Chris Lattner4024c002006-03-15 22:19:46 +00002322}
2323
2324SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Chenge71fe34d2006-10-09 20:57:25 +00002325 const Value *SV, SDOperand Root,
Christopher Lamb8af6d582007-04-22 23:15:30 +00002326 bool isVolatile,
2327 unsigned Alignment) {
Nate Begemanb2e089c2005-11-19 00:36:38 +00002328 SDOperand L;
Reid Spencerd84d35b2007-02-15 02:26:10 +00002329 if (const VectorType *PTy = dyn_cast<VectorType>(Ty)) {
Nate Begeman07890bb2005-11-22 01:29:36 +00002330 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Evan Chenge71fe34d2006-10-09 20:57:25 +00002331 L = DAG.getVecLoad(PTy->getNumElements(), PVT, Root, Ptr,
2332 DAG.getSrcValue(SV));
Nate Begemanb2e089c2005-11-19 00:36:38 +00002333 } else {
Christopher Lamb8af6d582007-04-22 23:15:30 +00002334 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SV, 0,
2335 isVolatile, Alignment);
Nate Begemanb2e089c2005-11-19 00:36:38 +00002336 }
Chris Lattner4d9651c2005-01-17 22:19:26 +00002337
Chris Lattner4024c002006-03-15 22:19:46 +00002338 if (isVolatile)
Chris Lattner4d9651c2005-01-17 22:19:26 +00002339 DAG.setRoot(L.getValue(1));
2340 else
2341 PendingLoads.push_back(L.getValue(1));
Chris Lattner4024c002006-03-15 22:19:46 +00002342
2343 return L;
Chris Lattner7a60d912005-01-07 07:47:53 +00002344}
2345
2346
2347void SelectionDAGLowering::visitStore(StoreInst &I) {
2348 Value *SrcV = I.getOperand(0);
2349 SDOperand Src = getValue(SrcV);
2350 SDOperand Ptr = getValue(I.getOperand(1));
Evan Cheng258657e2006-12-20 01:27:29 +00002351 DAG.setRoot(DAG.getStore(getRoot(), Src, Ptr, I.getOperand(1), 0,
Christopher Lamb8af6d582007-04-22 23:15:30 +00002352 I.isVolatile(), I.getAlignment()));
Chris Lattner7a60d912005-01-07 07:47:53 +00002353}
2354
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002355/// IntrinsicCannotAccessMemory - Return true if the specified intrinsic cannot
2356/// access memory and has no other side effects at all.
2357static bool IntrinsicCannotAccessMemory(unsigned IntrinsicID) {
2358#define GET_NO_MEMORY_INTRINSICS
2359#include "llvm/Intrinsics.gen"
2360#undef GET_NO_MEMORY_INTRINSICS
2361 return false;
2362}
2363
Chris Lattnera9c59156b2006-04-02 03:41:14 +00002364// IntrinsicOnlyReadsMemory - Return true if the specified intrinsic doesn't
2365// have any side-effects or if it only reads memory.
2366static bool IntrinsicOnlyReadsMemory(unsigned IntrinsicID) {
2367#define GET_SIDE_EFFECT_INFO
2368#include "llvm/Intrinsics.gen"
2369#undef GET_SIDE_EFFECT_INFO
2370 return false;
2371}
2372
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002373/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2374/// node.
2375void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
2376 unsigned Intrinsic) {
Chris Lattner313229c2006-03-24 22:49:42 +00002377 bool HasChain = !IntrinsicCannotAccessMemory(Intrinsic);
Chris Lattnera9c59156b2006-04-02 03:41:14 +00002378 bool OnlyLoad = HasChain && IntrinsicOnlyReadsMemory(Intrinsic);
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002379
2380 // Build the operand list.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002381 SmallVector<SDOperand, 8> Ops;
Chris Lattnera9c59156b2006-04-02 03:41:14 +00002382 if (HasChain) { // If this intrinsic has side-effects, chainify it.
2383 if (OnlyLoad) {
2384 // We don't need to serialize loads against other loads.
2385 Ops.push_back(DAG.getRoot());
2386 } else {
2387 Ops.push_back(getRoot());
2388 }
2389 }
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002390
2391 // Add the intrinsic ID as an integer operand.
2392 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
2393
2394 // Add all operands of the call to the operand list.
2395 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2396 SDOperand Op = getValue(I.getOperand(i));
2397
Reid Spencer09575ba2007-02-15 03:39:18 +00002398 // If this is a vector type, force it to the right vector type.
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002399 if (Op.getValueType() == MVT::Vector) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00002400 const VectorType *OpTy = cast<VectorType>(I.getOperand(i)->getType());
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002401 MVT::ValueType EltVT = TLI.getValueType(OpTy->getElementType());
2402
2403 MVT::ValueType VVT = MVT::getVectorType(EltVT, OpTy->getNumElements());
2404 assert(VVT != MVT::Other && "Intrinsic uses a non-legal type?");
2405 Op = DAG.getNode(ISD::VBIT_CONVERT, VVT, Op);
2406 }
2407
2408 assert(TLI.isTypeLegal(Op.getValueType()) &&
2409 "Intrinsic uses a non-legal type?");
2410 Ops.push_back(Op);
2411 }
2412
2413 std::vector<MVT::ValueType> VTs;
2414 if (I.getType() != Type::VoidTy) {
2415 MVT::ValueType VT = TLI.getValueType(I.getType());
2416 if (VT == MVT::Vector) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00002417 const VectorType *DestTy = cast<VectorType>(I.getType());
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002418 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
2419
2420 VT = MVT::getVectorType(EltVT, DestTy->getNumElements());
2421 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
2422 }
2423
2424 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
2425 VTs.push_back(VT);
2426 }
2427 if (HasChain)
2428 VTs.push_back(MVT::Other);
2429
Chris Lattnerbd887772006-08-14 23:53:35 +00002430 const MVT::ValueType *VTList = DAG.getNodeValueTypes(VTs);
2431
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002432 // Create the node.
Chris Lattnere55d1712006-03-28 00:40:33 +00002433 SDOperand Result;
2434 if (!HasChain)
Chris Lattnerbd887772006-08-14 23:53:35 +00002435 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
2436 &Ops[0], Ops.size());
Chris Lattnere55d1712006-03-28 00:40:33 +00002437 else if (I.getType() != Type::VoidTy)
Chris Lattnerbd887772006-08-14 23:53:35 +00002438 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
2439 &Ops[0], Ops.size());
Chris Lattnere55d1712006-03-28 00:40:33 +00002440 else
Chris Lattnerbd887772006-08-14 23:53:35 +00002441 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
2442 &Ops[0], Ops.size());
Chris Lattnere55d1712006-03-28 00:40:33 +00002443
Chris Lattnera9c59156b2006-04-02 03:41:14 +00002444 if (HasChain) {
2445 SDOperand Chain = Result.getValue(Result.Val->getNumValues()-1);
2446 if (OnlyLoad)
2447 PendingLoads.push_back(Chain);
2448 else
2449 DAG.setRoot(Chain);
2450 }
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002451 if (I.getType() != Type::VoidTy) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00002452 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002453 MVT::ValueType EVT = TLI.getValueType(PTy->getElementType());
2454 Result = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Result,
2455 DAG.getConstant(PTy->getNumElements(), MVT::i32),
2456 DAG.getValueType(EVT));
2457 }
2458 setValue(&I, Result);
2459 }
2460}
2461
Duncan Sands4cb9eb82007-05-04 17:12:26 +00002462/// ExtractGlobalVariable - If C is a global variable, or a bitcast of one
2463/// (possibly constant folded), return it. Otherwise return NULL.
2464static GlobalVariable *ExtractGlobalVariable (Constant *C) {
2465 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
2466 return GV;
2467 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2468 if (CE->getOpcode() == Instruction::BitCast)
2469 return dyn_cast<GlobalVariable>(CE->getOperand(0));
2470 else if (CE->getOpcode() == Instruction::GetElementPtr) {
2471 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
2472 if (!CE->getOperand(i)->isNullValue())
2473 return NULL;
2474 return dyn_cast<GlobalVariable>(CE->getOperand(0));
2475 }
2476 }
2477 return NULL;
2478}
2479
Duncan Sands92bf2c62007-06-15 19:04:19 +00002480/// addCatchInfo - Extract the personality and type infos from an eh.selector
2481/// or eh.filter call, and add them to the specified machine basic block.
2482static void addCatchInfo(CallInst &I, MachineModuleInfo *MMI,
2483 MachineBasicBlock *MBB) {
2484 // Inform the MachineModuleInfo of the personality for this landing pad.
2485 ConstantExpr *CE = cast<ConstantExpr>(I.getOperand(2));
2486 assert(CE->getOpcode() == Instruction::BitCast &&
2487 isa<Function>(CE->getOperand(0)) &&
2488 "Personality should be a function");
2489 MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0)));
2490
2491 // Gather all the type infos for this landing pad and pass them along to
2492 // MachineModuleInfo.
2493 std::vector<GlobalVariable *> TyInfo;
2494 for (unsigned i = 3, N = I.getNumOperands(); i < N; ++i) {
2495 Constant *C = cast<Constant>(I.getOperand(i));
2496 GlobalVariable *GV = ExtractGlobalVariable(C);
2497 assert (GV || isa<ConstantPointerNull>(C) &&
2498 "TypeInfo must be a global variable or NULL");
2499 TyInfo.push_back(GV);
2500 }
2501 if (I.getCalledFunction()->getIntrinsicID() == Intrinsic::eh_filter)
2502 MMI->addFilterTypeInfo(MBB, TyInfo);
2503 else
2504 MMI->addCatchTypeInfo(MBB, TyInfo);
2505}
2506
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002507/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
2508/// we want to emit this as a call to a named external function, return the name
2509/// otherwise lower it and return null.
2510const char *
2511SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
2512 switch (Intrinsic) {
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002513 default:
2514 // By default, turn this into a target intrinsic node.
2515 visitTargetIntrinsic(I, Intrinsic);
2516 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002517 case Intrinsic::vastart: visitVAStart(I); return 0;
2518 case Intrinsic::vaend: visitVAEnd(I); return 0;
2519 case Intrinsic::vacopy: visitVACopy(I); return 0;
Nate Begemaneda59972007-01-29 22:58:52 +00002520 case Intrinsic::returnaddress:
2521 setValue(&I, DAG.getNode(ISD::RETURNADDR, TLI.getPointerTy(),
2522 getValue(I.getOperand(1))));
2523 return 0;
2524 case Intrinsic::frameaddress:
2525 setValue(&I, DAG.getNode(ISD::FRAMEADDR, TLI.getPointerTy(),
2526 getValue(I.getOperand(1))));
2527 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002528 case Intrinsic::setjmp:
Anton Korobeynikov3b7c2572006-12-10 23:12:42 +00002529 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002530 break;
2531 case Intrinsic::longjmp:
Anton Korobeynikov3b7c2572006-12-10 23:12:42 +00002532 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002533 break;
Chris Lattner093c1592006-03-03 00:00:25 +00002534 case Intrinsic::memcpy_i32:
2535 case Intrinsic::memcpy_i64:
2536 visitMemIntrinsic(I, ISD::MEMCPY);
2537 return 0;
2538 case Intrinsic::memset_i32:
2539 case Intrinsic::memset_i64:
2540 visitMemIntrinsic(I, ISD::MEMSET);
2541 return 0;
2542 case Intrinsic::memmove_i32:
2543 case Intrinsic::memmove_i64:
2544 visitMemIntrinsic(I, ISD::MEMMOVE);
2545 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002546
Chris Lattner5d4e61d2005-12-13 17:40:33 +00002547 case Intrinsic::dbg_stoppoint: {
Jim Laskeyc56315c2007-01-26 21:22:28 +00002548 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskeya8bdac82006-03-23 18:06:46 +00002549 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Jim Laskeyc56315c2007-01-26 21:22:28 +00002550 if (MMI && SPI.getContext() && MMI->Verify(SPI.getContext())) {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002551 SDOperand Ops[5];
Chris Lattner435b4022005-11-29 06:21:05 +00002552
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002553 Ops[0] = getRoot();
2554 Ops[1] = getValue(SPI.getLineValue());
2555 Ops[2] = getValue(SPI.getColumnValue());
Chris Lattner435b4022005-11-29 06:21:05 +00002556
Jim Laskeyc56315c2007-01-26 21:22:28 +00002557 DebugInfoDesc *DD = MMI->getDescFor(SPI.getContext());
Jim Laskey5995d012006-02-11 01:01:30 +00002558 assert(DD && "Not a debug information descriptor");
Jim Laskeya8bdac82006-03-23 18:06:46 +00002559 CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
2560
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002561 Ops[3] = DAG.getString(CompileUnit->getFileName());
2562 Ops[4] = DAG.getString(CompileUnit->getDirectory());
Jim Laskey5995d012006-02-11 01:01:30 +00002563
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002564 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops, 5));
Chris Lattner5d4e61d2005-12-13 17:40:33 +00002565 }
Jim Laskeya8bdac82006-03-23 18:06:46 +00002566
Chris Lattnerf2b62f32005-11-16 07:22:30 +00002567 return 0;
Chris Lattner435b4022005-11-29 06:21:05 +00002568 }
Jim Laskeya8bdac82006-03-23 18:06:46 +00002569 case Intrinsic::dbg_region_start: {
Jim Laskeyc56315c2007-01-26 21:22:28 +00002570 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskeya8bdac82006-03-23 18:06:46 +00002571 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
Jim Laskeyc56315c2007-01-26 21:22:28 +00002572 if (MMI && RSI.getContext() && MMI->Verify(RSI.getContext())) {
2573 unsigned LabelID = MMI->RecordRegionStart(RSI.getContext());
Jim Laskeyf9e54452007-01-26 14:34:52 +00002574 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002575 DAG.getConstant(LabelID, MVT::i32)));
Jim Laskeya8bdac82006-03-23 18:06:46 +00002576 }
2577
Chris Lattnerf2b62f32005-11-16 07:22:30 +00002578 return 0;
Jim Laskeya8bdac82006-03-23 18:06:46 +00002579 }
2580 case Intrinsic::dbg_region_end: {
Jim Laskeyc56315c2007-01-26 21:22:28 +00002581 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskeya8bdac82006-03-23 18:06:46 +00002582 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
Jim Laskeyc56315c2007-01-26 21:22:28 +00002583 if (MMI && REI.getContext() && MMI->Verify(REI.getContext())) {
2584 unsigned LabelID = MMI->RecordRegionEnd(REI.getContext());
Jim Laskeyf9e54452007-01-26 14:34:52 +00002585 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other,
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002586 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
Jim Laskeya8bdac82006-03-23 18:06:46 +00002587 }
2588
Chris Lattnerf2b62f32005-11-16 07:22:30 +00002589 return 0;
Jim Laskeya8bdac82006-03-23 18:06:46 +00002590 }
2591 case Intrinsic::dbg_func_start: {
Jim Laskeyc56315c2007-01-26 21:22:28 +00002592 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskeya8bdac82006-03-23 18:06:46 +00002593 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
Jim Laskeyc56315c2007-01-26 21:22:28 +00002594 if (MMI && FSI.getSubprogram() &&
2595 MMI->Verify(FSI.getSubprogram())) {
2596 unsigned LabelID = MMI->RecordRegionStart(FSI.getSubprogram());
Jim Laskeyf9e54452007-01-26 14:34:52 +00002597 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other,
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002598 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
Jim Laskeya8bdac82006-03-23 18:06:46 +00002599 }
2600
Chris Lattnerf2b62f32005-11-16 07:22:30 +00002601 return 0;
Jim Laskeya8bdac82006-03-23 18:06:46 +00002602 }
2603 case Intrinsic::dbg_declare: {
Jim Laskeyc56315c2007-01-26 21:22:28 +00002604 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskeya8bdac82006-03-23 18:06:46 +00002605 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
Jim Laskeyc56315c2007-01-26 21:22:28 +00002606 if (MMI && DI.getVariable() && MMI->Verify(DI.getVariable())) {
Jim Laskey53f1ecc2006-03-24 09:50:27 +00002607 SDOperand AddressOp = getValue(DI.getAddress());
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002608 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(AddressOp))
Jim Laskeyc56315c2007-01-26 21:22:28 +00002609 MMI->RecordVariable(DI.getVariable(), FI->getIndex());
Jim Laskeya8bdac82006-03-23 18:06:46 +00002610 }
2611
2612 return 0;
2613 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002614
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002615 case Intrinsic::eh_exception: {
2616 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2617
Duncan Sands74137362007-06-13 16:53:21 +00002618 if (ExceptionHandling && MMI) {
Jim Laskey504e9942007-02-22 15:38:06 +00002619 // Mark exception register as live in.
2620 unsigned Reg = TLI.getExceptionAddressRegister();
2621 if (Reg) CurMBB->addLiveIn(Reg);
Duncan Sands61166502007-06-06 10:05:18 +00002622
Jim Laskey504e9942007-02-22 15:38:06 +00002623 // Insert the EXCEPTIONADDR instruction.
2624 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
2625 SDOperand Ops[1];
2626 Ops[0] = DAG.getRoot();
2627 SDOperand Op = DAG.getNode(ISD::EXCEPTIONADDR, VTs, Ops, 1);
2628 setValue(&I, Op);
2629 DAG.setRoot(Op.getValue(1));
Jim Laskeye1d1c052007-02-24 09:45:44 +00002630 } else {
Jim Laskeycf465fc2007-02-28 18:37:04 +00002631 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
Jim Laskey504e9942007-02-22 15:38:06 +00002632 }
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002633 return 0;
2634 }
2635
Jim Laskeyd5453d72007-03-01 20:24:30 +00002636 case Intrinsic::eh_selector:
2637 case Intrinsic::eh_filter:{
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002638 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002639
Duncan Sands92bf2c62007-06-15 19:04:19 +00002640 if (ExceptionHandling && MMI) {
2641 if (CurMBB->isLandingPad())
2642 addCatchInfo(I, MMI, CurMBB);
2643#ifndef NDEBUG
Duncan Sandsc063f5f2007-06-02 16:53:42 +00002644 else
Duncan Sands92bf2c62007-06-15 19:04:19 +00002645 FuncInfo.CatchInfoLost.insert(&I);
2646#endif
Duncan Sands61166502007-06-06 10:05:18 +00002647
Jim Laskey504e9942007-02-22 15:38:06 +00002648 // Mark exception selector register as live in.
2649 unsigned Reg = TLI.getExceptionSelectorRegister();
2650 if (Reg) CurMBB->addLiveIn(Reg);
2651
2652 // Insert the EHSELECTION instruction.
Anton Korobeynikov11940fb2007-05-02 22:15:48 +00002653 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
Jim Laskey504e9942007-02-22 15:38:06 +00002654 SDOperand Ops[2];
2655 Ops[0] = getValue(I.getOperand(1));
2656 Ops[1] = getRoot();
2657 SDOperand Op = DAG.getNode(ISD::EHSELECTION, VTs, Ops, 2);
2658 setValue(&I, Op);
2659 DAG.setRoot(Op.getValue(1));
Jim Laskeye1d1c052007-02-24 09:45:44 +00002660 } else {
Anton Korobeynikov11940fb2007-05-02 22:15:48 +00002661 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
Jim Laskey504e9942007-02-22 15:38:06 +00002662 }
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002663
2664 return 0;
2665 }
2666
2667 case Intrinsic::eh_typeid_for: {
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002668 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002669
Jim Laskey504e9942007-02-22 15:38:06 +00002670 if (MMI) {
2671 // Find the type id for the given typeinfo.
Duncan Sands4cb9eb82007-05-04 17:12:26 +00002672 Constant *C = cast<Constant>(I.getOperand(1));
2673 GlobalVariable *GV = ExtractGlobalVariable(C);
Duncan Sands706421e2007-06-01 08:18:30 +00002674 assert (GV || isa<ConstantPointerNull>(C) &&
Duncan Sands4cb9eb82007-05-04 17:12:26 +00002675 "TypeInfo must be a global variable or NULL");
2676
Jim Laskey504e9942007-02-22 15:38:06 +00002677 unsigned TypeID = MMI->getTypeIDFor(GV);
2678 setValue(&I, DAG.getConstant(TypeID, MVT::i32));
Jim Laskeye1d1c052007-02-24 09:45:44 +00002679 } else {
2680 setValue(&I, DAG.getConstant(0, MVT::i32));
Jim Laskey504e9942007-02-22 15:38:06 +00002681 }
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002682
2683 return 0;
2684 }
2685
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00002686 case Intrinsic::sqrt_f32:
2687 case Intrinsic::sqrt_f64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002688 setValue(&I, DAG.getNode(ISD::FSQRT,
2689 getValue(I.getOperand(1)).getValueType(),
2690 getValue(I.getOperand(1))));
2691 return 0;
Chris Lattnerf0359b32006-09-09 06:03:30 +00002692 case Intrinsic::powi_f32:
2693 case Intrinsic::powi_f64:
2694 setValue(&I, DAG.getNode(ISD::FPOWI,
2695 getValue(I.getOperand(1)).getValueType(),
2696 getValue(I.getOperand(1)),
2697 getValue(I.getOperand(2))));
2698 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002699 case Intrinsic::pcmarker: {
2700 SDOperand Tmp = getValue(I.getOperand(1));
2701 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
2702 return 0;
2703 }
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00002704 case Intrinsic::readcyclecounter: {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002705 SDOperand Op = getRoot();
Chris Lattnerbd887772006-08-14 23:53:35 +00002706 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
2707 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
2708 &Op, 1);
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00002709 setValue(&I, Tmp);
2710 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth01aa5632005-11-11 16:47:30 +00002711 return 0;
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00002712 }
Chris Lattnerf269d842007-04-10 03:20:39 +00002713 case Intrinsic::part_select: {
Reid Spencer85460ac2007-04-05 01:20:18 +00002714 // Currently not implemented: just abort
Reid Spencerc6251a72007-04-12 02:48:46 +00002715 assert(0 && "part_select intrinsic not implemented");
2716 abort();
2717 }
2718 case Intrinsic::part_set: {
2719 // Currently not implemented: just abort
2720 assert(0 && "part_set intrinsic not implemented");
Reid Spencer85460ac2007-04-05 01:20:18 +00002721 abort();
Reid Spencercce90f52007-04-04 23:48:25 +00002722 }
Reid Spencer3a0843e2007-04-01 07:34:11 +00002723 case Intrinsic::bswap:
Nate Begeman2fba8a32006-01-14 03:14:10 +00002724 setValue(&I, DAG.getNode(ISD::BSWAP,
2725 getValue(I.getOperand(1)).getValueType(),
2726 getValue(I.getOperand(1))));
2727 return 0;
Reid Spencer3a0843e2007-04-01 07:34:11 +00002728 case Intrinsic::cttz: {
2729 SDOperand Arg = getValue(I.getOperand(1));
2730 MVT::ValueType Ty = Arg.getValueType();
2731 SDOperand result = DAG.getNode(ISD::CTTZ, Ty, Arg);
2732 if (Ty < MVT::i32)
2733 result = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, result);
2734 else if (Ty > MVT::i32)
2735 result = DAG.getNode(ISD::TRUNCATE, MVT::i32, result);
2736 setValue(&I, result);
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002737 return 0;
Reid Spencer3a0843e2007-04-01 07:34:11 +00002738 }
2739 case Intrinsic::ctlz: {
2740 SDOperand Arg = getValue(I.getOperand(1));
2741 MVT::ValueType Ty = Arg.getValueType();
2742 SDOperand result = DAG.getNode(ISD::CTLZ, Ty, Arg);
2743 if (Ty < MVT::i32)
2744 result = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, result);
2745 else if (Ty > MVT::i32)
2746 result = DAG.getNode(ISD::TRUNCATE, MVT::i32, result);
2747 setValue(&I, result);
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002748 return 0;
Reid Spencer3a0843e2007-04-01 07:34:11 +00002749 }
2750 case Intrinsic::ctpop: {
2751 SDOperand Arg = getValue(I.getOperand(1));
2752 MVT::ValueType Ty = Arg.getValueType();
2753 SDOperand result = DAG.getNode(ISD::CTPOP, Ty, Arg);
2754 if (Ty < MVT::i32)
2755 result = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, result);
2756 else if (Ty > MVT::i32)
2757 result = DAG.getNode(ISD::TRUNCATE, MVT::i32, result);
2758 setValue(&I, result);
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002759 return 0;
Reid Spencer3a0843e2007-04-01 07:34:11 +00002760 }
Chris Lattnerb3266452006-01-13 02:50:02 +00002761 case Intrinsic::stacksave: {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002762 SDOperand Op = getRoot();
Chris Lattnerbd887772006-08-14 23:53:35 +00002763 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE,
2764 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
Chris Lattnerb3266452006-01-13 02:50:02 +00002765 setValue(&I, Tmp);
2766 DAG.setRoot(Tmp.getValue(1));
2767 return 0;
2768 }
Chris Lattnerdeda32a2006-01-23 05:22:07 +00002769 case Intrinsic::stackrestore: {
2770 SDOperand Tmp = getValue(I.getOperand(1));
2771 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
Chris Lattnerb3266452006-01-13 02:50:02 +00002772 return 0;
Chris Lattnerdeda32a2006-01-23 05:22:07 +00002773 }
Chris Lattner9e8b6332005-12-12 22:51:16 +00002774 case Intrinsic::prefetch:
2775 // FIXME: Currently discarding prefetches.
2776 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002777 }
2778}
2779
2780
Jim Laskey31fef782007-02-23 21:45:01 +00002781void SelectionDAGLowering::LowerCallTo(Instruction &I,
2782 const Type *CalledValueTy,
2783 unsigned CallingConv,
2784 bool IsTailCall,
Anton Korobeynikov3b327822007-05-23 11:08:31 +00002785 SDOperand Callee, unsigned OpIdx,
2786 MachineBasicBlock *LandingPad) {
Jim Laskey31fef782007-02-23 21:45:01 +00002787 const PointerType *PT = cast<PointerType>(CalledValueTy);
Jim Laskey504e9942007-02-22 15:38:06 +00002788 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Reid Spencer71b79e32007-04-09 06:17:21 +00002789 const ParamAttrsList *Attrs = FTy->getParamAttrs();
Anton Korobeynikov3b327822007-05-23 11:08:31 +00002790 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2791 unsigned BeginLabel = 0, EndLabel = 0;
2792
Jim Laskey504e9942007-02-22 15:38:06 +00002793 TargetLowering::ArgListTy Args;
2794 TargetLowering::ArgListEntry Entry;
2795 Args.reserve(I.getNumOperands());
2796 for (unsigned i = OpIdx, e = I.getNumOperands(); i != e; ++i) {
2797 Value *Arg = I.getOperand(i);
2798 SDOperand ArgNode = getValue(Arg);
2799 Entry.Node = ArgNode; Entry.Ty = Arg->getType();
Duncan Sands671e8c42007-05-07 20:49:28 +00002800
2801 unsigned attrInd = i - OpIdx + 1;
2802 Entry.isSExt = Attrs && Attrs->paramHasAttr(attrInd, ParamAttr::SExt);
2803 Entry.isZExt = Attrs && Attrs->paramHasAttr(attrInd, ParamAttr::ZExt);
2804 Entry.isInReg = Attrs && Attrs->paramHasAttr(attrInd, ParamAttr::InReg);
2805 Entry.isSRet = Attrs && Attrs->paramHasAttr(attrInd, ParamAttr::StructRet);
Jim Laskey504e9942007-02-22 15:38:06 +00002806 Args.push_back(Entry);
2807 }
2808
Duncan Sands61166502007-06-06 10:05:18 +00002809 if (ExceptionHandling && MMI) {
Anton Korobeynikov3b327822007-05-23 11:08:31 +00002810 // Insert a label before the invoke call to mark the try range. This can be
2811 // used to detect deletion of the invoke via the MachineModuleInfo.
2812 BeginLabel = MMI->NextLabelID();
2813 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
2814 DAG.getConstant(BeginLabel, MVT::i32)));
2815 }
2816
Jim Laskey504e9942007-02-22 15:38:06 +00002817 std::pair<SDOperand,SDOperand> Result =
2818 TLI.LowerCallTo(getRoot(), I.getType(),
Reid Spencera472f662007-04-11 02:44:20 +00002819 Attrs && Attrs->paramHasAttr(0, ParamAttr::SExt),
Jim Laskey31fef782007-02-23 21:45:01 +00002820 FTy->isVarArg(), CallingConv, IsTailCall,
Jim Laskey504e9942007-02-22 15:38:06 +00002821 Callee, Args, DAG);
2822 if (I.getType() != Type::VoidTy)
2823 setValue(&I, Result.first);
2824 DAG.setRoot(Result.second);
Anton Korobeynikov3b327822007-05-23 11:08:31 +00002825
Duncan Sands61166502007-06-06 10:05:18 +00002826 if (ExceptionHandling && MMI) {
Anton Korobeynikov3b327822007-05-23 11:08:31 +00002827 // Insert a label at the end of the invoke call to mark the try range. This
2828 // can be used to detect deletion of the invoke via the MachineModuleInfo.
2829 EndLabel = MMI->NextLabelID();
2830 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
2831 DAG.getConstant(EndLabel, MVT::i32)));
2832
2833 // Inform MachineModuleInfo of range.
2834 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
2835 }
Jim Laskey504e9942007-02-22 15:38:06 +00002836}
2837
2838
Chris Lattner7a60d912005-01-07 07:47:53 +00002839void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner18d2b342005-01-08 22:48:57 +00002840 const char *RenameFn = 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002841 if (Function *F = I.getCalledFunction()) {
Reid Spencer5301e7c2007-01-30 20:08:39 +00002842 if (F->isDeclaration())
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002843 if (unsigned IID = F->getIntrinsicID()) {
2844 RenameFn = visitIntrinsicCall(I, IID);
2845 if (!RenameFn)
2846 return;
2847 } else { // Not an LLVM intrinsic.
2848 const std::string &Name = F->getName();
Chris Lattner5c1ba2a2006-03-05 05:09:38 +00002849 if (Name[0] == 'c' && (Name == "copysign" || Name == "copysignf")) {
2850 if (I.getNumOperands() == 3 && // Basic sanity checks.
2851 I.getOperand(1)->getType()->isFloatingPoint() &&
2852 I.getType() == I.getOperand(1)->getType() &&
2853 I.getType() == I.getOperand(2)->getType()) {
2854 SDOperand LHS = getValue(I.getOperand(1));
2855 SDOperand RHS = getValue(I.getOperand(2));
2856 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
2857 LHS, RHS));
2858 return;
2859 }
2860 } else if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
Chris Lattner0c140002005-04-02 05:26:53 +00002861 if (I.getNumOperands() == 2 && // Basic sanity checks.
2862 I.getOperand(1)->getType()->isFloatingPoint() &&
2863 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002864 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner0c140002005-04-02 05:26:53 +00002865 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
2866 return;
2867 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002868 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
Chris Lattner80026402005-04-30 04:43:14 +00002869 if (I.getNumOperands() == 2 && // Basic sanity checks.
2870 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner1784a9d22006-02-14 05:39:35 +00002871 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002872 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +00002873 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
2874 return;
2875 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002876 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
Chris Lattner80026402005-04-30 04:43:14 +00002877 if (I.getNumOperands() == 2 && // Basic sanity checks.
2878 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner1784a9d22006-02-14 05:39:35 +00002879 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002880 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +00002881 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
2882 return;
2883 }
2884 }
Chris Lattnere4f71d02005-05-14 13:56:55 +00002885 }
Chris Lattner476e67b2006-01-26 22:24:51 +00002886 } else if (isa<InlineAsm>(I.getOperand(0))) {
2887 visitInlineAsm(I);
2888 return;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002889 }
Misha Brukman835702a2005-04-21 22:36:52 +00002890
Chris Lattner18d2b342005-01-08 22:48:57 +00002891 SDOperand Callee;
2892 if (!RenameFn)
2893 Callee = getValue(I.getOperand(0));
2894 else
2895 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Anton Korobeynikov3b327822007-05-23 11:08:31 +00002896
Jim Laskey31fef782007-02-23 21:45:01 +00002897 LowerCallTo(I, I.getCalledValue()->getType(),
Anton Korobeynikov3b327822007-05-23 11:08:31 +00002898 I.getCallingConv(),
2899 I.isTailCall(),
2900 Callee,
2901 1);
Chris Lattner7a60d912005-01-07 07:47:53 +00002902}
2903
Jim Laskey504e9942007-02-22 15:38:06 +00002904
Chris Lattner6f87d182006-02-22 22:37:12 +00002905SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002906 SDOperand &Chain, SDOperand &Flag)const{
Chris Lattner6f87d182006-02-22 22:37:12 +00002907 SDOperand Val = DAG.getCopyFromReg(Chain, Regs[0], RegVT, Flag);
2908 Chain = Val.getValue(1);
2909 Flag = Val.getValue(2);
2910
2911 // If the result was expanded, copy from the top part.
2912 if (Regs.size() > 1) {
2913 assert(Regs.size() == 2 &&
2914 "Cannot expand to more than 2 elts yet!");
2915 SDOperand Hi = DAG.getCopyFromReg(Chain, Regs[1], RegVT, Flag);
Evan Chengf80dfa82006-10-04 22:23:53 +00002916 Chain = Hi.getValue(1);
2917 Flag = Hi.getValue(2);
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002918 if (DAG.getTargetLoweringInfo().isLittleEndian())
2919 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi);
2920 else
2921 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Hi, Val);
Chris Lattner6f87d182006-02-22 22:37:12 +00002922 }
Chris Lattner1558fc62006-02-01 18:59:47 +00002923
Chris Lattner705948d2006-06-08 18:22:48 +00002924 // Otherwise, if the return value was promoted or extended, truncate it to the
Chris Lattner6f87d182006-02-22 22:37:12 +00002925 // appropriate type.
2926 if (RegVT == ValueVT)
2927 return Val;
2928
Chris Lattner77f04792007-03-25 05:00:54 +00002929 if (MVT::isVector(RegVT)) {
2930 assert(ValueVT == MVT::Vector && "Unknown vector conversion!");
2931 return DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Val,
2932 DAG.getConstant(MVT::getVectorNumElements(RegVT),
2933 MVT::i32),
Dan Gohman5c441312007-06-14 22:58:02 +00002934 DAG.getValueType(MVT::getVectorElementType(RegVT)));
Chris Lattner77f04792007-03-25 05:00:54 +00002935 }
2936
Chris Lattner705948d2006-06-08 18:22:48 +00002937 if (MVT::isInteger(RegVT)) {
2938 if (ValueVT < RegVT)
2939 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
2940 else
2941 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
Chris Lattner705948d2006-06-08 18:22:48 +00002942 }
Chris Lattner77f04792007-03-25 05:00:54 +00002943
2944 assert(MVT::isFloatingPoint(RegVT) && MVT::isFloatingPoint(ValueVT));
2945 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
Chris Lattner6f87d182006-02-22 22:37:12 +00002946}
2947
Chris Lattner571d9642006-02-23 19:21:04 +00002948/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
2949/// specified value into the registers specified by this object. This uses
2950/// Chain/Flag as the input and updates them for the output Chain/Flag.
2951void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Evan Chengef9e07d2006-06-15 08:11:54 +00002952 SDOperand &Chain, SDOperand &Flag,
2953 MVT::ValueType PtrVT) const {
Chris Lattner571d9642006-02-23 19:21:04 +00002954 if (Regs.size() == 1) {
2955 // If there is a single register and the types differ, this must be
2956 // a promotion.
2957 if (RegVT != ValueVT) {
Chris Lattner77f04792007-03-25 05:00:54 +00002958 if (MVT::isVector(RegVT)) {
2959 assert(Val.getValueType() == MVT::Vector &&"Not a vector-vector cast?");
2960 Val = DAG.getNode(ISD::VBIT_CONVERT, RegVT, Val);
Chris Lattner7b2decf2007-04-09 05:31:20 +00002961 } else if (MVT::isInteger(RegVT) && MVT::isInteger(Val.getValueType())) {
Chris Lattnerc03a9252006-06-08 18:27:11 +00002962 if (RegVT < ValueVT)
2963 Val = DAG.getNode(ISD::TRUNCATE, RegVT, Val);
2964 else
2965 Val = DAG.getNode(ISD::ANY_EXTEND, RegVT, Val);
Chris Lattner7b2decf2007-04-09 05:31:20 +00002966 } else if (MVT::isFloatingPoint(RegVT) &&
2967 MVT::isFloatingPoint(Val.getValueType())) {
Chris Lattner571d9642006-02-23 19:21:04 +00002968 Val = DAG.getNode(ISD::FP_EXTEND, RegVT, Val);
Chris Lattner7b2decf2007-04-09 05:31:20 +00002969 } else if (MVT::getSizeInBits(RegVT) ==
2970 MVT::getSizeInBits(Val.getValueType())) {
2971 Val = DAG.getNode(ISD::BIT_CONVERT, RegVT, Val);
2972 } else {
2973 assert(0 && "Unknown mismatch!");
2974 }
Chris Lattner571d9642006-02-23 19:21:04 +00002975 }
2976 Chain = DAG.getCopyToReg(Chain, Regs[0], Val, Flag);
2977 Flag = Chain.getValue(1);
2978 } else {
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002979 std::vector<unsigned> R(Regs);
2980 if (!DAG.getTargetLoweringInfo().isLittleEndian())
2981 std::reverse(R.begin(), R.end());
2982
2983 for (unsigned i = 0, e = R.size(); i != e; ++i) {
Chris Lattner571d9642006-02-23 19:21:04 +00002984 SDOperand Part = DAG.getNode(ISD::EXTRACT_ELEMENT, RegVT, Val,
Evan Chengef9e07d2006-06-15 08:11:54 +00002985 DAG.getConstant(i, PtrVT));
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002986 Chain = DAG.getCopyToReg(Chain, R[i], Part, Flag);
Chris Lattner571d9642006-02-23 19:21:04 +00002987 Flag = Chain.getValue(1);
2988 }
2989 }
2990}
Chris Lattner6f87d182006-02-22 22:37:12 +00002991
Chris Lattner571d9642006-02-23 19:21:04 +00002992/// AddInlineAsmOperands - Add this value to the specified inlineasm node
2993/// operand list. This adds the code marker and includes the number of
2994/// values added into it.
2995void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002996 std::vector<SDOperand> &Ops) const {
Chris Lattnerb49917d2007-04-09 00:33:58 +00002997 MVT::ValueType IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
2998 Ops.push_back(DAG.getTargetConstant(Code | (Regs.size() << 3), IntPtrTy));
Chris Lattner571d9642006-02-23 19:21:04 +00002999 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
3000 Ops.push_back(DAG.getRegister(Regs[i], RegVT));
3001}
Chris Lattner6f87d182006-02-22 22:37:12 +00003002
3003/// isAllocatableRegister - If the specified register is safe to allocate,
3004/// i.e. it isn't a stack pointer or some other special register, return the
3005/// register class for the register. Otherwise, return null.
3006static const TargetRegisterClass *
Chris Lattnerb1124f32006-02-22 23:09:03 +00003007isAllocatableRegister(unsigned Reg, MachineFunction &MF,
3008 const TargetLowering &TLI, const MRegisterInfo *MRI) {
Chris Lattnerbec582f2006-04-02 00:24:45 +00003009 MVT::ValueType FoundVT = MVT::Other;
3010 const TargetRegisterClass *FoundRC = 0;
Chris Lattnerb1124f32006-02-22 23:09:03 +00003011 for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
3012 E = MRI->regclass_end(); RCI != E; ++RCI) {
Chris Lattnerbec582f2006-04-02 00:24:45 +00003013 MVT::ValueType ThisVT = MVT::Other;
3014
Chris Lattnerb1124f32006-02-22 23:09:03 +00003015 const TargetRegisterClass *RC = *RCI;
3016 // If none of the the value types for this register class are valid, we
3017 // can't use it. For example, 64-bit reg classes on 32-bit targets.
Chris Lattnerb1124f32006-02-22 23:09:03 +00003018 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
3019 I != E; ++I) {
3020 if (TLI.isTypeLegal(*I)) {
Chris Lattnerbec582f2006-04-02 00:24:45 +00003021 // If we have already found this register in a different register class,
3022 // choose the one with the largest VT specified. For example, on
3023 // PowerPC, we favor f64 register classes over f32.
3024 if (FoundVT == MVT::Other ||
3025 MVT::getSizeInBits(FoundVT) < MVT::getSizeInBits(*I)) {
3026 ThisVT = *I;
3027 break;
3028 }
Chris Lattnerb1124f32006-02-22 23:09:03 +00003029 }
3030 }
3031
Chris Lattnerbec582f2006-04-02 00:24:45 +00003032 if (ThisVT == MVT::Other) continue;
Chris Lattnerb1124f32006-02-22 23:09:03 +00003033
Chris Lattner6f87d182006-02-22 22:37:12 +00003034 // NOTE: This isn't ideal. In particular, this might allocate the
3035 // frame pointer in functions that need it (due to them not being taken
3036 // out of allocation, because a variable sized allocation hasn't been seen
3037 // yet). This is a slight code pessimization, but should still work.
Chris Lattnerb1124f32006-02-22 23:09:03 +00003038 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
3039 E = RC->allocation_order_end(MF); I != E; ++I)
Chris Lattnerbec582f2006-04-02 00:24:45 +00003040 if (*I == Reg) {
3041 // We found a matching register class. Keep looking at others in case
3042 // we find one with larger registers that this physreg is also in.
3043 FoundRC = RC;
3044 FoundVT = ThisVT;
3045 break;
3046 }
Chris Lattner1558fc62006-02-01 18:59:47 +00003047 }
Chris Lattnerbec582f2006-04-02 00:24:45 +00003048 return FoundRC;
Chris Lattner6f87d182006-02-22 22:37:12 +00003049}
3050
Chris Lattner1558fc62006-02-01 18:59:47 +00003051
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003052namespace {
3053/// AsmOperandInfo - This contains information for each constraint that we are
3054/// lowering.
3055struct AsmOperandInfo : public InlineAsm::ConstraintInfo {
3056 /// ConstraintCode - This contains the actual string for the code, like "m".
3057 std::string ConstraintCode;
Chris Lattnerb2e55562007-04-28 21:01:43 +00003058
3059 /// ConstraintType - Information about the constraint code, e.g. Register,
3060 /// RegisterClass, Memory, Other, Unknown.
3061 TargetLowering::ConstraintType ConstraintType;
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003062
3063 /// CallOperand/CallOperandval - If this is the result output operand or a
3064 /// clobber, this is null, otherwise it is the incoming operand to the
3065 /// CallInst. This gets modified as the asm is processed.
3066 SDOperand CallOperand;
3067 Value *CallOperandVal;
3068
3069 /// ConstraintVT - The ValueType for the operand value.
3070 MVT::ValueType ConstraintVT;
3071
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003072 /// AssignedRegs - If this is a register or register class operand, this
3073 /// contains the set of register corresponding to the operand.
3074 RegsForValue AssignedRegs;
3075
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003076 AsmOperandInfo(const InlineAsm::ConstraintInfo &info)
Chris Lattnerb2e55562007-04-28 21:01:43 +00003077 : InlineAsm::ConstraintInfo(info),
3078 ConstraintType(TargetLowering::C_Unknown),
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003079 CallOperand(0,0), CallOperandVal(0), ConstraintVT(MVT::Other) {
3080 }
Chris Lattneref073322007-04-30 17:16:27 +00003081
3082 void ComputeConstraintToUse(const TargetLowering &TLI);
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003083
3084 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
3085 /// busy in OutputRegs/InputRegs.
3086 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
3087 std::set<unsigned> &OutputRegs,
3088 std::set<unsigned> &InputRegs) const {
3089 if (isOutReg)
3090 OutputRegs.insert(AssignedRegs.Regs.begin(), AssignedRegs.Regs.end());
3091 if (isInReg)
3092 InputRegs.insert(AssignedRegs.Regs.begin(), AssignedRegs.Regs.end());
3093 }
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003094};
3095} // end anon namespace.
Chris Lattner6f87d182006-02-22 22:37:12 +00003096
Chris Lattneref073322007-04-30 17:16:27 +00003097/// getConstraintGenerality - Return an integer indicating how general CT is.
3098static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT) {
3099 switch (CT) {
3100 default: assert(0 && "Unknown constraint type!");
3101 case TargetLowering::C_Other:
3102 case TargetLowering::C_Unknown:
3103 return 0;
3104 case TargetLowering::C_Register:
3105 return 1;
3106 case TargetLowering::C_RegisterClass:
3107 return 2;
3108 case TargetLowering::C_Memory:
3109 return 3;
3110 }
3111}
3112
3113void AsmOperandInfo::ComputeConstraintToUse(const TargetLowering &TLI) {
3114 assert(!Codes.empty() && "Must have at least one constraint");
3115
3116 std::string *Current = &Codes[0];
3117 TargetLowering::ConstraintType CurType = TLI.getConstraintType(*Current);
3118 if (Codes.size() == 1) { // Single-letter constraints ('r') are very common.
3119 ConstraintCode = *Current;
3120 ConstraintType = CurType;
3121 return;
3122 }
3123
3124 unsigned CurGenerality = getConstraintGenerality(CurType);
3125
3126 // If we have multiple constraints, try to pick the most general one ahead
3127 // of time. This isn't a wonderful solution, but handles common cases.
3128 for (unsigned j = 1, e = Codes.size(); j != e; ++j) {
3129 TargetLowering::ConstraintType ThisType = TLI.getConstraintType(Codes[j]);
3130 unsigned ThisGenerality = getConstraintGenerality(ThisType);
3131 if (ThisGenerality > CurGenerality) {
3132 // This constraint letter is more general than the previous one,
3133 // use it.
3134 CurType = ThisType;
3135 Current = &Codes[j];
3136 CurGenerality = ThisGenerality;
3137 }
3138 }
3139
3140 ConstraintCode = *Current;
3141 ConstraintType = CurType;
3142}
3143
3144
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003145void SelectionDAGLowering::
3146GetRegistersForValue(AsmOperandInfo &OpInfo, bool HasEarlyClobber,
Chris Lattner4333f8b2007-04-30 17:29:31 +00003147 std::set<unsigned> &OutputRegs,
3148 std::set<unsigned> &InputRegs) {
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003149 // Compute whether this value requires an input register, an output register,
3150 // or both.
3151 bool isOutReg = false;
3152 bool isInReg = false;
3153 switch (OpInfo.Type) {
3154 case InlineAsm::isOutput:
3155 isOutReg = true;
3156
3157 // If this is an early-clobber output, or if there is an input
3158 // constraint that matches this, we need to reserve the input register
3159 // so no other inputs allocate to it.
3160 isInReg = OpInfo.isEarlyClobber || OpInfo.hasMatchingInput;
3161 break;
3162 case InlineAsm::isInput:
3163 isInReg = true;
3164 isOutReg = false;
3165 break;
3166 case InlineAsm::isClobber:
3167 isOutReg = true;
3168 isInReg = true;
3169 break;
3170 }
3171
3172
3173 MachineFunction &MF = DAG.getMachineFunction();
Chris Lattner4333f8b2007-04-30 17:29:31 +00003174 std::vector<unsigned> Regs;
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003175
3176 // If this is a constraint for a single physreg, or a constraint for a
3177 // register class, find it.
3178 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
3179 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
3180 OpInfo.ConstraintVT);
Chris Lattner4333f8b2007-04-30 17:29:31 +00003181
3182 unsigned NumRegs = 1;
3183 if (OpInfo.ConstraintVT != MVT::Other)
3184 NumRegs = TLI.getNumElements(OpInfo.ConstraintVT);
3185 MVT::ValueType RegVT;
3186 MVT::ValueType ValueVT = OpInfo.ConstraintVT;
3187
Chris Lattner4333f8b2007-04-30 17:29:31 +00003188
3189 // If this is a constraint for a specific physical register, like {r17},
3190 // assign it now.
3191 if (PhysReg.first) {
3192 if (OpInfo.ConstraintVT == MVT::Other)
3193 ValueVT = *PhysReg.second->vt_begin();
3194
3195 // Get the actual register value type. This is important, because the user
3196 // may have asked for (e.g.) the AX register in i32 type. We need to
3197 // remember that AX is actually i16 to get the right extension.
3198 RegVT = *PhysReg.second->vt_begin();
3199
3200 // This is a explicit reference to a physical register.
3201 Regs.push_back(PhysReg.first);
3202
3203 // If this is an expanded reference, add the rest of the regs to Regs.
3204 if (NumRegs != 1) {
3205 TargetRegisterClass::iterator I = PhysReg.second->begin();
3206 TargetRegisterClass::iterator E = PhysReg.second->end();
3207 for (; *I != PhysReg.first; ++I)
3208 assert(I != E && "Didn't find reg!");
3209
3210 // Already added the first reg.
3211 --NumRegs; ++I;
3212 for (; NumRegs; --NumRegs, ++I) {
3213 assert(I != E && "Ran out of registers to allocate!");
3214 Regs.push_back(*I);
3215 }
3216 }
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003217 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
3218 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs);
3219 return;
Chris Lattner4333f8b2007-04-30 17:29:31 +00003220 }
3221
3222 // Otherwise, if this was a reference to an LLVM register class, create vregs
3223 // for this reference.
3224 std::vector<unsigned> RegClassRegs;
Chris Lattnerf852e332007-06-15 19:11:01 +00003225 const TargetRegisterClass *RC = PhysReg.second;
3226 if (RC) {
Chris Lattner4333f8b2007-04-30 17:29:31 +00003227 // If this is an early clobber or tied register, our regalloc doesn't know
3228 // how to maintain the constraint. If it isn't, go ahead and create vreg
3229 // and let the regalloc do the right thing.
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003230 if (!OpInfo.hasMatchingInput && !OpInfo.isEarlyClobber &&
3231 // If there is some other early clobber and this is an input register,
3232 // then we are forced to pre-allocate the input reg so it doesn't
3233 // conflict with the earlyclobber.
3234 !(OpInfo.Type == InlineAsm::isInput && HasEarlyClobber)) {
Chris Lattner4333f8b2007-04-30 17:29:31 +00003235 RegVT = *PhysReg.second->vt_begin();
3236
3237 if (OpInfo.ConstraintVT == MVT::Other)
3238 ValueVT = RegVT;
3239
3240 // Create the appropriate number of virtual registers.
3241 SSARegMap *RegMap = MF.getSSARegMap();
3242 for (; NumRegs; --NumRegs)
3243 Regs.push_back(RegMap->createVirtualRegister(PhysReg.second));
3244
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003245 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
3246 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs);
3247 return;
Chris Lattner4333f8b2007-04-30 17:29:31 +00003248 }
3249
3250 // Otherwise, we can't allocate it. Let the code below figure out how to
3251 // maintain these constraints.
3252 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
3253
3254 } else {
3255 // This is a reference to a register class that doesn't directly correspond
3256 // to an LLVM register class. Allocate NumRegs consecutive, available,
3257 // registers from the class.
3258 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
3259 OpInfo.ConstraintVT);
3260 }
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003261
Chris Lattner4333f8b2007-04-30 17:29:31 +00003262 const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
3263 unsigned NumAllocated = 0;
3264 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
3265 unsigned Reg = RegClassRegs[i];
3266 // See if this register is available.
3267 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
3268 (isInReg && InputRegs.count(Reg))) { // Already used.
3269 // Make sure we find consecutive registers.
3270 NumAllocated = 0;
3271 continue;
3272 }
3273
3274 // Check to see if this register is allocatable (i.e. don't give out the
3275 // stack pointer).
Chris Lattnerf852e332007-06-15 19:11:01 +00003276 if (RC == 0) {
3277 RC = isAllocatableRegister(Reg, MF, TLI, MRI);
3278 if (!RC) { // Couldn't allocate this register.
3279 // Reset NumAllocated to make sure we return consecutive registers.
3280 NumAllocated = 0;
3281 continue;
3282 }
Chris Lattner4333f8b2007-04-30 17:29:31 +00003283 }
3284
3285 // Okay, this register is good, we can use it.
3286 ++NumAllocated;
3287
3288 // If we allocated enough consecutive registers, succeed.
3289 if (NumAllocated == NumRegs) {
3290 unsigned RegStart = (i-NumAllocated)+1;
3291 unsigned RegEnd = i+1;
3292 // Mark all of the allocated registers used.
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003293 for (unsigned i = RegStart; i != RegEnd; ++i)
3294 Regs.push_back(RegClassRegs[i]);
Chris Lattner4333f8b2007-04-30 17:29:31 +00003295
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003296 OpInfo.AssignedRegs = RegsForValue(Regs, *RC->vt_begin(),
3297 OpInfo.ConstraintVT);
3298 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs);
3299 return;
Chris Lattner4333f8b2007-04-30 17:29:31 +00003300 }
3301 }
3302
3303 // Otherwise, we couldn't allocate enough registers for this.
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003304 return;
Chris Lattner4333f8b2007-04-30 17:29:31 +00003305}
3306
3307
Chris Lattner476e67b2006-01-26 22:24:51 +00003308/// visitInlineAsm - Handle a call to an InlineAsm object.
3309///
3310void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
3311 InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
Chris Lattner476e67b2006-01-26 22:24:51 +00003312
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003313 /// ConstraintOperands - Information about all of the constraints.
3314 std::vector<AsmOperandInfo> ConstraintOperands;
Chris Lattner476e67b2006-01-26 22:24:51 +00003315
3316 SDOperand Chain = getRoot();
3317 SDOperand Flag;
3318
Chris Lattner1558fc62006-02-01 18:59:47 +00003319 std::set<unsigned> OutputRegs, InputRegs;
Chris Lattner7ad77df2006-02-22 00:56:39 +00003320
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003321 // Do a prepass over the constraints, canonicalizing them, and building up the
3322 // ConstraintOperands list.
3323 std::vector<InlineAsm::ConstraintInfo>
3324 ConstraintInfos = IA->ParseConstraints();
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003325
3326 // SawEarlyClobber - Keep track of whether we saw an earlyclobber output
3327 // constraint. If so, we can't let the register allocator allocate any input
3328 // registers, because it will not know to avoid the earlyclobbered output reg.
3329 bool SawEarlyClobber = false;
3330
3331 unsigned OpNo = 1; // OpNo - The operand of the CallInst.
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003332 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
3333 ConstraintOperands.push_back(AsmOperandInfo(ConstraintInfos[i]));
3334 AsmOperandInfo &OpInfo = ConstraintOperands.back();
3335
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003336 MVT::ValueType OpVT = MVT::Other;
3337
3338 // Compute the value type for each operand.
3339 switch (OpInfo.Type) {
Chris Lattner7ad77df2006-02-22 00:56:39 +00003340 case InlineAsm::isOutput:
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003341 if (!OpInfo.isIndirect) {
3342 // The return value of the call is this value. As such, there is no
3343 // corresponding argument.
Chris Lattner7ad77df2006-02-22 00:56:39 +00003344 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
3345 OpVT = TLI.getValueType(I.getType());
3346 } else {
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003347 OpInfo.CallOperandVal = I.getOperand(OpNo++);
Chris Lattner7ad77df2006-02-22 00:56:39 +00003348 }
3349 break;
3350 case InlineAsm::isInput:
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003351 OpInfo.CallOperandVal = I.getOperand(OpNo++);
Chris Lattner7ad77df2006-02-22 00:56:39 +00003352 break;
3353 case InlineAsm::isClobber:
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003354 // Nothing to do.
Chris Lattner7ad77df2006-02-22 00:56:39 +00003355 break;
3356 }
Chris Lattner7ad77df2006-02-22 00:56:39 +00003357
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003358 // If this is an input or an indirect output, process the call argument.
3359 if (OpInfo.CallOperandVal) {
3360 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
3361 const Type *OpTy = OpInfo.CallOperandVal->getType();
Chris Lattner412d61a2007-04-29 18:58:03 +00003362 // If this is an indirect operand, the operand is a pointer to the
3363 // accessed type.
3364 if (OpInfo.isIndirect)
3365 OpTy = cast<PointerType>(OpTy)->getElementType();
3366
3367 // If OpTy is not a first-class value, it may be a struct/union that we
3368 // can tile with integers.
3369 if (!OpTy->isFirstClassType() && OpTy->isSized()) {
3370 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
3371 switch (BitSize) {
3372 default: break;
3373 case 1:
3374 case 8:
3375 case 16:
3376 case 32:
3377 case 64:
3378 OpTy = IntegerType::get(BitSize);
3379 break;
3380 }
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003381 }
Chris Lattner412d61a2007-04-29 18:58:03 +00003382
3383 OpVT = TLI.getValueType(OpTy, true);
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003384 }
3385
3386 OpInfo.ConstraintVT = OpVT;
Chris Lattnerb2e55562007-04-28 21:01:43 +00003387
Chris Lattneref073322007-04-30 17:16:27 +00003388 // Compute the constraint code and ConstraintType to use.
3389 OpInfo.ComputeConstraintToUse(TLI);
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003390
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003391 // Keep track of whether we see an earlyclobber.
3392 SawEarlyClobber |= OpInfo.isEarlyClobber;
Chris Lattner401d8db2007-04-28 21:12:06 +00003393
3394 // If this is a memory input, and if the operand is not indirect, do what we
3395 // need to to provide an address for the memory input.
3396 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
3397 !OpInfo.isIndirect) {
3398 assert(OpInfo.Type == InlineAsm::isInput &&
3399 "Can only indirectify direct input operands!");
3400
3401 // Memory operands really want the address of the value. If we don't have
3402 // an indirect input, put it in the constpool if we can, otherwise spill
3403 // it to a stack slot.
3404
3405 // If the operand is a float, integer, or vector constant, spill to a
3406 // constant pool entry to get its address.
3407 Value *OpVal = OpInfo.CallOperandVal;
3408 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
3409 isa<ConstantVector>(OpVal)) {
3410 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
3411 TLI.getPointerTy());
3412 } else {
3413 // Otherwise, create a stack slot and emit a store to it before the
3414 // asm.
3415 const Type *Ty = OpVal->getType();
3416 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
3417 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
3418 MachineFunction &MF = DAG.getMachineFunction();
3419 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align);
3420 SDOperand StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
3421 Chain = DAG.getStore(Chain, OpInfo.CallOperand, StackSlot, NULL, 0);
3422 OpInfo.CallOperand = StackSlot;
3423 }
3424
3425 // There is no longer a Value* corresponding to this operand.
3426 OpInfo.CallOperandVal = 0;
3427 // It is now an indirect operand.
3428 OpInfo.isIndirect = true;
3429 }
3430
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003431 // If this constraint is for a specific register, allocate it before
3432 // anything else.
3433 if (OpInfo.ConstraintType == TargetLowering::C_Register)
3434 GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003435 }
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003436 ConstraintInfos.clear();
3437
3438
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003439 // Second pass - Loop over all of the operands, assigning virtual or physregs
3440 // to registerclass operands.
3441 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
3442 AsmOperandInfo &OpInfo = ConstraintOperands[i];
3443
3444 // C_Register operands have already been allocated, Other/Memory don't need
3445 // to be.
3446 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
3447 GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
3448 }
3449
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003450 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
3451 std::vector<SDOperand> AsmNodeOperands;
3452 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
3453 AsmNodeOperands.push_back(
3454 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), MVT::Other));
3455
Chris Lattner3a5ed552006-02-01 01:28:23 +00003456
Chris Lattner5c79f982006-02-21 23:12:12 +00003457 // Loop over all of the inputs, copying the operand values into the
3458 // appropriate registers and processing the output regs.
Chris Lattner6f87d182006-02-22 22:37:12 +00003459 RegsForValue RetValRegs;
Chris Lattner5c79f982006-02-21 23:12:12 +00003460
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003461 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
3462 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
3463
3464 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
3465 AsmOperandInfo &OpInfo = ConstraintOperands[i];
Chris Lattner7ad77df2006-02-22 00:56:39 +00003466
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003467 switch (OpInfo.Type) {
Chris Lattner3a5ed552006-02-01 01:28:23 +00003468 case InlineAsm::isOutput: {
Chris Lattnerde339fa2007-04-28 21:03:16 +00003469 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
3470 OpInfo.ConstraintType != TargetLowering::C_Register) {
Chris Lattnerd102ed02007-04-28 06:08:13 +00003471 // Memory output, or 'other' output (e.g. 'X' constraint).
Chris Lattner401d8db2007-04-28 21:12:06 +00003472 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
Chris Lattner9fed5b62006-02-27 23:45:39 +00003473
Chris Lattner9fed5b62006-02-27 23:45:39 +00003474 // Add information to the INLINEASM node to know about this output.
3475 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
Chris Lattnerc7596ef2007-05-15 01:33:58 +00003476 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
3477 TLI.getPointerTy()));
Chris Lattner401d8db2007-04-28 21:12:06 +00003478 AsmNodeOperands.push_back(OpInfo.CallOperand);
Chris Lattner9fed5b62006-02-27 23:45:39 +00003479 break;
3480 }
3481
Chris Lattnerb2e55562007-04-28 21:01:43 +00003482 // Otherwise, this is a register or register class output.
Chris Lattner9fed5b62006-02-27 23:45:39 +00003483
Chris Lattner6f87d182006-02-22 22:37:12 +00003484 // Copy the output from the appropriate register. Find a register that
Chris Lattner7ad77df2006-02-22 00:56:39 +00003485 // we can use.
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003486 if (OpInfo.AssignedRegs.Regs.empty()) {
Bill Wendling22e978a2006-12-07 20:04:42 +00003487 cerr << "Couldn't allocate output reg for contraint '"
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003488 << OpInfo.ConstraintCode << "'!\n";
Chris Lattner968f8032006-10-31 07:33:13 +00003489 exit(1);
3490 }
Chris Lattner7ad77df2006-02-22 00:56:39 +00003491
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003492 if (!OpInfo.isIndirect) {
3493 // This is the result value of the call.
Chris Lattner6f87d182006-02-22 22:37:12 +00003494 assert(RetValRegs.Regs.empty() &&
Chris Lattner3a5ed552006-02-01 01:28:23 +00003495 "Cannot have multiple output constraints yet!");
Chris Lattner3a5ed552006-02-01 01:28:23 +00003496 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003497 RetValRegs = OpInfo.AssignedRegs;
Chris Lattner3a5ed552006-02-01 01:28:23 +00003498 } else {
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003499 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003500 OpInfo.CallOperandVal));
Chris Lattner3a5ed552006-02-01 01:28:23 +00003501 }
Chris Lattner2e56e892006-01-31 02:03:41 +00003502
3503 // Add information to the INLINEASM node to know that this register is
3504 // set.
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003505 OpInfo.AssignedRegs.AddInlineAsmOperands(2 /*REGDEF*/, DAG,
3506 AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00003507 break;
3508 }
3509 case InlineAsm::isInput: {
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003510 SDOperand InOperandVal = OpInfo.CallOperand;
Chris Lattner65ad53f2006-02-04 02:16:44 +00003511
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003512 if (isdigit(OpInfo.ConstraintCode[0])) { // Matching constraint?
Chris Lattner7f5880b2006-02-02 00:25:23 +00003513 // If this is required to match an output register we have already set,
3514 // just use its register.
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003515 unsigned OperandNo = atoi(OpInfo.ConstraintCode.c_str());
Chris Lattner65ad53f2006-02-04 02:16:44 +00003516
Chris Lattner571d9642006-02-23 19:21:04 +00003517 // Scan until we find the definition we already emitted of this operand.
3518 // When we find it, create a RegsForValue operand.
3519 unsigned CurOp = 2; // The first operand.
3520 for (; OperandNo; --OperandNo) {
3521 // Advance to the next operand.
3522 unsigned NumOps =
3523 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattnerb0305322006-07-20 19:02:21 +00003524 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
3525 (NumOps & 7) == 4 /*MEM*/) &&
Chris Lattner571d9642006-02-23 19:21:04 +00003526 "Skipped past definitions?");
3527 CurOp += (NumOps>>3)+1;
3528 }
3529
3530 unsigned NumOps =
3531 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattnere3eeb242007-02-01 01:21:12 +00003532 if ((NumOps & 7) == 2 /*REGDEF*/) {
3533 // Add NumOps>>3 registers to MatchedRegs.
3534 RegsForValue MatchedRegs;
3535 MatchedRegs.ValueVT = InOperandVal.getValueType();
3536 MatchedRegs.RegVT = AsmNodeOperands[CurOp+1].getValueType();
3537 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
3538 unsigned Reg =
3539 cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
3540 MatchedRegs.Regs.push_back(Reg);
3541 }
Chris Lattner571d9642006-02-23 19:21:04 +00003542
Chris Lattnere3eeb242007-02-01 01:21:12 +00003543 // Use the produced MatchedRegs object to
3544 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag,
3545 TLI.getPointerTy());
3546 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
3547 break;
3548 } else {
3549 assert((NumOps & 7) == 4/*MEM*/ && "Unknown matching constraint!");
3550 assert(0 && "matching constraints for memory operands unimp");
Chris Lattner571d9642006-02-23 19:21:04 +00003551 }
Chris Lattner7f5880b2006-02-02 00:25:23 +00003552 }
Chris Lattner7ef7a642006-02-24 01:11:24 +00003553
Chris Lattnerb2e55562007-04-28 21:01:43 +00003554 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003555 assert(!OpInfo.isIndirect &&
Chris Lattner1deacd62007-04-28 06:42:38 +00003556 "Don't know how to handle indirect other inputs yet!");
3557
Chris Lattner6f043b92006-10-31 19:41:18 +00003558 InOperandVal = TLI.isOperandValidForConstraint(InOperandVal,
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003559 OpInfo.ConstraintCode[0],
3560 DAG);
Chris Lattner6f043b92006-10-31 19:41:18 +00003561 if (!InOperandVal.Val) {
Bill Wendling22e978a2006-12-07 20:04:42 +00003562 cerr << "Invalid operand for inline asm constraint '"
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003563 << OpInfo.ConstraintCode << "'!\n";
Chris Lattner6f043b92006-10-31 19:41:18 +00003564 exit(1);
3565 }
Chris Lattner7ef7a642006-02-24 01:11:24 +00003566
3567 // Add information to the INLINEASM node to know about this input.
3568 unsigned ResOpType = 3 /*IMM*/ | (1 << 3);
Chris Lattnerc7596ef2007-05-15 01:33:58 +00003569 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
3570 TLI.getPointerTy()));
Chris Lattner7ef7a642006-02-24 01:11:24 +00003571 AsmNodeOperands.push_back(InOperandVal);
3572 break;
Chris Lattnerb2e55562007-04-28 21:01:43 +00003573 } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
Chris Lattner401d8db2007-04-28 21:12:06 +00003574 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
Chris Lattner1deacd62007-04-28 06:42:38 +00003575 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
3576 "Memory operands expect pointer values");
3577
Chris Lattner7ef7a642006-02-24 01:11:24 +00003578 // Add information to the INLINEASM node to know about this input.
3579 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
Chris Lattnerc7596ef2007-05-15 01:33:58 +00003580 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
3581 TLI.getPointerTy()));
Chris Lattner7ef7a642006-02-24 01:11:24 +00003582 AsmNodeOperands.push_back(InOperandVal);
3583 break;
3584 }
3585
Chris Lattnerb2e55562007-04-28 21:01:43 +00003586 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
3587 OpInfo.ConstraintType == TargetLowering::C_Register) &&
3588 "Unknown constraint type!");
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003589 assert(!OpInfo.isIndirect &&
Chris Lattner1deacd62007-04-28 06:42:38 +00003590 "Don't know how to handle indirect register inputs yet!");
Chris Lattner7ef7a642006-02-24 01:11:24 +00003591
3592 // Copy the input into the appropriate registers.
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003593 assert(!OpInfo.AssignedRegs.Regs.empty() &&
3594 "Couldn't allocate input reg!");
Chris Lattner7ef7a642006-02-24 01:11:24 +00003595
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003596 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag,
3597 TLI.getPointerTy());
Chris Lattner7ef7a642006-02-24 01:11:24 +00003598
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003599 OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG,
3600 AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00003601 break;
3602 }
Chris Lattner571d9642006-02-23 19:21:04 +00003603 case InlineAsm::isClobber: {
Chris Lattner571d9642006-02-23 19:21:04 +00003604 // Add the clobbered value to the operand list, so that the register
3605 // allocator is aware that the physreg got clobbered.
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003606 if (!OpInfo.AssignedRegs.Regs.empty())
3607 OpInfo.AssignedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG,
3608 AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00003609 break;
3610 }
Chris Lattner571d9642006-02-23 19:21:04 +00003611 }
Chris Lattner2e56e892006-01-31 02:03:41 +00003612 }
Chris Lattner476e67b2006-01-26 22:24:51 +00003613
3614 // Finish up input operands.
3615 AsmNodeOperands[0] = Chain;
3616 if (Flag.Val) AsmNodeOperands.push_back(Flag);
3617
Chris Lattnerbd887772006-08-14 23:53:35 +00003618 Chain = DAG.getNode(ISD::INLINEASM,
3619 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003620 &AsmNodeOperands[0], AsmNodeOperands.size());
Chris Lattner476e67b2006-01-26 22:24:51 +00003621 Flag = Chain.getValue(1);
3622
Chris Lattner2e56e892006-01-31 02:03:41 +00003623 // If this asm returns a register value, copy the result from that register
3624 // and set it as the value of the call.
Chris Lattner51114992007-04-12 06:00:20 +00003625 if (!RetValRegs.Regs.empty()) {
3626 SDOperand Val = RetValRegs.getCopyFromRegs(DAG, Chain, Flag);
3627
3628 // If the result of the inline asm is a vector, it may have the wrong
3629 // width/num elts. Make sure to convert it to the right type with
3630 // vbit_convert.
3631 if (Val.getValueType() == MVT::Vector) {
3632 const VectorType *VTy = cast<VectorType>(I.getType());
3633 unsigned DesiredNumElts = VTy->getNumElements();
3634 MVT::ValueType DesiredEltVT = TLI.getValueType(VTy->getElementType());
3635
3636 Val = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Val,
3637 DAG.getConstant(DesiredNumElts, MVT::i32),
3638 DAG.getValueType(DesiredEltVT));
3639 }
3640
3641 setValue(&I, Val);
3642 }
Chris Lattner476e67b2006-01-26 22:24:51 +00003643
Chris Lattner2e56e892006-01-31 02:03:41 +00003644 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
3645
3646 // Process indirect outputs, first output all of the flagged copies out of
3647 // physregs.
3648 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
Chris Lattner6f87d182006-02-22 22:37:12 +00003649 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Chris Lattner2e56e892006-01-31 02:03:41 +00003650 Value *Ptr = IndirectStoresToEmit[i].second;
Chris Lattner6f87d182006-02-22 22:37:12 +00003651 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, Flag);
3652 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner2e56e892006-01-31 02:03:41 +00003653 }
3654
3655 // Emit the non-flagged stores from the physregs.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003656 SmallVector<SDOperand, 8> OutChains;
Chris Lattner2e56e892006-01-31 02:03:41 +00003657 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003658 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
Chris Lattner2e56e892006-01-31 02:03:41 +00003659 getValue(StoresToEmit[i].second),
Evan Chengab51cf22006-10-13 21:14:26 +00003660 StoresToEmit[i].second, 0));
Chris Lattner2e56e892006-01-31 02:03:41 +00003661 if (!OutChains.empty())
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003662 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
3663 &OutChains[0], OutChains.size());
Chris Lattner476e67b2006-01-26 22:24:51 +00003664 DAG.setRoot(Chain);
3665}
3666
3667
Chris Lattner7a60d912005-01-07 07:47:53 +00003668void SelectionDAGLowering::visitMalloc(MallocInst &I) {
3669 SDOperand Src = getValue(I.getOperand(0));
3670
3671 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnereccb73d2005-01-22 23:04:37 +00003672
3673 if (IntPtr < Src.getValueType())
3674 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
3675 else if (IntPtr > Src.getValueType())
3676 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner7a60d912005-01-07 07:47:53 +00003677
3678 // Scale the source by the type size.
Owen Anderson20a631f2006-05-03 01:29:57 +00003679 uint64_t ElementSize = TD->getTypeSize(I.getType()->getElementType());
Chris Lattner7a60d912005-01-07 07:47:53 +00003680 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
3681 Src, getIntPtrConstant(ElementSize));
3682
Reid Spencere63b6512006-12-31 05:55:36 +00003683 TargetLowering::ArgListTy Args;
3684 TargetLowering::ArgListEntry Entry;
3685 Entry.Node = Src;
3686 Entry.Ty = TLI.getTargetData()->getIntPtrType();
Reid Spencere63b6512006-12-31 05:55:36 +00003687 Args.push_back(Entry);
Chris Lattner1f45cd72005-01-08 19:26:18 +00003688
3689 std::pair<SDOperand,SDOperand> Result =
Reid Spencere63b6512006-12-31 05:55:36 +00003690 TLI.LowerCallTo(getRoot(), I.getType(), false, false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00003691 DAG.getExternalSymbol("malloc", IntPtr),
3692 Args, DAG);
3693 setValue(&I, Result.first); // Pointers always fit in registers
3694 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00003695}
3696
3697void SelectionDAGLowering::visitFree(FreeInst &I) {
Reid Spencere63b6512006-12-31 05:55:36 +00003698 TargetLowering::ArgListTy Args;
3699 TargetLowering::ArgListEntry Entry;
3700 Entry.Node = getValue(I.getOperand(0));
3701 Entry.Ty = TLI.getTargetData()->getIntPtrType();
Reid Spencere63b6512006-12-31 05:55:36 +00003702 Args.push_back(Entry);
Chris Lattner7a60d912005-01-07 07:47:53 +00003703 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner1f45cd72005-01-08 19:26:18 +00003704 std::pair<SDOperand,SDOperand> Result =
Reid Spencere63b6512006-12-31 05:55:36 +00003705 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00003706 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
3707 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00003708}
3709
Chris Lattner13d7c252005-08-26 20:54:47 +00003710// InsertAtEndOfBasicBlock - This method should be implemented by targets that
3711// mark instructions with the 'usesCustomDAGSchedInserter' flag. These
3712// instructions are special in various ways, which require special support to
3713// insert. The specified MachineInstr is created but not inserted into any
3714// basic blocks, and the scheduler passes ownership of it to this method.
3715MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
3716 MachineBasicBlock *MBB) {
Bill Wendling22e978a2006-12-07 20:04:42 +00003717 cerr << "If a target marks an instruction with "
3718 << "'usesCustomDAGSchedInserter', it must implement "
3719 << "TargetLowering::InsertAtEndOfBasicBlock!\n";
Chris Lattner13d7c252005-08-26 20:54:47 +00003720 abort();
3721 return 0;
3722}
3723
Chris Lattner58cfd792005-01-09 00:00:49 +00003724void SelectionDAGLowering::visitVAStart(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00003725 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
3726 getValue(I.getOperand(1)),
3727 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner58cfd792005-01-09 00:00:49 +00003728}
3729
3730void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00003731 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
3732 getValue(I.getOperand(0)),
3733 DAG.getSrcValue(I.getOperand(0)));
3734 setValue(&I, V);
3735 DAG.setRoot(V.getValue(1));
Chris Lattner7a60d912005-01-07 07:47:53 +00003736}
3737
3738void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00003739 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
3740 getValue(I.getOperand(1)),
3741 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner7a60d912005-01-07 07:47:53 +00003742}
3743
3744void SelectionDAGLowering::visitVACopy(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00003745 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
3746 getValue(I.getOperand(1)),
3747 getValue(I.getOperand(2)),
3748 DAG.getSrcValue(I.getOperand(1)),
3749 DAG.getSrcValue(I.getOperand(2))));
Chris Lattner7a60d912005-01-07 07:47:53 +00003750}
3751
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003752/// ExpandScalarFormalArgs - Recursively expand the formal_argument node, either
3753/// bit_convert it or join a pair of them with a BUILD_PAIR when appropriate.
3754static SDOperand ExpandScalarFormalArgs(MVT::ValueType VT, SDNode *Arg,
3755 unsigned &i, SelectionDAG &DAG,
3756 TargetLowering &TLI) {
3757 if (TLI.getTypeAction(VT) != TargetLowering::Expand)
3758 return SDOperand(Arg, i++);
3759
3760 MVT::ValueType EVT = TLI.getTypeToTransformTo(VT);
3761 unsigned NumVals = MVT::getSizeInBits(VT) / MVT::getSizeInBits(EVT);
3762 if (NumVals == 1) {
3763 return DAG.getNode(ISD::BIT_CONVERT, VT,
3764 ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI));
3765 } else if (NumVals == 2) {
3766 SDOperand Lo = ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI);
3767 SDOperand Hi = ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI);
3768 if (!TLI.isLittleEndian())
3769 std::swap(Lo, Hi);
3770 return DAG.getNode(ISD::BUILD_PAIR, VT, Lo, Hi);
3771 } else {
3772 // Value scalarized into many values. Unimp for now.
3773 assert(0 && "Cannot expand i64 -> i16 yet!");
3774 }
3775 return SDOperand();
3776}
3777
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003778/// TargetLowering::LowerArguments - This is the default LowerArguments
3779/// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
Chris Lattneraaa23d92006-05-16 22:53:20 +00003780/// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
3781/// integrated into SDISel.
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003782std::vector<SDOperand>
3783TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003784 const FunctionType *FTy = F.getFunctionType();
Reid Spencer71b79e32007-04-09 06:17:21 +00003785 const ParamAttrsList *Attrs = FTy->getParamAttrs();
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003786 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
3787 std::vector<SDOperand> Ops;
Chris Lattner3d826992006-05-16 06:45:34 +00003788 Ops.push_back(DAG.getRoot());
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003789 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
3790 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
3791
3792 // Add one result value for each formal argument.
3793 std::vector<MVT::ValueType> RetVals;
Anton Korobeynikov06f7d4b2007-01-28 18:01:49 +00003794 unsigned j = 1;
Anton Korobeynikov9fa38392007-01-28 16:04:40 +00003795 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
3796 I != E; ++I, ++j) {
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003797 MVT::ValueType VT = getValueType(I->getType());
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003798 unsigned Flags = ISD::ParamFlags::NoFlagSet;
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003799 unsigned OriginalAlignment =
Chris Lattner945e4372007-02-14 05:52:17 +00003800 getTargetData()->getABITypeAlignment(I->getType());
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003801
Chris Lattnerab5d0ac2007-02-26 02:56:58 +00003802 // FIXME: Distinguish between a formal with no [sz]ext attribute from one
3803 // that is zero extended!
Reid Spencera472f662007-04-11 02:44:20 +00003804 if (Attrs && Attrs->paramHasAttr(j, ParamAttr::ZExt))
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003805 Flags &= ~(ISD::ParamFlags::SExt);
Reid Spencera472f662007-04-11 02:44:20 +00003806 if (Attrs && Attrs->paramHasAttr(j, ParamAttr::SExt))
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003807 Flags |= ISD::ParamFlags::SExt;
Reid Spencera472f662007-04-11 02:44:20 +00003808 if (Attrs && Attrs->paramHasAttr(j, ParamAttr::InReg))
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003809 Flags |= ISD::ParamFlags::InReg;
Reid Spencera472f662007-04-11 02:44:20 +00003810 if (Attrs && Attrs->paramHasAttr(j, ParamAttr::StructRet))
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003811 Flags |= ISD::ParamFlags::StructReturn;
3812 Flags |= (OriginalAlignment << ISD::ParamFlags::OrigAlignmentOffs);
Chris Lattnerab5d0ac2007-02-26 02:56:58 +00003813
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003814 switch (getTypeAction(VT)) {
3815 default: assert(0 && "Unknown type action!");
3816 case Legal:
3817 RetVals.push_back(VT);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003818 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003819 break;
3820 case Promote:
3821 RetVals.push_back(getTypeToTransformTo(VT));
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003822 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003823 break;
3824 case Expand:
3825 if (VT != MVT::Vector) {
3826 // If this is a large integer, it needs to be broken up into small
3827 // integers. Figure out what the destination type is and how many small
3828 // integers it turns into.
Evan Cheng22cf8992006-12-13 20:57:08 +00003829 MVT::ValueType NVT = getTypeToExpandTo(VT);
3830 unsigned NumVals = getNumElements(VT);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003831 for (unsigned i = 0; i != NumVals; ++i) {
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003832 RetVals.push_back(NVT);
Lauro Ramos Venancioabde3cc2007-02-13 18:10:13 +00003833 // if it isn't first piece, alignment must be 1
Anton Korobeynikovf0b93162007-03-06 06:10:33 +00003834 if (i > 0)
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003835 Flags = (Flags & (~ISD::ParamFlags::OrigAlignment)) |
3836 (1 << ISD::ParamFlags::OrigAlignmentOffs);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003837 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
3838 }
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003839 } else {
3840 // Otherwise, this is a vector type. We only support legal vectors
3841 // right now.
Reid Spencerd84d35b2007-02-15 02:26:10 +00003842 unsigned NumElems = cast<VectorType>(I->getType())->getNumElements();
3843 const Type *EltTy = cast<VectorType>(I->getType())->getElementType();
Evan Cheng3784f3c52006-04-27 08:29:42 +00003844
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003845 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencer09575ba2007-02-15 03:39:18 +00003846 // type. If so, convert to the vector type.
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003847 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
3848 if (TVT != MVT::Other && isTypeLegal(TVT)) {
3849 RetVals.push_back(TVT);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003850 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003851 } else {
3852 assert(0 && "Don't support illegal by-val vector arguments yet!");
3853 }
3854 }
3855 break;
3856 }
3857 }
Evan Cheng9618df12006-04-25 23:03:35 +00003858
Chris Lattner3d826992006-05-16 06:45:34 +00003859 RetVals.push_back(MVT::Other);
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003860
3861 // Create the node.
Chris Lattnerbd887772006-08-14 23:53:35 +00003862 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
3863 DAG.getNodeValueTypes(RetVals), RetVals.size(),
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003864 &Ops[0], Ops.size()).Val;
Chris Lattner3d826992006-05-16 06:45:34 +00003865
3866 DAG.setRoot(SDOperand(Result, Result->getNumValues()-1));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003867
3868 // Set up the return result vector.
3869 Ops.clear();
3870 unsigned i = 0;
Reid Spencere63b6512006-12-31 05:55:36 +00003871 unsigned Idx = 1;
3872 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
3873 ++I, ++Idx) {
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003874 MVT::ValueType VT = getValueType(I->getType());
3875
3876 switch (getTypeAction(VT)) {
3877 default: assert(0 && "Unknown type action!");
3878 case Legal:
3879 Ops.push_back(SDOperand(Result, i++));
3880 break;
3881 case Promote: {
3882 SDOperand Op(Result, i++);
3883 if (MVT::isInteger(VT)) {
Reid Spencera472f662007-04-11 02:44:20 +00003884 if (Attrs && Attrs->paramHasAttr(Idx, ParamAttr::SExt))
Chris Lattner96035be2007-01-04 22:22:37 +00003885 Op = DAG.getNode(ISD::AssertSext, Op.getValueType(), Op,
3886 DAG.getValueType(VT));
Reid Spencera472f662007-04-11 02:44:20 +00003887 else if (Attrs && Attrs->paramHasAttr(Idx, ParamAttr::ZExt))
Chris Lattner96035be2007-01-04 22:22:37 +00003888 Op = DAG.getNode(ISD::AssertZext, Op.getValueType(), Op,
3889 DAG.getValueType(VT));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003890 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
3891 } else {
3892 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
3893 Op = DAG.getNode(ISD::FP_ROUND, VT, Op);
3894 }
3895 Ops.push_back(Op);
3896 break;
3897 }
3898 case Expand:
3899 if (VT != MVT::Vector) {
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003900 // If this is a large integer or a floating point node that needs to be
3901 // expanded, it needs to be reassembled from small integers. Figure out
3902 // what the source elt type is and how many small integers it is.
3903 Ops.push_back(ExpandScalarFormalArgs(VT, Result, i, DAG, *this));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003904 } else {
3905 // Otherwise, this is a vector type. We only support legal vectors
3906 // right now.
Reid Spencerd84d35b2007-02-15 02:26:10 +00003907 const VectorType *PTy = cast<VectorType>(I->getType());
Evan Chengd43c5c62006-04-28 05:25:15 +00003908 unsigned NumElems = PTy->getNumElements();
3909 const Type *EltTy = PTy->getElementType();
Evan Cheng3784f3c52006-04-27 08:29:42 +00003910
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003911 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencer09575ba2007-02-15 03:39:18 +00003912 // type. If so, convert to the vector type.
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003913 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
Chris Lattner7949c2e2006-05-17 20:49:36 +00003914 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Evan Chengd43c5c62006-04-28 05:25:15 +00003915 SDOperand N = SDOperand(Result, i++);
3916 // Handle copies from generic vectors to registers.
Chris Lattner7949c2e2006-05-17 20:49:36 +00003917 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
3918 DAG.getConstant(NumElems, MVT::i32),
3919 DAG.getValueType(getValueType(EltTy)));
3920 Ops.push_back(N);
3921 } else {
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003922 assert(0 && "Don't support illegal by-val vector arguments yet!");
Chris Lattnerb77ba732006-05-16 23:39:44 +00003923 abort();
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003924 }
3925 }
3926 break;
3927 }
3928 }
3929 return Ops;
3930}
3931
Chris Lattneraaa23d92006-05-16 22:53:20 +00003932
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003933/// ExpandScalarCallArgs - Recursively expand call argument node by
3934/// bit_converting it or extract a pair of elements from the larger node.
3935static void ExpandScalarCallArgs(MVT::ValueType VT, SDOperand Arg,
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003936 unsigned Flags,
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003937 SmallVector<SDOperand, 32> &Ops,
3938 SelectionDAG &DAG,
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003939 TargetLowering &TLI,
3940 bool isFirst = true) {
3941
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003942 if (TLI.getTypeAction(VT) != TargetLowering::Expand) {
Lauro Ramos Venancioabde3cc2007-02-13 18:10:13 +00003943 // if it isn't first piece, alignment must be 1
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003944 if (!isFirst)
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003945 Flags = (Flags & (~ISD::ParamFlags::OrigAlignment)) |
3946 (1 << ISD::ParamFlags::OrigAlignmentOffs);
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003947 Ops.push_back(Arg);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003948 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003949 return;
3950 }
3951
3952 MVT::ValueType EVT = TLI.getTypeToTransformTo(VT);
3953 unsigned NumVals = MVT::getSizeInBits(VT) / MVT::getSizeInBits(EVT);
3954 if (NumVals == 1) {
3955 Arg = DAG.getNode(ISD::BIT_CONVERT, EVT, Arg);
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003956 ExpandScalarCallArgs(EVT, Arg, Flags, Ops, DAG, TLI, isFirst);
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003957 } else if (NumVals == 2) {
3958 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, EVT, Arg,
3959 DAG.getConstant(0, TLI.getPointerTy()));
3960 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, EVT, Arg,
3961 DAG.getConstant(1, TLI.getPointerTy()));
3962 if (!TLI.isLittleEndian())
3963 std::swap(Lo, Hi);
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003964 ExpandScalarCallArgs(EVT, Lo, Flags, Ops, DAG, TLI, isFirst);
3965 ExpandScalarCallArgs(EVT, Hi, Flags, Ops, DAG, TLI, false);
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003966 } else {
3967 // Value scalarized into many values. Unimp for now.
3968 assert(0 && "Cannot expand i64 -> i16 yet!");
3969 }
3970}
3971
Chris Lattneraaa23d92006-05-16 22:53:20 +00003972/// TargetLowering::LowerCallTo - This is the default LowerCallTo
3973/// implementation, which just inserts an ISD::CALL node, which is later custom
3974/// lowered by the target to something concrete. FIXME: When all targets are
3975/// migrated to using ISD::CALL, this hook should be integrated into SDISel.
3976std::pair<SDOperand, SDOperand>
Reid Spencere63b6512006-12-31 05:55:36 +00003977TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy,
3978 bool RetTyIsSigned, bool isVarArg,
Chris Lattneraaa23d92006-05-16 22:53:20 +00003979 unsigned CallingConv, bool isTailCall,
3980 SDOperand Callee,
3981 ArgListTy &Args, SelectionDAG &DAG) {
Chris Lattner65879ca2006-08-16 22:57:46 +00003982 SmallVector<SDOperand, 32> Ops;
Chris Lattneraaa23d92006-05-16 22:53:20 +00003983 Ops.push_back(Chain); // Op#0 - Chain
3984 Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
3985 Ops.push_back(DAG.getConstant(isVarArg, getPointerTy())); // Op#2 - VarArg
3986 Ops.push_back(DAG.getConstant(isTailCall, getPointerTy())); // Op#3 - Tail
3987 Ops.push_back(Callee);
3988
3989 // Handle all of the outgoing arguments.
3990 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
Reid Spencere63b6512006-12-31 05:55:36 +00003991 MVT::ValueType VT = getValueType(Args[i].Ty);
3992 SDOperand Op = Args[i].Node;
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003993 unsigned Flags = ISD::ParamFlags::NoFlagSet;
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003994 unsigned OriginalAlignment =
Chris Lattner945e4372007-02-14 05:52:17 +00003995 getTargetData()->getABITypeAlignment(Args[i].Ty);
Anton Korobeynikovf0b93162007-03-06 06:10:33 +00003996
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003997 if (Args[i].isSExt)
3998 Flags |= ISD::ParamFlags::SExt;
3999 if (Args[i].isZExt)
4000 Flags |= ISD::ParamFlags::ZExt;
Anton Korobeynikovf0b93162007-03-06 06:10:33 +00004001 if (Args[i].isInReg)
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00004002 Flags |= ISD::ParamFlags::InReg;
Anton Korobeynikovf0b93162007-03-06 06:10:33 +00004003 if (Args[i].isSRet)
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00004004 Flags |= ISD::ParamFlags::StructReturn;
4005 Flags |= OriginalAlignment << ISD::ParamFlags::OrigAlignmentOffs;
Anton Korobeynikovf0b93162007-03-06 06:10:33 +00004006
Chris Lattneraaa23d92006-05-16 22:53:20 +00004007 switch (getTypeAction(VT)) {
4008 default: assert(0 && "Unknown type action!");
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00004009 case Legal:
Chris Lattneraaa23d92006-05-16 22:53:20 +00004010 Ops.push_back(Op);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00004011 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattneraaa23d92006-05-16 22:53:20 +00004012 break;
4013 case Promote:
4014 if (MVT::isInteger(VT)) {
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00004015 unsigned ExtOp;
4016 if (Args[i].isSExt)
4017 ExtOp = ISD::SIGN_EXTEND;
4018 else if (Args[i].isZExt)
4019 ExtOp = ISD::ZERO_EXTEND;
4020 else
4021 ExtOp = ISD::ANY_EXTEND;
Chris Lattneraaa23d92006-05-16 22:53:20 +00004022 Op = DAG.getNode(ExtOp, getTypeToTransformTo(VT), Op);
4023 } else {
4024 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
Dale Johannesen9a4d9872007-06-07 21:07:15 +00004025 // A true promotion would change the size of the argument.
4026 // Instead, pretend this is an int. If FP objects are not
4027 // passed the same as ints, the original type should be Legal
4028 // and we should not get here.
4029 Op = DAG.getNode(ISD::BIT_CONVERT,
4030 VT==MVT::f32 ? MVT::i32 :
4031 (VT==MVT::f64 ? MVT::i64 :
4032 MVT::Other),
4033 Op);
Chris Lattneraaa23d92006-05-16 22:53:20 +00004034 }
4035 Ops.push_back(Op);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00004036 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattneraaa23d92006-05-16 22:53:20 +00004037 break;
4038 case Expand:
4039 if (VT != MVT::Vector) {
4040 // If this is a large integer, it needs to be broken down into small
4041 // integers. Figure out what the source elt type is and how many small
4042 // integers it is.
Anton Korobeynikov037c8672007-01-28 13:31:35 +00004043 ExpandScalarCallArgs(VT, Op, Flags, Ops, DAG, *this);
Chris Lattneraaa23d92006-05-16 22:53:20 +00004044 } else {
Chris Lattnerb77ba732006-05-16 23:39:44 +00004045 // Otherwise, this is a vector type. We only support legal vectors
4046 // right now.
Reid Spencerd84d35b2007-02-15 02:26:10 +00004047 const VectorType *PTy = cast<VectorType>(Args[i].Ty);
Chris Lattnerb77ba732006-05-16 23:39:44 +00004048 unsigned NumElems = PTy->getNumElements();
4049 const Type *EltTy = PTy->getElementType();
4050
4051 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencer09575ba2007-02-15 03:39:18 +00004052 // type. If so, convert to the vector type.
Chris Lattnerb77ba732006-05-16 23:39:44 +00004053 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
Chris Lattner938155c2006-05-17 20:43:21 +00004054 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Reid Spencer09575ba2007-02-15 03:39:18 +00004055 // Insert a VBIT_CONVERT of the MVT::Vector type to the vector type.
Chris Lattner938155c2006-05-17 20:43:21 +00004056 Op = DAG.getNode(ISD::VBIT_CONVERT, TVT, Op);
4057 Ops.push_back(Op);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00004058 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattner938155c2006-05-17 20:43:21 +00004059 } else {
Chris Lattnerb77ba732006-05-16 23:39:44 +00004060 assert(0 && "Don't support illegal by-val vector call args yet!");
4061 abort();
4062 }
Chris Lattneraaa23d92006-05-16 22:53:20 +00004063 }
4064 break;
4065 }
4066 }
4067
4068 // Figure out the result value types.
Chris Lattner65879ca2006-08-16 22:57:46 +00004069 SmallVector<MVT::ValueType, 4> RetTys;
Chris Lattneraaa23d92006-05-16 22:53:20 +00004070
4071 if (RetTy != Type::VoidTy) {
4072 MVT::ValueType VT = getValueType(RetTy);
4073 switch (getTypeAction(VT)) {
4074 default: assert(0 && "Unknown type action!");
4075 case Legal:
4076 RetTys.push_back(VT);
4077 break;
4078 case Promote:
4079 RetTys.push_back(getTypeToTransformTo(VT));
4080 break;
4081 case Expand:
4082 if (VT != MVT::Vector) {
4083 // If this is a large integer, it needs to be reassembled from small
4084 // integers. Figure out what the source elt type is and how many small
4085 // integers it is.
Evan Cheng22cf8992006-12-13 20:57:08 +00004086 MVT::ValueType NVT = getTypeToExpandTo(VT);
4087 unsigned NumVals = getNumElements(VT);
Chris Lattneraaa23d92006-05-16 22:53:20 +00004088 for (unsigned i = 0; i != NumVals; ++i)
4089 RetTys.push_back(NVT);
4090 } else {
Chris Lattnerb77ba732006-05-16 23:39:44 +00004091 // Otherwise, this is a vector type. We only support legal vectors
4092 // right now.
Reid Spencerd84d35b2007-02-15 02:26:10 +00004093 const VectorType *PTy = cast<VectorType>(RetTy);
Chris Lattnerb77ba732006-05-16 23:39:44 +00004094 unsigned NumElems = PTy->getNumElements();
4095 const Type *EltTy = PTy->getElementType();
4096
4097 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencer09575ba2007-02-15 03:39:18 +00004098 // type. If so, convert to the vector type.
Chris Lattnerb77ba732006-05-16 23:39:44 +00004099 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
4100 if (TVT != MVT::Other && isTypeLegal(TVT)) {
4101 RetTys.push_back(TVT);
4102 } else {
4103 assert(0 && "Don't support illegal by-val vector call results yet!");
4104 abort();
4105 }
Chris Lattneraaa23d92006-05-16 22:53:20 +00004106 }
4107 }
4108 }
4109
4110 RetTys.push_back(MVT::Other); // Always has a chain.
4111
4112 // Finally, create the CALL node.
Chris Lattner65879ca2006-08-16 22:57:46 +00004113 SDOperand Res = DAG.getNode(ISD::CALL,
4114 DAG.getVTList(&RetTys[0], RetTys.size()),
4115 &Ops[0], Ops.size());
Chris Lattneraaa23d92006-05-16 22:53:20 +00004116
4117 // This returns a pair of operands. The first element is the
4118 // return value for the function (if RetTy is not VoidTy). The second
4119 // element is the outgoing token chain.
4120 SDOperand ResVal;
4121 if (RetTys.size() != 1) {
4122 MVT::ValueType VT = getValueType(RetTy);
4123 if (RetTys.size() == 2) {
4124 ResVal = Res;
4125
4126 // If this value was promoted, truncate it down.
4127 if (ResVal.getValueType() != VT) {
Chris Lattnerb77ba732006-05-16 23:39:44 +00004128 if (VT == MVT::Vector) {
Chris Lattner77f04792007-03-25 05:00:54 +00004129 // Insert a VBIT_CONVERT to convert from the packed result type to the
Chris Lattnerb77ba732006-05-16 23:39:44 +00004130 // MVT::Vector type.
Reid Spencerd84d35b2007-02-15 02:26:10 +00004131 unsigned NumElems = cast<VectorType>(RetTy)->getNumElements();
4132 const Type *EltTy = cast<VectorType>(RetTy)->getElementType();
Chris Lattnerb77ba732006-05-16 23:39:44 +00004133
4134 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencer09575ba2007-02-15 03:39:18 +00004135 // type. If so, convert to the vector type.
Chris Lattner296a83c2007-02-01 04:55:59 +00004136 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy),NumElems);
Chris Lattnerb77ba732006-05-16 23:39:44 +00004137 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Chris Lattnerb77ba732006-05-16 23:39:44 +00004138 // Insert a VBIT_CONVERT of the FORMAL_ARGUMENTS to a
4139 // "N x PTyElementVT" MVT::Vector type.
4140 ResVal = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, ResVal,
Chris Lattner7949c2e2006-05-17 20:49:36 +00004141 DAG.getConstant(NumElems, MVT::i32),
4142 DAG.getValueType(getValueType(EltTy)));
Chris Lattnerb77ba732006-05-16 23:39:44 +00004143 } else {
4144 abort();
4145 }
4146 } else if (MVT::isInteger(VT)) {
Reid Spencere63b6512006-12-31 05:55:36 +00004147 unsigned AssertOp = ISD::AssertSext;
4148 if (!RetTyIsSigned)
4149 AssertOp = ISD::AssertZext;
Chris Lattneraaa23d92006-05-16 22:53:20 +00004150 ResVal = DAG.getNode(AssertOp, ResVal.getValueType(), ResVal,
4151 DAG.getValueType(VT));
4152 ResVal = DAG.getNode(ISD::TRUNCATE, VT, ResVal);
4153 } else {
4154 assert(MVT::isFloatingPoint(VT));
Evan Cheng4eee7242006-12-09 02:42:38 +00004155 if (getTypeAction(VT) == Expand)
4156 ResVal = DAG.getNode(ISD::BIT_CONVERT, VT, ResVal);
4157 else
4158 ResVal = DAG.getNode(ISD::FP_ROUND, VT, ResVal);
Chris Lattneraaa23d92006-05-16 22:53:20 +00004159 }
4160 }
4161 } else if (RetTys.size() == 3) {
4162 ResVal = DAG.getNode(ISD::BUILD_PAIR, VT,
4163 Res.getValue(0), Res.getValue(1));
4164
4165 } else {
4166 assert(0 && "Case not handled yet!");
4167 }
4168 }
4169
4170 return std::make_pair(ResVal, Res.getValue(Res.Val->getNumValues()-1));
4171}
4172
Chris Lattner29dcc712005-05-14 05:50:48 +00004173SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner897cd7d2005-01-16 07:28:41 +00004174 assert(0 && "LowerOperation not implemented for this target!");
4175 abort();
Misha Brukman73e929f2005-02-17 21:39:27 +00004176 return SDOperand();
Chris Lattner897cd7d2005-01-16 07:28:41 +00004177}
4178
Nate Begeman595ec732006-01-28 03:14:31 +00004179SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
4180 SelectionDAG &DAG) {
4181 assert(0 && "CustomPromoteOperation not implemented for this target!");
4182 abort();
4183 return SDOperand();
4184}
4185
Evan Cheng6781b6e2006-02-15 21:59:04 +00004186/// getMemsetValue - Vectorized representation of the memset value
Evan Cheng81fcea82006-02-14 08:22:34 +00004187/// operand.
4188static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
Evan Cheng93e48652006-02-15 22:12:35 +00004189 SelectionDAG &DAG) {
Evan Cheng81fcea82006-02-14 08:22:34 +00004190 MVT::ValueType CurVT = VT;
4191 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
4192 uint64_t Val = C->getValue() & 255;
4193 unsigned Shift = 8;
4194 while (CurVT != MVT::i8) {
4195 Val = (Val << Shift) | Val;
4196 Shift <<= 1;
4197 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00004198 }
4199 return DAG.getConstant(Val, VT);
4200 } else {
4201 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
4202 unsigned Shift = 8;
4203 while (CurVT != MVT::i8) {
4204 Value =
4205 DAG.getNode(ISD::OR, VT,
4206 DAG.getNode(ISD::SHL, VT, Value,
4207 DAG.getConstant(Shift, MVT::i8)), Value);
4208 Shift <<= 1;
4209 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00004210 }
4211
4212 return Value;
4213 }
4214}
4215
Evan Cheng6781b6e2006-02-15 21:59:04 +00004216/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
4217/// used when a memcpy is turned into a memset when the source is a constant
4218/// string ptr.
4219static SDOperand getMemsetStringVal(MVT::ValueType VT,
4220 SelectionDAG &DAG, TargetLowering &TLI,
4221 std::string &Str, unsigned Offset) {
Evan Cheng6781b6e2006-02-15 21:59:04 +00004222 uint64_t Val = 0;
Dan Gohman1796f1f2007-05-18 17:52:13 +00004223 unsigned MSB = MVT::getSizeInBits(VT) / 8;
Evan Cheng6781b6e2006-02-15 21:59:04 +00004224 if (TLI.isLittleEndian())
4225 Offset = Offset + MSB - 1;
4226 for (unsigned i = 0; i != MSB; ++i) {
Evan Cheng6e12a052006-11-29 01:38:07 +00004227 Val = (Val << 8) | (unsigned char)Str[Offset];
Evan Cheng6781b6e2006-02-15 21:59:04 +00004228 Offset += TLI.isLittleEndian() ? -1 : 1;
4229 }
4230 return DAG.getConstant(Val, VT);
4231}
4232
Evan Cheng81fcea82006-02-14 08:22:34 +00004233/// getMemBasePlusOffset - Returns base and offset node for the
4234static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
4235 SelectionDAG &DAG, TargetLowering &TLI) {
4236 MVT::ValueType VT = Base.getValueType();
4237 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
4238}
4239
Evan Chengdb2a7a72006-02-14 20:12:38 +00004240/// MeetsMaxMemopRequirement - Determines if the number of memory ops required
Evan Chengd5026102006-02-14 09:11:59 +00004241/// to replace the memset / memcpy is below the threshold. It also returns the
4242/// types of the sequence of memory ops to perform memset / memcpy.
Evan Chengdb2a7a72006-02-14 20:12:38 +00004243static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
4244 unsigned Limit, uint64_t Size,
4245 unsigned Align, TargetLowering &TLI) {
Evan Cheng81fcea82006-02-14 08:22:34 +00004246 MVT::ValueType VT;
4247
4248 if (TLI.allowsUnalignedMemoryAccesses()) {
4249 VT = MVT::i64;
4250 } else {
4251 switch (Align & 7) {
4252 case 0:
4253 VT = MVT::i64;
4254 break;
4255 case 4:
4256 VT = MVT::i32;
4257 break;
4258 case 2:
4259 VT = MVT::i16;
4260 break;
4261 default:
4262 VT = MVT::i8;
4263 break;
4264 }
4265 }
4266
Evan Chengd5026102006-02-14 09:11:59 +00004267 MVT::ValueType LVT = MVT::i64;
4268 while (!TLI.isTypeLegal(LVT))
4269 LVT = (MVT::ValueType)((unsigned)LVT - 1);
4270 assert(MVT::isInteger(LVT));
Evan Cheng81fcea82006-02-14 08:22:34 +00004271
Evan Chengd5026102006-02-14 09:11:59 +00004272 if (VT > LVT)
4273 VT = LVT;
4274
Evan Cheng04514992006-02-14 23:05:54 +00004275 unsigned NumMemOps = 0;
Evan Cheng81fcea82006-02-14 08:22:34 +00004276 while (Size != 0) {
Dan Gohman1796f1f2007-05-18 17:52:13 +00004277 unsigned VTSize = MVT::getSizeInBits(VT) / 8;
Evan Cheng81fcea82006-02-14 08:22:34 +00004278 while (VTSize > Size) {
4279 VT = (MVT::ValueType)((unsigned)VT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00004280 VTSize >>= 1;
4281 }
Evan Chengd5026102006-02-14 09:11:59 +00004282 assert(MVT::isInteger(VT));
4283
4284 if (++NumMemOps > Limit)
4285 return false;
Evan Cheng81fcea82006-02-14 08:22:34 +00004286 MemOps.push_back(VT);
4287 Size -= VTSize;
4288 }
Evan Chengd5026102006-02-14 09:11:59 +00004289
4290 return true;
Evan Cheng81fcea82006-02-14 08:22:34 +00004291}
4292
Chris Lattner875def92005-01-11 05:56:49 +00004293void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
Evan Cheng81fcea82006-02-14 08:22:34 +00004294 SDOperand Op1 = getValue(I.getOperand(1));
4295 SDOperand Op2 = getValue(I.getOperand(2));
4296 SDOperand Op3 = getValue(I.getOperand(3));
4297 SDOperand Op4 = getValue(I.getOperand(4));
4298 unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
4299 if (Align == 0) Align = 1;
4300
4301 if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
4302 std::vector<MVT::ValueType> MemOps;
Evan Cheng81fcea82006-02-14 08:22:34 +00004303
4304 // Expand memset / memcpy to a series of load / store ops
4305 // if the size operand falls below a certain threshold.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00004306 SmallVector<SDOperand, 8> OutChains;
Evan Cheng81fcea82006-02-14 08:22:34 +00004307 switch (Op) {
Evan Cheng038521e2006-02-14 19:45:56 +00004308 default: break; // Do nothing for now.
Evan Cheng81fcea82006-02-14 08:22:34 +00004309 case ISD::MEMSET: {
Evan Chengdb2a7a72006-02-14 20:12:38 +00004310 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
4311 Size->getValue(), Align, TLI)) {
Evan Chengd5026102006-02-14 09:11:59 +00004312 unsigned NumMemOps = MemOps.size();
Evan Cheng81fcea82006-02-14 08:22:34 +00004313 unsigned Offset = 0;
4314 for (unsigned i = 0; i < NumMemOps; i++) {
4315 MVT::ValueType VT = MemOps[i];
Dan Gohman1796f1f2007-05-18 17:52:13 +00004316 unsigned VTSize = MVT::getSizeInBits(VT) / 8;
Evan Cheng93e48652006-02-15 22:12:35 +00004317 SDOperand Value = getMemsetValue(Op2, VT, DAG);
Evan Chengdf9ac472006-10-05 23:01:46 +00004318 SDOperand Store = DAG.getStore(getRoot(), Value,
Chris Lattner6f87d182006-02-22 22:37:12 +00004319 getMemBasePlusOffset(Op1, Offset, DAG, TLI),
Evan Chengab51cf22006-10-13 21:14:26 +00004320 I.getOperand(1), Offset);
Evan Chenge2038bd2006-02-15 01:54:51 +00004321 OutChains.push_back(Store);
Evan Cheng81fcea82006-02-14 08:22:34 +00004322 Offset += VTSize;
4323 }
Evan Cheng81fcea82006-02-14 08:22:34 +00004324 }
Evan Chenge2038bd2006-02-15 01:54:51 +00004325 break;
Evan Cheng81fcea82006-02-14 08:22:34 +00004326 }
Evan Chenge2038bd2006-02-15 01:54:51 +00004327 case ISD::MEMCPY: {
4328 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
4329 Size->getValue(), Align, TLI)) {
4330 unsigned NumMemOps = MemOps.size();
Evan Chengc3dcf5a2006-02-16 23:11:42 +00004331 unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
Evan Cheng6781b6e2006-02-15 21:59:04 +00004332 GlobalAddressSDNode *G = NULL;
4333 std::string Str;
Evan Chengc3dcf5a2006-02-16 23:11:42 +00004334 bool CopyFromStr = false;
Evan Cheng6781b6e2006-02-15 21:59:04 +00004335
4336 if (Op2.getOpcode() == ISD::GlobalAddress)
4337 G = cast<GlobalAddressSDNode>(Op2);
4338 else if (Op2.getOpcode() == ISD::ADD &&
4339 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
4340 Op2.getOperand(1).getOpcode() == ISD::Constant) {
4341 G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
Evan Chengc3dcf5a2006-02-16 23:11:42 +00004342 SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
Evan Cheng6781b6e2006-02-15 21:59:04 +00004343 }
4344 if (G) {
4345 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
Evan Chengfeba5072006-11-29 01:58:12 +00004346 if (GV && GV->isConstant()) {
Evan Cheng38280c02006-03-10 23:52:03 +00004347 Str = GV->getStringValue(false);
Evan Chengc3dcf5a2006-02-16 23:11:42 +00004348 if (!Str.empty()) {
4349 CopyFromStr = true;
4350 SrcOff += SrcDelta;
4351 }
4352 }
Evan Cheng6781b6e2006-02-15 21:59:04 +00004353 }
4354
Evan Chenge2038bd2006-02-15 01:54:51 +00004355 for (unsigned i = 0; i < NumMemOps; i++) {
4356 MVT::ValueType VT = MemOps[i];
Dan Gohman1796f1f2007-05-18 17:52:13 +00004357 unsigned VTSize = MVT::getSizeInBits(VT) / 8;
Evan Cheng6781b6e2006-02-15 21:59:04 +00004358 SDOperand Value, Chain, Store;
4359
Evan Chengc3dcf5a2006-02-16 23:11:42 +00004360 if (CopyFromStr) {
Evan Cheng6781b6e2006-02-15 21:59:04 +00004361 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
4362 Chain = getRoot();
4363 Store =
Evan Chengdf9ac472006-10-05 23:01:46 +00004364 DAG.getStore(Chain, Value,
4365 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
Evan Chengab51cf22006-10-13 21:14:26 +00004366 I.getOperand(1), DstOff);
Evan Cheng6781b6e2006-02-15 21:59:04 +00004367 } else {
4368 Value = DAG.getLoad(VT, getRoot(),
4369 getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
Evan Chenge71fe34d2006-10-09 20:57:25 +00004370 I.getOperand(2), SrcOff);
Evan Cheng6781b6e2006-02-15 21:59:04 +00004371 Chain = Value.getValue(1);
4372 Store =
Evan Chengdf9ac472006-10-05 23:01:46 +00004373 DAG.getStore(Chain, Value,
4374 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
Evan Chengab51cf22006-10-13 21:14:26 +00004375 I.getOperand(1), DstOff);
Evan Cheng6781b6e2006-02-15 21:59:04 +00004376 }
Evan Chenge2038bd2006-02-15 01:54:51 +00004377 OutChains.push_back(Store);
Evan Cheng6781b6e2006-02-15 21:59:04 +00004378 SrcOff += VTSize;
4379 DstOff += VTSize;
Evan Chenge2038bd2006-02-15 01:54:51 +00004380 }
4381 }
4382 break;
4383 }
4384 }
4385
4386 if (!OutChains.empty()) {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00004387 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
4388 &OutChains[0], OutChains.size()));
Evan Chenge2038bd2006-02-15 01:54:51 +00004389 return;
Evan Cheng81fcea82006-02-14 08:22:34 +00004390 }
4391 }
4392
Chris Lattnerc24a1d32006-08-08 02:23:42 +00004393 DAG.setRoot(DAG.getNode(Op, MVT::Other, getRoot(), Op1, Op2, Op3, Op4));
Chris Lattner7a60d912005-01-07 07:47:53 +00004394}
4395
Chris Lattner875def92005-01-11 05:56:49 +00004396//===----------------------------------------------------------------------===//
4397// SelectionDAGISel code
4398//===----------------------------------------------------------------------===//
Chris Lattner7a60d912005-01-07 07:47:53 +00004399
4400unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
4401 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
4402}
4403
Chris Lattnerc9950c12005-08-17 06:37:43 +00004404void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Jim Laskeydcb2b832006-10-16 20:52:31 +00004405 AU.addRequired<AliasAnalysis>();
Chris Lattnerf6a6d3c2007-03-31 04:18:03 +00004406 AU.setPreservesAll();
Chris Lattnerc9950c12005-08-17 06:37:43 +00004407}
Chris Lattner7a60d912005-01-07 07:47:53 +00004408
Chris Lattner35397782005-12-05 07:10:48 +00004409
Chris Lattnerbba52192006-10-28 19:22:10 +00004410
Chris Lattner7a60d912005-01-07 07:47:53 +00004411bool SelectionDAGISel::runOnFunction(Function &Fn) {
4412 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
4413 RegMap = MF.getSSARegMap();
Bill Wendling22e978a2006-12-07 20:04:42 +00004414 DOUT << "\n\n\n=== " << Fn.getName() << "\n";
Chris Lattner7a60d912005-01-07 07:47:53 +00004415
4416 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
4417
Duncan Sands74137362007-06-13 16:53:21 +00004418 if (ExceptionHandling)
4419 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
4420 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(I->getTerminator()))
4421 // Mark landing pad.
4422 FuncInfo.MBBMap[Invoke->getSuccessor(1)]->setIsLandingPad();
Duncan Sands61166502007-06-06 10:05:18 +00004423
4424 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
Chris Lattner7a60d912005-01-07 07:47:53 +00004425 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukman835702a2005-04-21 22:36:52 +00004426
Evan Cheng276b44b2007-02-10 02:43:39 +00004427 // Add function live-ins to entry block live-in set.
4428 BasicBlock *EntryBB = &Fn.getEntryBlock();
4429 BB = FuncInfo.MBBMap[EntryBB];
4430 if (!MF.livein_empty())
4431 for (MachineFunction::livein_iterator I = MF.livein_begin(),
4432 E = MF.livein_end(); I != E; ++I)
4433 BB->addLiveIn(I->first);
4434
Duncan Sands92bf2c62007-06-15 19:04:19 +00004435#ifndef NDEBUG
4436 assert(FuncInfo.CatchInfoFound.size() == FuncInfo.CatchInfoLost.size() &&
4437 "Not all catch info was assigned to a landing pad!");
4438#endif
4439
Chris Lattner7a60d912005-01-07 07:47:53 +00004440 return true;
4441}
4442
Chris Lattnered0110b2006-10-27 21:36:01 +00004443SDOperand SelectionDAGLowering::CopyValueToVirtualRegister(Value *V,
4444 unsigned Reg) {
4445 SDOperand Op = getValue(V);
Chris Lattnere727af02005-01-13 20:50:02 +00004446 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattner33182322005-08-16 21:55:35 +00004447 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattnere727af02005-01-13 20:50:02 +00004448 "Copy from a reg to the same reg!");
Chris Lattner33182322005-08-16 21:55:35 +00004449
4450 // If this type is not legal, we must make sure to not create an invalid
4451 // register use.
4452 MVT::ValueType SrcVT = Op.getValueType();
4453 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
Chris Lattner33182322005-08-16 21:55:35 +00004454 if (SrcVT == DestVT) {
Chris Lattnered0110b2006-10-27 21:36:01 +00004455 return DAG.getCopyToReg(getRoot(), Reg, Op);
Chris Lattner672a42d2006-03-21 19:20:37 +00004456 } else if (SrcVT == MVT::Vector) {
Chris Lattner5fe1f542006-03-31 02:06:56 +00004457 // Handle copies from generic vectors to registers.
4458 MVT::ValueType PTyElementVT, PTyLegalElementVT;
Reid Spencerd84d35b2007-02-15 02:26:10 +00004459 unsigned NE = TLI.getVectorTypeBreakdown(cast<VectorType>(V->getType()),
Chris Lattner5fe1f542006-03-31 02:06:56 +00004460 PTyElementVT, PTyLegalElementVT);
Dan Gohman26455c42007-06-13 15:12:02 +00004461 uint64_t SrcVL = cast<ConstantSDNode>(*(Op.Val->op_end()-2))->getValue();
Chris Lattner672a42d2006-03-21 19:20:37 +00004462
Chris Lattner5fe1f542006-03-31 02:06:56 +00004463 // Loop over all of the elements of the resultant vector,
Dan Gohman26455c42007-06-13 15:12:02 +00004464 // VEXTRACT_VECTOR_ELT'ing or VEXTRACT_SUBVECTOR'ing them, converting them
4465 // to PTyLegalElementVT, then copying them into output registers.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00004466 SmallVector<SDOperand, 8> OutChains;
Chris Lattnered0110b2006-10-27 21:36:01 +00004467 SDOperand Root = getRoot();
Chris Lattner5fe1f542006-03-31 02:06:56 +00004468 for (unsigned i = 0; i != NE; ++i) {
Dan Gohman26455c42007-06-13 15:12:02 +00004469 SDOperand Elt = MVT::isVector(PTyElementVT) ?
4470 DAG.getNode(ISD::VEXTRACT_SUBVECTOR, PTyElementVT,
4471 Op, DAG.getConstant(i * (SrcVL / NE), TLI.getPointerTy())) :
4472 DAG.getNode(ISD::VEXTRACT_VECTOR_ELT, PTyElementVT,
4473 Op, DAG.getConstant(i, TLI.getPointerTy()));
Chris Lattner5fe1f542006-03-31 02:06:56 +00004474 if (PTyElementVT == PTyLegalElementVT) {
4475 // Elements are legal.
4476 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
4477 } else if (PTyLegalElementVT > PTyElementVT) {
4478 // Elements are promoted.
4479 if (MVT::isFloatingPoint(PTyLegalElementVT))
4480 Elt = DAG.getNode(ISD::FP_EXTEND, PTyLegalElementVT, Elt);
4481 else
4482 Elt = DAG.getNode(ISD::ANY_EXTEND, PTyLegalElementVT, Elt);
4483 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
4484 } else {
4485 // Elements are expanded.
4486 // The src value is expanded into multiple registers.
4487 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00004488 Elt, DAG.getConstant(0, TLI.getPointerTy()));
Chris Lattner5fe1f542006-03-31 02:06:56 +00004489 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00004490 Elt, DAG.getConstant(1, TLI.getPointerTy()));
Chris Lattner5fe1f542006-03-31 02:06:56 +00004491 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Lo));
4492 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Hi));
4493 }
Chris Lattner672a42d2006-03-21 19:20:37 +00004494 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +00004495 return DAG.getNode(ISD::TokenFactor, MVT::Other,
4496 &OutChains[0], OutChains.size());
Evan Cheng22cf8992006-12-13 20:57:08 +00004497 } else if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote) {
Chris Lattner33182322005-08-16 21:55:35 +00004498 // The src value is promoted to the register.
Chris Lattnerba28c272005-08-17 06:06:25 +00004499 if (MVT::isFloatingPoint(SrcVT))
4500 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
4501 else
Chris Lattnera66403d2005-09-02 00:19:37 +00004502 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
Chris Lattnered0110b2006-10-27 21:36:01 +00004503 return DAG.getCopyToReg(getRoot(), Reg, Op);
Chris Lattner33182322005-08-16 21:55:35 +00004504 } else {
Evan Cheng22cf8992006-12-13 20:57:08 +00004505 DestVT = TLI.getTypeToExpandTo(SrcVT);
4506 unsigned NumVals = TLI.getNumElements(SrcVT);
4507 if (NumVals == 1)
4508 return DAG.getCopyToReg(getRoot(), Reg,
4509 DAG.getNode(ISD::BIT_CONVERT, DestVT, Op));
4510 assert(NumVals == 2 && "1 to 4 (and more) expansion not implemented!");
Chris Lattner33182322005-08-16 21:55:35 +00004511 // The src value is expanded into multiple registers.
4512 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00004513 Op, DAG.getConstant(0, TLI.getPointerTy()));
Chris Lattner33182322005-08-16 21:55:35 +00004514 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00004515 Op, DAG.getConstant(1, TLI.getPointerTy()));
Chris Lattnered0110b2006-10-27 21:36:01 +00004516 Op = DAG.getCopyToReg(getRoot(), Reg, Lo);
Chris Lattner33182322005-08-16 21:55:35 +00004517 return DAG.getCopyToReg(Op, Reg+1, Hi);
4518 }
Chris Lattner7a60d912005-01-07 07:47:53 +00004519}
4520
Chris Lattner16f64df2005-01-17 17:15:02 +00004521void SelectionDAGISel::
Evan Chengde608342007-02-10 01:08:18 +00004522LowerArguments(BasicBlock *LLVMBB, SelectionDAGLowering &SDL,
Chris Lattner16f64df2005-01-17 17:15:02 +00004523 std::vector<SDOperand> &UnorderedChains) {
4524 // If this is the entry block, emit arguments.
Evan Chengde608342007-02-10 01:08:18 +00004525 Function &F = *LLVMBB->getParent();
Chris Lattnere3c2cf42005-01-17 17:55:19 +00004526 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattner6871b232005-10-30 19:42:35 +00004527 SDOperand OldRoot = SDL.DAG.getRoot();
4528 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner16f64df2005-01-17 17:15:02 +00004529
Chris Lattner6871b232005-10-30 19:42:35 +00004530 unsigned a = 0;
4531 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
4532 AI != E; ++AI, ++a)
4533 if (!AI->use_empty()) {
4534 SDL.setValue(AI, Args[a]);
Evan Cheng3784f3c52006-04-27 08:29:42 +00004535
Chris Lattner6871b232005-10-30 19:42:35 +00004536 // If this argument is live outside of the entry block, insert a copy from
4537 // whereever we got it to the vreg that other BB's will reference it as.
Chris Lattner8c504cf2007-02-25 18:40:32 +00004538 DenseMap<const Value*, unsigned>::iterator VMI=FuncInfo.ValueMap.find(AI);
4539 if (VMI != FuncInfo.ValueMap.end()) {
4540 SDOperand Copy = SDL.CopyValueToVirtualRegister(AI, VMI->second);
Chris Lattner6871b232005-10-30 19:42:35 +00004541 UnorderedChains.push_back(Copy);
4542 }
Chris Lattnere3c2cf42005-01-17 17:55:19 +00004543 }
Chris Lattner6871b232005-10-30 19:42:35 +00004544
Chris Lattner6871b232005-10-30 19:42:35 +00004545 // Finally, if the target has anything special to do, allow it to do so.
Chris Lattner957cb672006-05-16 06:10:58 +00004546 // FIXME: this should insert code into the DAG!
Chris Lattner6871b232005-10-30 19:42:35 +00004547 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner16f64df2005-01-17 17:15:02 +00004548}
4549
Duncan Sands92bf2c62007-06-15 19:04:19 +00004550static void copyCatchInfo(BasicBlock *SrcBB, BasicBlock *DestBB,
4551 MachineModuleInfo *MMI, FunctionLoweringInfo &FLI) {
4552 assert(!FLI.MBBMap[SrcBB]->isLandingPad() &&
4553 "Copying catch info out of a landing pad!");
4554 for (BasicBlock::iterator I = SrcBB->begin(), E = --SrcBB->end(); I != E; ++I)
4555 if (isFilterOrSelector(I)) {
4556 // Apply the catch info to DestBB.
4557 addCatchInfo(cast<CallInst>(*I), MMI, FLI.MBBMap[DestBB]);
4558#ifndef NDEBUG
4559 FLI.CatchInfoFound.insert(I);
4560#endif
4561 }
4562}
4563
Chris Lattner7a60d912005-01-07 07:47:53 +00004564void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
4565 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
Nate Begemaned728c12006-03-27 01:32:24 +00004566 FunctionLoweringInfo &FuncInfo) {
Chris Lattner7a60d912005-01-07 07:47:53 +00004567 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattner718b5c22005-01-13 17:59:43 +00004568
4569 std::vector<SDOperand> UnorderedChains;
Misha Brukman835702a2005-04-21 22:36:52 +00004570
Chris Lattner6871b232005-10-30 19:42:35 +00004571 // Lower any arguments needed in this block if this is the entry block.
Dan Gohmandcb291f2007-03-22 16:38:57 +00004572 if (LLVMBB == &LLVMBB->getParent()->getEntryBlock())
Chris Lattner6871b232005-10-30 19:42:35 +00004573 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner7a60d912005-01-07 07:47:53 +00004574
4575 BB = FuncInfo.MBBMap[LLVMBB];
4576 SDL.setCurrentBasicBlock(BB);
4577
Duncan Sands92bf2c62007-06-15 19:04:19 +00004578 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Duncan Sands61166502007-06-06 10:05:18 +00004579
Duncan Sands92bf2c62007-06-15 19:04:19 +00004580 if (ExceptionHandling && MMI && BB->isLandingPad()) {
4581 // Add a label to mark the beginning of the landing pad. Deletion of the
4582 // landing pad can thus be detected via the MachineModuleInfo.
4583 unsigned LabelID = MMI->addLandingPad(BB);
4584 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, DAG.getEntryNode(),
4585 DAG.getConstant(LabelID, MVT::i32)));
4586
4587 // FIXME: Hack around an exception handling flaw (PR1508): the personality
4588 // function and list of typeids logically belong to the invoke (or, if you
4589 // like, the basic block containing the invoke), and need to be associated
4590 // with it in the dwarf exception handling tables. Currently however the
4591 // information is provided by intrinsics (eh.filter and eh.selector) that
4592 // can be moved to unexpected places by the optimizers: if the unwind edge
4593 // is critical, then breaking it can result in the intrinsics being in the
4594 // successor of the landing pad, not the landing pad itself. This results
4595 // in exceptions not being caught because no typeids are associated with
4596 // the invoke. This may not be the only way things can go wrong, but it
4597 // is the only way we try to work around for the moment.
4598 BranchInst *Br = dyn_cast<BranchInst>(LLVMBB->getTerminator());
4599
4600 if (Br && Br->isUnconditional()) { // Critical edge?
4601 BasicBlock::iterator I, E;
4602 for (I = LLVMBB->begin(), E = --LLVMBB->end(); I != E; ++I)
4603 if (isFilterOrSelector(I))
4604 break;
4605
4606 if (I == E)
4607 // No catch info found - try to extract some from the successor.
4608 copyCatchInfo(Br->getSuccessor(0), LLVMBB, MMI, FuncInfo);
Duncan Sands61166502007-06-06 10:05:18 +00004609 }
4610 }
4611
Chris Lattner7a60d912005-01-07 07:47:53 +00004612 // Lower all of the non-terminator instructions.
4613 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
4614 I != E; ++I)
4615 SDL.visit(*I);
Duncan Sands97f72362007-06-13 05:51:31 +00004616
Chris Lattner7a60d912005-01-07 07:47:53 +00004617 // Ensure that all instructions which are used outside of their defining
Duncan Sands97f72362007-06-13 05:51:31 +00004618 // blocks are available as virtual registers. Invoke is handled elsewhere.
Chris Lattner7a60d912005-01-07 07:47:53 +00004619 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Duncan Sands97f72362007-06-13 05:51:31 +00004620 if (!I->use_empty() && !isa<PHINode>(I) && !isa<InvokeInst>(I)) {
Chris Lattner289aa442007-02-04 01:35:11 +00004621 DenseMap<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner7a60d912005-01-07 07:47:53 +00004622 if (VMI != FuncInfo.ValueMap.end())
Chris Lattner718b5c22005-01-13 17:59:43 +00004623 UnorderedChains.push_back(
Chris Lattnered0110b2006-10-27 21:36:01 +00004624 SDL.CopyValueToVirtualRegister(I, VMI->second));
Chris Lattner7a60d912005-01-07 07:47:53 +00004625 }
4626
4627 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
4628 // ensure constants are generated when needed. Remember the virtual registers
4629 // that need to be added to the Machine PHI nodes as input. We cannot just
4630 // directly add them, because expansion might result in multiple MBB's for one
4631 // BB. As such, the start of the BB might correspond to a different MBB than
4632 // the end.
Misha Brukman835702a2005-04-21 22:36:52 +00004633 //
Chris Lattner84a03502006-10-27 23:50:33 +00004634 TerminatorInst *TI = LLVMBB->getTerminator();
Chris Lattner7a60d912005-01-07 07:47:53 +00004635
4636 // Emit constants only once even if used by multiple PHI nodes.
4637 std::map<Constant*, unsigned> ConstantsOut;
Chris Lattner707339a52006-09-07 01:59:34 +00004638
Chris Lattner84a03502006-10-27 23:50:33 +00004639 // Vector bool would be better, but vector<bool> is really slow.
4640 std::vector<unsigned char> SuccsHandled;
4641 if (TI->getNumSuccessors())
4642 SuccsHandled.resize(BB->getParent()->getNumBlockIDs());
4643
Chris Lattner7a60d912005-01-07 07:47:53 +00004644 // Check successor nodes PHI nodes that expect a constant to be available from
4645 // this block.
Chris Lattner7a60d912005-01-07 07:47:53 +00004646 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
4647 BasicBlock *SuccBB = TI->getSuccessor(succ);
Chris Lattner707339a52006-09-07 01:59:34 +00004648 if (!isa<PHINode>(SuccBB->begin())) continue;
Chris Lattner84a03502006-10-27 23:50:33 +00004649 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
Chris Lattner707339a52006-09-07 01:59:34 +00004650
Chris Lattner84a03502006-10-27 23:50:33 +00004651 // If this terminator has multiple identical successors (common for
4652 // switches), only handle each succ once.
4653 unsigned SuccMBBNo = SuccMBB->getNumber();
4654 if (SuccsHandled[SuccMBBNo]) continue;
4655 SuccsHandled[SuccMBBNo] = true;
4656
4657 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
Chris Lattner7a60d912005-01-07 07:47:53 +00004658 PHINode *PN;
4659
4660 // At this point we know that there is a 1-1 correspondence between LLVM PHI
4661 // nodes and Machine PHI nodes, but the incoming operands have not been
4662 // emitted yet.
4663 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner84a03502006-10-27 23:50:33 +00004664 (PN = dyn_cast<PHINode>(I)); ++I) {
4665 // Ignore dead phi's.
4666 if (PN->use_empty()) continue;
4667
4668 unsigned Reg;
4669 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
Chris Lattner90f42382006-11-29 01:12:32 +00004670
Chris Lattner84a03502006-10-27 23:50:33 +00004671 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
4672 unsigned &RegOut = ConstantsOut[C];
4673 if (RegOut == 0) {
4674 RegOut = FuncInfo.CreateRegForValue(C);
4675 UnorderedChains.push_back(
4676 SDL.CopyValueToVirtualRegister(C, RegOut));
Chris Lattner7a60d912005-01-07 07:47:53 +00004677 }
Chris Lattner84a03502006-10-27 23:50:33 +00004678 Reg = RegOut;
4679 } else {
4680 Reg = FuncInfo.ValueMap[PHIOp];
4681 if (Reg == 0) {
4682 assert(isa<AllocaInst>(PHIOp) &&
4683 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
4684 "Didn't codegen value into a register!??");
4685 Reg = FuncInfo.CreateRegForValue(PHIOp);
4686 UnorderedChains.push_back(
4687 SDL.CopyValueToVirtualRegister(PHIOp, Reg));
Chris Lattnerba380352006-03-31 02:12:18 +00004688 }
Chris Lattner7a60d912005-01-07 07:47:53 +00004689 }
Chris Lattner84a03502006-10-27 23:50:33 +00004690
4691 // Remember that this register needs to added to the machine PHI node as
4692 // the input for this MBB.
4693 MVT::ValueType VT = TLI.getValueType(PN->getType());
4694 unsigned NumElements;
4695 if (VT != MVT::Vector)
4696 NumElements = TLI.getNumElements(VT);
4697 else {
4698 MVT::ValueType VT1,VT2;
4699 NumElements =
Reid Spencerd84d35b2007-02-15 02:26:10 +00004700 TLI.getVectorTypeBreakdown(cast<VectorType>(PN->getType()),
Chris Lattner84a03502006-10-27 23:50:33 +00004701 VT1, VT2);
4702 }
4703 for (unsigned i = 0, e = NumElements; i != e; ++i)
4704 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
4705 }
Chris Lattner7a60d912005-01-07 07:47:53 +00004706 }
4707 ConstantsOut.clear();
4708
Chris Lattner718b5c22005-01-13 17:59:43 +00004709 // Turn all of the unordered chains into one factored node.
Chris Lattner24516842005-01-13 19:53:14 +00004710 if (!UnorderedChains.empty()) {
Chris Lattnerb7cad902005-11-09 05:03:03 +00004711 SDOperand Root = SDL.getRoot();
4712 if (Root.getOpcode() != ISD::EntryToken) {
4713 unsigned i = 0, e = UnorderedChains.size();
4714 for (; i != e; ++i) {
4715 assert(UnorderedChains[i].Val->getNumOperands() > 1);
4716 if (UnorderedChains[i].Val->getOperand(0) == Root)
4717 break; // Don't add the root if we already indirectly depend on it.
4718 }
4719
4720 if (i == e)
4721 UnorderedChains.push_back(Root);
4722 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +00004723 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
4724 &UnorderedChains[0], UnorderedChains.size()));
Chris Lattner718b5c22005-01-13 17:59:43 +00004725 }
4726
Chris Lattner7a60d912005-01-07 07:47:53 +00004727 // Lower the terminator after the copies are emitted.
Duncan Sands97f72362007-06-13 05:51:31 +00004728 SDL.visit(*LLVMBB->getTerminator());
Chris Lattner4108bb02005-01-17 19:43:36 +00004729
Nate Begemaned728c12006-03-27 01:32:24 +00004730 // Copy over any CaseBlock records that may now exist due to SwitchInst
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004731 // lowering, as well as any jump table information.
Nate Begemaned728c12006-03-27 01:32:24 +00004732 SwitchCases.clear();
4733 SwitchCases = SDL.SwitchCases;
Anton Korobeynikov70378262007-03-25 15:07:15 +00004734 JTCases.clear();
4735 JTCases = SDL.JTCases;
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00004736 BitTestCases.clear();
4737 BitTestCases = SDL.BitTestCases;
4738
Chris Lattner4108bb02005-01-17 19:43:36 +00004739 // Make sure the root of the DAG is up-to-date.
4740 DAG.setRoot(SDL.getRoot());
Chris Lattner7a60d912005-01-07 07:47:53 +00004741}
4742
Nate Begemaned728c12006-03-27 01:32:24 +00004743void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
Jim Laskeydcb2b832006-10-16 20:52:31 +00004744 // Get alias analysis for load/store combining.
4745 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
4746
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00004747 // Run the DAG combiner in pre-legalize mode.
Jim Laskeydcb2b832006-10-16 20:52:31 +00004748 DAG.Combine(false, AA);
Nate Begeman007c6502005-09-07 00:15:36 +00004749
Bill Wendling22e978a2006-12-07 20:04:42 +00004750 DOUT << "Lowered selection DAG:\n";
Chris Lattner7a60d912005-01-07 07:47:53 +00004751 DEBUG(DAG.dump());
Nate Begemaned728c12006-03-27 01:32:24 +00004752
Chris Lattner7a60d912005-01-07 07:47:53 +00004753 // Second step, hack on the DAG until it only uses operations and types that
4754 // the target supports.
Chris Lattnerffcb0ae2005-01-23 04:36:26 +00004755 DAG.Legalize();
Nate Begemaned728c12006-03-27 01:32:24 +00004756
Bill Wendling22e978a2006-12-07 20:04:42 +00004757 DOUT << "Legalized selection DAG:\n";
Chris Lattner7a60d912005-01-07 07:47:53 +00004758 DEBUG(DAG.dump());
Nate Begemaned728c12006-03-27 01:32:24 +00004759
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00004760 // Run the DAG combiner in post-legalize mode.
Jim Laskeydcb2b832006-10-16 20:52:31 +00004761 DAG.Combine(true, AA);
Nate Begeman007c6502005-09-07 00:15:36 +00004762
Evan Cheng739a6a42006-01-21 02:32:06 +00004763 if (ViewISelDAGs) DAG.viewGraph();
Evan Cheng51ab4492006-04-28 02:09:19 +00004764
Chris Lattner5ca31d92005-03-30 01:10:47 +00004765 // Third, instruction select all of the operations to machine code, adding the
4766 // code to the MachineBasicBlock.
Chris Lattner7a60d912005-01-07 07:47:53 +00004767 InstructionSelectBasicBlock(DAG);
Nate Begemaned728c12006-03-27 01:32:24 +00004768
Bill Wendling22e978a2006-12-07 20:04:42 +00004769 DOUT << "Selected machine code:\n";
Chris Lattner7a60d912005-01-07 07:47:53 +00004770 DEBUG(BB->dump());
Nate Begemaned728c12006-03-27 01:32:24 +00004771}
Chris Lattner7a60d912005-01-07 07:47:53 +00004772
Nate Begemaned728c12006-03-27 01:32:24 +00004773void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
4774 FunctionLoweringInfo &FuncInfo) {
4775 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
4776 {
Jim Laskeyc56315c2007-01-26 21:22:28 +00004777 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
Nate Begemaned728c12006-03-27 01:32:24 +00004778 CurDAG = &DAG;
4779
4780 // First step, lower LLVM code to some DAG. This DAG may use operations and
4781 // types that are not supported by the target.
4782 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
4783
4784 // Second step, emit the lowered DAG as machine code.
4785 CodeGenAndEmitDAG(DAG);
4786 }
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00004787
4788 DOUT << "Total amount of phi nodes to update: "
4789 << PHINodesToUpdate.size() << "\n";
4790 DEBUG(for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i)
4791 DOUT << "Node " << i << " : (" << PHINodesToUpdate[i].first
4792 << ", " << PHINodesToUpdate[i].second << ")\n";);
Nate Begemaned728c12006-03-27 01:32:24 +00004793
Chris Lattner5ca31d92005-03-30 01:10:47 +00004794 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner7a60d912005-01-07 07:47:53 +00004795 // PHI nodes in successors.
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00004796 if (SwitchCases.empty() && JTCases.empty() && BitTestCases.empty()) {
Nate Begemaned728c12006-03-27 01:32:24 +00004797 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4798 MachineInstr *PHI = PHINodesToUpdate[i].first;
4799 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4800 "This is not a machine PHI node that we are updating!");
Chris Lattneraf23f9b2006-09-05 02:31:13 +00004801 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
Nate Begemaned728c12006-03-27 01:32:24 +00004802 PHI->addMachineBasicBlockOperand(BB);
4803 }
4804 return;
Chris Lattner7a60d912005-01-07 07:47:53 +00004805 }
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00004806
4807 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i) {
4808 // Lower header first, if it wasn't already lowered
4809 if (!BitTestCases[i].Emitted) {
4810 SelectionDAG HSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4811 CurDAG = &HSDAG;
4812 SelectionDAGLowering HSDL(HSDAG, TLI, FuncInfo);
4813 // Set the current basic block to the mbb we wish to insert the code into
4814 BB = BitTestCases[i].Parent;
4815 HSDL.setCurrentBasicBlock(BB);
4816 // Emit the code
4817 HSDL.visitBitTestHeader(BitTestCases[i]);
4818 HSDAG.setRoot(HSDL.getRoot());
4819 CodeGenAndEmitDAG(HSDAG);
4820 }
4821
4822 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
4823 SelectionDAG BSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4824 CurDAG = &BSDAG;
4825 SelectionDAGLowering BSDL(BSDAG, TLI, FuncInfo);
4826 // Set the current basic block to the mbb we wish to insert the code into
4827 BB = BitTestCases[i].Cases[j].ThisBB;
4828 BSDL.setCurrentBasicBlock(BB);
4829 // Emit the code
4830 if (j+1 != ej)
4831 BSDL.visitBitTestCase(BitTestCases[i].Cases[j+1].ThisBB,
4832 BitTestCases[i].Reg,
4833 BitTestCases[i].Cases[j]);
4834 else
4835 BSDL.visitBitTestCase(BitTestCases[i].Default,
4836 BitTestCases[i].Reg,
4837 BitTestCases[i].Cases[j]);
4838
4839
4840 BSDAG.setRoot(BSDL.getRoot());
4841 CodeGenAndEmitDAG(BSDAG);
4842 }
4843
4844 // Update PHI Nodes
4845 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
4846 MachineInstr *PHI = PHINodesToUpdate[pi].first;
4847 MachineBasicBlock *PHIBB = PHI->getParent();
4848 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4849 "This is not a machine PHI node that we are updating!");
4850 // This is "default" BB. We have two jumps to it. From "header" BB and
4851 // from last "case" BB.
4852 if (PHIBB == BitTestCases[i].Default) {
4853 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
4854 PHI->addMachineBasicBlockOperand(BitTestCases[i].Parent);
Anton Korobeynikove2880402007-04-13 06:53:51 +00004855 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00004856 PHI->addMachineBasicBlockOperand(BitTestCases[i].Cases.back().ThisBB);
4857 }
4858 // One of "cases" BB.
4859 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
4860 MachineBasicBlock* cBB = BitTestCases[i].Cases[j].ThisBB;
4861 if (cBB->succ_end() !=
4862 std::find(cBB->succ_begin(),cBB->succ_end(), PHIBB)) {
4863 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
4864 PHI->addMachineBasicBlockOperand(cBB);
4865 }
4866 }
4867 }
4868 }
4869
Nate Begeman866b4b42006-04-23 06:26:20 +00004870 // If the JumpTable record is filled in, then we need to emit a jump table.
4871 // Updating the PHI nodes is tricky in this case, since we need to determine
4872 // whether the PHI is a successor of the range check MBB or the jump table MBB
Anton Korobeynikov70378262007-03-25 15:07:15 +00004873 for (unsigned i = 0, e = JTCases.size(); i != e; ++i) {
4874 // Lower header first, if it wasn't already lowered
4875 if (!JTCases[i].first.Emitted) {
4876 SelectionDAG HSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4877 CurDAG = &HSDAG;
4878 SelectionDAGLowering HSDL(HSDAG, TLI, FuncInfo);
4879 // Set the current basic block to the mbb we wish to insert the code into
4880 BB = JTCases[i].first.HeaderBB;
4881 HSDL.setCurrentBasicBlock(BB);
4882 // Emit the code
4883 HSDL.visitJumpTableHeader(JTCases[i].second, JTCases[i].first);
4884 HSDAG.setRoot(HSDL.getRoot());
4885 CodeGenAndEmitDAG(HSDAG);
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00004886 }
Anton Korobeynikov70378262007-03-25 15:07:15 +00004887
4888 SelectionDAG JSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4889 CurDAG = &JSDAG;
4890 SelectionDAGLowering JSDL(JSDAG, TLI, FuncInfo);
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004891 // Set the current basic block to the mbb we wish to insert the code into
Anton Korobeynikov70378262007-03-25 15:07:15 +00004892 BB = JTCases[i].second.MBB;
4893 JSDL.setCurrentBasicBlock(BB);
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004894 // Emit the code
Anton Korobeynikov70378262007-03-25 15:07:15 +00004895 JSDL.visitJumpTable(JTCases[i].second);
4896 JSDAG.setRoot(JSDL.getRoot());
4897 CodeGenAndEmitDAG(JSDAG);
4898
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004899 // Update PHI Nodes
4900 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
4901 MachineInstr *PHI = PHINodesToUpdate[pi].first;
4902 MachineBasicBlock *PHIBB = PHI->getParent();
4903 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4904 "This is not a machine PHI node that we are updating!");
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00004905 // "default" BB. We can go there only from header BB.
Anton Korobeynikov70378262007-03-25 15:07:15 +00004906 if (PHIBB == JTCases[i].second.Default) {
Chris Lattneraf23f9b2006-09-05 02:31:13 +00004907 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Anton Korobeynikov70378262007-03-25 15:07:15 +00004908 PHI->addMachineBasicBlockOperand(JTCases[i].first.HeaderBB);
Nate Begemandf488392006-05-03 03:48:02 +00004909 }
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00004910 // JT BB. Just iterate over successors here
Nate Begemandf488392006-05-03 03:48:02 +00004911 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
Chris Lattneraf23f9b2006-09-05 02:31:13 +00004912 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Nate Begemandf488392006-05-03 03:48:02 +00004913 PHI->addMachineBasicBlockOperand(BB);
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004914 }
4915 }
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004916 }
4917
Chris Lattner76a7bc82006-10-22 23:00:53 +00004918 // If the switch block involved a branch to one of the actual successors, we
4919 // need to update PHI nodes in that block.
4920 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4921 MachineInstr *PHI = PHINodesToUpdate[i].first;
4922 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4923 "This is not a machine PHI node that we are updating!");
4924 if (BB->isSuccessor(PHI->getParent())) {
4925 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
4926 PHI->addMachineBasicBlockOperand(BB);
4927 }
4928 }
4929
Nate Begemaned728c12006-03-27 01:32:24 +00004930 // If we generated any switch lowering information, build and codegen any
4931 // additional DAGs necessary.
Chris Lattner707339a52006-09-07 01:59:34 +00004932 for (unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
Jim Laskeyc56315c2007-01-26 21:22:28 +00004933 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
Nate Begemaned728c12006-03-27 01:32:24 +00004934 CurDAG = &SDAG;
4935 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
Chris Lattner707339a52006-09-07 01:59:34 +00004936
Nate Begemaned728c12006-03-27 01:32:24 +00004937 // Set the current basic block to the mbb we wish to insert the code into
4938 BB = SwitchCases[i].ThisBB;
4939 SDL.setCurrentBasicBlock(BB);
Chris Lattner707339a52006-09-07 01:59:34 +00004940
Nate Begemaned728c12006-03-27 01:32:24 +00004941 // Emit the code
4942 SDL.visitSwitchCase(SwitchCases[i]);
4943 SDAG.setRoot(SDL.getRoot());
4944 CodeGenAndEmitDAG(SDAG);
Chris Lattner707339a52006-09-07 01:59:34 +00004945
4946 // Handle any PHI nodes in successors of this chunk, as if we were coming
4947 // from the original BB before switch expansion. Note that PHI nodes can
4948 // occur multiple times in PHINodesToUpdate. We have to be very careful to
4949 // handle them the right number of times.
Chris Lattner963ddad2006-10-24 17:57:59 +00004950 while ((BB = SwitchCases[i].TrueBB)) { // Handle LHS and RHS.
Chris Lattner707339a52006-09-07 01:59:34 +00004951 for (MachineBasicBlock::iterator Phi = BB->begin();
4952 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
4953 // This value for this PHI node is recorded in PHINodesToUpdate, get it.
4954 for (unsigned pn = 0; ; ++pn) {
4955 assert(pn != PHINodesToUpdate.size() && "Didn't find PHI entry!");
4956 if (PHINodesToUpdate[pn].first == Phi) {
4957 Phi->addRegOperand(PHINodesToUpdate[pn].second, false);
4958 Phi->addMachineBasicBlockOperand(SwitchCases[i].ThisBB);
4959 break;
4960 }
4961 }
Nate Begemaned728c12006-03-27 01:32:24 +00004962 }
Chris Lattner707339a52006-09-07 01:59:34 +00004963
4964 // Don't process RHS if same block as LHS.
Chris Lattner963ddad2006-10-24 17:57:59 +00004965 if (BB == SwitchCases[i].FalseBB)
4966 SwitchCases[i].FalseBB = 0;
Chris Lattner707339a52006-09-07 01:59:34 +00004967
4968 // If we haven't handled the RHS, do so now. Otherwise, we're done.
Chris Lattner61bcf912006-10-24 18:07:37 +00004969 SwitchCases[i].TrueBB = SwitchCases[i].FalseBB;
Chris Lattner963ddad2006-10-24 17:57:59 +00004970 SwitchCases[i].FalseBB = 0;
Nate Begemaned728c12006-03-27 01:32:24 +00004971 }
Chris Lattner963ddad2006-10-24 17:57:59 +00004972 assert(SwitchCases[i].TrueBB == 0 && SwitchCases[i].FalseBB == 0);
Chris Lattner5ca31d92005-03-30 01:10:47 +00004973 }
Chris Lattner7a60d912005-01-07 07:47:53 +00004974}
Evan Cheng739a6a42006-01-21 02:32:06 +00004975
Jim Laskey95eda5b2006-08-01 14:21:23 +00004976
Evan Cheng739a6a42006-01-21 02:32:06 +00004977//===----------------------------------------------------------------------===//
4978/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
4979/// target node in the graph.
4980void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
4981 if (ViewSchedDAGs) DAG.viewGraph();
Evan Chengc1e1d972006-01-23 07:01:07 +00004982
Jim Laskey29e635d2006-08-02 12:30:23 +00004983 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
Jim Laskey95eda5b2006-08-01 14:21:23 +00004984
4985 if (!Ctor) {
Jim Laskey29e635d2006-08-02 12:30:23 +00004986 Ctor = ISHeuristic;
Jim Laskey17c67ef2006-08-01 19:14:14 +00004987 RegisterScheduler::setDefault(Ctor);
Evan Chengc1e1d972006-01-23 07:01:07 +00004988 }
Jim Laskey95eda5b2006-08-01 14:21:23 +00004989
Jim Laskey03593f72006-08-01 18:29:48 +00004990 ScheduleDAG *SL = Ctor(this, &DAG, BB);
Chris Lattnere23928c2006-01-21 19:12:11 +00004991 BB = SL->Run();
Evan Chengf9adce92006-02-04 06:49:00 +00004992 delete SL;
Evan Cheng739a6a42006-01-21 02:32:06 +00004993}
Chris Lattnerdcf785b2006-02-24 02:13:54 +00004994
Chris Lattner47639db2006-03-06 00:22:00 +00004995
Jim Laskey03593f72006-08-01 18:29:48 +00004996HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
4997 return new HazardRecognizer();
4998}
4999
Chris Lattner6df34962006-10-11 03:58:02 +00005000//===----------------------------------------------------------------------===//
5001// Helper functions used by the generated instruction selector.
5002//===----------------------------------------------------------------------===//
5003// Calls to these methods are generated by tblgen.
5004
5005/// CheckAndMask - The isel is trying to match something like (and X, 255). If
5006/// the dag combiner simplified the 255, we still want to match. RHS is the
5007/// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
5008/// specified in the .td file (e.g. 255).
5009bool SelectionDAGISel::CheckAndMask(SDOperand LHS, ConstantSDNode *RHS,
5010 int64_t DesiredMaskS) {
5011 uint64_t ActualMask = RHS->getValue();
5012 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
5013
5014 // If the actual mask exactly matches, success!
5015 if (ActualMask == DesiredMask)
5016 return true;
5017
5018 // If the actual AND mask is allowing unallowed bits, this doesn't match.
5019 if (ActualMask & ~DesiredMask)
5020 return false;
5021
5022 // Otherwise, the DAG Combiner may have proven that the value coming in is
5023 // either already zero or is not demanded. Check for known zero input bits.
5024 uint64_t NeededMask = DesiredMask & ~ActualMask;
5025 if (getTargetLowering().MaskedValueIsZero(LHS, NeededMask))
5026 return true;
5027
5028 // TODO: check to see if missing bits are just not demanded.
5029
5030 // Otherwise, this pattern doesn't match.
5031 return false;
5032}
5033
5034/// CheckOrMask - The isel is trying to match something like (or X, 255). If
5035/// the dag combiner simplified the 255, we still want to match. RHS is the
5036/// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
5037/// specified in the .td file (e.g. 255).
5038bool SelectionDAGISel::CheckOrMask(SDOperand LHS, ConstantSDNode *RHS,
5039 int64_t DesiredMaskS) {
5040 uint64_t ActualMask = RHS->getValue();
5041 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
5042
5043 // If the actual mask exactly matches, success!
5044 if (ActualMask == DesiredMask)
5045 return true;
5046
5047 // If the actual AND mask is allowing unallowed bits, this doesn't match.
5048 if (ActualMask & ~DesiredMask)
5049 return false;
5050
5051 // Otherwise, the DAG Combiner may have proven that the value coming in is
5052 // either already zero or is not demanded. Check for known zero input bits.
5053 uint64_t NeededMask = DesiredMask & ~ActualMask;
5054
5055 uint64_t KnownZero, KnownOne;
5056 getTargetLowering().ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
5057
5058 // If all the missing bits in the or are already known to be set, match!
5059 if ((NeededMask & KnownOne) == NeededMask)
5060 return true;
5061
5062 // TODO: check to see if missing bits are just not demanded.
5063
5064 // Otherwise, this pattern doesn't match.
5065 return false;
5066}
5067
Jim Laskey03593f72006-08-01 18:29:48 +00005068
Chris Lattnerdcf785b2006-02-24 02:13:54 +00005069/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
5070/// by tblgen. Others should not call it.
5071void SelectionDAGISel::
5072SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
5073 std::vector<SDOperand> InOps;
5074 std::swap(InOps, Ops);
5075
5076 Ops.push_back(InOps[0]); // input chain.
5077 Ops.push_back(InOps[1]); // input asm string.
5078
Chris Lattnerdcf785b2006-02-24 02:13:54 +00005079 unsigned i = 2, e = InOps.size();
5080 if (InOps[e-1].getValueType() == MVT::Flag)
5081 --e; // Don't process a flag operand if it is here.
5082
5083 while (i != e) {
5084 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
5085 if ((Flags & 7) != 4 /*MEM*/) {
5086 // Just skip over this operand, copying the operands verbatim.
5087 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
5088 i += (Flags >> 3) + 1;
5089 } else {
5090 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
5091 // Otherwise, this is a memory operand. Ask the target to select it.
5092 std::vector<SDOperand> SelOps;
5093 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
Bill Wendling22e978a2006-12-07 20:04:42 +00005094 cerr << "Could not match memory address. Inline asm failure!\n";
Chris Lattnerdcf785b2006-02-24 02:13:54 +00005095 exit(1);
5096 }
5097
5098 // Add this to the output node.
Chris Lattnerb49917d2007-04-09 00:33:58 +00005099 MVT::ValueType IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
Chris Lattner9bd5ed62006-12-16 21:14:48 +00005100 Ops.push_back(DAG.getTargetConstant(4/*MEM*/ | (SelOps.size() << 3),
Chris Lattnerb49917d2007-04-09 00:33:58 +00005101 IntPtrTy));
Chris Lattnerdcf785b2006-02-24 02:13:54 +00005102 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
5103 i += 2;
5104 }
5105 }
5106
5107 // Add the flag input back if present.
5108 if (e != InOps.size())
5109 Ops.push_back(InOps.back());
5110}
Devang Patel09f162c2007-05-01 21:15:47 +00005111
Devang Patel8c78a0b2007-05-03 01:11:54 +00005112char SelectionDAGISel::ID = 0;