blob: 472ca4963755a2849f9bdc2198c11f44d6827e35 [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());
Dan Gohmana8665142007-06-25 16:23:39 +0000293 unsigned NumRegisters = TLI.getNumRegisters(VT);
Chris Lattner84a03502006-10-27 23:50:33 +0000294 unsigned PHIReg = ValueMap[PN];
295 assert(PHIReg && "PHI node does not have an assigned virtual register!");
Evan Cheng20350c42006-11-27 23:37:22 +0000296 const TargetInstrInfo *TII = TLI.getTargetMachine().getInstrInfo();
Dan Gohman04deef32007-06-21 14:42:22 +0000297 for (unsigned i = 0; i != NumRegisters; ++i)
Evan Cheng20350c42006-11-27 23:37:22 +0000298 BuildMI(MBB, TII->get(TargetInstrInfo::PHI), PHIReg+i);
Chris Lattner84a03502006-10-27 23:50:33 +0000299 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000300 }
301}
302
Chris Lattner49409cb2006-03-16 19:51:18 +0000303/// CreateRegForValue - Allocate the appropriate number of virtual registers of
304/// the correctly promoted or expanded types. Assign these registers
305/// consecutive vreg numbers and return the first assigned number.
306unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
307 MVT::ValueType VT = TLI.getValueType(V->getType());
308
309 // The number of multiples of registers that we need, to, e.g., split up
310 // a <2 x int64> -> 4 x i32 registers.
311 unsigned NumVectorRegs = 1;
312
Reid Spencer09575ba2007-02-15 03:39:18 +0000313 // If this is a vector type, figure out what type it will decompose into
Chris Lattner49409cb2006-03-16 19:51:18 +0000314 // and how many of the elements it will use.
Dan Gohmana8665142007-06-25 16:23:39 +0000315 if (MVT::isVector(VT)) {
Reid Spencerd84d35b2007-02-15 02:26:10 +0000316 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner49409cb2006-03-16 19:51:18 +0000317 unsigned NumElts = PTy->getNumElements();
318 MVT::ValueType EltTy = TLI.getValueType(PTy->getElementType());
Dan Gohman1796f1f2007-05-18 17:52:13 +0000319 MVT::ValueType VecTy = MVT::getVectorType(EltTy, NumElts);
Chris Lattner49409cb2006-03-16 19:51:18 +0000320
321 // Divide the input until we get to a supported size. This will always
322 // end with a scalar if the target doesn't support vectors.
Bill Wendling47917b62007-04-24 21:13:23 +0000323 while (NumElts > 1 && !TLI.isTypeLegal(VecTy)) {
Chris Lattner49409cb2006-03-16 19:51:18 +0000324 NumElts >>= 1;
325 NumVectorRegs <<= 1;
Dan Gohman1796f1f2007-05-18 17:52:13 +0000326 VecTy = MVT::getVectorType(EltTy, NumElts);
Chris Lattner49409cb2006-03-16 19:51:18 +0000327 }
Bill Wendling47917b62007-04-24 21:13:23 +0000328
329 // Check that VecTy isn't a 1-element vector.
330 if (NumElts == 1 && VecTy == MVT::Other)
Chris Lattner7ececaa2006-03-16 23:05:19 +0000331 VT = EltTy;
332 else
Bill Wendling47917b62007-04-24 21:13:23 +0000333 VT = VecTy;
Chris Lattner49409cb2006-03-16 19:51:18 +0000334 }
Bill Wendling47917b62007-04-24 21:13:23 +0000335
Chris Lattner49409cb2006-03-16 19:51:18 +0000336 // The common case is that we will only create one register for this
337 // value. If we have that case, create and return the virtual register.
Dan Gohman04deef32007-06-21 14:42:22 +0000338 unsigned NV = TLI.getNumRegisters(VT);
Chris Lattner49409cb2006-03-16 19:51:18 +0000339 if (NV == 1) {
340 // If we are promoting this value, pick the next largest supported type.
341 MVT::ValueType PromotedType = TLI.getTypeToTransformTo(VT);
342 unsigned Reg = MakeReg(PromotedType);
343 // If this is a vector of supported or promoted types (e.g. 4 x i16),
344 // create all of the registers.
345 for (unsigned i = 1; i != NumVectorRegs; ++i)
346 MakeReg(PromotedType);
347 return Reg;
348 }
349
350 // If this value is represented with multiple target registers, make sure
351 // to create enough consecutive registers of the right (smaller) type.
Evan Cheng22cf8992006-12-13 20:57:08 +0000352 VT = TLI.getTypeToExpandTo(VT);
353 unsigned R = MakeReg(VT);
Chris Lattner49409cb2006-03-16 19:51:18 +0000354 for (unsigned i = 1; i != NV*NumVectorRegs; ++i)
Evan Cheng22cf8992006-12-13 20:57:08 +0000355 MakeReg(VT);
Chris Lattner49409cb2006-03-16 19:51:18 +0000356 return R;
357}
Chris Lattner7a60d912005-01-07 07:47:53 +0000358
359//===----------------------------------------------------------------------===//
360/// SelectionDAGLowering - This is the common target-independent lowering
361/// implementation that is parameterized by a TargetLowering object.
362/// Also, targets can overload any lowering method.
363///
364namespace llvm {
365class SelectionDAGLowering {
366 MachineBasicBlock *CurMBB;
367
Chris Lattner79084302007-02-04 01:31:47 +0000368 DenseMap<const Value*, SDOperand> NodeMap;
Chris Lattner7a60d912005-01-07 07:47:53 +0000369
Chris Lattner4d9651c2005-01-17 22:19:26 +0000370 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
371 /// them up and then emit token factor nodes when possible. This allows us to
372 /// get simple disambiguation between loads without worrying about alias
373 /// analysis.
374 std::vector<SDOperand> PendingLoads;
375
Anton Korobeynikov915e6172007-04-04 21:14:49 +0000376 /// Case - A struct to record the Value for a switch case, and the
377 /// case's target basic block.
378 struct Case {
379 Constant* Low;
380 Constant* High;
381 MachineBasicBlock* BB;
382
383 Case() : Low(0), High(0), BB(0) { }
384 Case(Constant* low, Constant* high, MachineBasicBlock* bb) :
385 Low(low), High(high), BB(bb) { }
386 uint64_t size() const {
387 uint64_t rHigh = cast<ConstantInt>(High)->getSExtValue();
388 uint64_t rLow = cast<ConstantInt>(Low)->getSExtValue();
389 return (rHigh - rLow + 1ULL);
390 }
391 };
392
Anton Korobeynikov506eaf72007-04-09 12:31:58 +0000393 struct CaseBits {
394 uint64_t Mask;
395 MachineBasicBlock* BB;
396 unsigned Bits;
397
398 CaseBits(uint64_t mask, MachineBasicBlock* bb, unsigned bits):
399 Mask(mask), BB(bb), Bits(bits) { }
400 };
401
Anton Korobeynikov915e6172007-04-04 21:14:49 +0000402 typedef std::vector<Case> CaseVector;
Anton Korobeynikov506eaf72007-04-09 12:31:58 +0000403 typedef std::vector<CaseBits> CaseBitsVector;
Anton Korobeynikov915e6172007-04-04 21:14:49 +0000404 typedef CaseVector::iterator CaseItr;
405 typedef std::pair<CaseItr, CaseItr> CaseRange;
Nate Begemaned728c12006-03-27 01:32:24 +0000406
407 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
408 /// of conditional branches.
409 struct CaseRec {
410 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
411 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
412
413 /// CaseBB - The MBB in which to emit the compare and branch
414 MachineBasicBlock *CaseBB;
415 /// LT, GE - If nonzero, we know the current case value must be less-than or
416 /// greater-than-or-equal-to these Constants.
417 Constant *LT;
418 Constant *GE;
419 /// Range - A pair of iterators representing the range of case values to be
420 /// processed at this point in the binary search tree.
421 CaseRange Range;
422 };
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +0000423
424 typedef std::vector<CaseRec> CaseRecVector;
Anton Korobeynikov915e6172007-04-04 21:14:49 +0000425
426 /// The comparison function for sorting the switch case values in the vector.
427 /// WARNING: Case ranges should be disjoint!
Nate Begemaned728c12006-03-27 01:32:24 +0000428 struct CaseCmp {
Anton Korobeynikov506eaf72007-04-09 12:31:58 +0000429 bool operator () (const Case& C1, const Case& C2) {
Anton Korobeynikov915e6172007-04-04 21:14:49 +0000430 assert(isa<ConstantInt>(C1.Low) && isa<ConstantInt>(C2.High));
431 const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
432 const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
433 return CI1->getValue().slt(CI2->getValue());
Nate Begemaned728c12006-03-27 01:32:24 +0000434 }
435 };
Anton Korobeynikov915e6172007-04-04 21:14:49 +0000436
Anton Korobeynikov506eaf72007-04-09 12:31:58 +0000437 struct CaseBitsCmp {
438 bool operator () (const CaseBits& C1, const CaseBits& C2) {
439 return C1.Bits > C2.Bits;
440 }
441 };
442
Anton Korobeynikov915e6172007-04-04 21:14:49 +0000443 unsigned Clusterify(CaseVector& Cases, const SwitchInst &SI);
Nate Begemaned728c12006-03-27 01:32:24 +0000444
Chris Lattner7a60d912005-01-07 07:47:53 +0000445public:
446 // TLI - This is information that describes the available target features we
447 // need for lowering. This indicates when operations are unavailable,
448 // implemented with a libcall, etc.
449 TargetLowering &TLI;
450 SelectionDAG &DAG;
Owen Anderson20a631f2006-05-03 01:29:57 +0000451 const TargetData *TD;
Chris Lattner7a60d912005-01-07 07:47:53 +0000452
Nate Begemaned728c12006-03-27 01:32:24 +0000453 /// SwitchCases - Vector of CaseBlock structures used to communicate
454 /// SwitchInst code generation information.
455 std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
Anton Korobeynikov70378262007-03-25 15:07:15 +0000456 /// JTCases - Vector of JumpTable structures used to communicate
457 /// SwitchInst code generation information.
458 std::vector<SelectionDAGISel::JumpTableBlock> JTCases;
Anton Korobeynikov506eaf72007-04-09 12:31:58 +0000459 std::vector<SelectionDAGISel::BitTestBlock> BitTestCases;
Nate Begemaned728c12006-03-27 01:32:24 +0000460
Chris Lattner7a60d912005-01-07 07:47:53 +0000461 /// FuncInfo - Information about the function as a whole.
462 ///
463 FunctionLoweringInfo &FuncInfo;
464
465 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Misha Brukman835702a2005-04-21 22:36:52 +0000466 FunctionLoweringInfo &funcinfo)
Chris Lattner7a60d912005-01-07 07:47:53 +0000467 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
Anton Korobeynikov70378262007-03-25 15:07:15 +0000468 FuncInfo(funcinfo) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000469 }
470
Chris Lattner4108bb02005-01-17 19:43:36 +0000471 /// getRoot - Return the current virtual root of the Selection DAG.
472 ///
473 SDOperand getRoot() {
Chris Lattner4d9651c2005-01-17 22:19:26 +0000474 if (PendingLoads.empty())
475 return DAG.getRoot();
Misha Brukman835702a2005-04-21 22:36:52 +0000476
Chris Lattner4d9651c2005-01-17 22:19:26 +0000477 if (PendingLoads.size() == 1) {
478 SDOperand Root = PendingLoads[0];
479 DAG.setRoot(Root);
480 PendingLoads.clear();
481 return Root;
482 }
483
484 // Otherwise, we have to make a token factor node.
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000485 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
486 &PendingLoads[0], PendingLoads.size());
Chris Lattner4d9651c2005-01-17 22:19:26 +0000487 PendingLoads.clear();
488 DAG.setRoot(Root);
489 return Root;
Chris Lattner4108bb02005-01-17 19:43:36 +0000490 }
491
Chris Lattnered0110b2006-10-27 21:36:01 +0000492 SDOperand CopyValueToVirtualRegister(Value *V, unsigned Reg);
493
Chris Lattner7a60d912005-01-07 07:47:53 +0000494 void visit(Instruction &I) { visit(I.getOpcode(), I); }
495
496 void visit(unsigned Opcode, User &I) {
Chris Lattnerd5e604d2006-11-10 04:41:34 +0000497 // Note: this doesn't use InstVisitor, because it has to work with
498 // ConstantExpr's in addition to instructions.
Chris Lattner7a60d912005-01-07 07:47:53 +0000499 switch (Opcode) {
500 default: assert(0 && "Unknown instruction type encountered!");
501 abort();
502 // Build the switch statement using the Instruction.def file.
503#define HANDLE_INST(NUM, OPCODE, CLASS) \
504 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
505#include "llvm/Instruction.def"
506 }
507 }
508
509 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
510
Chris Lattner4024c002006-03-15 22:19:46 +0000511 SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Chenge71fe34d2006-10-09 20:57:25 +0000512 const Value *SV, SDOperand Root,
Christopher Lamb8af6d582007-04-22 23:15:30 +0000513 bool isVolatile, unsigned Alignment);
Chris Lattner7a60d912005-01-07 07:47:53 +0000514
515 SDOperand getIntPtrConstant(uint64_t Val) {
516 return DAG.getConstant(Val, TLI.getPointerTy());
517 }
518
Chris Lattner8471b152006-03-16 19:57:50 +0000519 SDOperand getValue(const Value *V);
Chris Lattner7a60d912005-01-07 07:47:53 +0000520
Chris Lattner79084302007-02-04 01:31:47 +0000521 void setValue(const Value *V, SDOperand NewN) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000522 SDOperand &N = NodeMap[V];
523 assert(N.Val == 0 && "Already set a value for this node!");
Chris Lattner79084302007-02-04 01:31:47 +0000524 N = NewN;
Chris Lattner7a60d912005-01-07 07:47:53 +0000525 }
Chris Lattner1558fc62006-02-01 18:59:47 +0000526
Chris Lattner8cfd33b2007-04-30 21:11:17 +0000527 void GetRegistersForValue(AsmOperandInfo &OpInfo, bool HasEarlyClobber,
528 std::set<unsigned> &OutputRegs,
529 std::set<unsigned> &InputRegs);
Nate Begemaned728c12006-03-27 01:32:24 +0000530
Chris Lattnered0110b2006-10-27 21:36:01 +0000531 void FindMergedConditions(Value *Cond, MachineBasicBlock *TBB,
532 MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
533 unsigned Opc);
Chris Lattner84a03502006-10-27 23:50:33 +0000534 bool isExportableFromCurrentBlock(Value *V, const BasicBlock *FromBB);
Chris Lattnered0110b2006-10-27 21:36:01 +0000535 void ExportFromCurrentBlock(Value *V);
Jim Laskey31fef782007-02-23 21:45:01 +0000536 void LowerCallTo(Instruction &I,
537 const Type *CalledValueTy, unsigned CallingConv,
Anton Korobeynikov3b327822007-05-23 11:08:31 +0000538 bool IsTailCall, SDOperand Callee, unsigned OpIdx,
539 MachineBasicBlock *LandingPad = NULL);
540
Chris Lattner7a60d912005-01-07 07:47:53 +0000541 // Terminator instructions.
542 void visitRet(ReturnInst &I);
543 void visitBr(BranchInst &I);
Nate Begemaned728c12006-03-27 01:32:24 +0000544 void visitSwitch(SwitchInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000545 void visitUnreachable(UnreachableInst &I) { /* noop */ }
546
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +0000547 // Helpers for visitSwitch
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +0000548 bool handleSmallSwitchRange(CaseRec& CR,
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +0000549 CaseRecVector& WorkList,
550 Value* SV,
551 MachineBasicBlock* Default);
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +0000552 bool handleJTSwitchCase(CaseRec& CR,
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +0000553 CaseRecVector& WorkList,
554 Value* SV,
555 MachineBasicBlock* Default);
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +0000556 bool handleBTSplitSwitchCase(CaseRec& CR,
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +0000557 CaseRecVector& WorkList,
558 Value* SV,
559 MachineBasicBlock* Default);
Anton Korobeynikov506eaf72007-04-09 12:31:58 +0000560 bool handleBitTestsSwitchCase(CaseRec& CR,
561 CaseRecVector& WorkList,
562 Value* SV,
563 MachineBasicBlock* Default);
Nate Begemaned728c12006-03-27 01:32:24 +0000564 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
Anton Korobeynikov506eaf72007-04-09 12:31:58 +0000565 void visitBitTestHeader(SelectionDAGISel::BitTestBlock &B);
566 void visitBitTestCase(MachineBasicBlock* NextMBB,
567 unsigned Reg,
568 SelectionDAGISel::BitTestCase &B);
Nate Begeman4ca2ea52006-04-22 18:53:45 +0000569 void visitJumpTable(SelectionDAGISel::JumpTable &JT);
Anton Korobeynikov70378262007-03-25 15:07:15 +0000570 void visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
571 SelectionDAGISel::JumpTableHeader &JTH);
Nate Begemaned728c12006-03-27 01:32:24 +0000572
Chris Lattner7a60d912005-01-07 07:47:53 +0000573 // These all get lowered before this pass.
Jim Laskey4b37a4c2007-02-21 22:53:45 +0000574 void visitInvoke(InvokeInst &I);
575 void visitUnwind(UnwindInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000576
Dan Gohmana8665142007-06-25 16:23:39 +0000577 void visitBinary(User &I, unsigned OpCode);
Nate Begeman127321b2005-11-18 07:42:56 +0000578 void visitShift(User &I, unsigned Opcode);
Nate Begemanb2e089c2005-11-19 00:36:38 +0000579 void visitAdd(User &I) {
Dan Gohmana8665142007-06-25 16:23:39 +0000580 if (I.getType()->isFPOrFPVector())
581 visitBinary(I, ISD::FADD);
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000582 else
Dan Gohmana8665142007-06-25 16:23:39 +0000583 visitBinary(I, ISD::ADD);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000584 }
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000585 void visitSub(User &I);
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000586 void visitMul(User &I) {
Dan Gohmana8665142007-06-25 16:23:39 +0000587 if (I.getType()->isFPOrFPVector())
588 visitBinary(I, ISD::FMUL);
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000589 else
Dan Gohmana8665142007-06-25 16:23:39 +0000590 visitBinary(I, ISD::MUL);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000591 }
Dan Gohmana8665142007-06-25 16:23:39 +0000592 void visitURem(User &I) { visitBinary(I, ISD::UREM); }
593 void visitSRem(User &I) { visitBinary(I, ISD::SREM); }
594 void visitFRem(User &I) { visitBinary(I, ISD::FREM); }
595 void visitUDiv(User &I) { visitBinary(I, ISD::UDIV); }
596 void visitSDiv(User &I) { visitBinary(I, ISD::SDIV); }
597 void visitFDiv(User &I) { visitBinary(I, ISD::FDIV); }
598 void visitAnd (User &I) { visitBinary(I, ISD::AND); }
599 void visitOr (User &I) { visitBinary(I, ISD::OR); }
600 void visitXor (User &I) { visitBinary(I, ISD::XOR); }
Reid Spencer2eadb532007-01-21 00:29:26 +0000601 void visitShl (User &I) { visitShift(I, ISD::SHL); }
Reid Spencerfdff9382006-11-08 06:47:33 +0000602 void visitLShr(User &I) { visitShift(I, ISD::SRL); }
603 void visitAShr(User &I) { visitShift(I, ISD::SRA); }
Reid Spencerd9436b62006-11-20 01:22:35 +0000604 void visitICmp(User &I);
605 void visitFCmp(User &I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000606 // Visit the conversion instructions
607 void visitTrunc(User &I);
608 void visitZExt(User &I);
609 void visitSExt(User &I);
610 void visitFPTrunc(User &I);
611 void visitFPExt(User &I);
612 void visitFPToUI(User &I);
613 void visitFPToSI(User &I);
614 void visitUIToFP(User &I);
615 void visitSIToFP(User &I);
616 void visitPtrToInt(User &I);
617 void visitIntToPtr(User &I);
618 void visitBitCast(User &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000619
Chris Lattner67271862006-03-29 00:11:43 +0000620 void visitExtractElement(User &I);
621 void visitInsertElement(User &I);
Chris Lattner098c01e2006-04-08 04:15:24 +0000622 void visitShuffleVector(User &I);
Chris Lattner32206f52006-03-18 01:44:44 +0000623
Chris Lattner7a60d912005-01-07 07:47:53 +0000624 void visitGetElementPtr(User &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000625 void visitSelect(User &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000626
627 void visitMalloc(MallocInst &I);
628 void visitFree(FreeInst &I);
629 void visitAlloca(AllocaInst &I);
630 void visitLoad(LoadInst &I);
631 void visitStore(StoreInst &I);
632 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
633 void visitCall(CallInst &I);
Chris Lattner476e67b2006-01-26 22:24:51 +0000634 void visitInlineAsm(CallInst &I);
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000635 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattnerd96b09a2006-03-24 02:22:33 +0000636 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
Chris Lattner7a60d912005-01-07 07:47:53 +0000637
Chris Lattner7a60d912005-01-07 07:47:53 +0000638 void visitVAStart(CallInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000639 void visitVAArg(VAArgInst &I);
640 void visitVAEnd(CallInst &I);
641 void visitVACopy(CallInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000642
Chris Lattner875def92005-01-11 05:56:49 +0000643 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner7a60d912005-01-07 07:47:53 +0000644
645 void visitUserOp1(Instruction &I) {
646 assert(0 && "UserOp1 should not exist at instruction selection time!");
647 abort();
648 }
649 void visitUserOp2(Instruction &I) {
650 assert(0 && "UserOp2 should not exist at instruction selection time!");
651 abort();
652 }
653};
654} // end namespace llvm
655
Chris Lattner8471b152006-03-16 19:57:50 +0000656SDOperand SelectionDAGLowering::getValue(const Value *V) {
657 SDOperand &N = NodeMap[V];
658 if (N.Val) return N;
659
660 const Type *VTy = V->getType();
661 MVT::ValueType VT = TLI.getValueType(VTy);
662 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
663 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
664 visit(CE->getOpcode(), *CE);
Chris Lattner79084302007-02-04 01:31:47 +0000665 SDOperand N1 = NodeMap[V];
666 assert(N1.Val && "visit didn't populate the ValueMap!");
667 return N1;
Chris Lattner8471b152006-03-16 19:57:50 +0000668 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
669 return N = DAG.getGlobalAddress(GV, VT);
670 } else if (isa<ConstantPointerNull>(C)) {
671 return N = DAG.getConstant(0, TLI.getPointerTy());
672 } else if (isa<UndefValue>(C)) {
Reid Spencerd84d35b2007-02-15 02:26:10 +0000673 if (!isa<VectorType>(VTy))
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000674 return N = DAG.getNode(ISD::UNDEF, VT);
675
Dan Gohmana8665142007-06-25 16:23:39 +0000676 // Create a BUILD_VECTOR of undef nodes.
Reid Spencerd84d35b2007-02-15 02:26:10 +0000677 const VectorType *PTy = cast<VectorType>(VTy);
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000678 unsigned NumElements = PTy->getNumElements();
679 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
680
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000681 SmallVector<SDOperand, 8> Ops;
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000682 Ops.assign(NumElements, DAG.getNode(ISD::UNDEF, PVT));
683
684 // Create a VConstant node with generic Vector type.
Dan Gohmana8665142007-06-25 16:23:39 +0000685 MVT::ValueType VT = MVT::getVectorType(PVT, NumElements);
686 return N = DAG.getNode(ISD::BUILD_VECTOR, VT,
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000687 &Ops[0], Ops.size());
Chris Lattner8471b152006-03-16 19:57:50 +0000688 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
689 return N = DAG.getConstantFP(CFP->getValue(), VT);
Reid Spencerd84d35b2007-02-15 02:26:10 +0000690 } else if (const VectorType *PTy = dyn_cast<VectorType>(VTy)) {
Chris Lattner8471b152006-03-16 19:57:50 +0000691 unsigned NumElements = PTy->getNumElements();
692 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Chris Lattner8471b152006-03-16 19:57:50 +0000693
694 // Now that we know the number and type of the elements, push a
695 // Constant or ConstantFP node onto the ops list for each element of
696 // the packed constant.
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000697 SmallVector<SDOperand, 8> Ops;
Reid Spencerd84d35b2007-02-15 02:26:10 +0000698 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
Chris Lattner67271862006-03-29 00:11:43 +0000699 for (unsigned i = 0; i != NumElements; ++i)
700 Ops.push_back(getValue(CP->getOperand(i)));
Chris Lattner8471b152006-03-16 19:57:50 +0000701 } else {
702 assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
703 SDOperand Op;
704 if (MVT::isFloatingPoint(PVT))
705 Op = DAG.getConstantFP(0, PVT);
706 else
707 Op = DAG.getConstant(0, PVT);
708 Ops.assign(NumElements, Op);
709 }
710
Dan Gohmana8665142007-06-25 16:23:39 +0000711 // Create a BUILD_VECTOR node.
712 MVT::ValueType VT = MVT::getVectorType(PVT, NumElements);
713 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0],
Chris Lattner79084302007-02-04 01:31:47 +0000714 Ops.size());
Chris Lattner8471b152006-03-16 19:57:50 +0000715 } else {
716 // Canonicalize all constant ints to be unsigned.
Zhou Sheng75b871f2007-01-11 12:24:14 +0000717 return N = DAG.getConstant(cast<ConstantInt>(C)->getZExtValue(),VT);
Chris Lattner8471b152006-03-16 19:57:50 +0000718 }
719 }
720
721 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
722 std::map<const AllocaInst*, int>::iterator SI =
723 FuncInfo.StaticAllocaMap.find(AI);
724 if (SI != FuncInfo.StaticAllocaMap.end())
725 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
726 }
727
Chris Lattner8c504cf2007-02-25 18:40:32 +0000728 unsigned InReg = FuncInfo.ValueMap[V];
729 assert(InReg && "Value not in map!");
Chris Lattner8471b152006-03-16 19:57:50 +0000730
731 // If this type is not legal, make it so now.
Dan Gohmana8665142007-06-25 16:23:39 +0000732 if (!MVT::isVector(VT)) {
Evan Cheng22cf8992006-12-13 20:57:08 +0000733 if (TLI.getTypeAction(VT) == TargetLowering::Expand) {
Chris Lattner5fe1f542006-03-31 02:06:56 +0000734 // Source must be expanded. This input value is actually coming from the
Chris Lattner8c504cf2007-02-25 18:40:32 +0000735 // register pair InReg and InReg+1.
Evan Cheng22cf8992006-12-13 20:57:08 +0000736 MVT::ValueType DestVT = TLI.getTypeToExpandTo(VT);
Dan Gohman04deef32007-06-21 14:42:22 +0000737 unsigned NumVals = TLI.getNumRegisters(VT);
Evan Cheng22cf8992006-12-13 20:57:08 +0000738 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
739 if (NumVals == 1)
740 N = DAG.getNode(ISD::BIT_CONVERT, VT, N);
741 else {
742 assert(NumVals == 2 && "1 to 4 (and more) expansion not implemented!");
743 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
Dan Gohmana8665142007-06-25 16:23:39 +0000744 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
Evan Cheng22cf8992006-12-13 20:57:08 +0000745 }
746 } else {
747 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
748 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
749 if (TLI.getTypeAction(VT) == TargetLowering::Promote) // Promotion case
750 N = MVT::isFloatingPoint(VT)
751 ? DAG.getNode(ISD::FP_ROUND, VT, N)
752 : DAG.getNode(ISD::TRUNCATE, VT, N);
Chris Lattner8471b152006-03-16 19:57:50 +0000753 }
Chris Lattner5fe1f542006-03-31 02:06:56 +0000754 } else {
Dan Gohmana8665142007-06-25 16:23:39 +0000755 // Otherwise, if this is a vector, make it available as a vector
Chris Lattner5fe1f542006-03-31 02:06:56 +0000756 // here.
Dan Gohmana8665142007-06-25 16:23:39 +0000757 MVT::ValueType ElementVT, LegalElementVT;
758 unsigned NE = TLI.getVectorTypeBreakdown(VT, ElementVT,
759 LegalElementVT);
Chris Lattner5fe1f542006-03-31 02:06:56 +0000760
Dan Gohmana8665142007-06-25 16:23:39 +0000761 // Build a BUILD_VECTOR or CONCAT_VECTORS with the input registers.
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000762 SmallVector<SDOperand, 8> Ops;
Dan Gohmana8665142007-06-25 16:23:39 +0000763 if (ElementVT == LegalElementVT) {
764 // If the value types are legal, just BUILD the CopyFromReg nodes.
Chris Lattner5fe1f542006-03-31 02:06:56 +0000765 for (unsigned i = 0; i != NE; ++i)
766 Ops.push_back(DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
Dan Gohmana8665142007-06-25 16:23:39 +0000767 ElementVT));
768 } else if (ElementVT < LegalElementVT) {
Dan Gohman30978072007-05-24 14:36:04 +0000769 // If the register was promoted, use TRUNCATE or FP_ROUND as appropriate.
Chris Lattner5fe1f542006-03-31 02:06:56 +0000770 for (unsigned i = 0; i != NE; ++i) {
771 SDOperand Op = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
Dan Gohmana8665142007-06-25 16:23:39 +0000772 LegalElementVT);
773 if (MVT::isFloatingPoint(ElementVT))
774 Op = DAG.getNode(ISD::FP_ROUND, ElementVT, Op);
Chris Lattner5fe1f542006-03-31 02:06:56 +0000775 else
Dan Gohmana8665142007-06-25 16:23:39 +0000776 Op = DAG.getNode(ISD::TRUNCATE, ElementVT, Op);
Chris Lattner5fe1f542006-03-31 02:06:56 +0000777 Ops.push_back(Op);
778 }
779 } else {
780 // If the register was expanded, use BUILD_PAIR.
781 assert((NE & 1) == 0 && "Must expand into a multiple of 2 elements!");
Dan Gohmancbd51c82007-06-13 14:55:16 +0000782 for (unsigned i = 0; i != NE; ++i) {
Chris Lattner5fe1f542006-03-31 02:06:56 +0000783 SDOperand Op0 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
Dan Gohmana8665142007-06-25 16:23:39 +0000784 LegalElementVT);
Chris Lattner5fe1f542006-03-31 02:06:56 +0000785 SDOperand Op1 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
Dan Gohmana8665142007-06-25 16:23:39 +0000786 LegalElementVT);
787 Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, ElementVT, Op0, Op1));
Chris Lattner5fe1f542006-03-31 02:06:56 +0000788 }
789 }
790
Dan Gohmana8665142007-06-25 16:23:39 +0000791 if (MVT::isVector(ElementVT)) {
792 N = DAG.getNode(ISD::CONCAT_VECTORS,
793 MVT::getVectorType(MVT::getVectorElementType(ElementVT),
794 NE * MVT::getVectorNumElements(ElementVT)),
795 &Ops[0], Ops.size());
Dan Gohman26455c42007-06-13 15:12:02 +0000796 } else {
Dan Gohmana8665142007-06-25 16:23:39 +0000797 N = DAG.getNode(ISD::BUILD_VECTOR,
798 MVT::getVectorType(ElementVT, NE),
799 &Ops[0], Ops.size());
Dan Gohman26455c42007-06-13 15:12:02 +0000800 }
Chris Lattner8471b152006-03-16 19:57:50 +0000801 }
802
803 return N;
804}
805
806
Chris Lattner7a60d912005-01-07 07:47:53 +0000807void SelectionDAGLowering::visitRet(ReturnInst &I) {
808 if (I.getNumOperands() == 0) {
Chris Lattner4108bb02005-01-17 19:43:36 +0000809 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
Chris Lattner7a60d912005-01-07 07:47:53 +0000810 return;
811 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000812 SmallVector<SDOperand, 8> NewValues;
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000813 NewValues.push_back(getRoot());
814 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
815 SDOperand RetOp = getValue(I.getOperand(i));
816
817 // If this is an integer return value, we need to promote it ourselves to
818 // the full width of a register, since LegalizeOp will use ANY_EXTEND rather
819 // than sign/zero.
Evan Chenga2e99532006-05-26 23:09:09 +0000820 // FIXME: C calling convention requires the return type to be promoted to
821 // at least 32-bit. But this is not necessary for non-C calling conventions.
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000822 if (MVT::isInteger(RetOp.getValueType()) &&
823 RetOp.getValueType() < MVT::i64) {
824 MVT::ValueType TmpVT;
825 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
826 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
827 else
828 TmpVT = MVT::i32;
Reid Spencere63b6512006-12-31 05:55:36 +0000829 const FunctionType *FTy = I.getParent()->getParent()->getFunctionType();
Reid Spencer71b79e32007-04-09 06:17:21 +0000830 const ParamAttrsList *Attrs = FTy->getParamAttrs();
Reid Spencere6f81872007-01-03 16:49:33 +0000831 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
Reid Spencera472f662007-04-11 02:44:20 +0000832 if (Attrs && Attrs->paramHasAttr(0, ParamAttr::SExt))
Reid Spencer0917adf2007-01-03 04:25:33 +0000833 ExtendKind = ISD::SIGN_EXTEND;
Reid Spencera472f662007-04-11 02:44:20 +0000834 if (Attrs && Attrs->paramHasAttr(0, ParamAttr::ZExt))
Reid Spencere63b6512006-12-31 05:55:36 +0000835 ExtendKind = ISD::ZERO_EXTEND;
Reid Spencer2a34b912007-01-03 05:03:05 +0000836 RetOp = DAG.getNode(ExtendKind, TmpVT, RetOp);
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000837 }
838 NewValues.push_back(RetOp);
Reid Spencere63b6512006-12-31 05:55:36 +0000839 NewValues.push_back(DAG.getConstant(false, MVT::i32));
Chris Lattner7a60d912005-01-07 07:47:53 +0000840 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000841 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
842 &NewValues[0], NewValues.size()));
Chris Lattner7a60d912005-01-07 07:47:53 +0000843}
844
Chris Lattnered0110b2006-10-27 21:36:01 +0000845/// ExportFromCurrentBlock - If this condition isn't known to be exported from
846/// the current basic block, add it to ValueMap now so that we'll get a
847/// CopyTo/FromReg.
848void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
849 // No need to export constants.
850 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
851
852 // Already exported?
853 if (FuncInfo.isExportedInst(V)) return;
854
855 unsigned Reg = FuncInfo.InitializeRegForValue(V);
856 PendingLoads.push_back(CopyValueToVirtualRegister(V, Reg));
857}
858
Chris Lattner84a03502006-10-27 23:50:33 +0000859bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
860 const BasicBlock *FromBB) {
861 // The operands of the setcc have to be in this block. We don't know
862 // how to export them from some other block.
863 if (Instruction *VI = dyn_cast<Instruction>(V)) {
864 // Can export from current BB.
865 if (VI->getParent() == FromBB)
866 return true;
867
868 // Is already exported, noop.
869 return FuncInfo.isExportedInst(V);
870 }
871
872 // If this is an argument, we can export it if the BB is the entry block or
873 // if it is already exported.
874 if (isa<Argument>(V)) {
875 if (FromBB == &FromBB->getParent()->getEntryBlock())
876 return true;
877
878 // Otherwise, can only export this if it is already exported.
879 return FuncInfo.isExportedInst(V);
880 }
881
882 // Otherwise, constants can always be exported.
883 return true;
884}
885
Chris Lattnere60ae822006-10-29 21:01:20 +0000886static bool InBlock(const Value *V, const BasicBlock *BB) {
887 if (const Instruction *I = dyn_cast<Instruction>(V))
888 return I->getParent() == BB;
889 return true;
890}
891
Chris Lattnered0110b2006-10-27 21:36:01 +0000892/// FindMergedConditions - If Cond is an expression like
893void SelectionDAGLowering::FindMergedConditions(Value *Cond,
894 MachineBasicBlock *TBB,
895 MachineBasicBlock *FBB,
896 MachineBasicBlock *CurBB,
897 unsigned Opc) {
Chris Lattnered0110b2006-10-27 21:36:01 +0000898 // If this node is not part of the or/and tree, emit it as a branch.
Reid Spencer266e42b2006-12-23 06:05:41 +0000899 Instruction *BOp = dyn_cast<Instruction>(Cond);
Chris Lattnered0110b2006-10-27 21:36:01 +0000900
Reid Spencer266e42b2006-12-23 06:05:41 +0000901 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
902 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
Chris Lattnere60ae822006-10-29 21:01:20 +0000903 BOp->getParent() != CurBB->getBasicBlock() ||
904 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
905 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
Chris Lattnered0110b2006-10-27 21:36:01 +0000906 const BasicBlock *BB = CurBB->getBasicBlock();
907
Reid Spencer266e42b2006-12-23 06:05:41 +0000908 // If the leaf of the tree is a comparison, merge the condition into
909 // the caseblock.
910 if ((isa<ICmpInst>(Cond) || isa<FCmpInst>(Cond)) &&
911 // The operands of the cmp have to be in this block. We don't know
Chris Lattnerf31b9ef2006-10-29 18:23:37 +0000912 // how to export them from some other block. If this is the first block
913 // of the sequence, no exporting is needed.
914 (CurBB == CurMBB ||
915 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
916 isExportableFromCurrentBlock(BOp->getOperand(1), BB)))) {
Reid Spencer266e42b2006-12-23 06:05:41 +0000917 BOp = cast<Instruction>(Cond);
918 ISD::CondCode Condition;
919 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
920 switch (IC->getPredicate()) {
921 default: assert(0 && "Unknown icmp predicate opcode!");
922 case ICmpInst::ICMP_EQ: Condition = ISD::SETEQ; break;
923 case ICmpInst::ICMP_NE: Condition = ISD::SETNE; break;
924 case ICmpInst::ICMP_SLE: Condition = ISD::SETLE; break;
925 case ICmpInst::ICMP_ULE: Condition = ISD::SETULE; break;
926 case ICmpInst::ICMP_SGE: Condition = ISD::SETGE; break;
927 case ICmpInst::ICMP_UGE: Condition = ISD::SETUGE; break;
928 case ICmpInst::ICMP_SLT: Condition = ISD::SETLT; break;
929 case ICmpInst::ICMP_ULT: Condition = ISD::SETULT; break;
930 case ICmpInst::ICMP_SGT: Condition = ISD::SETGT; break;
931 case ICmpInst::ICMP_UGT: Condition = ISD::SETUGT; break;
932 }
933 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
934 ISD::CondCode FPC, FOC;
935 switch (FC->getPredicate()) {
936 default: assert(0 && "Unknown fcmp predicate opcode!");
937 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
938 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
939 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
940 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
941 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
942 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
943 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
944 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
945 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
946 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
947 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
948 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
949 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
950 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
951 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
952 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
953 }
954 if (FiniteOnlyFPMath())
955 Condition = FOC;
956 else
957 Condition = FPC;
958 } else {
Chris Lattner79084302007-02-04 01:31:47 +0000959 Condition = ISD::SETEQ; // silence warning.
Reid Spencer266e42b2006-12-23 06:05:41 +0000960 assert(0 && "Unknown compare instruction");
Chris Lattnered0110b2006-10-27 21:36:01 +0000961 }
962
Chris Lattnered0110b2006-10-27 21:36:01 +0000963 SelectionDAGISel::CaseBlock CB(Condition, BOp->getOperand(0),
Anton Korobeynikov915e6172007-04-04 21:14:49 +0000964 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
Chris Lattnered0110b2006-10-27 21:36:01 +0000965 SwitchCases.push_back(CB);
966 return;
967 }
968
969 // Create a CaseBlock record representing this branch.
Zhou Sheng75b871f2007-01-11 12:24:14 +0000970 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
Anton Korobeynikov915e6172007-04-04 21:14:49 +0000971 NULL, TBB, FBB, CurBB);
Chris Lattnered0110b2006-10-27 21:36:01 +0000972 SwitchCases.push_back(CB);
Chris Lattnered0110b2006-10-27 21:36:01 +0000973 return;
974 }
975
Chris Lattnerf1b54fd2006-10-27 21:54:23 +0000976
977 // Create TmpBB after CurBB.
Chris Lattnered0110b2006-10-27 21:36:01 +0000978 MachineFunction::iterator BBI = CurBB;
979 MachineBasicBlock *TmpBB = new MachineBasicBlock(CurBB->getBasicBlock());
980 CurBB->getParent()->getBasicBlockList().insert(++BBI, TmpBB);
981
Chris Lattnerf1b54fd2006-10-27 21:54:23 +0000982 if (Opc == Instruction::Or) {
983 // Codegen X | Y as:
984 // jmp_if_X TBB
985 // jmp TmpBB
986 // TmpBB:
987 // jmp_if_Y TBB
988 // jmp FBB
989 //
Chris Lattnered0110b2006-10-27 21:36:01 +0000990
Chris Lattnerf1b54fd2006-10-27 21:54:23 +0000991 // Emit the LHS condition.
992 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
993
994 // Emit the RHS condition into TmpBB.
995 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
996 } else {
997 assert(Opc == Instruction::And && "Unknown merge op!");
998 // Codegen X & Y as:
999 // jmp_if_X TmpBB
1000 // jmp FBB
1001 // TmpBB:
1002 // jmp_if_Y TBB
1003 // jmp FBB
1004 //
1005 // This requires creation of TmpBB after CurBB.
1006
1007 // Emit the LHS condition.
1008 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
1009
1010 // Emit the RHS condition into TmpBB.
1011 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1012 }
Chris Lattnered0110b2006-10-27 21:36:01 +00001013}
1014
Chris Lattner427301f2006-10-31 22:37:42 +00001015/// If the set of cases should be emitted as a series of branches, return true.
1016/// If we should emit this as a bunch of and/or'd together conditions, return
1017/// false.
1018static bool
1019ShouldEmitAsBranches(const std::vector<SelectionDAGISel::CaseBlock> &Cases) {
1020 if (Cases.size() != 2) return true;
1021
Chris Lattnerfe43bef2006-10-31 23:06:00 +00001022 // If this is two comparisons of the same values or'd or and'd together, they
1023 // will get folded into a single comparison, so don't emit two blocks.
1024 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1025 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1026 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1027 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1028 return false;
1029 }
1030
Chris Lattner427301f2006-10-31 22:37:42 +00001031 return true;
1032}
1033
Chris Lattner7a60d912005-01-07 07:47:53 +00001034void SelectionDAGLowering::visitBr(BranchInst &I) {
1035 // Update machine-CFG edges.
1036 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner7a60d912005-01-07 07:47:53 +00001037
1038 // Figure out which block is immediately after the current one.
1039 MachineBasicBlock *NextBlock = 0;
1040 MachineFunction::iterator BBI = CurMBB;
1041 if (++BBI != CurMBB->getParent()->end())
1042 NextBlock = BBI;
1043
1044 if (I.isUnconditional()) {
1045 // If this is not a fall-through branch, emit the branch.
1046 if (Succ0MBB != NextBlock)
Chris Lattner4108bb02005-01-17 19:43:36 +00001047 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +00001048 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +00001049
Chris Lattner963ddad2006-10-24 17:57:59 +00001050 // Update machine-CFG edges.
1051 CurMBB->addSuccessor(Succ0MBB);
1052
1053 return;
1054 }
1055
1056 // If this condition is one of the special cases we handle, do special stuff
1057 // now.
1058 Value *CondVal = I.getCondition();
Chris Lattner963ddad2006-10-24 17:57:59 +00001059 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattnered0110b2006-10-27 21:36:01 +00001060
1061 // If this is a series of conditions that are or'd or and'd together, emit
1062 // this as a sequence of branches instead of setcc's with and/or operations.
1063 // For example, instead of something like:
1064 // cmp A, B
1065 // C = seteq
1066 // cmp D, E
1067 // F = setle
1068 // or C, F
1069 // jnz foo
1070 // Emit:
1071 // cmp A, B
1072 // je foo
1073 // cmp D, E
1074 // jle foo
1075 //
1076 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1077 if (BOp->hasOneUse() &&
Chris Lattnerf1b54fd2006-10-27 21:54:23 +00001078 (BOp->getOpcode() == Instruction::And ||
Chris Lattnered0110b2006-10-27 21:36:01 +00001079 BOp->getOpcode() == Instruction::Or)) {
1080 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
Chris Lattnerfe43bef2006-10-31 23:06:00 +00001081 // If the compares in later blocks need to use values not currently
1082 // exported from this block, export them now. This block should always
1083 // be the first entry.
1084 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1085
Chris Lattner427301f2006-10-31 22:37:42 +00001086 // Allow some cases to be rejected.
1087 if (ShouldEmitAsBranches(SwitchCases)) {
Chris Lattner427301f2006-10-31 22:37:42 +00001088 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1089 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1090 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1091 }
1092
1093 // Emit the branch for this block.
1094 visitSwitchCase(SwitchCases[0]);
1095 SwitchCases.erase(SwitchCases.begin());
1096 return;
Chris Lattnerf31b9ef2006-10-29 18:23:37 +00001097 }
1098
Chris Lattnerfe43bef2006-10-31 23:06:00 +00001099 // Okay, we decided not to do this, remove any inserted MBB's and clear
1100 // SwitchCases.
1101 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1102 CurMBB->getParent()->getBasicBlockList().erase(SwitchCases[i].ThisBB);
1103
Chris Lattner427301f2006-10-31 22:37:42 +00001104 SwitchCases.clear();
Chris Lattnered0110b2006-10-27 21:36:01 +00001105 }
1106 }
Chris Lattner61bcf912006-10-24 18:07:37 +00001107
1108 // Create a CaseBlock record representing this branch.
Zhou Sheng75b871f2007-01-11 12:24:14 +00001109 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001110 NULL, Succ0MBB, Succ1MBB, CurMBB);
Chris Lattner61bcf912006-10-24 18:07:37 +00001111 // Use visitSwitchCase to actually insert the fast branch sequence for this
1112 // cond branch.
1113 visitSwitchCase(CB);
Chris Lattner7a60d912005-01-07 07:47:53 +00001114}
1115
Nate Begemaned728c12006-03-27 01:32:24 +00001116/// visitSwitchCase - Emits the necessary code to represent a single node in
1117/// the binary search tree resulting from lowering a switch instruction.
1118void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
Chris Lattner963ddad2006-10-24 17:57:59 +00001119 SDOperand Cond;
1120 SDOperand CondLHS = getValue(CB.CmpLHS);
1121
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001122 // Build the setcc now.
1123 if (CB.CmpMHS == NULL) {
1124 // Fold "(X == true)" to X and "(X == false)" to !X to
1125 // handle common cases produced by branch lowering.
1126 if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
1127 Cond = CondLHS;
1128 else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
1129 SDOperand True = DAG.getConstant(1, CondLHS.getValueType());
1130 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1131 } else
1132 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1133 } else {
1134 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
Anton Korobeynikov70378262007-03-25 15:07:15 +00001135
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001136 uint64_t Low = cast<ConstantInt>(CB.CmpLHS)->getSExtValue();
1137 uint64_t High = cast<ConstantInt>(CB.CmpRHS)->getSExtValue();
1138
1139 SDOperand CmpOp = getValue(CB.CmpMHS);
1140 MVT::ValueType VT = CmpOp.getValueType();
1141
1142 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1143 Cond = DAG.getSetCC(MVT::i1, CmpOp, DAG.getConstant(High, VT), ISD::SETLE);
1144 } else {
1145 SDOperand SUB = DAG.getNode(ISD::SUB, VT, CmpOp, DAG.getConstant(Low, VT));
1146 Cond = DAG.getSetCC(MVT::i1, SUB,
1147 DAG.getConstant(High-Low, VT), ISD::SETULE);
1148 }
1149
1150 }
1151
Nate Begemaned728c12006-03-27 01:32:24 +00001152 // Set NextBlock to be the MBB immediately after the current one, if any.
1153 // This is used to avoid emitting unnecessary branches to the next block.
1154 MachineBasicBlock *NextBlock = 0;
1155 MachineFunction::iterator BBI = CurMBB;
1156 if (++BBI != CurMBB->getParent()->end())
1157 NextBlock = BBI;
1158
1159 // If the lhs block is the next block, invert the condition so that we can
1160 // fall through to the lhs instead of the rhs block.
Chris Lattner963ddad2006-10-24 17:57:59 +00001161 if (CB.TrueBB == NextBlock) {
1162 std::swap(CB.TrueBB, CB.FalseBB);
Nate Begemaned728c12006-03-27 01:32:24 +00001163 SDOperand True = DAG.getConstant(1, Cond.getValueType());
1164 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1165 }
1166 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
Chris Lattner963ddad2006-10-24 17:57:59 +00001167 DAG.getBasicBlock(CB.TrueBB));
1168 if (CB.FalseBB == NextBlock)
Nate Begemaned728c12006-03-27 01:32:24 +00001169 DAG.setRoot(BrCond);
1170 else
1171 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
Chris Lattner963ddad2006-10-24 17:57:59 +00001172 DAG.getBasicBlock(CB.FalseBB)));
Nate Begemaned728c12006-03-27 01:32:24 +00001173 // Update successor info
Chris Lattner963ddad2006-10-24 17:57:59 +00001174 CurMBB->addSuccessor(CB.TrueBB);
1175 CurMBB->addSuccessor(CB.FalseBB);
Nate Begemaned728c12006-03-27 01:32:24 +00001176}
1177
Anton Korobeynikov70378262007-03-25 15:07:15 +00001178/// visitJumpTable - Emit JumpTable node in the current MBB
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001179void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001180 // Emit the code for the jump table
Scott Michel4cfa6162007-04-24 01:24:20 +00001181 assert(JT.Reg != -1U && "Should lower JT Header first!");
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001182 MVT::ValueType PTy = TLI.getPointerTy();
Evan Cheng84a28d42006-10-30 08:00:44 +00001183 SDOperand Index = DAG.getCopyFromReg(getRoot(), JT.Reg, PTy);
1184 SDOperand Table = DAG.getJumpTable(JT.JTI, PTy);
1185 DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1186 Table, Index));
1187 return;
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001188}
1189
Anton Korobeynikov70378262007-03-25 15:07:15 +00001190/// visitJumpTableHeader - This function emits necessary code to produce index
1191/// in the JumpTable from switch case.
1192void SelectionDAGLowering::visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
1193 SelectionDAGISel::JumpTableHeader &JTH) {
1194 // Subtract the lowest switch case value from the value being switched on
1195 // and conditional branch to default mbb if the result is greater than the
1196 // difference between smallest and largest cases.
1197 SDOperand SwitchOp = getValue(JTH.SValue);
1198 MVT::ValueType VT = SwitchOp.getValueType();
1199 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1200 DAG.getConstant(JTH.First, VT));
1201
1202 // The SDNode we just created, which holds the value being switched on
1203 // minus the the smallest case value, needs to be copied to a virtual
1204 // register so it can be used as an index into the jump table in a
1205 // subsequent basic block. This value may be smaller or larger than the
1206 // target's pointer type, and therefore require extension or truncating.
Dan Gohmana8665142007-06-25 16:23:39 +00001207 if (MVT::getSizeInBits(VT) > MVT::getSizeInBits(TLI.getPointerTy()))
Anton Korobeynikov70378262007-03-25 15:07:15 +00001208 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1209 else
1210 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
1211
1212 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1213 SDOperand CopyTo = DAG.getCopyToReg(getRoot(), JumpTableReg, SwitchOp);
1214 JT.Reg = JumpTableReg;
1215
1216 // Emit the range check for the jump table, and branch to the default
1217 // block for the switch statement if the value being switched on exceeds
1218 // the largest case in the switch.
1219 SDOperand CMP = DAG.getSetCC(TLI.getSetCCResultTy(), SUB,
1220 DAG.getConstant(JTH.Last-JTH.First,VT),
1221 ISD::SETUGT);
1222
1223 // Set NextBlock to be the MBB immediately after the current one, if any.
1224 // This is used to avoid emitting unnecessary branches to the next block.
1225 MachineBasicBlock *NextBlock = 0;
1226 MachineFunction::iterator BBI = CurMBB;
1227 if (++BBI != CurMBB->getParent()->end())
1228 NextBlock = BBI;
1229
1230 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
1231 DAG.getBasicBlock(JT.Default));
1232
1233 if (JT.MBB == NextBlock)
1234 DAG.setRoot(BrCond);
1235 else
1236 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001237 DAG.getBasicBlock(JT.MBB)));
1238
1239 return;
Anton Korobeynikov70378262007-03-25 15:07:15 +00001240}
1241
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001242/// visitBitTestHeader - This function emits necessary code to produce value
1243/// suitable for "bit tests"
1244void SelectionDAGLowering::visitBitTestHeader(SelectionDAGISel::BitTestBlock &B) {
1245 // Subtract the minimum value
1246 SDOperand SwitchOp = getValue(B.SValue);
1247 MVT::ValueType VT = SwitchOp.getValueType();
1248 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1249 DAG.getConstant(B.First, VT));
1250
1251 // Check range
1252 SDOperand RangeCmp = DAG.getSetCC(TLI.getSetCCResultTy(), SUB,
1253 DAG.getConstant(B.Range, VT),
1254 ISD::SETUGT);
1255
1256 SDOperand ShiftOp;
Dan Gohmana8665142007-06-25 16:23:39 +00001257 if (MVT::getSizeInBits(VT) > MVT::getSizeInBits(TLI.getShiftAmountTy()))
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001258 ShiftOp = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), SUB);
1259 else
1260 ShiftOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getShiftAmountTy(), SUB);
1261
1262 // Make desired shift
1263 SDOperand SwitchVal = DAG.getNode(ISD::SHL, TLI.getPointerTy(),
1264 DAG.getConstant(1, TLI.getPointerTy()),
1265 ShiftOp);
1266
1267 unsigned SwitchReg = FuncInfo.MakeReg(TLI.getPointerTy());
1268 SDOperand CopyTo = DAG.getCopyToReg(getRoot(), SwitchReg, SwitchVal);
1269 B.Reg = SwitchReg;
1270
1271 SDOperand BrRange = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, RangeCmp,
1272 DAG.getBasicBlock(B.Default));
1273
1274 // Set NextBlock to be the MBB immediately after the current one, if any.
1275 // This is used to avoid emitting unnecessary branches to the next block.
1276 MachineBasicBlock *NextBlock = 0;
1277 MachineFunction::iterator BBI = CurMBB;
1278 if (++BBI != CurMBB->getParent()->end())
1279 NextBlock = BBI;
1280
1281 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1282 if (MBB == NextBlock)
1283 DAG.setRoot(BrRange);
1284 else
1285 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, CopyTo,
1286 DAG.getBasicBlock(MBB)));
1287
1288 CurMBB->addSuccessor(B.Default);
1289 CurMBB->addSuccessor(MBB);
1290
1291 return;
1292}
1293
1294/// visitBitTestCase - this function produces one "bit test"
1295void SelectionDAGLowering::visitBitTestCase(MachineBasicBlock* NextMBB,
1296 unsigned Reg,
1297 SelectionDAGISel::BitTestCase &B) {
1298 // Emit bit tests and jumps
1299 SDOperand SwitchVal = DAG.getCopyFromReg(getRoot(), Reg, TLI.getPointerTy());
1300
1301 SDOperand AndOp = DAG.getNode(ISD::AND, TLI.getPointerTy(),
1302 SwitchVal,
1303 DAG.getConstant(B.Mask,
1304 TLI.getPointerTy()));
1305 SDOperand AndCmp = DAG.getSetCC(TLI.getSetCCResultTy(), AndOp,
1306 DAG.getConstant(0, TLI.getPointerTy()),
1307 ISD::SETNE);
1308 SDOperand BrAnd = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
1309 AndCmp, DAG.getBasicBlock(B.TargetBB));
1310
1311 // Set NextBlock to be the MBB immediately after the current one, if any.
1312 // This is used to avoid emitting unnecessary branches to the next block.
1313 MachineBasicBlock *NextBlock = 0;
1314 MachineFunction::iterator BBI = CurMBB;
1315 if (++BBI != CurMBB->getParent()->end())
1316 NextBlock = BBI;
1317
1318 if (NextMBB == NextBlock)
1319 DAG.setRoot(BrAnd);
1320 else
1321 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrAnd,
1322 DAG.getBasicBlock(NextMBB)));
1323
1324 CurMBB->addSuccessor(B.TargetBB);
1325 CurMBB->addSuccessor(NextMBB);
1326
1327 return;
1328}
Anton Korobeynikov70378262007-03-25 15:07:15 +00001329
Jim Laskey4b37a4c2007-02-21 22:53:45 +00001330void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
1331 // Retrieve successors.
1332 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
Duncan Sands97f72362007-06-13 05:51:31 +00001333 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
Duncan Sands61166502007-06-06 10:05:18 +00001334
Duncan Sands97f72362007-06-13 05:51:31 +00001335 LowerCallTo(I, I.getCalledValue()->getType(),
1336 I.getCallingConv(),
1337 false,
1338 getValue(I.getOperand(0)),
1339 3, LandingPad);
Duncan Sands61166502007-06-06 10:05:18 +00001340
Duncan Sands97f72362007-06-13 05:51:31 +00001341 // If the value of the invoke is used outside of its defining block, make it
1342 // available as a virtual register.
1343 if (!I.use_empty()) {
1344 DenseMap<const Value*, unsigned>::iterator VMI = FuncInfo.ValueMap.find(&I);
1345 if (VMI != FuncInfo.ValueMap.end())
1346 DAG.setRoot(CopyValueToVirtualRegister(&I, VMI->second));
Jim Laskey14059d92007-02-25 21:43:59 +00001347 }
Duncan Sands97f72362007-06-13 05:51:31 +00001348
1349 // Drop into normal successor.
1350 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
1351 DAG.getBasicBlock(Return)));
1352
1353 // Update successor info
1354 CurMBB->addSuccessor(Return);
1355 CurMBB->addSuccessor(LandingPad);
Jim Laskey4b37a4c2007-02-21 22:53:45 +00001356}
1357
1358void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1359}
1360
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001361/// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001362/// small case ranges).
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001363bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR,
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001364 CaseRecVector& WorkList,
1365 Value* SV,
1366 MachineBasicBlock* Default) {
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001367 Case& BackCase = *(CR.Range.second-1);
1368
1369 // Size is the number of Cases represented by this range.
1370 unsigned Size = CR.Range.second - CR.Range.first;
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001371 if (Size > 3)
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001372 return false;
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001373
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001374 // Get the MachineFunction which holds the current MBB. This is used when
1375 // inserting any additional MBBs necessary to represent the switch.
1376 MachineFunction *CurMF = CurMBB->getParent();
1377
1378 // Figure out which block is immediately after the current one.
1379 MachineBasicBlock *NextBlock = 0;
1380 MachineFunction::iterator BBI = CR.CaseBB;
1381
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001382 if (++BBI != CurMBB->getParent()->end())
1383 NextBlock = BBI;
1384
1385 // TODO: If any two of the cases has the same destination, and if one value
1386 // is the same as the other, but has one bit unset that the other has set,
1387 // use bit manipulation to do two compares at once. For example:
1388 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1389
1390 // Rearrange the case blocks so that the last one falls through if possible.
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001391 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001392 // The last case block won't fall through into 'NextBlock' if we emit the
1393 // branches in this order. See if rearranging a case value would help.
1394 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001395 if (I->BB == NextBlock) {
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001396 std::swap(*I, BackCase);
1397 break;
1398 }
1399 }
1400 }
1401
1402 // Create a CaseBlock record representing a conditional branch to
1403 // the Case's target mbb if the value being switched on SV is equal
1404 // to C.
1405 MachineBasicBlock *CurBlock = CR.CaseBB;
1406 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1407 MachineBasicBlock *FallThrough;
1408 if (I != E-1) {
1409 FallThrough = new MachineBasicBlock(CurBlock->getBasicBlock());
1410 CurMF->getBasicBlockList().insert(BBI, FallThrough);
1411 } else {
1412 // If the last case doesn't match, go to the default block.
1413 FallThrough = Default;
1414 }
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001415
1416 Value *RHS, *LHS, *MHS;
1417 ISD::CondCode CC;
1418 if (I->High == I->Low) {
1419 // This is just small small case range :) containing exactly 1 case
1420 CC = ISD::SETEQ;
1421 LHS = SV; RHS = I->High; MHS = NULL;
1422 } else {
1423 CC = ISD::SETLE;
1424 LHS = I->Low; MHS = SV; RHS = I->High;
1425 }
1426 SelectionDAGISel::CaseBlock CB(CC, LHS, RHS, MHS,
1427 I->BB, FallThrough, CurBlock);
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001428
1429 // If emitting the first comparison, just call visitSwitchCase to emit the
1430 // code into the current block. Otherwise, push the CaseBlock onto the
1431 // vector to be later processed by SDISel, and insert the node's MBB
1432 // before the next MBB.
1433 if (CurBlock == CurMBB)
1434 visitSwitchCase(CB);
1435 else
1436 SwitchCases.push_back(CB);
1437
1438 CurBlock = FallThrough;
1439 }
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001440
1441 return true;
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001442}
1443
Anton Korobeynikov192d09c2007-05-09 20:07:08 +00001444static inline bool areJTsAllowed(const TargetLowering &TLI) {
1445 return (TLI.isOperationLegal(ISD::BR_JT, MVT::Other) ||
1446 TLI.isOperationLegal(ISD::BRIND, MVT::Other));
1447}
1448
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001449/// handleJTSwitchCase - Emit jumptable for current switch case range
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001450bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR,
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001451 CaseRecVector& WorkList,
1452 Value* SV,
1453 MachineBasicBlock* Default) {
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001454 Case& FrontCase = *CR.Range.first;
1455 Case& BackCase = *(CR.Range.second-1);
1456
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001457 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1458 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
1459
1460 uint64_t TSize = 0;
1461 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1462 I!=E; ++I)
1463 TSize += I->size();
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001464
Anton Korobeynikov192d09c2007-05-09 20:07:08 +00001465 if (!areJTsAllowed(TLI) || TSize <= 3)
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001466 return false;
1467
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001468 double Density = (double)TSize / (double)((Last - First) + 1ULL);
1469 if (Density < 0.4)
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001470 return false;
1471
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001472 DOUT << "Lowering jump table\n"
1473 << "First entry: " << First << ". Last entry: " << Last << "\n"
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001474 << "Size: " << TSize << ". Density: " << Density << "\n\n";
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001475
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001476 // Get the MachineFunction which holds the current MBB. This is used when
1477 // inserting any additional MBBs necessary to represent the switch.
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001478 MachineFunction *CurMF = CurMBB->getParent();
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001479
1480 // Figure out which block is immediately after the current one.
1481 MachineBasicBlock *NextBlock = 0;
1482 MachineFunction::iterator BBI = CR.CaseBB;
1483
1484 if (++BBI != CurMBB->getParent()->end())
1485 NextBlock = BBI;
1486
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001487 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1488
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001489 // Create a new basic block to hold the code for loading the address
1490 // of the jump table, and jumping to it. Update successor information;
1491 // we will either branch to the default case for the switch, or the jump
1492 // table.
1493 MachineBasicBlock *JumpTableBB = new MachineBasicBlock(LLVMBB);
1494 CurMF->getBasicBlockList().insert(BBI, JumpTableBB);
1495 CR.CaseBB->addSuccessor(Default);
1496 CR.CaseBB->addSuccessor(JumpTableBB);
1497
1498 // Build a vector of destination BBs, corresponding to each target
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001499 // of the jump table. If the value of the jump table slot corresponds to
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001500 // a case statement, push the case's BB onto the vector, otherwise, push
1501 // the default BB.
1502 std::vector<MachineBasicBlock*> DestBBs;
1503 int64_t TEI = First;
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001504 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
1505 int64_t Low = cast<ConstantInt>(I->Low)->getSExtValue();
1506 int64_t High = cast<ConstantInt>(I->High)->getSExtValue();
1507
1508 if ((Low <= TEI) && (TEI <= High)) {
1509 DestBBs.push_back(I->BB);
1510 if (TEI==High)
1511 ++I;
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001512 } else {
1513 DestBBs.push_back(Default);
1514 }
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001515 }
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001516
1517 // Update successor info. Add one edge to each unique successor.
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001518 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001519 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
1520 E = DestBBs.end(); I != E; ++I) {
1521 if (!SuccsHandled[(*I)->getNumber()]) {
1522 SuccsHandled[(*I)->getNumber()] = true;
1523 JumpTableBB->addSuccessor(*I);
1524 }
1525 }
1526
1527 // Create a jump table index for this jump table, or return an existing
1528 // one.
1529 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1530
1531 // Set the jump table information so that we can codegen it as a second
1532 // MachineBasicBlock
Scott Michel4cfa6162007-04-24 01:24:20 +00001533 SelectionDAGISel::JumpTable JT(-1U, JTI, JumpTableBB, Default);
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001534 SelectionDAGISel::JumpTableHeader JTH(First, Last, SV, CR.CaseBB,
1535 (CR.CaseBB == CurMBB));
1536 if (CR.CaseBB == CurMBB)
1537 visitJumpTableHeader(JT, JTH);
1538
1539 JTCases.push_back(SelectionDAGISel::JumpTableBlock(JTH, JT));
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001540
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001541 return true;
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001542}
1543
1544/// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1545/// 2 subtrees.
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001546bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR,
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001547 CaseRecVector& WorkList,
1548 Value* SV,
1549 MachineBasicBlock* Default) {
1550 // Get the MachineFunction which holds the current MBB. This is used when
1551 // inserting any additional MBBs necessary to represent the switch.
1552 MachineFunction *CurMF = CurMBB->getParent();
1553
1554 // Figure out which block is immediately after the current one.
1555 MachineBasicBlock *NextBlock = 0;
1556 MachineFunction::iterator BBI = CR.CaseBB;
1557
1558 if (++BBI != CurMBB->getParent()->end())
1559 NextBlock = BBI;
1560
1561 Case& FrontCase = *CR.Range.first;
1562 Case& BackCase = *(CR.Range.second-1);
1563 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1564
1565 // Size is the number of Cases represented by this range.
1566 unsigned Size = CR.Range.second - CR.Range.first;
1567
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001568 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1569 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001570 double FMetric = 0;
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001571 CaseItr Pivot = CR.Range.first + Size/2;
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001572
1573 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
1574 // (heuristically) allow us to emit JumpTable's later.
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001575 uint64_t TSize = 0;
1576 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1577 I!=E; ++I)
1578 TSize += I->size();
1579
1580 uint64_t LSize = FrontCase.size();
1581 uint64_t RSize = TSize-LSize;
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001582 DOUT << "Selecting best pivot: \n"
1583 << "First: " << First << ", Last: " << Last <<"\n"
1584 << "LSize: " << LSize << ", RSize: " << RSize << "\n";
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001585 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001586 J!=E; ++I, ++J) {
1587 int64_t LEnd = cast<ConstantInt>(I->High)->getSExtValue();
1588 int64_t RBegin = cast<ConstantInt>(J->Low)->getSExtValue();
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001589 assert((RBegin-LEnd>=1) && "Invalid case distance");
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001590 double LDensity = (double)LSize / (double)((LEnd - First) + 1ULL);
1591 double RDensity = (double)RSize / (double)((Last - RBegin) + 1ULL);
Anton Korobeynikovda964a22007-04-09 21:57:03 +00001592 double Metric = Log2_64(RBegin-LEnd)*(LDensity+RDensity);
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001593 // Should always split in some non-trivial place
1594 DOUT <<"=>Step\n"
1595 << "LEnd: " << LEnd << ", RBegin: " << RBegin << "\n"
1596 << "LDensity: " << LDensity << ", RDensity: " << RDensity << "\n"
1597 << "Metric: " << Metric << "\n";
1598 if (FMetric < Metric) {
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001599 Pivot = J;
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001600 FMetric = Metric;
1601 DOUT << "Current metric set to: " << FMetric << "\n";
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001602 }
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001603
1604 LSize += J->size();
1605 RSize -= J->size();
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001606 }
Anton Korobeynikov192d09c2007-05-09 20:07:08 +00001607 if (areJTsAllowed(TLI)) {
1608 // If our case is dense we *really* should handle it earlier!
1609 assert((FMetric > 0) && "Should handle dense range earlier!");
1610 } else {
1611 Pivot = CR.Range.first + Size/2;
1612 }
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001613
1614 CaseRange LHSR(CR.Range.first, Pivot);
1615 CaseRange RHSR(Pivot, CR.Range.second);
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001616 Constant *C = Pivot->Low;
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001617 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
1618
1619 // We know that we branch to the LHS if the Value being switched on is
1620 // less than the Pivot value, C. We use this to optimize our binary
1621 // tree a bit, by recognizing that if SV is greater than or equal to the
1622 // LHS's Case Value, and that Case Value is exactly one less than the
1623 // Pivot's Value, then we can branch directly to the LHS's Target,
1624 // rather than creating a leaf node for it.
1625 if ((LHSR.second - LHSR.first) == 1 &&
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001626 LHSR.first->High == CR.GE &&
1627 cast<ConstantInt>(C)->getSExtValue() ==
1628 (cast<ConstantInt>(CR.GE)->getSExtValue() + 1LL)) {
1629 TrueBB = LHSR.first->BB;
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001630 } else {
1631 TrueBB = new MachineBasicBlock(LLVMBB);
1632 CurMF->getBasicBlockList().insert(BBI, TrueBB);
1633 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
1634 }
1635
1636 // Similar to the optimization above, if the Value being switched on is
1637 // known to be less than the Constant CR.LT, and the current Case Value
1638 // is CR.LT - 1, then we can branch directly to the target block for
1639 // the current Case Value, rather than emitting a RHS leaf node for it.
1640 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001641 cast<ConstantInt>(RHSR.first->Low)->getSExtValue() ==
1642 (cast<ConstantInt>(CR.LT)->getSExtValue() - 1LL)) {
1643 FalseBB = RHSR.first->BB;
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001644 } else {
1645 FalseBB = new MachineBasicBlock(LLVMBB);
1646 CurMF->getBasicBlockList().insert(BBI, FalseBB);
1647 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
1648 }
1649
1650 // Create a CaseBlock record representing a conditional branch to
1651 // the LHS node if the value being switched on SV is less than C.
1652 // Otherwise, branch to LHS.
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001653 SelectionDAGISel::CaseBlock CB(ISD::SETLT, SV, C, NULL,
1654 TrueBB, FalseBB, CR.CaseBB);
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001655
1656 if (CR.CaseBB == CurMBB)
1657 visitSwitchCase(CB);
1658 else
1659 SwitchCases.push_back(CB);
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001660
1661 return true;
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001662}
1663
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001664/// handleBitTestsSwitchCase - if current case range has few destination and
1665/// range span less, than machine word bitwidth, encode case range into series
1666/// of masks and emit bit tests with these masks.
1667bool SelectionDAGLowering::handleBitTestsSwitchCase(CaseRec& CR,
1668 CaseRecVector& WorkList,
1669 Value* SV,
Chris Lattner7196f092007-04-14 02:26:56 +00001670 MachineBasicBlock* Default){
Dan Gohman1796f1f2007-05-18 17:52:13 +00001671 unsigned IntPtrBits = MVT::getSizeInBits(TLI.getPointerTy());
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001672
1673 Case& FrontCase = *CR.Range.first;
1674 Case& BackCase = *(CR.Range.second-1);
1675
1676 // Get the MachineFunction which holds the current MBB. This is used when
1677 // inserting any additional MBBs necessary to represent the switch.
1678 MachineFunction *CurMF = CurMBB->getParent();
1679
1680 unsigned numCmps = 0;
1681 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1682 I!=E; ++I) {
1683 // Single case counts one, case range - two.
1684 if (I->Low == I->High)
1685 numCmps +=1;
1686 else
1687 numCmps +=2;
1688 }
1689
1690 // Count unique destinations
1691 SmallSet<MachineBasicBlock*, 4> Dests;
1692 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1693 Dests.insert(I->BB);
1694 if (Dests.size() > 3)
1695 // Don't bother the code below, if there are too much unique destinations
1696 return false;
1697 }
1698 DOUT << "Total number of unique destinations: " << Dests.size() << "\n"
1699 << "Total number of comparisons: " << numCmps << "\n";
1700
1701 // Compute span of values.
1702 Constant* minValue = FrontCase.Low;
1703 Constant* maxValue = BackCase.High;
1704 uint64_t range = cast<ConstantInt>(maxValue)->getSExtValue() -
1705 cast<ConstantInt>(minValue)->getSExtValue();
1706 DOUT << "Compare range: " << range << "\n"
1707 << "Low bound: " << cast<ConstantInt>(minValue)->getSExtValue() << "\n"
1708 << "High bound: " << cast<ConstantInt>(maxValue)->getSExtValue() << "\n";
1709
Anton Korobeynikovd7ae7f12007-04-26 20:44:04 +00001710 if (range>=IntPtrBits ||
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001711 (!(Dests.size() == 1 && numCmps >= 3) &&
1712 !(Dests.size() == 2 && numCmps >= 5) &&
1713 !(Dests.size() >= 3 && numCmps >= 6)))
1714 return false;
1715
1716 DOUT << "Emitting bit tests\n";
1717 int64_t lowBound = 0;
1718
1719 // Optimize the case where all the case values fit in a
1720 // word without having to subtract minValue. In this case,
1721 // we can optimize away the subtraction.
1722 if (cast<ConstantInt>(minValue)->getSExtValue() >= 0 &&
Anton Korobeynikov8a1a84f2007-04-14 13:25:55 +00001723 cast<ConstantInt>(maxValue)->getSExtValue() < IntPtrBits) {
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001724 range = cast<ConstantInt>(maxValue)->getSExtValue();
1725 } else {
1726 lowBound = cast<ConstantInt>(minValue)->getSExtValue();
1727 }
1728
1729 CaseBitsVector CasesBits;
1730 unsigned i, count = 0;
1731
1732 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1733 MachineBasicBlock* Dest = I->BB;
1734 for (i = 0; i < count; ++i)
1735 if (Dest == CasesBits[i].BB)
1736 break;
1737
1738 if (i == count) {
1739 assert((count < 3) && "Too much destinations to test!");
1740 CasesBits.push_back(CaseBits(0, Dest, 0));
1741 count++;
1742 }
1743
1744 uint64_t lo = cast<ConstantInt>(I->Low)->getSExtValue() - lowBound;
1745 uint64_t hi = cast<ConstantInt>(I->High)->getSExtValue() - lowBound;
1746
1747 for (uint64_t j = lo; j <= hi; j++) {
Anton Korobeynikov8a1a84f2007-04-14 13:25:55 +00001748 CasesBits[i].Mask |= 1ULL << j;
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001749 CasesBits[i].Bits++;
1750 }
1751
1752 }
1753 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
1754
1755 SelectionDAGISel::BitTestInfo BTC;
1756
1757 // Figure out which block is immediately after the current one.
1758 MachineFunction::iterator BBI = CR.CaseBB;
1759 ++BBI;
1760
1761 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1762
1763 DOUT << "Cases:\n";
1764 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
1765 DOUT << "Mask: " << CasesBits[i].Mask << ", Bits: " << CasesBits[i].Bits
1766 << ", BB: " << CasesBits[i].BB << "\n";
1767
1768 MachineBasicBlock *CaseBB = new MachineBasicBlock(LLVMBB);
1769 CurMF->getBasicBlockList().insert(BBI, CaseBB);
1770 BTC.push_back(SelectionDAGISel::BitTestCase(CasesBits[i].Mask,
1771 CaseBB,
1772 CasesBits[i].BB));
1773 }
1774
1775 SelectionDAGISel::BitTestBlock BTB(lowBound, range, SV,
Jeff Cohen0475f3b2007-04-09 14:32:59 +00001776 -1U, (CR.CaseBB == CurMBB),
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001777 CR.CaseBB, Default, BTC);
1778
1779 if (CR.CaseBB == CurMBB)
1780 visitBitTestHeader(BTB);
1781
1782 BitTestCases.push_back(BTB);
1783
1784 return true;
1785}
1786
1787
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001788// Clusterify - Transform simple list of Cases into list of CaseRange's
1789unsigned SelectionDAGLowering::Clusterify(CaseVector& Cases,
1790 const SwitchInst& SI) {
1791 unsigned numCmps = 0;
1792
1793 // Start with "simple" cases
1794 for (unsigned i = 1; i < SI.getNumSuccessors(); ++i) {
1795 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
1796 Cases.push_back(Case(SI.getSuccessorValue(i),
1797 SI.getSuccessorValue(i),
1798 SMBB));
1799 }
1800 sort(Cases.begin(), Cases.end(), CaseCmp());
1801
1802 // Merge case into clusters
1803 if (Cases.size()>=2)
1804 for (CaseItr I=Cases.begin(), J=++(Cases.begin()), E=Cases.end(); J!=E; ) {
1805 int64_t nextValue = cast<ConstantInt>(J->Low)->getSExtValue();
1806 int64_t currentValue = cast<ConstantInt>(I->High)->getSExtValue();
1807 MachineBasicBlock* nextBB = J->BB;
1808 MachineBasicBlock* currentBB = I->BB;
1809
1810 // If the two neighboring cases go to the same destination, merge them
1811 // into a single case.
1812 if ((nextValue-currentValue==1) && (currentBB == nextBB)) {
1813 I->High = J->High;
1814 J = Cases.erase(J);
1815 } else {
1816 I = J++;
1817 }
1818 }
1819
1820 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
1821 if (I->Low != I->High)
1822 // A range counts double, since it requires two compares.
1823 ++numCmps;
1824 }
1825
1826 return numCmps;
1827}
1828
1829void SelectionDAGLowering::visitSwitch(SwitchInst &SI) {
Nate Begemaned728c12006-03-27 01:32:24 +00001830 // Figure out which block is immediately after the current one.
1831 MachineBasicBlock *NextBlock = 0;
1832 MachineFunction::iterator BBI = CurMBB;
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001833
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001834 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
Chris Lattner6d6fc262006-10-22 21:36:53 +00001835
Nate Begemaned728c12006-03-27 01:32:24 +00001836 // If there is only the default destination, branch to it if it is not the
1837 // next basic block. Otherwise, just fall through.
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001838 if (SI.getNumOperands() == 2) {
Nate Begemaned728c12006-03-27 01:32:24 +00001839 // Update machine-CFG edges.
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001840
Nate Begemaned728c12006-03-27 01:32:24 +00001841 // If this is not a fall-through branch, emit the branch.
Chris Lattner6d6fc262006-10-22 21:36:53 +00001842 if (Default != NextBlock)
Nate Begemaned728c12006-03-27 01:32:24 +00001843 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Chris Lattner6d6fc262006-10-22 21:36:53 +00001844 DAG.getBasicBlock(Default)));
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001845
Chris Lattner6d6fc262006-10-22 21:36:53 +00001846 CurMBB->addSuccessor(Default);
Nate Begemaned728c12006-03-27 01:32:24 +00001847 return;
1848 }
1849
1850 // If there are any non-default case statements, create a vector of Cases
1851 // representing each one, and sort the vector so that we can efficiently
1852 // create a binary search tree from them.
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001853 CaseVector Cases;
1854 unsigned numCmps = Clusterify(Cases, SI);
1855 DOUT << "Clusterify finished. Total clusters: " << Cases.size()
1856 << ". Total compares: " << numCmps << "\n";
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001857
Nate Begemaned728c12006-03-27 01:32:24 +00001858 // Get the Value to be switched on and default basic blocks, which will be
1859 // inserted into CaseBlock records, representing basic blocks in the binary
1860 // search tree.
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001861 Value *SV = SI.getOperand(0);
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001862
Nate Begemaned728c12006-03-27 01:32:24 +00001863 // Push the initial CaseRec onto the worklist
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001864 CaseRecVector WorkList;
Anton Korobeynikov70378262007-03-25 15:07:15 +00001865 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
1866
1867 while (!WorkList.empty()) {
Nate Begemaned728c12006-03-27 01:32:24 +00001868 // Grab a record representing a case range to process off the worklist
Anton Korobeynikov70378262007-03-25 15:07:15 +00001869 CaseRec CR = WorkList.back();
1870 WorkList.pop_back();
Anton Korobeynikov70378262007-03-25 15:07:15 +00001871
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001872 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
1873 continue;
1874
Anton Korobeynikov70378262007-03-25 15:07:15 +00001875 // If the range has few cases (two or less) emit a series of specific
1876 // tests.
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001877 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
1878 continue;
1879
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001880 // If the switch has more than 5 blocks, and at least 40% dense, and the
Anton Korobeynikov70378262007-03-25 15:07:15 +00001881 // target supports indirect branches, then emit a jump table rather than
1882 // lowering the switch to a binary tree of conditional branches.
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001883 if (handleJTSwitchCase(CR, WorkList, SV, Default))
1884 continue;
1885
1886 // Emit binary tree. We need to pick a pivot, and push left and right ranges
1887 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
1888 handleBTSplitSwitchCase(CR, WorkList, SV, Default);
Nate Begemaned728c12006-03-27 01:32:24 +00001889 }
1890}
1891
Anton Korobeynikov70378262007-03-25 15:07:15 +00001892
Chris Lattnerf68fd0b2005-04-02 05:04:50 +00001893void SelectionDAGLowering::visitSub(User &I) {
1894 // -0.0 - X --> fneg
Reid Spencer2eadb532007-01-21 00:29:26 +00001895 const Type *Ty = I.getType();
Reid Spencerd84d35b2007-02-15 02:26:10 +00001896 if (isa<VectorType>(Ty)) {
Dan Gohmana8665142007-06-25 16:23:39 +00001897 if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
1898 const VectorType *DestTy = cast<VectorType>(I.getType());
1899 const Type *ElTy = DestTy->getElementType();
1900 unsigned VL = DestTy->getNumElements();
1901 std::vector<Constant*> NZ(VL, ConstantFP::get(ElTy, -0.0));
1902 Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
1903 if (CV == CNZ) {
1904 SDOperand Op2 = getValue(I.getOperand(1));
1905 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
1906 return;
1907 }
1908 }
1909 }
1910 if (Ty->isFloatingPoint()) {
Chris Lattner6f3b5772005-09-28 22:28:18 +00001911 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
1912 if (CFP->isExactlyValue(-0.0)) {
1913 SDOperand Op2 = getValue(I.getOperand(1));
1914 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
1915 return;
1916 }
Dan Gohmana8665142007-06-25 16:23:39 +00001917 }
1918
1919 visitBinary(I, Ty->isFPOrFPVector() ? ISD::FSUB : ISD::SUB);
Chris Lattnerf68fd0b2005-04-02 05:04:50 +00001920}
1921
Dan Gohmana8665142007-06-25 16:23:39 +00001922void SelectionDAGLowering::visitBinary(User &I, unsigned OpCode) {
Chris Lattner7a60d912005-01-07 07:47:53 +00001923 SDOperand Op1 = getValue(I.getOperand(0));
1924 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencer2eadb532007-01-21 00:29:26 +00001925
1926 setValue(&I, DAG.getNode(OpCode, Op1.getValueType(), Op1, Op2));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001927}
1928
Nate Begeman127321b2005-11-18 07:42:56 +00001929void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
1930 SDOperand Op1 = getValue(I.getOperand(0));
1931 SDOperand Op2 = getValue(I.getOperand(1));
1932
Dan Gohmana8665142007-06-25 16:23:39 +00001933 if (MVT::getSizeInBits(TLI.getShiftAmountTy()) <
1934 MVT::getSizeInBits(Op2.getValueType()))
Reid Spencer2341c222007-02-02 02:16:23 +00001935 Op2 = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), Op2);
1936 else if (TLI.getShiftAmountTy() > Op2.getValueType())
1937 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
Nate Begeman127321b2005-11-18 07:42:56 +00001938
Chris Lattner7a60d912005-01-07 07:47:53 +00001939 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
1940}
1941
Reid Spencerd9436b62006-11-20 01:22:35 +00001942void SelectionDAGLowering::visitICmp(User &I) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001943 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
1944 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
1945 predicate = IC->getPredicate();
1946 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
1947 predicate = ICmpInst::Predicate(IC->getPredicate());
1948 SDOperand Op1 = getValue(I.getOperand(0));
1949 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencerd9436b62006-11-20 01:22:35 +00001950 ISD::CondCode Opcode;
Reid Spencer266e42b2006-12-23 06:05:41 +00001951 switch (predicate) {
Reid Spencerd9436b62006-11-20 01:22:35 +00001952 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
1953 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
1954 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
1955 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
1956 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
1957 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
1958 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
1959 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
1960 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
1961 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
1962 default:
1963 assert(!"Invalid ICmp predicate value");
1964 Opcode = ISD::SETEQ;
1965 break;
1966 }
1967 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
1968}
1969
1970void SelectionDAGLowering::visitFCmp(User &I) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001971 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
1972 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
1973 predicate = FC->getPredicate();
1974 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
1975 predicate = FCmpInst::Predicate(FC->getPredicate());
Chris Lattner7a60d912005-01-07 07:47:53 +00001976 SDOperand Op1 = getValue(I.getOperand(0));
1977 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencer266e42b2006-12-23 06:05:41 +00001978 ISD::CondCode Condition, FOC, FPC;
1979 switch (predicate) {
1980 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1981 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1982 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1983 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1984 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1985 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1986 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
1987 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
1988 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
1989 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1990 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1991 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1992 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1993 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1994 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1995 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
1996 default:
1997 assert(!"Invalid FCmp predicate value");
1998 FOC = FPC = ISD::SETFALSE;
1999 break;
2000 }
2001 if (FiniteOnlyFPMath())
2002 Condition = FOC;
2003 else
2004 Condition = FPC;
2005 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Condition));
Chris Lattner7a60d912005-01-07 07:47:53 +00002006}
2007
2008void SelectionDAGLowering::visitSelect(User &I) {
2009 SDOperand Cond = getValue(I.getOperand(0));
2010 SDOperand TrueVal = getValue(I.getOperand(1));
2011 SDOperand FalseVal = getValue(I.getOperand(2));
Dan Gohmana8665142007-06-25 16:23:39 +00002012 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
2013 TrueVal, FalseVal));
Chris Lattner7a60d912005-01-07 07:47:53 +00002014}
2015
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002016
2017void SelectionDAGLowering::visitTrunc(User &I) {
2018 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2019 SDOperand N = getValue(I.getOperand(0));
2020 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2021 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2022}
2023
2024void SelectionDAGLowering::visitZExt(User &I) {
2025 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2026 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2027 SDOperand N = getValue(I.getOperand(0));
2028 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2029 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2030}
2031
2032void SelectionDAGLowering::visitSExt(User &I) {
2033 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2034 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2035 SDOperand N = getValue(I.getOperand(0));
2036 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2037 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
2038}
2039
2040void SelectionDAGLowering::visitFPTrunc(User &I) {
2041 // FPTrunc is never a no-op cast, no need to check
2042 SDOperand N = getValue(I.getOperand(0));
2043 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2044 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N));
2045}
2046
2047void SelectionDAGLowering::visitFPExt(User &I){
2048 // FPTrunc is never a no-op cast, no need to check
2049 SDOperand N = getValue(I.getOperand(0));
2050 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2051 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
2052}
2053
2054void SelectionDAGLowering::visitFPToUI(User &I) {
2055 // FPToUI is never a no-op cast, no need to check
2056 SDOperand N = getValue(I.getOperand(0));
2057 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2058 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
2059}
2060
2061void SelectionDAGLowering::visitFPToSI(User &I) {
2062 // FPToSI is never a no-op cast, no need to check
2063 SDOperand N = getValue(I.getOperand(0));
2064 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2065 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
2066}
2067
2068void SelectionDAGLowering::visitUIToFP(User &I) {
2069 // UIToFP is never a no-op cast, no need to check
2070 SDOperand N = getValue(I.getOperand(0));
2071 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2072 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
2073}
2074
2075void SelectionDAGLowering::visitSIToFP(User &I){
2076 // UIToFP is never a no-op cast, no need to check
2077 SDOperand N = getValue(I.getOperand(0));
2078 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2079 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
2080}
2081
2082void SelectionDAGLowering::visitPtrToInt(User &I) {
2083 // What to do depends on the size of the integer and the size of the pointer.
2084 // We can either truncate, zero extend, or no-op, accordingly.
Chris Lattner7a60d912005-01-07 07:47:53 +00002085 SDOperand N = getValue(I.getOperand(0));
Chris Lattner2f4119a2006-03-22 20:09:35 +00002086 MVT::ValueType SrcVT = N.getValueType();
Chris Lattner4024c002006-03-15 22:19:46 +00002087 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002088 SDOperand Result;
2089 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
2090 Result = DAG.getNode(ISD::TRUNCATE, DestVT, N);
2091 else
2092 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2093 Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N);
2094 setValue(&I, Result);
2095}
Chris Lattner7a60d912005-01-07 07:47:53 +00002096
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002097void SelectionDAGLowering::visitIntToPtr(User &I) {
2098 // What to do depends on the size of the integer and the size of the pointer.
2099 // We can either truncate, zero extend, or no-op, accordingly.
2100 SDOperand N = getValue(I.getOperand(0));
2101 MVT::ValueType SrcVT = N.getValueType();
2102 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2103 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
2104 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2105 else
2106 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2107 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2108}
2109
2110void SelectionDAGLowering::visitBitCast(User &I) {
2111 SDOperand N = getValue(I.getOperand(0));
2112 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002113
2114 // BitCast assures us that source and destination are the same size so this
2115 // is either a BIT_CONVERT or a no-op.
2116 if (DestVT != N.getValueType())
2117 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types
2118 else
2119 setValue(&I, N); // noop cast.
Chris Lattner7a60d912005-01-07 07:47:53 +00002120}
2121
Chris Lattner67271862006-03-29 00:11:43 +00002122void SelectionDAGLowering::visitInsertElement(User &I) {
Chris Lattner32206f52006-03-18 01:44:44 +00002123 SDOperand InVec = getValue(I.getOperand(0));
2124 SDOperand InVal = getValue(I.getOperand(1));
2125 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2126 getValue(I.getOperand(2)));
2127
Dan Gohmana8665142007-06-25 16:23:39 +00002128 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT,
2129 TLI.getValueType(I.getType()),
2130 InVec, InVal, InIdx));
Chris Lattner32206f52006-03-18 01:44:44 +00002131}
2132
Chris Lattner67271862006-03-29 00:11:43 +00002133void SelectionDAGLowering::visitExtractElement(User &I) {
Chris Lattner7c0cd8c2006-03-21 20:44:12 +00002134 SDOperand InVec = getValue(I.getOperand(0));
2135 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2136 getValue(I.getOperand(1)));
Dan Gohmana8665142007-06-25 16:23:39 +00002137 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
Chris Lattner7c0cd8c2006-03-21 20:44:12 +00002138 TLI.getValueType(I.getType()), InVec, InIdx));
2139}
Chris Lattner32206f52006-03-18 01:44:44 +00002140
Chris Lattner098c01e2006-04-08 04:15:24 +00002141void SelectionDAGLowering::visitShuffleVector(User &I) {
2142 SDOperand V1 = getValue(I.getOperand(0));
2143 SDOperand V2 = getValue(I.getOperand(1));
2144 SDOperand Mask = getValue(I.getOperand(2));
2145
Dan Gohmana8665142007-06-25 16:23:39 +00002146 setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE,
2147 TLI.getValueType(I.getType()),
2148 V1, V2, Mask));
Chris Lattner098c01e2006-04-08 04:15:24 +00002149}
2150
2151
Chris Lattner7a60d912005-01-07 07:47:53 +00002152void SelectionDAGLowering::visitGetElementPtr(User &I) {
2153 SDOperand N = getValue(I.getOperand(0));
2154 const Type *Ty = I.getOperand(0)->getType();
Chris Lattner7a60d912005-01-07 07:47:53 +00002155
2156 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2157 OI != E; ++OI) {
2158 Value *Idx = *OI;
Chris Lattner35397782005-12-05 07:10:48 +00002159 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002160 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
Chris Lattner7a60d912005-01-07 07:47:53 +00002161 if (Field) {
2162 // N = N + Offset
Chris Lattnerc473d8e2007-02-10 19:55:17 +00002163 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
Chris Lattner7a60d912005-01-07 07:47:53 +00002164 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Misha Brukman77451162005-04-22 04:01:18 +00002165 getIntPtrConstant(Offset));
Chris Lattner7a60d912005-01-07 07:47:53 +00002166 }
2167 Ty = StTy->getElementType(Field);
2168 } else {
2169 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner19a83992005-01-07 21:56:57 +00002170
Chris Lattner43535a12005-11-09 04:45:33 +00002171 // If this is a constant subscript, handle it quickly.
2172 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002173 if (CI->getZExtValue() == 0) continue;
Reid Spencere63b6512006-12-31 05:55:36 +00002174 uint64_t Offs =
Evan Cheng8ec52832007-01-05 01:46:20 +00002175 TD->getTypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
Chris Lattner43535a12005-11-09 04:45:33 +00002176 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
2177 continue;
Chris Lattner7a60d912005-01-07 07:47:53 +00002178 }
Chris Lattner43535a12005-11-09 04:45:33 +00002179
2180 // N = N + Idx * ElementSize;
Owen Anderson20a631f2006-05-03 01:29:57 +00002181 uint64_t ElementSize = TD->getTypeSize(Ty);
Chris Lattner43535a12005-11-09 04:45:33 +00002182 SDOperand IdxN = getValue(Idx);
2183
2184 // If the index is smaller or larger than intptr_t, truncate or extend
2185 // it.
2186 if (IdxN.getValueType() < N.getValueType()) {
Reid Spencere63b6512006-12-31 05:55:36 +00002187 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
Chris Lattner43535a12005-11-09 04:45:33 +00002188 } else if (IdxN.getValueType() > N.getValueType())
2189 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
2190
2191 // If this is a multiply by a power of two, turn it into a shl
2192 // immediately. This is a very common case.
2193 if (isPowerOf2_64(ElementSize)) {
2194 unsigned Amt = Log2_64(ElementSize);
2195 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner41fd6d52005-11-09 16:50:40 +00002196 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner43535a12005-11-09 04:45:33 +00002197 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
2198 continue;
2199 }
2200
2201 SDOperand Scale = getIntPtrConstant(ElementSize);
2202 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
2203 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner7a60d912005-01-07 07:47:53 +00002204 }
2205 }
2206 setValue(&I, N);
2207}
2208
2209void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
2210 // If this is a fixed sized alloca in the entry block of the function,
2211 // allocate it statically on the stack.
2212 if (FuncInfo.StaticAllocaMap.count(&I))
2213 return; // getValue will auto-populate this.
2214
2215 const Type *Ty = I.getAllocatedType();
Owen Anderson20a631f2006-05-03 01:29:57 +00002216 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
Chris Lattner50ee0e42007-01-20 22:35:55 +00002217 unsigned Align =
Chris Lattner945e4372007-02-14 05:52:17 +00002218 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
Chris Lattner50ee0e42007-01-20 22:35:55 +00002219 I.getAlignment());
Chris Lattner7a60d912005-01-07 07:47:53 +00002220
2221 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattnereccb73d2005-01-22 23:04:37 +00002222 MVT::ValueType IntPtr = TLI.getPointerTy();
2223 if (IntPtr < AllocSize.getValueType())
2224 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
2225 else if (IntPtr > AllocSize.getValueType())
2226 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner7a60d912005-01-07 07:47:53 +00002227
Chris Lattnereccb73d2005-01-22 23:04:37 +00002228 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner7a60d912005-01-07 07:47:53 +00002229 getIntPtrConstant(TySize));
2230
2231 // Handle alignment. If the requested alignment is less than or equal to the
2232 // stack alignment, ignore it and round the size of the allocation up to the
2233 // stack alignment size. If the size is greater than the stack alignment, we
2234 // note this in the DYNAMIC_STACKALLOC node.
2235 unsigned StackAlign =
2236 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
2237 if (Align <= StackAlign) {
2238 Align = 0;
2239 // Add SA-1 to the size.
2240 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
2241 getIntPtrConstant(StackAlign-1));
2242 // Mask out the low bits for alignment purposes.
2243 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
2244 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
2245 }
2246
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002247 SDOperand Ops[] = { getRoot(), AllocSize, getIntPtrConstant(Align) };
Chris Lattnerbd887772006-08-14 23:53:35 +00002248 const MVT::ValueType *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
2249 MVT::Other);
2250 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
Chris Lattner79084302007-02-04 01:31:47 +00002251 setValue(&I, DSA);
2252 DAG.setRoot(DSA.getValue(1));
Chris Lattner7a60d912005-01-07 07:47:53 +00002253
2254 // Inform the Frame Information that we have just allocated a variable-sized
2255 // object.
2256 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
2257}
2258
Chris Lattner7a60d912005-01-07 07:47:53 +00002259void SelectionDAGLowering::visitLoad(LoadInst &I) {
2260 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukman835702a2005-04-21 22:36:52 +00002261
Chris Lattner4d9651c2005-01-17 22:19:26 +00002262 SDOperand Root;
2263 if (I.isVolatile())
2264 Root = getRoot();
2265 else {
2266 // Do not serialize non-volatile loads against each other.
2267 Root = DAG.getRoot();
2268 }
Chris Lattner4024c002006-03-15 22:19:46 +00002269
Evan Chenge71fe34d2006-10-09 20:57:25 +00002270 setValue(&I, getLoadFrom(I.getType(), Ptr, I.getOperand(0),
Christopher Lamb8af6d582007-04-22 23:15:30 +00002271 Root, I.isVolatile(), I.getAlignment()));
Chris Lattner4024c002006-03-15 22:19:46 +00002272}
2273
2274SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Chenge71fe34d2006-10-09 20:57:25 +00002275 const Value *SV, SDOperand Root,
Christopher Lamb8af6d582007-04-22 23:15:30 +00002276 bool isVolatile,
2277 unsigned Alignment) {
Dan Gohmana8665142007-06-25 16:23:39 +00002278 SDOperand L =
2279 DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SV, 0,
2280 isVolatile, Alignment);
Chris Lattner4d9651c2005-01-17 22:19:26 +00002281
Chris Lattner4024c002006-03-15 22:19:46 +00002282 if (isVolatile)
Chris Lattner4d9651c2005-01-17 22:19:26 +00002283 DAG.setRoot(L.getValue(1));
2284 else
2285 PendingLoads.push_back(L.getValue(1));
Chris Lattner4024c002006-03-15 22:19:46 +00002286
2287 return L;
Chris Lattner7a60d912005-01-07 07:47:53 +00002288}
2289
2290
2291void SelectionDAGLowering::visitStore(StoreInst &I) {
2292 Value *SrcV = I.getOperand(0);
2293 SDOperand Src = getValue(SrcV);
2294 SDOperand Ptr = getValue(I.getOperand(1));
Evan Cheng258657e2006-12-20 01:27:29 +00002295 DAG.setRoot(DAG.getStore(getRoot(), Src, Ptr, I.getOperand(1), 0,
Christopher Lamb8af6d582007-04-22 23:15:30 +00002296 I.isVolatile(), I.getAlignment()));
Chris Lattner7a60d912005-01-07 07:47:53 +00002297}
2298
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002299/// IntrinsicCannotAccessMemory - Return true if the specified intrinsic cannot
2300/// access memory and has no other side effects at all.
2301static bool IntrinsicCannotAccessMemory(unsigned IntrinsicID) {
2302#define GET_NO_MEMORY_INTRINSICS
2303#include "llvm/Intrinsics.gen"
2304#undef GET_NO_MEMORY_INTRINSICS
2305 return false;
2306}
2307
Chris Lattnera9c59156b2006-04-02 03:41:14 +00002308// IntrinsicOnlyReadsMemory - Return true if the specified intrinsic doesn't
2309// have any side-effects or if it only reads memory.
2310static bool IntrinsicOnlyReadsMemory(unsigned IntrinsicID) {
2311#define GET_SIDE_EFFECT_INFO
2312#include "llvm/Intrinsics.gen"
2313#undef GET_SIDE_EFFECT_INFO
2314 return false;
2315}
2316
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002317/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2318/// node.
2319void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
2320 unsigned Intrinsic) {
Chris Lattner313229c2006-03-24 22:49:42 +00002321 bool HasChain = !IntrinsicCannotAccessMemory(Intrinsic);
Chris Lattnera9c59156b2006-04-02 03:41:14 +00002322 bool OnlyLoad = HasChain && IntrinsicOnlyReadsMemory(Intrinsic);
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002323
2324 // Build the operand list.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002325 SmallVector<SDOperand, 8> Ops;
Chris Lattnera9c59156b2006-04-02 03:41:14 +00002326 if (HasChain) { // If this intrinsic has side-effects, chainify it.
2327 if (OnlyLoad) {
2328 // We don't need to serialize loads against other loads.
2329 Ops.push_back(DAG.getRoot());
2330 } else {
2331 Ops.push_back(getRoot());
2332 }
2333 }
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002334
2335 // Add the intrinsic ID as an integer operand.
2336 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
2337
2338 // Add all operands of the call to the operand list.
2339 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2340 SDOperand Op = getValue(I.getOperand(i));
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002341 assert(TLI.isTypeLegal(Op.getValueType()) &&
2342 "Intrinsic uses a non-legal type?");
2343 Ops.push_back(Op);
2344 }
2345
2346 std::vector<MVT::ValueType> VTs;
2347 if (I.getType() != Type::VoidTy) {
2348 MVT::ValueType VT = TLI.getValueType(I.getType());
Dan Gohmana8665142007-06-25 16:23:39 +00002349 if (MVT::isVector(VT)) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00002350 const VectorType *DestTy = cast<VectorType>(I.getType());
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002351 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
2352
2353 VT = MVT::getVectorType(EltVT, DestTy->getNumElements());
2354 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
2355 }
2356
2357 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
2358 VTs.push_back(VT);
2359 }
2360 if (HasChain)
2361 VTs.push_back(MVT::Other);
2362
Chris Lattnerbd887772006-08-14 23:53:35 +00002363 const MVT::ValueType *VTList = DAG.getNodeValueTypes(VTs);
2364
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002365 // Create the node.
Chris Lattnere55d1712006-03-28 00:40:33 +00002366 SDOperand Result;
2367 if (!HasChain)
Chris Lattnerbd887772006-08-14 23:53:35 +00002368 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
2369 &Ops[0], Ops.size());
Chris Lattnere55d1712006-03-28 00:40:33 +00002370 else if (I.getType() != Type::VoidTy)
Chris Lattnerbd887772006-08-14 23:53:35 +00002371 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
2372 &Ops[0], Ops.size());
Chris Lattnere55d1712006-03-28 00:40:33 +00002373 else
Chris Lattnerbd887772006-08-14 23:53:35 +00002374 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
2375 &Ops[0], Ops.size());
Chris Lattnere55d1712006-03-28 00:40:33 +00002376
Chris Lattnera9c59156b2006-04-02 03:41:14 +00002377 if (HasChain) {
2378 SDOperand Chain = Result.getValue(Result.Val->getNumValues()-1);
2379 if (OnlyLoad)
2380 PendingLoads.push_back(Chain);
2381 else
2382 DAG.setRoot(Chain);
2383 }
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002384 if (I.getType() != Type::VoidTy) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00002385 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
Dan Gohmana8665142007-06-25 16:23:39 +00002386 MVT::ValueType VT = TLI.getValueType(PTy);
2387 Result = DAG.getNode(ISD::BIT_CONVERT, VT, Result);
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002388 }
2389 setValue(&I, Result);
2390 }
2391}
2392
Duncan Sands4cb9eb82007-05-04 17:12:26 +00002393/// ExtractGlobalVariable - If C is a global variable, or a bitcast of one
2394/// (possibly constant folded), return it. Otherwise return NULL.
2395static GlobalVariable *ExtractGlobalVariable (Constant *C) {
2396 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
2397 return GV;
2398 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2399 if (CE->getOpcode() == Instruction::BitCast)
2400 return dyn_cast<GlobalVariable>(CE->getOperand(0));
2401 else if (CE->getOpcode() == Instruction::GetElementPtr) {
2402 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
2403 if (!CE->getOperand(i)->isNullValue())
2404 return NULL;
2405 return dyn_cast<GlobalVariable>(CE->getOperand(0));
2406 }
2407 }
2408 return NULL;
2409}
2410
Duncan Sands92bf2c62007-06-15 19:04:19 +00002411/// addCatchInfo - Extract the personality and type infos from an eh.selector
2412/// or eh.filter call, and add them to the specified machine basic block.
2413static void addCatchInfo(CallInst &I, MachineModuleInfo *MMI,
2414 MachineBasicBlock *MBB) {
2415 // Inform the MachineModuleInfo of the personality for this landing pad.
2416 ConstantExpr *CE = cast<ConstantExpr>(I.getOperand(2));
2417 assert(CE->getOpcode() == Instruction::BitCast &&
2418 isa<Function>(CE->getOperand(0)) &&
2419 "Personality should be a function");
2420 MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0)));
2421
2422 // Gather all the type infos for this landing pad and pass them along to
2423 // MachineModuleInfo.
2424 std::vector<GlobalVariable *> TyInfo;
2425 for (unsigned i = 3, N = I.getNumOperands(); i < N; ++i) {
2426 Constant *C = cast<Constant>(I.getOperand(i));
2427 GlobalVariable *GV = ExtractGlobalVariable(C);
2428 assert (GV || isa<ConstantPointerNull>(C) &&
2429 "TypeInfo must be a global variable or NULL");
2430 TyInfo.push_back(GV);
2431 }
2432 if (I.getCalledFunction()->getIntrinsicID() == Intrinsic::eh_filter)
2433 MMI->addFilterTypeInfo(MBB, TyInfo);
2434 else
2435 MMI->addCatchTypeInfo(MBB, TyInfo);
2436}
2437
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002438/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
2439/// we want to emit this as a call to a named external function, return the name
2440/// otherwise lower it and return null.
2441const char *
2442SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
2443 switch (Intrinsic) {
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002444 default:
2445 // By default, turn this into a target intrinsic node.
2446 visitTargetIntrinsic(I, Intrinsic);
2447 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002448 case Intrinsic::vastart: visitVAStart(I); return 0;
2449 case Intrinsic::vaend: visitVAEnd(I); return 0;
2450 case Intrinsic::vacopy: visitVACopy(I); return 0;
Nate Begemaneda59972007-01-29 22:58:52 +00002451 case Intrinsic::returnaddress:
2452 setValue(&I, DAG.getNode(ISD::RETURNADDR, TLI.getPointerTy(),
2453 getValue(I.getOperand(1))));
2454 return 0;
2455 case Intrinsic::frameaddress:
2456 setValue(&I, DAG.getNode(ISD::FRAMEADDR, TLI.getPointerTy(),
2457 getValue(I.getOperand(1))));
2458 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002459 case Intrinsic::setjmp:
Anton Korobeynikov3b7c2572006-12-10 23:12:42 +00002460 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002461 break;
2462 case Intrinsic::longjmp:
Anton Korobeynikov3b7c2572006-12-10 23:12:42 +00002463 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002464 break;
Chris Lattner093c1592006-03-03 00:00:25 +00002465 case Intrinsic::memcpy_i32:
2466 case Intrinsic::memcpy_i64:
2467 visitMemIntrinsic(I, ISD::MEMCPY);
2468 return 0;
2469 case Intrinsic::memset_i32:
2470 case Intrinsic::memset_i64:
2471 visitMemIntrinsic(I, ISD::MEMSET);
2472 return 0;
2473 case Intrinsic::memmove_i32:
2474 case Intrinsic::memmove_i64:
2475 visitMemIntrinsic(I, ISD::MEMMOVE);
2476 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002477
Chris Lattner5d4e61d2005-12-13 17:40:33 +00002478 case Intrinsic::dbg_stoppoint: {
Jim Laskeyc56315c2007-01-26 21:22:28 +00002479 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskeya8bdac82006-03-23 18:06:46 +00002480 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Jim Laskeyc56315c2007-01-26 21:22:28 +00002481 if (MMI && SPI.getContext() && MMI->Verify(SPI.getContext())) {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002482 SDOperand Ops[5];
Chris Lattner435b4022005-11-29 06:21:05 +00002483
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002484 Ops[0] = getRoot();
2485 Ops[1] = getValue(SPI.getLineValue());
2486 Ops[2] = getValue(SPI.getColumnValue());
Chris Lattner435b4022005-11-29 06:21:05 +00002487
Jim Laskeyc56315c2007-01-26 21:22:28 +00002488 DebugInfoDesc *DD = MMI->getDescFor(SPI.getContext());
Jim Laskey5995d012006-02-11 01:01:30 +00002489 assert(DD && "Not a debug information descriptor");
Jim Laskeya8bdac82006-03-23 18:06:46 +00002490 CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
2491
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002492 Ops[3] = DAG.getString(CompileUnit->getFileName());
2493 Ops[4] = DAG.getString(CompileUnit->getDirectory());
Jim Laskey5995d012006-02-11 01:01:30 +00002494
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002495 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops, 5));
Chris Lattner5d4e61d2005-12-13 17:40:33 +00002496 }
Jim Laskeya8bdac82006-03-23 18:06:46 +00002497
Chris Lattnerf2b62f32005-11-16 07:22:30 +00002498 return 0;
Chris Lattner435b4022005-11-29 06:21:05 +00002499 }
Jim Laskeya8bdac82006-03-23 18:06:46 +00002500 case Intrinsic::dbg_region_start: {
Jim Laskeyc56315c2007-01-26 21:22:28 +00002501 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskeya8bdac82006-03-23 18:06:46 +00002502 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
Jim Laskeyc56315c2007-01-26 21:22:28 +00002503 if (MMI && RSI.getContext() && MMI->Verify(RSI.getContext())) {
2504 unsigned LabelID = MMI->RecordRegionStart(RSI.getContext());
Jim Laskeyf9e54452007-01-26 14:34:52 +00002505 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002506 DAG.getConstant(LabelID, MVT::i32)));
Jim Laskeya8bdac82006-03-23 18:06:46 +00002507 }
2508
Chris Lattnerf2b62f32005-11-16 07:22:30 +00002509 return 0;
Jim Laskeya8bdac82006-03-23 18:06:46 +00002510 }
2511 case Intrinsic::dbg_region_end: {
Jim Laskeyc56315c2007-01-26 21:22:28 +00002512 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskeya8bdac82006-03-23 18:06:46 +00002513 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
Jim Laskeyc56315c2007-01-26 21:22:28 +00002514 if (MMI && REI.getContext() && MMI->Verify(REI.getContext())) {
2515 unsigned LabelID = MMI->RecordRegionEnd(REI.getContext());
Jim Laskeyf9e54452007-01-26 14:34:52 +00002516 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other,
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002517 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
Jim Laskeya8bdac82006-03-23 18:06:46 +00002518 }
2519
Chris Lattnerf2b62f32005-11-16 07:22:30 +00002520 return 0;
Jim Laskeya8bdac82006-03-23 18:06:46 +00002521 }
2522 case Intrinsic::dbg_func_start: {
Jim Laskeyc56315c2007-01-26 21:22:28 +00002523 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskeya8bdac82006-03-23 18:06:46 +00002524 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
Jim Laskeyc56315c2007-01-26 21:22:28 +00002525 if (MMI && FSI.getSubprogram() &&
2526 MMI->Verify(FSI.getSubprogram())) {
2527 unsigned LabelID = MMI->RecordRegionStart(FSI.getSubprogram());
Jim Laskeyf9e54452007-01-26 14:34:52 +00002528 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other,
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002529 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
Jim Laskeya8bdac82006-03-23 18:06:46 +00002530 }
2531
Chris Lattnerf2b62f32005-11-16 07:22:30 +00002532 return 0;
Jim Laskeya8bdac82006-03-23 18:06:46 +00002533 }
2534 case Intrinsic::dbg_declare: {
Jim Laskeyc56315c2007-01-26 21:22:28 +00002535 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskeya8bdac82006-03-23 18:06:46 +00002536 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
Jim Laskeyc56315c2007-01-26 21:22:28 +00002537 if (MMI && DI.getVariable() && MMI->Verify(DI.getVariable())) {
Jim Laskey53f1ecc2006-03-24 09:50:27 +00002538 SDOperand AddressOp = getValue(DI.getAddress());
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002539 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(AddressOp))
Jim Laskeyc56315c2007-01-26 21:22:28 +00002540 MMI->RecordVariable(DI.getVariable(), FI->getIndex());
Jim Laskeya8bdac82006-03-23 18:06:46 +00002541 }
2542
2543 return 0;
2544 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002545
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002546 case Intrinsic::eh_exception: {
2547 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2548
Duncan Sands74137362007-06-13 16:53:21 +00002549 if (ExceptionHandling && MMI) {
Jim Laskey504e9942007-02-22 15:38:06 +00002550 // Mark exception register as live in.
2551 unsigned Reg = TLI.getExceptionAddressRegister();
2552 if (Reg) CurMBB->addLiveIn(Reg);
Duncan Sands61166502007-06-06 10:05:18 +00002553
Jim Laskey504e9942007-02-22 15:38:06 +00002554 // Insert the EXCEPTIONADDR instruction.
2555 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
2556 SDOperand Ops[1];
2557 Ops[0] = DAG.getRoot();
2558 SDOperand Op = DAG.getNode(ISD::EXCEPTIONADDR, VTs, Ops, 1);
2559 setValue(&I, Op);
2560 DAG.setRoot(Op.getValue(1));
Jim Laskeye1d1c052007-02-24 09:45:44 +00002561 } else {
Jim Laskeycf465fc2007-02-28 18:37:04 +00002562 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
Jim Laskey504e9942007-02-22 15:38:06 +00002563 }
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002564 return 0;
2565 }
2566
Jim Laskeyd5453d72007-03-01 20:24:30 +00002567 case Intrinsic::eh_selector:
2568 case Intrinsic::eh_filter:{
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002569 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002570
Duncan Sands92bf2c62007-06-15 19:04:19 +00002571 if (ExceptionHandling && MMI) {
2572 if (CurMBB->isLandingPad())
2573 addCatchInfo(I, MMI, CurMBB);
2574#ifndef NDEBUG
Duncan Sandsc063f5f2007-06-02 16:53:42 +00002575 else
Duncan Sands92bf2c62007-06-15 19:04:19 +00002576 FuncInfo.CatchInfoLost.insert(&I);
2577#endif
Duncan Sands61166502007-06-06 10:05:18 +00002578
Jim Laskey504e9942007-02-22 15:38:06 +00002579 // Mark exception selector register as live in.
2580 unsigned Reg = TLI.getExceptionSelectorRegister();
2581 if (Reg) CurMBB->addLiveIn(Reg);
2582
2583 // Insert the EHSELECTION instruction.
Anton Korobeynikov11940fb2007-05-02 22:15:48 +00002584 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
Jim Laskey504e9942007-02-22 15:38:06 +00002585 SDOperand Ops[2];
2586 Ops[0] = getValue(I.getOperand(1));
2587 Ops[1] = getRoot();
2588 SDOperand Op = DAG.getNode(ISD::EHSELECTION, VTs, Ops, 2);
2589 setValue(&I, Op);
2590 DAG.setRoot(Op.getValue(1));
Jim Laskeye1d1c052007-02-24 09:45:44 +00002591 } else {
Anton Korobeynikov11940fb2007-05-02 22:15:48 +00002592 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
Jim Laskey504e9942007-02-22 15:38:06 +00002593 }
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002594
2595 return 0;
2596 }
2597
2598 case Intrinsic::eh_typeid_for: {
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002599 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002600
Jim Laskey504e9942007-02-22 15:38:06 +00002601 if (MMI) {
2602 // Find the type id for the given typeinfo.
Duncan Sands4cb9eb82007-05-04 17:12:26 +00002603 Constant *C = cast<Constant>(I.getOperand(1));
2604 GlobalVariable *GV = ExtractGlobalVariable(C);
Duncan Sands706421e2007-06-01 08:18:30 +00002605 assert (GV || isa<ConstantPointerNull>(C) &&
Duncan Sands4cb9eb82007-05-04 17:12:26 +00002606 "TypeInfo must be a global variable or NULL");
2607
Jim Laskey504e9942007-02-22 15:38:06 +00002608 unsigned TypeID = MMI->getTypeIDFor(GV);
2609 setValue(&I, DAG.getConstant(TypeID, MVT::i32));
Jim Laskeye1d1c052007-02-24 09:45:44 +00002610 } else {
2611 setValue(&I, DAG.getConstant(0, MVT::i32));
Jim Laskey504e9942007-02-22 15:38:06 +00002612 }
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002613
2614 return 0;
2615 }
2616
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00002617 case Intrinsic::sqrt_f32:
2618 case Intrinsic::sqrt_f64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002619 setValue(&I, DAG.getNode(ISD::FSQRT,
2620 getValue(I.getOperand(1)).getValueType(),
2621 getValue(I.getOperand(1))));
2622 return 0;
Chris Lattnerf0359b32006-09-09 06:03:30 +00002623 case Intrinsic::powi_f32:
2624 case Intrinsic::powi_f64:
2625 setValue(&I, DAG.getNode(ISD::FPOWI,
2626 getValue(I.getOperand(1)).getValueType(),
2627 getValue(I.getOperand(1)),
2628 getValue(I.getOperand(2))));
2629 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002630 case Intrinsic::pcmarker: {
2631 SDOperand Tmp = getValue(I.getOperand(1));
2632 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
2633 return 0;
2634 }
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00002635 case Intrinsic::readcyclecounter: {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002636 SDOperand Op = getRoot();
Chris Lattnerbd887772006-08-14 23:53:35 +00002637 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
2638 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
2639 &Op, 1);
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00002640 setValue(&I, Tmp);
2641 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth01aa5632005-11-11 16:47:30 +00002642 return 0;
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00002643 }
Chris Lattnerf269d842007-04-10 03:20:39 +00002644 case Intrinsic::part_select: {
Reid Spencer85460ac2007-04-05 01:20:18 +00002645 // Currently not implemented: just abort
Reid Spencerc6251a72007-04-12 02:48:46 +00002646 assert(0 && "part_select intrinsic not implemented");
2647 abort();
2648 }
2649 case Intrinsic::part_set: {
2650 // Currently not implemented: just abort
2651 assert(0 && "part_set intrinsic not implemented");
Reid Spencer85460ac2007-04-05 01:20:18 +00002652 abort();
Reid Spencercce90f52007-04-04 23:48:25 +00002653 }
Reid Spencer3a0843e2007-04-01 07:34:11 +00002654 case Intrinsic::bswap:
Nate Begeman2fba8a32006-01-14 03:14:10 +00002655 setValue(&I, DAG.getNode(ISD::BSWAP,
2656 getValue(I.getOperand(1)).getValueType(),
2657 getValue(I.getOperand(1))));
2658 return 0;
Reid Spencer3a0843e2007-04-01 07:34:11 +00002659 case Intrinsic::cttz: {
2660 SDOperand Arg = getValue(I.getOperand(1));
2661 MVT::ValueType Ty = Arg.getValueType();
2662 SDOperand result = DAG.getNode(ISD::CTTZ, Ty, Arg);
2663 if (Ty < MVT::i32)
2664 result = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, result);
2665 else if (Ty > MVT::i32)
2666 result = DAG.getNode(ISD::TRUNCATE, MVT::i32, result);
2667 setValue(&I, result);
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002668 return 0;
Reid Spencer3a0843e2007-04-01 07:34:11 +00002669 }
2670 case Intrinsic::ctlz: {
2671 SDOperand Arg = getValue(I.getOperand(1));
2672 MVT::ValueType Ty = Arg.getValueType();
2673 SDOperand result = DAG.getNode(ISD::CTLZ, Ty, Arg);
2674 if (Ty < MVT::i32)
2675 result = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, result);
2676 else if (Ty > MVT::i32)
2677 result = DAG.getNode(ISD::TRUNCATE, MVT::i32, result);
2678 setValue(&I, result);
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002679 return 0;
Reid Spencer3a0843e2007-04-01 07:34:11 +00002680 }
2681 case Intrinsic::ctpop: {
2682 SDOperand Arg = getValue(I.getOperand(1));
2683 MVT::ValueType Ty = Arg.getValueType();
2684 SDOperand result = DAG.getNode(ISD::CTPOP, Ty, Arg);
2685 if (Ty < MVT::i32)
2686 result = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, result);
2687 else if (Ty > MVT::i32)
2688 result = DAG.getNode(ISD::TRUNCATE, MVT::i32, result);
2689 setValue(&I, result);
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002690 return 0;
Reid Spencer3a0843e2007-04-01 07:34:11 +00002691 }
Chris Lattnerb3266452006-01-13 02:50:02 +00002692 case Intrinsic::stacksave: {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002693 SDOperand Op = getRoot();
Chris Lattnerbd887772006-08-14 23:53:35 +00002694 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE,
2695 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
Chris Lattnerb3266452006-01-13 02:50:02 +00002696 setValue(&I, Tmp);
2697 DAG.setRoot(Tmp.getValue(1));
2698 return 0;
2699 }
Chris Lattnerdeda32a2006-01-23 05:22:07 +00002700 case Intrinsic::stackrestore: {
2701 SDOperand Tmp = getValue(I.getOperand(1));
2702 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
Chris Lattnerb3266452006-01-13 02:50:02 +00002703 return 0;
Chris Lattnerdeda32a2006-01-23 05:22:07 +00002704 }
Chris Lattner9e8b6332005-12-12 22:51:16 +00002705 case Intrinsic::prefetch:
2706 // FIXME: Currently discarding prefetches.
2707 return 0;
Tanya Lattnere199f972007-06-15 22:26:58 +00002708
2709 case Intrinsic::var_annotation:
2710 // Discard annotate attributes
2711 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002712 }
2713}
2714
2715
Jim Laskey31fef782007-02-23 21:45:01 +00002716void SelectionDAGLowering::LowerCallTo(Instruction &I,
2717 const Type *CalledValueTy,
2718 unsigned CallingConv,
2719 bool IsTailCall,
Anton Korobeynikov3b327822007-05-23 11:08:31 +00002720 SDOperand Callee, unsigned OpIdx,
2721 MachineBasicBlock *LandingPad) {
Jim Laskey31fef782007-02-23 21:45:01 +00002722 const PointerType *PT = cast<PointerType>(CalledValueTy);
Jim Laskey504e9942007-02-22 15:38:06 +00002723 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Reid Spencer71b79e32007-04-09 06:17:21 +00002724 const ParamAttrsList *Attrs = FTy->getParamAttrs();
Anton Korobeynikov3b327822007-05-23 11:08:31 +00002725 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2726 unsigned BeginLabel = 0, EndLabel = 0;
2727
Jim Laskey504e9942007-02-22 15:38:06 +00002728 TargetLowering::ArgListTy Args;
2729 TargetLowering::ArgListEntry Entry;
2730 Args.reserve(I.getNumOperands());
2731 for (unsigned i = OpIdx, e = I.getNumOperands(); i != e; ++i) {
2732 Value *Arg = I.getOperand(i);
2733 SDOperand ArgNode = getValue(Arg);
2734 Entry.Node = ArgNode; Entry.Ty = Arg->getType();
Duncan Sands671e8c42007-05-07 20:49:28 +00002735
2736 unsigned attrInd = i - OpIdx + 1;
2737 Entry.isSExt = Attrs && Attrs->paramHasAttr(attrInd, ParamAttr::SExt);
2738 Entry.isZExt = Attrs && Attrs->paramHasAttr(attrInd, ParamAttr::ZExt);
2739 Entry.isInReg = Attrs && Attrs->paramHasAttr(attrInd, ParamAttr::InReg);
2740 Entry.isSRet = Attrs && Attrs->paramHasAttr(attrInd, ParamAttr::StructRet);
Jim Laskey504e9942007-02-22 15:38:06 +00002741 Args.push_back(Entry);
2742 }
2743
Duncan Sands61166502007-06-06 10:05:18 +00002744 if (ExceptionHandling && MMI) {
Anton Korobeynikov3b327822007-05-23 11:08:31 +00002745 // Insert a label before the invoke call to mark the try range. This can be
2746 // used to detect deletion of the invoke via the MachineModuleInfo.
2747 BeginLabel = MMI->NextLabelID();
2748 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
2749 DAG.getConstant(BeginLabel, MVT::i32)));
2750 }
2751
Jim Laskey504e9942007-02-22 15:38:06 +00002752 std::pair<SDOperand,SDOperand> Result =
2753 TLI.LowerCallTo(getRoot(), I.getType(),
Reid Spencera472f662007-04-11 02:44:20 +00002754 Attrs && Attrs->paramHasAttr(0, ParamAttr::SExt),
Jim Laskey31fef782007-02-23 21:45:01 +00002755 FTy->isVarArg(), CallingConv, IsTailCall,
Jim Laskey504e9942007-02-22 15:38:06 +00002756 Callee, Args, DAG);
2757 if (I.getType() != Type::VoidTy)
2758 setValue(&I, Result.first);
2759 DAG.setRoot(Result.second);
Anton Korobeynikov3b327822007-05-23 11:08:31 +00002760
Duncan Sands61166502007-06-06 10:05:18 +00002761 if (ExceptionHandling && MMI) {
Anton Korobeynikov3b327822007-05-23 11:08:31 +00002762 // Insert a label at the end of the invoke call to mark the try range. This
2763 // can be used to detect deletion of the invoke via the MachineModuleInfo.
2764 EndLabel = MMI->NextLabelID();
2765 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
2766 DAG.getConstant(EndLabel, MVT::i32)));
2767
2768 // Inform MachineModuleInfo of range.
2769 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
2770 }
Jim Laskey504e9942007-02-22 15:38:06 +00002771}
2772
2773
Chris Lattner7a60d912005-01-07 07:47:53 +00002774void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner18d2b342005-01-08 22:48:57 +00002775 const char *RenameFn = 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002776 if (Function *F = I.getCalledFunction()) {
Reid Spencer5301e7c2007-01-30 20:08:39 +00002777 if (F->isDeclaration())
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002778 if (unsigned IID = F->getIntrinsicID()) {
2779 RenameFn = visitIntrinsicCall(I, IID);
2780 if (!RenameFn)
2781 return;
2782 } else { // Not an LLVM intrinsic.
2783 const std::string &Name = F->getName();
Chris Lattner5c1ba2a2006-03-05 05:09:38 +00002784 if (Name[0] == 'c' && (Name == "copysign" || Name == "copysignf")) {
2785 if (I.getNumOperands() == 3 && // Basic sanity checks.
2786 I.getOperand(1)->getType()->isFloatingPoint() &&
2787 I.getType() == I.getOperand(1)->getType() &&
2788 I.getType() == I.getOperand(2)->getType()) {
2789 SDOperand LHS = getValue(I.getOperand(1));
2790 SDOperand RHS = getValue(I.getOperand(2));
2791 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
2792 LHS, RHS));
2793 return;
2794 }
2795 } else if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
Chris Lattner0c140002005-04-02 05:26:53 +00002796 if (I.getNumOperands() == 2 && // Basic sanity checks.
2797 I.getOperand(1)->getType()->isFloatingPoint() &&
2798 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002799 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner0c140002005-04-02 05:26:53 +00002800 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
2801 return;
2802 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002803 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
Chris Lattner80026402005-04-30 04:43:14 +00002804 if (I.getNumOperands() == 2 && // Basic sanity checks.
2805 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner1784a9d22006-02-14 05:39:35 +00002806 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002807 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +00002808 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
2809 return;
2810 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002811 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
Chris Lattner80026402005-04-30 04:43:14 +00002812 if (I.getNumOperands() == 2 && // Basic sanity checks.
2813 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner1784a9d22006-02-14 05:39:35 +00002814 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002815 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +00002816 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
2817 return;
2818 }
2819 }
Chris Lattnere4f71d02005-05-14 13:56:55 +00002820 }
Chris Lattner476e67b2006-01-26 22:24:51 +00002821 } else if (isa<InlineAsm>(I.getOperand(0))) {
2822 visitInlineAsm(I);
2823 return;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002824 }
Misha Brukman835702a2005-04-21 22:36:52 +00002825
Chris Lattner18d2b342005-01-08 22:48:57 +00002826 SDOperand Callee;
2827 if (!RenameFn)
2828 Callee = getValue(I.getOperand(0));
2829 else
2830 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Anton Korobeynikov3b327822007-05-23 11:08:31 +00002831
Jim Laskey31fef782007-02-23 21:45:01 +00002832 LowerCallTo(I, I.getCalledValue()->getType(),
Anton Korobeynikov3b327822007-05-23 11:08:31 +00002833 I.getCallingConv(),
2834 I.isTailCall(),
2835 Callee,
2836 1);
Chris Lattner7a60d912005-01-07 07:47:53 +00002837}
2838
Jim Laskey504e9942007-02-22 15:38:06 +00002839
Chris Lattner6f87d182006-02-22 22:37:12 +00002840SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002841 SDOperand &Chain, SDOperand &Flag)const{
Chris Lattner6f87d182006-02-22 22:37:12 +00002842 SDOperand Val = DAG.getCopyFromReg(Chain, Regs[0], RegVT, Flag);
2843 Chain = Val.getValue(1);
2844 Flag = Val.getValue(2);
2845
2846 // If the result was expanded, copy from the top part.
2847 if (Regs.size() > 1) {
2848 assert(Regs.size() == 2 &&
2849 "Cannot expand to more than 2 elts yet!");
2850 SDOperand Hi = DAG.getCopyFromReg(Chain, Regs[1], RegVT, Flag);
Evan Chengf80dfa82006-10-04 22:23:53 +00002851 Chain = Hi.getValue(1);
2852 Flag = Hi.getValue(2);
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002853 if (DAG.getTargetLoweringInfo().isLittleEndian())
2854 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi);
2855 else
2856 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Hi, Val);
Chris Lattner6f87d182006-02-22 22:37:12 +00002857 }
Chris Lattner1558fc62006-02-01 18:59:47 +00002858
Chris Lattner705948d2006-06-08 18:22:48 +00002859 // Otherwise, if the return value was promoted or extended, truncate it to the
Chris Lattner6f87d182006-02-22 22:37:12 +00002860 // appropriate type.
2861 if (RegVT == ValueVT)
2862 return Val;
2863
Chris Lattner77f04792007-03-25 05:00:54 +00002864 if (MVT::isVector(RegVT)) {
Dan Gohmana8665142007-06-25 16:23:39 +00002865 assert(MVT::isVector(ValueVT) && "Unknown vector conversion!");
2866 return DAG.getNode(ISD::BIT_CONVERT, RegVT, Val);
Chris Lattner77f04792007-03-25 05:00:54 +00002867 }
2868
Chris Lattner705948d2006-06-08 18:22:48 +00002869 if (MVT::isInteger(RegVT)) {
2870 if (ValueVT < RegVT)
2871 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
2872 else
2873 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
Chris Lattner705948d2006-06-08 18:22:48 +00002874 }
Chris Lattner77f04792007-03-25 05:00:54 +00002875
2876 assert(MVT::isFloatingPoint(RegVT) && MVT::isFloatingPoint(ValueVT));
2877 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
Chris Lattner6f87d182006-02-22 22:37:12 +00002878}
2879
Chris Lattner571d9642006-02-23 19:21:04 +00002880/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
2881/// specified value into the registers specified by this object. This uses
2882/// Chain/Flag as the input and updates them for the output Chain/Flag.
2883void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Evan Chengef9e07d2006-06-15 08:11:54 +00002884 SDOperand &Chain, SDOperand &Flag,
2885 MVT::ValueType PtrVT) const {
Chris Lattner571d9642006-02-23 19:21:04 +00002886 if (Regs.size() == 1) {
2887 // If there is a single register and the types differ, this must be
2888 // a promotion.
2889 if (RegVT != ValueVT) {
Chris Lattner77f04792007-03-25 05:00:54 +00002890 if (MVT::isVector(RegVT)) {
Dan Gohmana8665142007-06-25 16:23:39 +00002891 assert(MVT::isVector(Val.getValueType()) &&
2892 "Not a vector-vector cast?");
2893 Val = DAG.getNode(ISD::BIT_CONVERT, RegVT, Val);
Chris Lattner7b2decf2007-04-09 05:31:20 +00002894 } else if (MVT::isInteger(RegVT) && MVT::isInteger(Val.getValueType())) {
Chris Lattnerc03a9252006-06-08 18:27:11 +00002895 if (RegVT < ValueVT)
2896 Val = DAG.getNode(ISD::TRUNCATE, RegVT, Val);
2897 else
2898 Val = DAG.getNode(ISD::ANY_EXTEND, RegVT, Val);
Chris Lattner7b2decf2007-04-09 05:31:20 +00002899 } else if (MVT::isFloatingPoint(RegVT) &&
2900 MVT::isFloatingPoint(Val.getValueType())) {
Chris Lattner571d9642006-02-23 19:21:04 +00002901 Val = DAG.getNode(ISD::FP_EXTEND, RegVT, Val);
Chris Lattner7b2decf2007-04-09 05:31:20 +00002902 } else if (MVT::getSizeInBits(RegVT) ==
2903 MVT::getSizeInBits(Val.getValueType())) {
2904 Val = DAG.getNode(ISD::BIT_CONVERT, RegVT, Val);
2905 } else {
2906 assert(0 && "Unknown mismatch!");
2907 }
Chris Lattner571d9642006-02-23 19:21:04 +00002908 }
2909 Chain = DAG.getCopyToReg(Chain, Regs[0], Val, Flag);
2910 Flag = Chain.getValue(1);
2911 } else {
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002912 std::vector<unsigned> R(Regs);
2913 if (!DAG.getTargetLoweringInfo().isLittleEndian())
2914 std::reverse(R.begin(), R.end());
2915
2916 for (unsigned i = 0, e = R.size(); i != e; ++i) {
Chris Lattner571d9642006-02-23 19:21:04 +00002917 SDOperand Part = DAG.getNode(ISD::EXTRACT_ELEMENT, RegVT, Val,
Evan Chengef9e07d2006-06-15 08:11:54 +00002918 DAG.getConstant(i, PtrVT));
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002919 Chain = DAG.getCopyToReg(Chain, R[i], Part, Flag);
Chris Lattner571d9642006-02-23 19:21:04 +00002920 Flag = Chain.getValue(1);
2921 }
2922 }
2923}
Chris Lattner6f87d182006-02-22 22:37:12 +00002924
Chris Lattner571d9642006-02-23 19:21:04 +00002925/// AddInlineAsmOperands - Add this value to the specified inlineasm node
2926/// operand list. This adds the code marker and includes the number of
2927/// values added into it.
2928void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002929 std::vector<SDOperand> &Ops) const {
Chris Lattnerb49917d2007-04-09 00:33:58 +00002930 MVT::ValueType IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
2931 Ops.push_back(DAG.getTargetConstant(Code | (Regs.size() << 3), IntPtrTy));
Chris Lattner571d9642006-02-23 19:21:04 +00002932 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
2933 Ops.push_back(DAG.getRegister(Regs[i], RegVT));
2934}
Chris Lattner6f87d182006-02-22 22:37:12 +00002935
2936/// isAllocatableRegister - If the specified register is safe to allocate,
2937/// i.e. it isn't a stack pointer or some other special register, return the
2938/// register class for the register. Otherwise, return null.
2939static const TargetRegisterClass *
Chris Lattnerb1124f32006-02-22 23:09:03 +00002940isAllocatableRegister(unsigned Reg, MachineFunction &MF,
2941 const TargetLowering &TLI, const MRegisterInfo *MRI) {
Chris Lattnerbec582f2006-04-02 00:24:45 +00002942 MVT::ValueType FoundVT = MVT::Other;
2943 const TargetRegisterClass *FoundRC = 0;
Chris Lattnerb1124f32006-02-22 23:09:03 +00002944 for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
2945 E = MRI->regclass_end(); RCI != E; ++RCI) {
Chris Lattnerbec582f2006-04-02 00:24:45 +00002946 MVT::ValueType ThisVT = MVT::Other;
2947
Chris Lattnerb1124f32006-02-22 23:09:03 +00002948 const TargetRegisterClass *RC = *RCI;
2949 // If none of the the value types for this register class are valid, we
2950 // can't use it. For example, 64-bit reg classes on 32-bit targets.
Chris Lattnerb1124f32006-02-22 23:09:03 +00002951 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
2952 I != E; ++I) {
2953 if (TLI.isTypeLegal(*I)) {
Chris Lattnerbec582f2006-04-02 00:24:45 +00002954 // If we have already found this register in a different register class,
2955 // choose the one with the largest VT specified. For example, on
2956 // PowerPC, we favor f64 register classes over f32.
2957 if (FoundVT == MVT::Other ||
2958 MVT::getSizeInBits(FoundVT) < MVT::getSizeInBits(*I)) {
2959 ThisVT = *I;
2960 break;
2961 }
Chris Lattnerb1124f32006-02-22 23:09:03 +00002962 }
2963 }
2964
Chris Lattnerbec582f2006-04-02 00:24:45 +00002965 if (ThisVT == MVT::Other) continue;
Chris Lattnerb1124f32006-02-22 23:09:03 +00002966
Chris Lattner6f87d182006-02-22 22:37:12 +00002967 // NOTE: This isn't ideal. In particular, this might allocate the
2968 // frame pointer in functions that need it (due to them not being taken
2969 // out of allocation, because a variable sized allocation hasn't been seen
2970 // yet). This is a slight code pessimization, but should still work.
Chris Lattnerb1124f32006-02-22 23:09:03 +00002971 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
2972 E = RC->allocation_order_end(MF); I != E; ++I)
Chris Lattnerbec582f2006-04-02 00:24:45 +00002973 if (*I == Reg) {
2974 // We found a matching register class. Keep looking at others in case
2975 // we find one with larger registers that this physreg is also in.
2976 FoundRC = RC;
2977 FoundVT = ThisVT;
2978 break;
2979 }
Chris Lattner1558fc62006-02-01 18:59:47 +00002980 }
Chris Lattnerbec582f2006-04-02 00:24:45 +00002981 return FoundRC;
Chris Lattner6f87d182006-02-22 22:37:12 +00002982}
2983
Chris Lattner1558fc62006-02-01 18:59:47 +00002984
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00002985namespace {
2986/// AsmOperandInfo - This contains information for each constraint that we are
2987/// lowering.
2988struct AsmOperandInfo : public InlineAsm::ConstraintInfo {
2989 /// ConstraintCode - This contains the actual string for the code, like "m".
2990 std::string ConstraintCode;
Chris Lattnerb2e55562007-04-28 21:01:43 +00002991
2992 /// ConstraintType - Information about the constraint code, e.g. Register,
2993 /// RegisterClass, Memory, Other, Unknown.
2994 TargetLowering::ConstraintType ConstraintType;
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00002995
2996 /// CallOperand/CallOperandval - If this is the result output operand or a
2997 /// clobber, this is null, otherwise it is the incoming operand to the
2998 /// CallInst. This gets modified as the asm is processed.
2999 SDOperand CallOperand;
3000 Value *CallOperandVal;
3001
3002 /// ConstraintVT - The ValueType for the operand value.
3003 MVT::ValueType ConstraintVT;
3004
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003005 /// AssignedRegs - If this is a register or register class operand, this
3006 /// contains the set of register corresponding to the operand.
3007 RegsForValue AssignedRegs;
3008
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003009 AsmOperandInfo(const InlineAsm::ConstraintInfo &info)
Chris Lattnerb2e55562007-04-28 21:01:43 +00003010 : InlineAsm::ConstraintInfo(info),
3011 ConstraintType(TargetLowering::C_Unknown),
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003012 CallOperand(0,0), CallOperandVal(0), ConstraintVT(MVT::Other) {
3013 }
Chris Lattneref073322007-04-30 17:16:27 +00003014
3015 void ComputeConstraintToUse(const TargetLowering &TLI);
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003016
3017 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
3018 /// busy in OutputRegs/InputRegs.
3019 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
3020 std::set<unsigned> &OutputRegs,
3021 std::set<unsigned> &InputRegs) const {
3022 if (isOutReg)
3023 OutputRegs.insert(AssignedRegs.Regs.begin(), AssignedRegs.Regs.end());
3024 if (isInReg)
3025 InputRegs.insert(AssignedRegs.Regs.begin(), AssignedRegs.Regs.end());
3026 }
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003027};
3028} // end anon namespace.
Chris Lattner6f87d182006-02-22 22:37:12 +00003029
Chris Lattneref073322007-04-30 17:16:27 +00003030/// getConstraintGenerality - Return an integer indicating how general CT is.
3031static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT) {
3032 switch (CT) {
3033 default: assert(0 && "Unknown constraint type!");
3034 case TargetLowering::C_Other:
3035 case TargetLowering::C_Unknown:
3036 return 0;
3037 case TargetLowering::C_Register:
3038 return 1;
3039 case TargetLowering::C_RegisterClass:
3040 return 2;
3041 case TargetLowering::C_Memory:
3042 return 3;
3043 }
3044}
3045
3046void AsmOperandInfo::ComputeConstraintToUse(const TargetLowering &TLI) {
3047 assert(!Codes.empty() && "Must have at least one constraint");
3048
3049 std::string *Current = &Codes[0];
3050 TargetLowering::ConstraintType CurType = TLI.getConstraintType(*Current);
3051 if (Codes.size() == 1) { // Single-letter constraints ('r') are very common.
3052 ConstraintCode = *Current;
3053 ConstraintType = CurType;
3054 return;
3055 }
3056
3057 unsigned CurGenerality = getConstraintGenerality(CurType);
3058
3059 // If we have multiple constraints, try to pick the most general one ahead
3060 // of time. This isn't a wonderful solution, but handles common cases.
3061 for (unsigned j = 1, e = Codes.size(); j != e; ++j) {
3062 TargetLowering::ConstraintType ThisType = TLI.getConstraintType(Codes[j]);
3063 unsigned ThisGenerality = getConstraintGenerality(ThisType);
3064 if (ThisGenerality > CurGenerality) {
3065 // This constraint letter is more general than the previous one,
3066 // use it.
3067 CurType = ThisType;
3068 Current = &Codes[j];
3069 CurGenerality = ThisGenerality;
3070 }
3071 }
3072
3073 ConstraintCode = *Current;
3074 ConstraintType = CurType;
3075}
3076
3077
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003078void SelectionDAGLowering::
3079GetRegistersForValue(AsmOperandInfo &OpInfo, bool HasEarlyClobber,
Chris Lattner4333f8b2007-04-30 17:29:31 +00003080 std::set<unsigned> &OutputRegs,
3081 std::set<unsigned> &InputRegs) {
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003082 // Compute whether this value requires an input register, an output register,
3083 // or both.
3084 bool isOutReg = false;
3085 bool isInReg = false;
3086 switch (OpInfo.Type) {
3087 case InlineAsm::isOutput:
3088 isOutReg = true;
3089
3090 // If this is an early-clobber output, or if there is an input
3091 // constraint that matches this, we need to reserve the input register
3092 // so no other inputs allocate to it.
3093 isInReg = OpInfo.isEarlyClobber || OpInfo.hasMatchingInput;
3094 break;
3095 case InlineAsm::isInput:
3096 isInReg = true;
3097 isOutReg = false;
3098 break;
3099 case InlineAsm::isClobber:
3100 isOutReg = true;
3101 isInReg = true;
3102 break;
3103 }
3104
3105
3106 MachineFunction &MF = DAG.getMachineFunction();
Chris Lattner4333f8b2007-04-30 17:29:31 +00003107 std::vector<unsigned> Regs;
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003108
3109 // If this is a constraint for a single physreg, or a constraint for a
3110 // register class, find it.
3111 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
3112 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
3113 OpInfo.ConstraintVT);
Chris Lattner4333f8b2007-04-30 17:29:31 +00003114
3115 unsigned NumRegs = 1;
3116 if (OpInfo.ConstraintVT != MVT::Other)
Dan Gohman04deef32007-06-21 14:42:22 +00003117 NumRegs = TLI.getNumRegisters(OpInfo.ConstraintVT);
Chris Lattner4333f8b2007-04-30 17:29:31 +00003118 MVT::ValueType RegVT;
3119 MVT::ValueType ValueVT = OpInfo.ConstraintVT;
3120
Chris Lattner4333f8b2007-04-30 17:29:31 +00003121
3122 // If this is a constraint for a specific physical register, like {r17},
3123 // assign it now.
3124 if (PhysReg.first) {
3125 if (OpInfo.ConstraintVT == MVT::Other)
3126 ValueVT = *PhysReg.second->vt_begin();
3127
3128 // Get the actual register value type. This is important, because the user
3129 // may have asked for (e.g.) the AX register in i32 type. We need to
3130 // remember that AX is actually i16 to get the right extension.
3131 RegVT = *PhysReg.second->vt_begin();
3132
3133 // This is a explicit reference to a physical register.
3134 Regs.push_back(PhysReg.first);
3135
3136 // If this is an expanded reference, add the rest of the regs to Regs.
3137 if (NumRegs != 1) {
3138 TargetRegisterClass::iterator I = PhysReg.second->begin();
3139 TargetRegisterClass::iterator E = PhysReg.second->end();
3140 for (; *I != PhysReg.first; ++I)
3141 assert(I != E && "Didn't find reg!");
3142
3143 // Already added the first reg.
3144 --NumRegs; ++I;
3145 for (; NumRegs; --NumRegs, ++I) {
3146 assert(I != E && "Ran out of registers to allocate!");
3147 Regs.push_back(*I);
3148 }
3149 }
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003150 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
3151 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs);
3152 return;
Chris Lattner4333f8b2007-04-30 17:29:31 +00003153 }
3154
3155 // Otherwise, if this was a reference to an LLVM register class, create vregs
3156 // for this reference.
3157 std::vector<unsigned> RegClassRegs;
Chris Lattnerf852e332007-06-15 19:11:01 +00003158 const TargetRegisterClass *RC = PhysReg.second;
3159 if (RC) {
Chris Lattner4333f8b2007-04-30 17:29:31 +00003160 // If this is an early clobber or tied register, our regalloc doesn't know
3161 // how to maintain the constraint. If it isn't, go ahead and create vreg
3162 // and let the regalloc do the right thing.
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003163 if (!OpInfo.hasMatchingInput && !OpInfo.isEarlyClobber &&
3164 // If there is some other early clobber and this is an input register,
3165 // then we are forced to pre-allocate the input reg so it doesn't
3166 // conflict with the earlyclobber.
3167 !(OpInfo.Type == InlineAsm::isInput && HasEarlyClobber)) {
Chris Lattner4333f8b2007-04-30 17:29:31 +00003168 RegVT = *PhysReg.second->vt_begin();
3169
3170 if (OpInfo.ConstraintVT == MVT::Other)
3171 ValueVT = RegVT;
3172
3173 // Create the appropriate number of virtual registers.
3174 SSARegMap *RegMap = MF.getSSARegMap();
3175 for (; NumRegs; --NumRegs)
3176 Regs.push_back(RegMap->createVirtualRegister(PhysReg.second));
3177
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003178 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
3179 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs);
3180 return;
Chris Lattner4333f8b2007-04-30 17:29:31 +00003181 }
3182
3183 // Otherwise, we can't allocate it. Let the code below figure out how to
3184 // maintain these constraints.
3185 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
3186
3187 } else {
3188 // This is a reference to a register class that doesn't directly correspond
3189 // to an LLVM register class. Allocate NumRegs consecutive, available,
3190 // registers from the class.
3191 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
3192 OpInfo.ConstraintVT);
3193 }
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003194
Chris Lattner4333f8b2007-04-30 17:29:31 +00003195 const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
3196 unsigned NumAllocated = 0;
3197 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
3198 unsigned Reg = RegClassRegs[i];
3199 // See if this register is available.
3200 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
3201 (isInReg && InputRegs.count(Reg))) { // Already used.
3202 // Make sure we find consecutive registers.
3203 NumAllocated = 0;
3204 continue;
3205 }
3206
3207 // Check to see if this register is allocatable (i.e. don't give out the
3208 // stack pointer).
Chris Lattnerf852e332007-06-15 19:11:01 +00003209 if (RC == 0) {
3210 RC = isAllocatableRegister(Reg, MF, TLI, MRI);
3211 if (!RC) { // Couldn't allocate this register.
3212 // Reset NumAllocated to make sure we return consecutive registers.
3213 NumAllocated = 0;
3214 continue;
3215 }
Chris Lattner4333f8b2007-04-30 17:29:31 +00003216 }
3217
3218 // Okay, this register is good, we can use it.
3219 ++NumAllocated;
3220
3221 // If we allocated enough consecutive registers, succeed.
3222 if (NumAllocated == NumRegs) {
3223 unsigned RegStart = (i-NumAllocated)+1;
3224 unsigned RegEnd = i+1;
3225 // Mark all of the allocated registers used.
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003226 for (unsigned i = RegStart; i != RegEnd; ++i)
3227 Regs.push_back(RegClassRegs[i]);
Chris Lattner4333f8b2007-04-30 17:29:31 +00003228
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003229 OpInfo.AssignedRegs = RegsForValue(Regs, *RC->vt_begin(),
3230 OpInfo.ConstraintVT);
3231 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs);
3232 return;
Chris Lattner4333f8b2007-04-30 17:29:31 +00003233 }
3234 }
3235
3236 // Otherwise, we couldn't allocate enough registers for this.
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003237 return;
Chris Lattner4333f8b2007-04-30 17:29:31 +00003238}
3239
3240
Chris Lattner476e67b2006-01-26 22:24:51 +00003241/// visitInlineAsm - Handle a call to an InlineAsm object.
3242///
3243void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
3244 InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
Chris Lattner476e67b2006-01-26 22:24:51 +00003245
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003246 /// ConstraintOperands - Information about all of the constraints.
3247 std::vector<AsmOperandInfo> ConstraintOperands;
Chris Lattner476e67b2006-01-26 22:24:51 +00003248
3249 SDOperand Chain = getRoot();
3250 SDOperand Flag;
3251
Chris Lattner1558fc62006-02-01 18:59:47 +00003252 std::set<unsigned> OutputRegs, InputRegs;
Chris Lattner7ad77df2006-02-22 00:56:39 +00003253
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003254 // Do a prepass over the constraints, canonicalizing them, and building up the
3255 // ConstraintOperands list.
3256 std::vector<InlineAsm::ConstraintInfo>
3257 ConstraintInfos = IA->ParseConstraints();
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003258
3259 // SawEarlyClobber - Keep track of whether we saw an earlyclobber output
3260 // constraint. If so, we can't let the register allocator allocate any input
3261 // registers, because it will not know to avoid the earlyclobbered output reg.
3262 bool SawEarlyClobber = false;
3263
3264 unsigned OpNo = 1; // OpNo - The operand of the CallInst.
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003265 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
3266 ConstraintOperands.push_back(AsmOperandInfo(ConstraintInfos[i]));
3267 AsmOperandInfo &OpInfo = ConstraintOperands.back();
3268
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003269 MVT::ValueType OpVT = MVT::Other;
3270
3271 // Compute the value type for each operand.
3272 switch (OpInfo.Type) {
Chris Lattner7ad77df2006-02-22 00:56:39 +00003273 case InlineAsm::isOutput:
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003274 if (!OpInfo.isIndirect) {
3275 // The return value of the call is this value. As such, there is no
3276 // corresponding argument.
Chris Lattner7ad77df2006-02-22 00:56:39 +00003277 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
3278 OpVT = TLI.getValueType(I.getType());
3279 } else {
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003280 OpInfo.CallOperandVal = I.getOperand(OpNo++);
Chris Lattner7ad77df2006-02-22 00:56:39 +00003281 }
3282 break;
3283 case InlineAsm::isInput:
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003284 OpInfo.CallOperandVal = I.getOperand(OpNo++);
Chris Lattner7ad77df2006-02-22 00:56:39 +00003285 break;
3286 case InlineAsm::isClobber:
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003287 // Nothing to do.
Chris Lattner7ad77df2006-02-22 00:56:39 +00003288 break;
3289 }
Chris Lattner7ad77df2006-02-22 00:56:39 +00003290
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003291 // If this is an input or an indirect output, process the call argument.
3292 if (OpInfo.CallOperandVal) {
3293 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
3294 const Type *OpTy = OpInfo.CallOperandVal->getType();
Chris Lattner412d61a2007-04-29 18:58:03 +00003295 // If this is an indirect operand, the operand is a pointer to the
3296 // accessed type.
3297 if (OpInfo.isIndirect)
3298 OpTy = cast<PointerType>(OpTy)->getElementType();
3299
3300 // If OpTy is not a first-class value, it may be a struct/union that we
3301 // can tile with integers.
3302 if (!OpTy->isFirstClassType() && OpTy->isSized()) {
3303 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
3304 switch (BitSize) {
3305 default: break;
3306 case 1:
3307 case 8:
3308 case 16:
3309 case 32:
3310 case 64:
3311 OpTy = IntegerType::get(BitSize);
3312 break;
3313 }
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003314 }
Chris Lattner412d61a2007-04-29 18:58:03 +00003315
3316 OpVT = TLI.getValueType(OpTy, true);
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003317 }
3318
3319 OpInfo.ConstraintVT = OpVT;
Chris Lattnerb2e55562007-04-28 21:01:43 +00003320
Chris Lattneref073322007-04-30 17:16:27 +00003321 // Compute the constraint code and ConstraintType to use.
3322 OpInfo.ComputeConstraintToUse(TLI);
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003323
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003324 // Keep track of whether we see an earlyclobber.
3325 SawEarlyClobber |= OpInfo.isEarlyClobber;
Chris Lattner401d8db2007-04-28 21:12:06 +00003326
3327 // If this is a memory input, and if the operand is not indirect, do what we
3328 // need to to provide an address for the memory input.
3329 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
3330 !OpInfo.isIndirect) {
3331 assert(OpInfo.Type == InlineAsm::isInput &&
3332 "Can only indirectify direct input operands!");
3333
3334 // Memory operands really want the address of the value. If we don't have
3335 // an indirect input, put it in the constpool if we can, otherwise spill
3336 // it to a stack slot.
3337
3338 // If the operand is a float, integer, or vector constant, spill to a
3339 // constant pool entry to get its address.
3340 Value *OpVal = OpInfo.CallOperandVal;
3341 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
3342 isa<ConstantVector>(OpVal)) {
3343 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
3344 TLI.getPointerTy());
3345 } else {
3346 // Otherwise, create a stack slot and emit a store to it before the
3347 // asm.
3348 const Type *Ty = OpVal->getType();
3349 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
3350 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
3351 MachineFunction &MF = DAG.getMachineFunction();
3352 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align);
3353 SDOperand StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
3354 Chain = DAG.getStore(Chain, OpInfo.CallOperand, StackSlot, NULL, 0);
3355 OpInfo.CallOperand = StackSlot;
3356 }
3357
3358 // There is no longer a Value* corresponding to this operand.
3359 OpInfo.CallOperandVal = 0;
3360 // It is now an indirect operand.
3361 OpInfo.isIndirect = true;
3362 }
3363
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003364 // If this constraint is for a specific register, allocate it before
3365 // anything else.
3366 if (OpInfo.ConstraintType == TargetLowering::C_Register)
3367 GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003368 }
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003369 ConstraintInfos.clear();
3370
3371
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003372 // Second pass - Loop over all of the operands, assigning virtual or physregs
3373 // to registerclass operands.
3374 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
3375 AsmOperandInfo &OpInfo = ConstraintOperands[i];
3376
3377 // C_Register operands have already been allocated, Other/Memory don't need
3378 // to be.
3379 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
3380 GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
3381 }
3382
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003383 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
3384 std::vector<SDOperand> AsmNodeOperands;
3385 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
3386 AsmNodeOperands.push_back(
3387 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), MVT::Other));
3388
Chris Lattner3a5ed552006-02-01 01:28:23 +00003389
Chris Lattner5c79f982006-02-21 23:12:12 +00003390 // Loop over all of the inputs, copying the operand values into the
3391 // appropriate registers and processing the output regs.
Chris Lattner6f87d182006-02-22 22:37:12 +00003392 RegsForValue RetValRegs;
Chris Lattner5c79f982006-02-21 23:12:12 +00003393
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003394 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
3395 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
3396
3397 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
3398 AsmOperandInfo &OpInfo = ConstraintOperands[i];
Chris Lattner7ad77df2006-02-22 00:56:39 +00003399
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003400 switch (OpInfo.Type) {
Chris Lattner3a5ed552006-02-01 01:28:23 +00003401 case InlineAsm::isOutput: {
Chris Lattnerde339fa2007-04-28 21:03:16 +00003402 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
3403 OpInfo.ConstraintType != TargetLowering::C_Register) {
Chris Lattnerd102ed02007-04-28 06:08:13 +00003404 // Memory output, or 'other' output (e.g. 'X' constraint).
Chris Lattner401d8db2007-04-28 21:12:06 +00003405 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
Chris Lattner9fed5b62006-02-27 23:45:39 +00003406
Chris Lattner9fed5b62006-02-27 23:45:39 +00003407 // Add information to the INLINEASM node to know about this output.
3408 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
Chris Lattnerc7596ef2007-05-15 01:33:58 +00003409 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
3410 TLI.getPointerTy()));
Chris Lattner401d8db2007-04-28 21:12:06 +00003411 AsmNodeOperands.push_back(OpInfo.CallOperand);
Chris Lattner9fed5b62006-02-27 23:45:39 +00003412 break;
3413 }
3414
Chris Lattnerb2e55562007-04-28 21:01:43 +00003415 // Otherwise, this is a register or register class output.
Chris Lattner9fed5b62006-02-27 23:45:39 +00003416
Chris Lattner6f87d182006-02-22 22:37:12 +00003417 // Copy the output from the appropriate register. Find a register that
Chris Lattner7ad77df2006-02-22 00:56:39 +00003418 // we can use.
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003419 if (OpInfo.AssignedRegs.Regs.empty()) {
Bill Wendling22e978a2006-12-07 20:04:42 +00003420 cerr << "Couldn't allocate output reg for contraint '"
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003421 << OpInfo.ConstraintCode << "'!\n";
Chris Lattner968f8032006-10-31 07:33:13 +00003422 exit(1);
3423 }
Chris Lattner7ad77df2006-02-22 00:56:39 +00003424
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003425 if (!OpInfo.isIndirect) {
3426 // This is the result value of the call.
Chris Lattner6f87d182006-02-22 22:37:12 +00003427 assert(RetValRegs.Regs.empty() &&
Chris Lattner3a5ed552006-02-01 01:28:23 +00003428 "Cannot have multiple output constraints yet!");
Chris Lattner3a5ed552006-02-01 01:28:23 +00003429 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003430 RetValRegs = OpInfo.AssignedRegs;
Chris Lattner3a5ed552006-02-01 01:28:23 +00003431 } else {
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003432 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003433 OpInfo.CallOperandVal));
Chris Lattner3a5ed552006-02-01 01:28:23 +00003434 }
Chris Lattner2e56e892006-01-31 02:03:41 +00003435
3436 // Add information to the INLINEASM node to know that this register is
3437 // set.
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003438 OpInfo.AssignedRegs.AddInlineAsmOperands(2 /*REGDEF*/, DAG,
3439 AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00003440 break;
3441 }
3442 case InlineAsm::isInput: {
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003443 SDOperand InOperandVal = OpInfo.CallOperand;
Chris Lattner65ad53f2006-02-04 02:16:44 +00003444
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003445 if (isdigit(OpInfo.ConstraintCode[0])) { // Matching constraint?
Chris Lattner7f5880b2006-02-02 00:25:23 +00003446 // If this is required to match an output register we have already set,
3447 // just use its register.
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003448 unsigned OperandNo = atoi(OpInfo.ConstraintCode.c_str());
Chris Lattner65ad53f2006-02-04 02:16:44 +00003449
Chris Lattner571d9642006-02-23 19:21:04 +00003450 // Scan until we find the definition we already emitted of this operand.
3451 // When we find it, create a RegsForValue operand.
3452 unsigned CurOp = 2; // The first operand.
3453 for (; OperandNo; --OperandNo) {
3454 // Advance to the next operand.
3455 unsigned NumOps =
3456 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattnerb0305322006-07-20 19:02:21 +00003457 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
3458 (NumOps & 7) == 4 /*MEM*/) &&
Chris Lattner571d9642006-02-23 19:21:04 +00003459 "Skipped past definitions?");
3460 CurOp += (NumOps>>3)+1;
3461 }
3462
3463 unsigned NumOps =
3464 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattnere3eeb242007-02-01 01:21:12 +00003465 if ((NumOps & 7) == 2 /*REGDEF*/) {
3466 // Add NumOps>>3 registers to MatchedRegs.
3467 RegsForValue MatchedRegs;
3468 MatchedRegs.ValueVT = InOperandVal.getValueType();
3469 MatchedRegs.RegVT = AsmNodeOperands[CurOp+1].getValueType();
3470 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
3471 unsigned Reg =
3472 cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
3473 MatchedRegs.Regs.push_back(Reg);
3474 }
Chris Lattner571d9642006-02-23 19:21:04 +00003475
Chris Lattnere3eeb242007-02-01 01:21:12 +00003476 // Use the produced MatchedRegs object to
3477 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag,
3478 TLI.getPointerTy());
3479 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
3480 break;
3481 } else {
3482 assert((NumOps & 7) == 4/*MEM*/ && "Unknown matching constraint!");
3483 assert(0 && "matching constraints for memory operands unimp");
Chris Lattner571d9642006-02-23 19:21:04 +00003484 }
Chris Lattner7f5880b2006-02-02 00:25:23 +00003485 }
Chris Lattner7ef7a642006-02-24 01:11:24 +00003486
Chris Lattnerb2e55562007-04-28 21:01:43 +00003487 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003488 assert(!OpInfo.isIndirect &&
Chris Lattner1deacd62007-04-28 06:42:38 +00003489 "Don't know how to handle indirect other inputs yet!");
3490
Chris Lattner6f043b92006-10-31 19:41:18 +00003491 InOperandVal = TLI.isOperandValidForConstraint(InOperandVal,
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003492 OpInfo.ConstraintCode[0],
3493 DAG);
Chris Lattner6f043b92006-10-31 19:41:18 +00003494 if (!InOperandVal.Val) {
Bill Wendling22e978a2006-12-07 20:04:42 +00003495 cerr << "Invalid operand for inline asm constraint '"
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003496 << OpInfo.ConstraintCode << "'!\n";
Chris Lattner6f043b92006-10-31 19:41:18 +00003497 exit(1);
3498 }
Chris Lattner7ef7a642006-02-24 01:11:24 +00003499
3500 // Add information to the INLINEASM node to know about this input.
3501 unsigned ResOpType = 3 /*IMM*/ | (1 << 3);
Chris Lattnerc7596ef2007-05-15 01:33:58 +00003502 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
3503 TLI.getPointerTy()));
Chris Lattner7ef7a642006-02-24 01:11:24 +00003504 AsmNodeOperands.push_back(InOperandVal);
3505 break;
Chris Lattnerb2e55562007-04-28 21:01:43 +00003506 } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
Chris Lattner401d8db2007-04-28 21:12:06 +00003507 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
Chris Lattner1deacd62007-04-28 06:42:38 +00003508 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
3509 "Memory operands expect pointer values");
3510
Chris Lattner7ef7a642006-02-24 01:11:24 +00003511 // Add information to the INLINEASM node to know about this input.
3512 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
Chris Lattnerc7596ef2007-05-15 01:33:58 +00003513 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
3514 TLI.getPointerTy()));
Chris Lattner7ef7a642006-02-24 01:11:24 +00003515 AsmNodeOperands.push_back(InOperandVal);
3516 break;
3517 }
3518
Chris Lattnerb2e55562007-04-28 21:01:43 +00003519 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
3520 OpInfo.ConstraintType == TargetLowering::C_Register) &&
3521 "Unknown constraint type!");
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003522 assert(!OpInfo.isIndirect &&
Chris Lattner1deacd62007-04-28 06:42:38 +00003523 "Don't know how to handle indirect register inputs yet!");
Chris Lattner7ef7a642006-02-24 01:11:24 +00003524
3525 // Copy the input into the appropriate registers.
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003526 assert(!OpInfo.AssignedRegs.Regs.empty() &&
3527 "Couldn't allocate input reg!");
Chris Lattner7ef7a642006-02-24 01:11:24 +00003528
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003529 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag,
3530 TLI.getPointerTy());
Chris Lattner7ef7a642006-02-24 01:11:24 +00003531
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003532 OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG,
3533 AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00003534 break;
3535 }
Chris Lattner571d9642006-02-23 19:21:04 +00003536 case InlineAsm::isClobber: {
Chris Lattner571d9642006-02-23 19:21:04 +00003537 // Add the clobbered value to the operand list, so that the register
3538 // allocator is aware that the physreg got clobbered.
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003539 if (!OpInfo.AssignedRegs.Regs.empty())
3540 OpInfo.AssignedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG,
3541 AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00003542 break;
3543 }
Chris Lattner571d9642006-02-23 19:21:04 +00003544 }
Chris Lattner2e56e892006-01-31 02:03:41 +00003545 }
Chris Lattner476e67b2006-01-26 22:24:51 +00003546
3547 // Finish up input operands.
3548 AsmNodeOperands[0] = Chain;
3549 if (Flag.Val) AsmNodeOperands.push_back(Flag);
3550
Chris Lattnerbd887772006-08-14 23:53:35 +00003551 Chain = DAG.getNode(ISD::INLINEASM,
3552 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003553 &AsmNodeOperands[0], AsmNodeOperands.size());
Chris Lattner476e67b2006-01-26 22:24:51 +00003554 Flag = Chain.getValue(1);
3555
Chris Lattner2e56e892006-01-31 02:03:41 +00003556 // If this asm returns a register value, copy the result from that register
3557 // and set it as the value of the call.
Chris Lattner51114992007-04-12 06:00:20 +00003558 if (!RetValRegs.Regs.empty()) {
3559 SDOperand Val = RetValRegs.getCopyFromRegs(DAG, Chain, Flag);
3560
3561 // If the result of the inline asm is a vector, it may have the wrong
3562 // width/num elts. Make sure to convert it to the right type with
Dan Gohmana8665142007-06-25 16:23:39 +00003563 // bit_convert.
3564 if (MVT::isVector(Val.getValueType())) {
Chris Lattner51114992007-04-12 06:00:20 +00003565 const VectorType *VTy = cast<VectorType>(I.getType());
Dan Gohmana8665142007-06-25 16:23:39 +00003566 MVT::ValueType DesiredVT = TLI.getValueType(VTy);
Chris Lattner51114992007-04-12 06:00:20 +00003567
Dan Gohmana8665142007-06-25 16:23:39 +00003568 Val = DAG.getNode(ISD::BIT_CONVERT, DesiredVT, Val);
Chris Lattner51114992007-04-12 06:00:20 +00003569 }
3570
3571 setValue(&I, Val);
3572 }
Chris Lattner476e67b2006-01-26 22:24:51 +00003573
Chris Lattner2e56e892006-01-31 02:03:41 +00003574 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
3575
3576 // Process indirect outputs, first output all of the flagged copies out of
3577 // physregs.
3578 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
Chris Lattner6f87d182006-02-22 22:37:12 +00003579 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Chris Lattner2e56e892006-01-31 02:03:41 +00003580 Value *Ptr = IndirectStoresToEmit[i].second;
Chris Lattner6f87d182006-02-22 22:37:12 +00003581 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, Flag);
3582 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner2e56e892006-01-31 02:03:41 +00003583 }
3584
3585 // Emit the non-flagged stores from the physregs.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003586 SmallVector<SDOperand, 8> OutChains;
Chris Lattner2e56e892006-01-31 02:03:41 +00003587 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003588 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
Chris Lattner2e56e892006-01-31 02:03:41 +00003589 getValue(StoresToEmit[i].second),
Evan Chengab51cf22006-10-13 21:14:26 +00003590 StoresToEmit[i].second, 0));
Chris Lattner2e56e892006-01-31 02:03:41 +00003591 if (!OutChains.empty())
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003592 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
3593 &OutChains[0], OutChains.size());
Chris Lattner476e67b2006-01-26 22:24:51 +00003594 DAG.setRoot(Chain);
3595}
3596
3597
Chris Lattner7a60d912005-01-07 07:47:53 +00003598void SelectionDAGLowering::visitMalloc(MallocInst &I) {
3599 SDOperand Src = getValue(I.getOperand(0));
3600
3601 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnereccb73d2005-01-22 23:04:37 +00003602
3603 if (IntPtr < Src.getValueType())
3604 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
3605 else if (IntPtr > Src.getValueType())
3606 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner7a60d912005-01-07 07:47:53 +00003607
3608 // Scale the source by the type size.
Owen Anderson20a631f2006-05-03 01:29:57 +00003609 uint64_t ElementSize = TD->getTypeSize(I.getType()->getElementType());
Chris Lattner7a60d912005-01-07 07:47:53 +00003610 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
3611 Src, getIntPtrConstant(ElementSize));
3612
Reid Spencere63b6512006-12-31 05:55:36 +00003613 TargetLowering::ArgListTy Args;
3614 TargetLowering::ArgListEntry Entry;
3615 Entry.Node = Src;
3616 Entry.Ty = TLI.getTargetData()->getIntPtrType();
Reid Spencere63b6512006-12-31 05:55:36 +00003617 Args.push_back(Entry);
Chris Lattner1f45cd72005-01-08 19:26:18 +00003618
3619 std::pair<SDOperand,SDOperand> Result =
Reid Spencere63b6512006-12-31 05:55:36 +00003620 TLI.LowerCallTo(getRoot(), I.getType(), false, false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00003621 DAG.getExternalSymbol("malloc", IntPtr),
3622 Args, DAG);
3623 setValue(&I, Result.first); // Pointers always fit in registers
3624 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00003625}
3626
3627void SelectionDAGLowering::visitFree(FreeInst &I) {
Reid Spencere63b6512006-12-31 05:55:36 +00003628 TargetLowering::ArgListTy Args;
3629 TargetLowering::ArgListEntry Entry;
3630 Entry.Node = getValue(I.getOperand(0));
3631 Entry.Ty = TLI.getTargetData()->getIntPtrType();
Reid Spencere63b6512006-12-31 05:55:36 +00003632 Args.push_back(Entry);
Chris Lattner7a60d912005-01-07 07:47:53 +00003633 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner1f45cd72005-01-08 19:26:18 +00003634 std::pair<SDOperand,SDOperand> Result =
Reid Spencere63b6512006-12-31 05:55:36 +00003635 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00003636 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
3637 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00003638}
3639
Chris Lattner13d7c252005-08-26 20:54:47 +00003640// InsertAtEndOfBasicBlock - This method should be implemented by targets that
3641// mark instructions with the 'usesCustomDAGSchedInserter' flag. These
3642// instructions are special in various ways, which require special support to
3643// insert. The specified MachineInstr is created but not inserted into any
3644// basic blocks, and the scheduler passes ownership of it to this method.
3645MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
3646 MachineBasicBlock *MBB) {
Bill Wendling22e978a2006-12-07 20:04:42 +00003647 cerr << "If a target marks an instruction with "
3648 << "'usesCustomDAGSchedInserter', it must implement "
3649 << "TargetLowering::InsertAtEndOfBasicBlock!\n";
Chris Lattner13d7c252005-08-26 20:54:47 +00003650 abort();
3651 return 0;
3652}
3653
Chris Lattner58cfd792005-01-09 00:00:49 +00003654void SelectionDAGLowering::visitVAStart(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00003655 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
3656 getValue(I.getOperand(1)),
3657 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner58cfd792005-01-09 00:00:49 +00003658}
3659
3660void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00003661 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
3662 getValue(I.getOperand(0)),
3663 DAG.getSrcValue(I.getOperand(0)));
3664 setValue(&I, V);
3665 DAG.setRoot(V.getValue(1));
Chris Lattner7a60d912005-01-07 07:47:53 +00003666}
3667
3668void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00003669 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
3670 getValue(I.getOperand(1)),
3671 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner7a60d912005-01-07 07:47:53 +00003672}
3673
3674void SelectionDAGLowering::visitVACopy(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00003675 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
3676 getValue(I.getOperand(1)),
3677 getValue(I.getOperand(2)),
3678 DAG.getSrcValue(I.getOperand(1)),
3679 DAG.getSrcValue(I.getOperand(2))));
Chris Lattner7a60d912005-01-07 07:47:53 +00003680}
3681
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003682/// ExpandScalarFormalArgs - Recursively expand the formal_argument node, either
3683/// bit_convert it or join a pair of them with a BUILD_PAIR when appropriate.
3684static SDOperand ExpandScalarFormalArgs(MVT::ValueType VT, SDNode *Arg,
3685 unsigned &i, SelectionDAG &DAG,
3686 TargetLowering &TLI) {
3687 if (TLI.getTypeAction(VT) != TargetLowering::Expand)
3688 return SDOperand(Arg, i++);
3689
3690 MVT::ValueType EVT = TLI.getTypeToTransformTo(VT);
3691 unsigned NumVals = MVT::getSizeInBits(VT) / MVT::getSizeInBits(EVT);
3692 if (NumVals == 1) {
3693 return DAG.getNode(ISD::BIT_CONVERT, VT,
3694 ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI));
3695 } else if (NumVals == 2) {
3696 SDOperand Lo = ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI);
3697 SDOperand Hi = ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI);
3698 if (!TLI.isLittleEndian())
3699 std::swap(Lo, Hi);
3700 return DAG.getNode(ISD::BUILD_PAIR, VT, Lo, Hi);
3701 } else {
3702 // Value scalarized into many values. Unimp for now.
3703 assert(0 && "Cannot expand i64 -> i16 yet!");
3704 }
3705 return SDOperand();
3706}
3707
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003708/// TargetLowering::LowerArguments - This is the default LowerArguments
3709/// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
Chris Lattneraaa23d92006-05-16 22:53:20 +00003710/// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
3711/// integrated into SDISel.
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003712std::vector<SDOperand>
3713TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003714 const FunctionType *FTy = F.getFunctionType();
Reid Spencer71b79e32007-04-09 06:17:21 +00003715 const ParamAttrsList *Attrs = FTy->getParamAttrs();
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003716 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
3717 std::vector<SDOperand> Ops;
Chris Lattner3d826992006-05-16 06:45:34 +00003718 Ops.push_back(DAG.getRoot());
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003719 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
3720 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
3721
3722 // Add one result value for each formal argument.
3723 std::vector<MVT::ValueType> RetVals;
Anton Korobeynikov06f7d4b2007-01-28 18:01:49 +00003724 unsigned j = 1;
Anton Korobeynikov9fa38392007-01-28 16:04:40 +00003725 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
3726 I != E; ++I, ++j) {
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003727 MVT::ValueType VT = getValueType(I->getType());
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003728 unsigned Flags = ISD::ParamFlags::NoFlagSet;
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003729 unsigned OriginalAlignment =
Chris Lattner945e4372007-02-14 05:52:17 +00003730 getTargetData()->getABITypeAlignment(I->getType());
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003731
Chris Lattnerab5d0ac2007-02-26 02:56:58 +00003732 // FIXME: Distinguish between a formal with no [sz]ext attribute from one
3733 // that is zero extended!
Reid Spencera472f662007-04-11 02:44:20 +00003734 if (Attrs && Attrs->paramHasAttr(j, ParamAttr::ZExt))
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003735 Flags &= ~(ISD::ParamFlags::SExt);
Reid Spencera472f662007-04-11 02:44:20 +00003736 if (Attrs && Attrs->paramHasAttr(j, ParamAttr::SExt))
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003737 Flags |= ISD::ParamFlags::SExt;
Reid Spencera472f662007-04-11 02:44:20 +00003738 if (Attrs && Attrs->paramHasAttr(j, ParamAttr::InReg))
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003739 Flags |= ISD::ParamFlags::InReg;
Reid Spencera472f662007-04-11 02:44:20 +00003740 if (Attrs && Attrs->paramHasAttr(j, ParamAttr::StructRet))
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003741 Flags |= ISD::ParamFlags::StructReturn;
3742 Flags |= (OriginalAlignment << ISD::ParamFlags::OrigAlignmentOffs);
Chris Lattnerab5d0ac2007-02-26 02:56:58 +00003743
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003744 switch (getTypeAction(VT)) {
3745 default: assert(0 && "Unknown type action!");
3746 case Legal:
3747 RetVals.push_back(VT);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003748 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003749 break;
3750 case Promote:
3751 RetVals.push_back(getTypeToTransformTo(VT));
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003752 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003753 break;
3754 case Expand:
Dan Gohmana8665142007-06-25 16:23:39 +00003755 if (!MVT::isVector(VT)) {
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003756 // If this is a large integer, it needs to be broken up into small
3757 // integers. Figure out what the destination type is and how many small
3758 // integers it turns into.
Evan Cheng22cf8992006-12-13 20:57:08 +00003759 MVT::ValueType NVT = getTypeToExpandTo(VT);
Dan Gohman04deef32007-06-21 14:42:22 +00003760 unsigned NumVals = getNumRegisters(VT);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003761 for (unsigned i = 0; i != NumVals; ++i) {
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003762 RetVals.push_back(NVT);
Lauro Ramos Venancioabde3cc2007-02-13 18:10:13 +00003763 // if it isn't first piece, alignment must be 1
Anton Korobeynikovf0b93162007-03-06 06:10:33 +00003764 if (i > 0)
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003765 Flags = (Flags & (~ISD::ParamFlags::OrigAlignment)) |
3766 (1 << ISD::ParamFlags::OrigAlignmentOffs);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003767 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
3768 }
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003769 } else {
3770 // Otherwise, this is a vector type. We only support legal vectors
3771 // right now.
Reid Spencerd84d35b2007-02-15 02:26:10 +00003772 unsigned NumElems = cast<VectorType>(I->getType())->getNumElements();
3773 const Type *EltTy = cast<VectorType>(I->getType())->getElementType();
Evan Cheng3784f3c52006-04-27 08:29:42 +00003774
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003775 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencer09575ba2007-02-15 03:39:18 +00003776 // type. If so, convert to the vector type.
Dan Gohmana8665142007-06-25 16:23:39 +00003777 MVT::ValueType TVT =
3778 MVT::getVectorType(getValueType(EltTy), NumElems);
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003779 if (TVT != MVT::Other && isTypeLegal(TVT)) {
3780 RetVals.push_back(TVT);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003781 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003782 } else {
3783 assert(0 && "Don't support illegal by-val vector arguments yet!");
3784 }
3785 }
3786 break;
3787 }
3788 }
Evan Cheng9618df12006-04-25 23:03:35 +00003789
Chris Lattner3d826992006-05-16 06:45:34 +00003790 RetVals.push_back(MVT::Other);
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003791
3792 // Create the node.
Chris Lattnerbd887772006-08-14 23:53:35 +00003793 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
3794 DAG.getNodeValueTypes(RetVals), RetVals.size(),
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003795 &Ops[0], Ops.size()).Val;
Chris Lattner3d826992006-05-16 06:45:34 +00003796
3797 DAG.setRoot(SDOperand(Result, Result->getNumValues()-1));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003798
3799 // Set up the return result vector.
3800 Ops.clear();
3801 unsigned i = 0;
Reid Spencere63b6512006-12-31 05:55:36 +00003802 unsigned Idx = 1;
3803 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
3804 ++I, ++Idx) {
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003805 MVT::ValueType VT = getValueType(I->getType());
3806
3807 switch (getTypeAction(VT)) {
3808 default: assert(0 && "Unknown type action!");
3809 case Legal:
3810 Ops.push_back(SDOperand(Result, i++));
3811 break;
3812 case Promote: {
3813 SDOperand Op(Result, i++);
3814 if (MVT::isInteger(VT)) {
Reid Spencera472f662007-04-11 02:44:20 +00003815 if (Attrs && Attrs->paramHasAttr(Idx, ParamAttr::SExt))
Chris Lattner96035be2007-01-04 22:22:37 +00003816 Op = DAG.getNode(ISD::AssertSext, Op.getValueType(), Op,
3817 DAG.getValueType(VT));
Reid Spencera472f662007-04-11 02:44:20 +00003818 else if (Attrs && Attrs->paramHasAttr(Idx, ParamAttr::ZExt))
Chris Lattner96035be2007-01-04 22:22:37 +00003819 Op = DAG.getNode(ISD::AssertZext, Op.getValueType(), Op,
3820 DAG.getValueType(VT));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003821 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
3822 } else {
3823 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
3824 Op = DAG.getNode(ISD::FP_ROUND, VT, Op);
3825 }
3826 Ops.push_back(Op);
3827 break;
3828 }
3829 case Expand:
Dan Gohmana8665142007-06-25 16:23:39 +00003830 if (!MVT::isVector(VT)) {
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003831 // If this is a large integer or a floating point node that needs to be
3832 // expanded, it needs to be reassembled from small integers. Figure out
3833 // what the source elt type is and how many small integers it is.
3834 Ops.push_back(ExpandScalarFormalArgs(VT, Result, i, DAG, *this));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003835 } else {
3836 // Otherwise, this is a vector type. We only support legal vectors
3837 // right now.
Reid Spencerd84d35b2007-02-15 02:26:10 +00003838 const VectorType *PTy = cast<VectorType>(I->getType());
Evan Chengd43c5c62006-04-28 05:25:15 +00003839 unsigned NumElems = PTy->getNumElements();
3840 const Type *EltTy = PTy->getElementType();
Evan Cheng3784f3c52006-04-27 08:29:42 +00003841
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003842 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencer09575ba2007-02-15 03:39:18 +00003843 // type. If so, convert to the vector type.
Dan Gohmana8665142007-06-25 16:23:39 +00003844 MVT::ValueType TVT =
3845 MVT::getVectorType(getValueType(EltTy), NumElems);
Chris Lattner7949c2e2006-05-17 20:49:36 +00003846 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Evan Chengd43c5c62006-04-28 05:25:15 +00003847 SDOperand N = SDOperand(Result, i++);
Dan Gohmana8665142007-06-25 16:23:39 +00003848 // Handle copies from vectors to registers.
3849 N = DAG.getNode(ISD::BIT_CONVERT, TVT, N);
Chris Lattner7949c2e2006-05-17 20:49:36 +00003850 Ops.push_back(N);
3851 } else {
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003852 assert(0 && "Don't support illegal by-val vector arguments yet!");
Chris Lattnerb77ba732006-05-16 23:39:44 +00003853 abort();
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003854 }
3855 }
3856 break;
3857 }
3858 }
3859 return Ops;
3860}
3861
Chris Lattneraaa23d92006-05-16 22:53:20 +00003862
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003863/// ExpandScalarCallArgs - Recursively expand call argument node by
3864/// bit_converting it or extract a pair of elements from the larger node.
3865static void ExpandScalarCallArgs(MVT::ValueType VT, SDOperand Arg,
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003866 unsigned Flags,
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003867 SmallVector<SDOperand, 32> &Ops,
3868 SelectionDAG &DAG,
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003869 TargetLowering &TLI,
3870 bool isFirst = true) {
3871
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003872 if (TLI.getTypeAction(VT) != TargetLowering::Expand) {
Lauro Ramos Venancioabde3cc2007-02-13 18:10:13 +00003873 // if it isn't first piece, alignment must be 1
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003874 if (!isFirst)
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003875 Flags = (Flags & (~ISD::ParamFlags::OrigAlignment)) |
3876 (1 << ISD::ParamFlags::OrigAlignmentOffs);
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003877 Ops.push_back(Arg);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003878 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003879 return;
3880 }
3881
3882 MVT::ValueType EVT = TLI.getTypeToTransformTo(VT);
3883 unsigned NumVals = MVT::getSizeInBits(VT) / MVT::getSizeInBits(EVT);
3884 if (NumVals == 1) {
3885 Arg = DAG.getNode(ISD::BIT_CONVERT, EVT, Arg);
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003886 ExpandScalarCallArgs(EVT, Arg, Flags, Ops, DAG, TLI, isFirst);
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003887 } else if (NumVals == 2) {
3888 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, EVT, Arg,
3889 DAG.getConstant(0, TLI.getPointerTy()));
3890 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, EVT, Arg,
3891 DAG.getConstant(1, TLI.getPointerTy()));
3892 if (!TLI.isLittleEndian())
3893 std::swap(Lo, Hi);
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003894 ExpandScalarCallArgs(EVT, Lo, Flags, Ops, DAG, TLI, isFirst);
3895 ExpandScalarCallArgs(EVT, Hi, Flags, Ops, DAG, TLI, false);
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003896 } else {
3897 // Value scalarized into many values. Unimp for now.
3898 assert(0 && "Cannot expand i64 -> i16 yet!");
3899 }
3900}
3901
Chris Lattneraaa23d92006-05-16 22:53:20 +00003902/// TargetLowering::LowerCallTo - This is the default LowerCallTo
3903/// implementation, which just inserts an ISD::CALL node, which is later custom
3904/// lowered by the target to something concrete. FIXME: When all targets are
3905/// migrated to using ISD::CALL, this hook should be integrated into SDISel.
3906std::pair<SDOperand, SDOperand>
Reid Spencere63b6512006-12-31 05:55:36 +00003907TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy,
3908 bool RetTyIsSigned, bool isVarArg,
Chris Lattneraaa23d92006-05-16 22:53:20 +00003909 unsigned CallingConv, bool isTailCall,
3910 SDOperand Callee,
3911 ArgListTy &Args, SelectionDAG &DAG) {
Chris Lattner65879ca2006-08-16 22:57:46 +00003912 SmallVector<SDOperand, 32> Ops;
Chris Lattneraaa23d92006-05-16 22:53:20 +00003913 Ops.push_back(Chain); // Op#0 - Chain
3914 Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
3915 Ops.push_back(DAG.getConstant(isVarArg, getPointerTy())); // Op#2 - VarArg
3916 Ops.push_back(DAG.getConstant(isTailCall, getPointerTy())); // Op#3 - Tail
3917 Ops.push_back(Callee);
3918
3919 // Handle all of the outgoing arguments.
3920 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
Reid Spencere63b6512006-12-31 05:55:36 +00003921 MVT::ValueType VT = getValueType(Args[i].Ty);
3922 SDOperand Op = Args[i].Node;
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003923 unsigned Flags = ISD::ParamFlags::NoFlagSet;
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003924 unsigned OriginalAlignment =
Chris Lattner945e4372007-02-14 05:52:17 +00003925 getTargetData()->getABITypeAlignment(Args[i].Ty);
Anton Korobeynikovf0b93162007-03-06 06:10:33 +00003926
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003927 if (Args[i].isSExt)
3928 Flags |= ISD::ParamFlags::SExt;
3929 if (Args[i].isZExt)
3930 Flags |= ISD::ParamFlags::ZExt;
Anton Korobeynikovf0b93162007-03-06 06:10:33 +00003931 if (Args[i].isInReg)
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003932 Flags |= ISD::ParamFlags::InReg;
Anton Korobeynikovf0b93162007-03-06 06:10:33 +00003933 if (Args[i].isSRet)
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003934 Flags |= ISD::ParamFlags::StructReturn;
3935 Flags |= OriginalAlignment << ISD::ParamFlags::OrigAlignmentOffs;
Anton Korobeynikovf0b93162007-03-06 06:10:33 +00003936
Chris Lattneraaa23d92006-05-16 22:53:20 +00003937 switch (getTypeAction(VT)) {
3938 default: assert(0 && "Unknown type action!");
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003939 case Legal:
Chris Lattneraaa23d92006-05-16 22:53:20 +00003940 Ops.push_back(Op);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003941 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattneraaa23d92006-05-16 22:53:20 +00003942 break;
3943 case Promote:
3944 if (MVT::isInteger(VT)) {
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003945 unsigned ExtOp;
3946 if (Args[i].isSExt)
3947 ExtOp = ISD::SIGN_EXTEND;
3948 else if (Args[i].isZExt)
3949 ExtOp = ISD::ZERO_EXTEND;
3950 else
3951 ExtOp = ISD::ANY_EXTEND;
Chris Lattneraaa23d92006-05-16 22:53:20 +00003952 Op = DAG.getNode(ExtOp, getTypeToTransformTo(VT), Op);
3953 } else {
3954 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
Dale Johannesen9a4d9872007-06-07 21:07:15 +00003955 // A true promotion would change the size of the argument.
3956 // Instead, pretend this is an int. If FP objects are not
3957 // passed the same as ints, the original type should be Legal
3958 // and we should not get here.
3959 Op = DAG.getNode(ISD::BIT_CONVERT,
3960 VT==MVT::f32 ? MVT::i32 :
3961 (VT==MVT::f64 ? MVT::i64 :
3962 MVT::Other),
3963 Op);
Chris Lattneraaa23d92006-05-16 22:53:20 +00003964 }
3965 Ops.push_back(Op);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003966 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattneraaa23d92006-05-16 22:53:20 +00003967 break;
3968 case Expand:
Dan Gohmana8665142007-06-25 16:23:39 +00003969 if (!MVT::isVector(VT)) {
Chris Lattneraaa23d92006-05-16 22:53:20 +00003970 // If this is a large integer, it needs to be broken down into small
3971 // integers. Figure out what the source elt type is and how many small
3972 // integers it is.
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003973 ExpandScalarCallArgs(VT, Op, Flags, Ops, DAG, *this);
Chris Lattneraaa23d92006-05-16 22:53:20 +00003974 } else {
Chris Lattnerb77ba732006-05-16 23:39:44 +00003975 // Otherwise, this is a vector type. We only support legal vectors
3976 // right now.
Reid Spencerd84d35b2007-02-15 02:26:10 +00003977 const VectorType *PTy = cast<VectorType>(Args[i].Ty);
Chris Lattnerb77ba732006-05-16 23:39:44 +00003978 unsigned NumElems = PTy->getNumElements();
3979 const Type *EltTy = PTy->getElementType();
3980
3981 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencer09575ba2007-02-15 03:39:18 +00003982 // type. If so, convert to the vector type.
Dan Gohmana8665142007-06-25 16:23:39 +00003983 MVT::ValueType TVT =
3984 MVT::getVectorType(getValueType(EltTy), NumElems);
Chris Lattner938155c2006-05-17 20:43:21 +00003985 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Dan Gohmana8665142007-06-25 16:23:39 +00003986 // Insert a BIT_CONVERT of the original type to the vector type.
3987 Op = DAG.getNode(ISD::BIT_CONVERT, TVT, Op);
Chris Lattner938155c2006-05-17 20:43:21 +00003988 Ops.push_back(Op);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003989 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattner938155c2006-05-17 20:43:21 +00003990 } else {
Chris Lattnerb77ba732006-05-16 23:39:44 +00003991 assert(0 && "Don't support illegal by-val vector call args yet!");
3992 abort();
3993 }
Chris Lattneraaa23d92006-05-16 22:53:20 +00003994 }
3995 break;
3996 }
3997 }
3998
3999 // Figure out the result value types.
Chris Lattner65879ca2006-08-16 22:57:46 +00004000 SmallVector<MVT::ValueType, 4> RetTys;
Chris Lattneraaa23d92006-05-16 22:53:20 +00004001
4002 if (RetTy != Type::VoidTy) {
4003 MVT::ValueType VT = getValueType(RetTy);
4004 switch (getTypeAction(VT)) {
4005 default: assert(0 && "Unknown type action!");
4006 case Legal:
4007 RetTys.push_back(VT);
4008 break;
4009 case Promote:
4010 RetTys.push_back(getTypeToTransformTo(VT));
4011 break;
4012 case Expand:
Dan Gohmana8665142007-06-25 16:23:39 +00004013 if (!MVT::isVector(VT)) {
Chris Lattneraaa23d92006-05-16 22:53:20 +00004014 // If this is a large integer, it needs to be reassembled from small
4015 // integers. Figure out what the source elt type is and how many small
4016 // integers it is.
Evan Cheng22cf8992006-12-13 20:57:08 +00004017 MVT::ValueType NVT = getTypeToExpandTo(VT);
Dan Gohman04deef32007-06-21 14:42:22 +00004018 unsigned NumVals = getNumRegisters(VT);
Chris Lattneraaa23d92006-05-16 22:53:20 +00004019 for (unsigned i = 0; i != NumVals; ++i)
4020 RetTys.push_back(NVT);
4021 } else {
Chris Lattnerb77ba732006-05-16 23:39:44 +00004022 // Otherwise, this is a vector type. We only support legal vectors
4023 // right now.
Reid Spencerd84d35b2007-02-15 02:26:10 +00004024 const VectorType *PTy = cast<VectorType>(RetTy);
Chris Lattnerb77ba732006-05-16 23:39:44 +00004025 unsigned NumElems = PTy->getNumElements();
4026 const Type *EltTy = PTy->getElementType();
4027
4028 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencer09575ba2007-02-15 03:39:18 +00004029 // type. If so, convert to the vector type.
Dan Gohmana8665142007-06-25 16:23:39 +00004030 MVT::ValueType TVT =
4031 MVT::getVectorType(getValueType(EltTy), NumElems);
Chris Lattnerb77ba732006-05-16 23:39:44 +00004032 if (TVT != MVT::Other && isTypeLegal(TVT)) {
4033 RetTys.push_back(TVT);
4034 } else {
4035 assert(0 && "Don't support illegal by-val vector call results yet!");
4036 abort();
4037 }
Chris Lattneraaa23d92006-05-16 22:53:20 +00004038 }
4039 }
4040 }
4041
4042 RetTys.push_back(MVT::Other); // Always has a chain.
4043
4044 // Finally, create the CALL node.
Chris Lattner65879ca2006-08-16 22:57:46 +00004045 SDOperand Res = DAG.getNode(ISD::CALL,
4046 DAG.getVTList(&RetTys[0], RetTys.size()),
4047 &Ops[0], Ops.size());
Chris Lattneraaa23d92006-05-16 22:53:20 +00004048
4049 // This returns a pair of operands. The first element is the
4050 // return value for the function (if RetTy is not VoidTy). The second
4051 // element is the outgoing token chain.
4052 SDOperand ResVal;
4053 if (RetTys.size() != 1) {
4054 MVT::ValueType VT = getValueType(RetTy);
4055 if (RetTys.size() == 2) {
4056 ResVal = Res;
4057
4058 // If this value was promoted, truncate it down.
4059 if (ResVal.getValueType() != VT) {
Dan Gohmana8665142007-06-25 16:23:39 +00004060 if (MVT::isVector(VT)) {
4061 // Insert a BIT_CONVERT to convert from the packed result type to the
4062 // new vector type.
Reid Spencerd84d35b2007-02-15 02:26:10 +00004063 unsigned NumElems = cast<VectorType>(RetTy)->getNumElements();
4064 const Type *EltTy = cast<VectorType>(RetTy)->getElementType();
Chris Lattnerb77ba732006-05-16 23:39:44 +00004065
4066 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencer09575ba2007-02-15 03:39:18 +00004067 // type. If so, convert to the vector type.
Dan Gohmana8665142007-06-25 16:23:39 +00004068 MVT::ValueType TVT =
4069 MVT::getVectorType(getValueType(EltTy),NumElems);
Chris Lattnerb77ba732006-05-16 23:39:44 +00004070 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Dan Gohmana8665142007-06-25 16:23:39 +00004071 // Insert a BIT_CONVERT of the FORMAL_ARGUMENTS to a
4072 // "N x PTyElementVT" vector type.
4073 ResVal = DAG.getNode(ISD::BIT_CONVERT, TVT, ResVal);
Chris Lattnerb77ba732006-05-16 23:39:44 +00004074 } else {
4075 abort();
4076 }
4077 } else if (MVT::isInteger(VT)) {
Reid Spencere63b6512006-12-31 05:55:36 +00004078 unsigned AssertOp = ISD::AssertSext;
4079 if (!RetTyIsSigned)
4080 AssertOp = ISD::AssertZext;
Chris Lattneraaa23d92006-05-16 22:53:20 +00004081 ResVal = DAG.getNode(AssertOp, ResVal.getValueType(), ResVal,
4082 DAG.getValueType(VT));
4083 ResVal = DAG.getNode(ISD::TRUNCATE, VT, ResVal);
4084 } else {
4085 assert(MVT::isFloatingPoint(VT));
Evan Cheng4eee7242006-12-09 02:42:38 +00004086 if (getTypeAction(VT) == Expand)
4087 ResVal = DAG.getNode(ISD::BIT_CONVERT, VT, ResVal);
4088 else
4089 ResVal = DAG.getNode(ISD::FP_ROUND, VT, ResVal);
Chris Lattneraaa23d92006-05-16 22:53:20 +00004090 }
4091 }
4092 } else if (RetTys.size() == 3) {
4093 ResVal = DAG.getNode(ISD::BUILD_PAIR, VT,
4094 Res.getValue(0), Res.getValue(1));
4095
4096 } else {
4097 assert(0 && "Case not handled yet!");
4098 }
4099 }
4100
4101 return std::make_pair(ResVal, Res.getValue(Res.Val->getNumValues()-1));
4102}
4103
Chris Lattner29dcc712005-05-14 05:50:48 +00004104SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner897cd7d2005-01-16 07:28:41 +00004105 assert(0 && "LowerOperation not implemented for this target!");
4106 abort();
Misha Brukman73e929f2005-02-17 21:39:27 +00004107 return SDOperand();
Chris Lattner897cd7d2005-01-16 07:28:41 +00004108}
4109
Nate Begeman595ec732006-01-28 03:14:31 +00004110SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
4111 SelectionDAG &DAG) {
4112 assert(0 && "CustomPromoteOperation not implemented for this target!");
4113 abort();
4114 return SDOperand();
4115}
4116
Evan Cheng6781b6e2006-02-15 21:59:04 +00004117/// getMemsetValue - Vectorized representation of the memset value
Evan Cheng81fcea82006-02-14 08:22:34 +00004118/// operand.
4119static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
Evan Cheng93e48652006-02-15 22:12:35 +00004120 SelectionDAG &DAG) {
Evan Cheng81fcea82006-02-14 08:22:34 +00004121 MVT::ValueType CurVT = VT;
4122 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
4123 uint64_t Val = C->getValue() & 255;
4124 unsigned Shift = 8;
4125 while (CurVT != MVT::i8) {
4126 Val = (Val << Shift) | Val;
4127 Shift <<= 1;
4128 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00004129 }
4130 return DAG.getConstant(Val, VT);
4131 } else {
4132 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
4133 unsigned Shift = 8;
4134 while (CurVT != MVT::i8) {
4135 Value =
4136 DAG.getNode(ISD::OR, VT,
4137 DAG.getNode(ISD::SHL, VT, Value,
4138 DAG.getConstant(Shift, MVT::i8)), Value);
4139 Shift <<= 1;
4140 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00004141 }
4142
4143 return Value;
4144 }
4145}
4146
Evan Cheng6781b6e2006-02-15 21:59:04 +00004147/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
4148/// used when a memcpy is turned into a memset when the source is a constant
4149/// string ptr.
4150static SDOperand getMemsetStringVal(MVT::ValueType VT,
4151 SelectionDAG &DAG, TargetLowering &TLI,
4152 std::string &Str, unsigned Offset) {
Evan Cheng6781b6e2006-02-15 21:59:04 +00004153 uint64_t Val = 0;
Dan Gohman1796f1f2007-05-18 17:52:13 +00004154 unsigned MSB = MVT::getSizeInBits(VT) / 8;
Evan Cheng6781b6e2006-02-15 21:59:04 +00004155 if (TLI.isLittleEndian())
4156 Offset = Offset + MSB - 1;
4157 for (unsigned i = 0; i != MSB; ++i) {
Evan Cheng6e12a052006-11-29 01:38:07 +00004158 Val = (Val << 8) | (unsigned char)Str[Offset];
Evan Cheng6781b6e2006-02-15 21:59:04 +00004159 Offset += TLI.isLittleEndian() ? -1 : 1;
4160 }
4161 return DAG.getConstant(Val, VT);
4162}
4163
Evan Cheng81fcea82006-02-14 08:22:34 +00004164/// getMemBasePlusOffset - Returns base and offset node for the
4165static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
4166 SelectionDAG &DAG, TargetLowering &TLI) {
4167 MVT::ValueType VT = Base.getValueType();
4168 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
4169}
4170
Evan Chengdb2a7a72006-02-14 20:12:38 +00004171/// MeetsMaxMemopRequirement - Determines if the number of memory ops required
Evan Chengd5026102006-02-14 09:11:59 +00004172/// to replace the memset / memcpy is below the threshold. It also returns the
4173/// types of the sequence of memory ops to perform memset / memcpy.
Evan Chengdb2a7a72006-02-14 20:12:38 +00004174static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
4175 unsigned Limit, uint64_t Size,
4176 unsigned Align, TargetLowering &TLI) {
Evan Cheng81fcea82006-02-14 08:22:34 +00004177 MVT::ValueType VT;
4178
4179 if (TLI.allowsUnalignedMemoryAccesses()) {
4180 VT = MVT::i64;
4181 } else {
4182 switch (Align & 7) {
4183 case 0:
4184 VT = MVT::i64;
4185 break;
4186 case 4:
4187 VT = MVT::i32;
4188 break;
4189 case 2:
4190 VT = MVT::i16;
4191 break;
4192 default:
4193 VT = MVT::i8;
4194 break;
4195 }
4196 }
4197
Evan Chengd5026102006-02-14 09:11:59 +00004198 MVT::ValueType LVT = MVT::i64;
4199 while (!TLI.isTypeLegal(LVT))
4200 LVT = (MVT::ValueType)((unsigned)LVT - 1);
4201 assert(MVT::isInteger(LVT));
Evan Cheng81fcea82006-02-14 08:22:34 +00004202
Evan Chengd5026102006-02-14 09:11:59 +00004203 if (VT > LVT)
4204 VT = LVT;
4205
Evan Cheng04514992006-02-14 23:05:54 +00004206 unsigned NumMemOps = 0;
Evan Cheng81fcea82006-02-14 08:22:34 +00004207 while (Size != 0) {
Dan Gohman1796f1f2007-05-18 17:52:13 +00004208 unsigned VTSize = MVT::getSizeInBits(VT) / 8;
Evan Cheng81fcea82006-02-14 08:22:34 +00004209 while (VTSize > Size) {
4210 VT = (MVT::ValueType)((unsigned)VT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00004211 VTSize >>= 1;
4212 }
Evan Chengd5026102006-02-14 09:11:59 +00004213 assert(MVT::isInteger(VT));
4214
4215 if (++NumMemOps > Limit)
4216 return false;
Evan Cheng81fcea82006-02-14 08:22:34 +00004217 MemOps.push_back(VT);
4218 Size -= VTSize;
4219 }
Evan Chengd5026102006-02-14 09:11:59 +00004220
4221 return true;
Evan Cheng81fcea82006-02-14 08:22:34 +00004222}
4223
Chris Lattner875def92005-01-11 05:56:49 +00004224void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
Evan Cheng81fcea82006-02-14 08:22:34 +00004225 SDOperand Op1 = getValue(I.getOperand(1));
4226 SDOperand Op2 = getValue(I.getOperand(2));
4227 SDOperand Op3 = getValue(I.getOperand(3));
4228 SDOperand Op4 = getValue(I.getOperand(4));
4229 unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
4230 if (Align == 0) Align = 1;
4231
4232 if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
4233 std::vector<MVT::ValueType> MemOps;
Evan Cheng81fcea82006-02-14 08:22:34 +00004234
4235 // Expand memset / memcpy to a series of load / store ops
4236 // if the size operand falls below a certain threshold.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00004237 SmallVector<SDOperand, 8> OutChains;
Evan Cheng81fcea82006-02-14 08:22:34 +00004238 switch (Op) {
Evan Cheng038521e2006-02-14 19:45:56 +00004239 default: break; // Do nothing for now.
Evan Cheng81fcea82006-02-14 08:22:34 +00004240 case ISD::MEMSET: {
Evan Chengdb2a7a72006-02-14 20:12:38 +00004241 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
4242 Size->getValue(), Align, TLI)) {
Evan Chengd5026102006-02-14 09:11:59 +00004243 unsigned NumMemOps = MemOps.size();
Evan Cheng81fcea82006-02-14 08:22:34 +00004244 unsigned Offset = 0;
4245 for (unsigned i = 0; i < NumMemOps; i++) {
4246 MVT::ValueType VT = MemOps[i];
Dan Gohman1796f1f2007-05-18 17:52:13 +00004247 unsigned VTSize = MVT::getSizeInBits(VT) / 8;
Evan Cheng93e48652006-02-15 22:12:35 +00004248 SDOperand Value = getMemsetValue(Op2, VT, DAG);
Evan Chengdf9ac472006-10-05 23:01:46 +00004249 SDOperand Store = DAG.getStore(getRoot(), Value,
Chris Lattner6f87d182006-02-22 22:37:12 +00004250 getMemBasePlusOffset(Op1, Offset, DAG, TLI),
Evan Chengab51cf22006-10-13 21:14:26 +00004251 I.getOperand(1), Offset);
Evan Chenge2038bd2006-02-15 01:54:51 +00004252 OutChains.push_back(Store);
Evan Cheng81fcea82006-02-14 08:22:34 +00004253 Offset += VTSize;
4254 }
Evan Cheng81fcea82006-02-14 08:22:34 +00004255 }
Evan Chenge2038bd2006-02-15 01:54:51 +00004256 break;
Evan Cheng81fcea82006-02-14 08:22:34 +00004257 }
Evan Chenge2038bd2006-02-15 01:54:51 +00004258 case ISD::MEMCPY: {
4259 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
4260 Size->getValue(), Align, TLI)) {
4261 unsigned NumMemOps = MemOps.size();
Evan Chengc3dcf5a2006-02-16 23:11:42 +00004262 unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
Evan Cheng6781b6e2006-02-15 21:59:04 +00004263 GlobalAddressSDNode *G = NULL;
4264 std::string Str;
Evan Chengc3dcf5a2006-02-16 23:11:42 +00004265 bool CopyFromStr = false;
Evan Cheng6781b6e2006-02-15 21:59:04 +00004266
4267 if (Op2.getOpcode() == ISD::GlobalAddress)
4268 G = cast<GlobalAddressSDNode>(Op2);
4269 else if (Op2.getOpcode() == ISD::ADD &&
4270 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
4271 Op2.getOperand(1).getOpcode() == ISD::Constant) {
4272 G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
Evan Chengc3dcf5a2006-02-16 23:11:42 +00004273 SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
Evan Cheng6781b6e2006-02-15 21:59:04 +00004274 }
4275 if (G) {
4276 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
Evan Chengfeba5072006-11-29 01:58:12 +00004277 if (GV && GV->isConstant()) {
Evan Cheng38280c02006-03-10 23:52:03 +00004278 Str = GV->getStringValue(false);
Evan Chengc3dcf5a2006-02-16 23:11:42 +00004279 if (!Str.empty()) {
4280 CopyFromStr = true;
4281 SrcOff += SrcDelta;
4282 }
4283 }
Evan Cheng6781b6e2006-02-15 21:59:04 +00004284 }
4285
Evan Chenge2038bd2006-02-15 01:54:51 +00004286 for (unsigned i = 0; i < NumMemOps; i++) {
4287 MVT::ValueType VT = MemOps[i];
Dan Gohman1796f1f2007-05-18 17:52:13 +00004288 unsigned VTSize = MVT::getSizeInBits(VT) / 8;
Evan Cheng6781b6e2006-02-15 21:59:04 +00004289 SDOperand Value, Chain, Store;
4290
Evan Chengc3dcf5a2006-02-16 23:11:42 +00004291 if (CopyFromStr) {
Evan Cheng6781b6e2006-02-15 21:59:04 +00004292 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
4293 Chain = getRoot();
4294 Store =
Evan Chengdf9ac472006-10-05 23:01:46 +00004295 DAG.getStore(Chain, Value,
4296 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
Evan Chengab51cf22006-10-13 21:14:26 +00004297 I.getOperand(1), DstOff);
Evan Cheng6781b6e2006-02-15 21:59:04 +00004298 } else {
4299 Value = DAG.getLoad(VT, getRoot(),
4300 getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
Evan Chenge71fe34d2006-10-09 20:57:25 +00004301 I.getOperand(2), SrcOff);
Evan Cheng6781b6e2006-02-15 21:59:04 +00004302 Chain = Value.getValue(1);
4303 Store =
Evan Chengdf9ac472006-10-05 23:01:46 +00004304 DAG.getStore(Chain, Value,
4305 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
Evan Chengab51cf22006-10-13 21:14:26 +00004306 I.getOperand(1), DstOff);
Evan Cheng6781b6e2006-02-15 21:59:04 +00004307 }
Evan Chenge2038bd2006-02-15 01:54:51 +00004308 OutChains.push_back(Store);
Evan Cheng6781b6e2006-02-15 21:59:04 +00004309 SrcOff += VTSize;
4310 DstOff += VTSize;
Evan Chenge2038bd2006-02-15 01:54:51 +00004311 }
4312 }
4313 break;
4314 }
4315 }
4316
4317 if (!OutChains.empty()) {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00004318 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
4319 &OutChains[0], OutChains.size()));
Evan Chenge2038bd2006-02-15 01:54:51 +00004320 return;
Evan Cheng81fcea82006-02-14 08:22:34 +00004321 }
4322 }
4323
Chris Lattnerc24a1d32006-08-08 02:23:42 +00004324 DAG.setRoot(DAG.getNode(Op, MVT::Other, getRoot(), Op1, Op2, Op3, Op4));
Chris Lattner7a60d912005-01-07 07:47:53 +00004325}
4326
Chris Lattner875def92005-01-11 05:56:49 +00004327//===----------------------------------------------------------------------===//
4328// SelectionDAGISel code
4329//===----------------------------------------------------------------------===//
Chris Lattner7a60d912005-01-07 07:47:53 +00004330
4331unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
4332 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
4333}
4334
Chris Lattnerc9950c12005-08-17 06:37:43 +00004335void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Jim Laskeydcb2b832006-10-16 20:52:31 +00004336 AU.addRequired<AliasAnalysis>();
Chris Lattnerf6a6d3c2007-03-31 04:18:03 +00004337 AU.setPreservesAll();
Chris Lattnerc9950c12005-08-17 06:37:43 +00004338}
Chris Lattner7a60d912005-01-07 07:47:53 +00004339
Chris Lattner35397782005-12-05 07:10:48 +00004340
Chris Lattnerbba52192006-10-28 19:22:10 +00004341
Chris Lattner7a60d912005-01-07 07:47:53 +00004342bool SelectionDAGISel::runOnFunction(Function &Fn) {
4343 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
4344 RegMap = MF.getSSARegMap();
Bill Wendling22e978a2006-12-07 20:04:42 +00004345 DOUT << "\n\n\n=== " << Fn.getName() << "\n";
Chris Lattner7a60d912005-01-07 07:47:53 +00004346
4347 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
4348
Duncan Sands74137362007-06-13 16:53:21 +00004349 if (ExceptionHandling)
4350 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
4351 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(I->getTerminator()))
4352 // Mark landing pad.
4353 FuncInfo.MBBMap[Invoke->getSuccessor(1)]->setIsLandingPad();
Duncan Sands61166502007-06-06 10:05:18 +00004354
4355 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
Chris Lattner7a60d912005-01-07 07:47:53 +00004356 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukman835702a2005-04-21 22:36:52 +00004357
Evan Cheng276b44b2007-02-10 02:43:39 +00004358 // Add function live-ins to entry block live-in set.
4359 BasicBlock *EntryBB = &Fn.getEntryBlock();
4360 BB = FuncInfo.MBBMap[EntryBB];
4361 if (!MF.livein_empty())
4362 for (MachineFunction::livein_iterator I = MF.livein_begin(),
4363 E = MF.livein_end(); I != E; ++I)
4364 BB->addLiveIn(I->first);
4365
Duncan Sands92bf2c62007-06-15 19:04:19 +00004366#ifndef NDEBUG
4367 assert(FuncInfo.CatchInfoFound.size() == FuncInfo.CatchInfoLost.size() &&
4368 "Not all catch info was assigned to a landing pad!");
4369#endif
4370
Chris Lattner7a60d912005-01-07 07:47:53 +00004371 return true;
4372}
4373
Chris Lattnered0110b2006-10-27 21:36:01 +00004374SDOperand SelectionDAGLowering::CopyValueToVirtualRegister(Value *V,
4375 unsigned Reg) {
4376 SDOperand Op = getValue(V);
Chris Lattnere727af02005-01-13 20:50:02 +00004377 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattner33182322005-08-16 21:55:35 +00004378 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattnere727af02005-01-13 20:50:02 +00004379 "Copy from a reg to the same reg!");
Chris Lattner33182322005-08-16 21:55:35 +00004380
4381 // If this type is not legal, we must make sure to not create an invalid
4382 // register use.
4383 MVT::ValueType SrcVT = Op.getValueType();
4384 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
Chris Lattner33182322005-08-16 21:55:35 +00004385 if (SrcVT == DestVT) {
Chris Lattnered0110b2006-10-27 21:36:01 +00004386 return DAG.getCopyToReg(getRoot(), Reg, Op);
Dan Gohmana8665142007-06-25 16:23:39 +00004387 } else if (MVT::isVector(SrcVT)) {
Chris Lattner5fe1f542006-03-31 02:06:56 +00004388 // Handle copies from generic vectors to registers.
Dan Gohmana8665142007-06-25 16:23:39 +00004389 MVT::ValueType ElementVT, LegalElementVT;
4390 unsigned NE = TLI.getVectorTypeBreakdown(SrcVT,
4391 ElementVT, LegalElementVT);
4392 uint64_t SrcVL = MVT::getVectorNumElements(SrcVT);
Chris Lattner672a42d2006-03-21 19:20:37 +00004393
Chris Lattner5fe1f542006-03-31 02:06:56 +00004394 // Loop over all of the elements of the resultant vector,
Dan Gohmana8665142007-06-25 16:23:39 +00004395 // EXTRACT_VECTOR_ELT'ing or EXTRACT_SUBVECTOR'ing them, converting them
4396 // to LegalElementVT, then copying them into output registers.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00004397 SmallVector<SDOperand, 8> OutChains;
Chris Lattnered0110b2006-10-27 21:36:01 +00004398 SDOperand Root = getRoot();
Chris Lattner5fe1f542006-03-31 02:06:56 +00004399 for (unsigned i = 0; i != NE; ++i) {
Dan Gohmana8665142007-06-25 16:23:39 +00004400 SDOperand Elt = MVT::isVector(ElementVT) ?
4401 DAG.getNode(ISD::EXTRACT_SUBVECTOR, ElementVT,
Dan Gohman26455c42007-06-13 15:12:02 +00004402 Op, DAG.getConstant(i * (SrcVL / NE), TLI.getPointerTy())) :
Dan Gohmana8665142007-06-25 16:23:39 +00004403 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, ElementVT,
Dan Gohman26455c42007-06-13 15:12:02 +00004404 Op, DAG.getConstant(i, TLI.getPointerTy()));
Dan Gohmana8665142007-06-25 16:23:39 +00004405 if (ElementVT == LegalElementVT) {
Chris Lattner5fe1f542006-03-31 02:06:56 +00004406 // Elements are legal.
4407 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
Dan Gohmana8665142007-06-25 16:23:39 +00004408 } else if (LegalElementVT > ElementVT) {
Chris Lattner5fe1f542006-03-31 02:06:56 +00004409 // Elements are promoted.
Dan Gohmana8665142007-06-25 16:23:39 +00004410 if (MVT::isFloatingPoint(LegalElementVT))
4411 Elt = DAG.getNode(ISD::FP_EXTEND, LegalElementVT, Elt);
Chris Lattner5fe1f542006-03-31 02:06:56 +00004412 else
Dan Gohmana8665142007-06-25 16:23:39 +00004413 Elt = DAG.getNode(ISD::ANY_EXTEND, LegalElementVT, Elt);
Chris Lattner5fe1f542006-03-31 02:06:56 +00004414 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
4415 } else {
4416 // Elements are expanded.
4417 // The src value is expanded into multiple registers.
Dan Gohmana8665142007-06-25 16:23:39 +00004418 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, LegalElementVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00004419 Elt, DAG.getConstant(0, TLI.getPointerTy()));
Dan Gohmana8665142007-06-25 16:23:39 +00004420 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, LegalElementVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00004421 Elt, DAG.getConstant(1, TLI.getPointerTy()));
Chris Lattner5fe1f542006-03-31 02:06:56 +00004422 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Lo));
4423 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Hi));
4424 }
Chris Lattner672a42d2006-03-21 19:20:37 +00004425 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +00004426 return DAG.getNode(ISD::TokenFactor, MVT::Other,
4427 &OutChains[0], OutChains.size());
Evan Cheng22cf8992006-12-13 20:57:08 +00004428 } else if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote) {
Chris Lattner33182322005-08-16 21:55:35 +00004429 // The src value is promoted to the register.
Chris Lattnerba28c272005-08-17 06:06:25 +00004430 if (MVT::isFloatingPoint(SrcVT))
4431 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
4432 else
Chris Lattnera66403d2005-09-02 00:19:37 +00004433 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
Chris Lattnered0110b2006-10-27 21:36:01 +00004434 return DAG.getCopyToReg(getRoot(), Reg, Op);
Chris Lattner33182322005-08-16 21:55:35 +00004435 } else {
Evan Cheng22cf8992006-12-13 20:57:08 +00004436 DestVT = TLI.getTypeToExpandTo(SrcVT);
Dan Gohman04deef32007-06-21 14:42:22 +00004437 unsigned NumVals = TLI.getNumRegisters(SrcVT);
Evan Cheng22cf8992006-12-13 20:57:08 +00004438 if (NumVals == 1)
4439 return DAG.getCopyToReg(getRoot(), Reg,
4440 DAG.getNode(ISD::BIT_CONVERT, DestVT, Op));
4441 assert(NumVals == 2 && "1 to 4 (and more) expansion not implemented!");
Chris Lattner33182322005-08-16 21:55:35 +00004442 // The src value is expanded into multiple registers.
4443 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00004444 Op, DAG.getConstant(0, TLI.getPointerTy()));
Chris Lattner33182322005-08-16 21:55:35 +00004445 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00004446 Op, DAG.getConstant(1, TLI.getPointerTy()));
Chris Lattnered0110b2006-10-27 21:36:01 +00004447 Op = DAG.getCopyToReg(getRoot(), Reg, Lo);
Chris Lattner33182322005-08-16 21:55:35 +00004448 return DAG.getCopyToReg(Op, Reg+1, Hi);
4449 }
Chris Lattner7a60d912005-01-07 07:47:53 +00004450}
4451
Chris Lattner16f64df2005-01-17 17:15:02 +00004452void SelectionDAGISel::
Evan Chengde608342007-02-10 01:08:18 +00004453LowerArguments(BasicBlock *LLVMBB, SelectionDAGLowering &SDL,
Chris Lattner16f64df2005-01-17 17:15:02 +00004454 std::vector<SDOperand> &UnorderedChains) {
4455 // If this is the entry block, emit arguments.
Evan Chengde608342007-02-10 01:08:18 +00004456 Function &F = *LLVMBB->getParent();
Chris Lattnere3c2cf42005-01-17 17:55:19 +00004457 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattner6871b232005-10-30 19:42:35 +00004458 SDOperand OldRoot = SDL.DAG.getRoot();
4459 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner16f64df2005-01-17 17:15:02 +00004460
Chris Lattner6871b232005-10-30 19:42:35 +00004461 unsigned a = 0;
4462 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
4463 AI != E; ++AI, ++a)
4464 if (!AI->use_empty()) {
4465 SDL.setValue(AI, Args[a]);
Evan Cheng3784f3c52006-04-27 08:29:42 +00004466
Chris Lattner6871b232005-10-30 19:42:35 +00004467 // If this argument is live outside of the entry block, insert a copy from
4468 // whereever we got it to the vreg that other BB's will reference it as.
Chris Lattner8c504cf2007-02-25 18:40:32 +00004469 DenseMap<const Value*, unsigned>::iterator VMI=FuncInfo.ValueMap.find(AI);
4470 if (VMI != FuncInfo.ValueMap.end()) {
4471 SDOperand Copy = SDL.CopyValueToVirtualRegister(AI, VMI->second);
Chris Lattner6871b232005-10-30 19:42:35 +00004472 UnorderedChains.push_back(Copy);
4473 }
Chris Lattnere3c2cf42005-01-17 17:55:19 +00004474 }
Chris Lattner6871b232005-10-30 19:42:35 +00004475
Chris Lattner6871b232005-10-30 19:42:35 +00004476 // Finally, if the target has anything special to do, allow it to do so.
Chris Lattner957cb672006-05-16 06:10:58 +00004477 // FIXME: this should insert code into the DAG!
Chris Lattner6871b232005-10-30 19:42:35 +00004478 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner16f64df2005-01-17 17:15:02 +00004479}
4480
Duncan Sands92bf2c62007-06-15 19:04:19 +00004481static void copyCatchInfo(BasicBlock *SrcBB, BasicBlock *DestBB,
4482 MachineModuleInfo *MMI, FunctionLoweringInfo &FLI) {
4483 assert(!FLI.MBBMap[SrcBB]->isLandingPad() &&
4484 "Copying catch info out of a landing pad!");
4485 for (BasicBlock::iterator I = SrcBB->begin(), E = --SrcBB->end(); I != E; ++I)
4486 if (isFilterOrSelector(I)) {
4487 // Apply the catch info to DestBB.
4488 addCatchInfo(cast<CallInst>(*I), MMI, FLI.MBBMap[DestBB]);
4489#ifndef NDEBUG
4490 FLI.CatchInfoFound.insert(I);
4491#endif
4492 }
4493}
4494
Chris Lattner7a60d912005-01-07 07:47:53 +00004495void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
4496 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
Nate Begemaned728c12006-03-27 01:32:24 +00004497 FunctionLoweringInfo &FuncInfo) {
Chris Lattner7a60d912005-01-07 07:47:53 +00004498 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattner718b5c22005-01-13 17:59:43 +00004499
4500 std::vector<SDOperand> UnorderedChains;
Misha Brukman835702a2005-04-21 22:36:52 +00004501
Chris Lattner6871b232005-10-30 19:42:35 +00004502 // Lower any arguments needed in this block if this is the entry block.
Dan Gohmandcb291f2007-03-22 16:38:57 +00004503 if (LLVMBB == &LLVMBB->getParent()->getEntryBlock())
Chris Lattner6871b232005-10-30 19:42:35 +00004504 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner7a60d912005-01-07 07:47:53 +00004505
4506 BB = FuncInfo.MBBMap[LLVMBB];
4507 SDL.setCurrentBasicBlock(BB);
4508
Duncan Sands92bf2c62007-06-15 19:04:19 +00004509 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Duncan Sands61166502007-06-06 10:05:18 +00004510
Duncan Sands92bf2c62007-06-15 19:04:19 +00004511 if (ExceptionHandling && MMI && BB->isLandingPad()) {
4512 // Add a label to mark the beginning of the landing pad. Deletion of the
4513 // landing pad can thus be detected via the MachineModuleInfo.
4514 unsigned LabelID = MMI->addLandingPad(BB);
4515 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, DAG.getEntryNode(),
4516 DAG.getConstant(LabelID, MVT::i32)));
4517
4518 // FIXME: Hack around an exception handling flaw (PR1508): the personality
4519 // function and list of typeids logically belong to the invoke (or, if you
4520 // like, the basic block containing the invoke), and need to be associated
4521 // with it in the dwarf exception handling tables. Currently however the
4522 // information is provided by intrinsics (eh.filter and eh.selector) that
4523 // can be moved to unexpected places by the optimizers: if the unwind edge
4524 // is critical, then breaking it can result in the intrinsics being in the
4525 // successor of the landing pad, not the landing pad itself. This results
4526 // in exceptions not being caught because no typeids are associated with
4527 // the invoke. This may not be the only way things can go wrong, but it
4528 // is the only way we try to work around for the moment.
4529 BranchInst *Br = dyn_cast<BranchInst>(LLVMBB->getTerminator());
4530
4531 if (Br && Br->isUnconditional()) { // Critical edge?
4532 BasicBlock::iterator I, E;
4533 for (I = LLVMBB->begin(), E = --LLVMBB->end(); I != E; ++I)
4534 if (isFilterOrSelector(I))
4535 break;
4536
4537 if (I == E)
4538 // No catch info found - try to extract some from the successor.
4539 copyCatchInfo(Br->getSuccessor(0), LLVMBB, MMI, FuncInfo);
Duncan Sands61166502007-06-06 10:05:18 +00004540 }
4541 }
4542
Chris Lattner7a60d912005-01-07 07:47:53 +00004543 // Lower all of the non-terminator instructions.
4544 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
4545 I != E; ++I)
4546 SDL.visit(*I);
Duncan Sands97f72362007-06-13 05:51:31 +00004547
Chris Lattner7a60d912005-01-07 07:47:53 +00004548 // Ensure that all instructions which are used outside of their defining
Duncan Sands97f72362007-06-13 05:51:31 +00004549 // blocks are available as virtual registers. Invoke is handled elsewhere.
Chris Lattner7a60d912005-01-07 07:47:53 +00004550 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Duncan Sands97f72362007-06-13 05:51:31 +00004551 if (!I->use_empty() && !isa<PHINode>(I) && !isa<InvokeInst>(I)) {
Chris Lattner289aa442007-02-04 01:35:11 +00004552 DenseMap<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner7a60d912005-01-07 07:47:53 +00004553 if (VMI != FuncInfo.ValueMap.end())
Chris Lattner718b5c22005-01-13 17:59:43 +00004554 UnorderedChains.push_back(
Chris Lattnered0110b2006-10-27 21:36:01 +00004555 SDL.CopyValueToVirtualRegister(I, VMI->second));
Chris Lattner7a60d912005-01-07 07:47:53 +00004556 }
4557
4558 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
4559 // ensure constants are generated when needed. Remember the virtual registers
4560 // that need to be added to the Machine PHI nodes as input. We cannot just
4561 // directly add them, because expansion might result in multiple MBB's for one
4562 // BB. As such, the start of the BB might correspond to a different MBB than
4563 // the end.
Misha Brukman835702a2005-04-21 22:36:52 +00004564 //
Chris Lattner84a03502006-10-27 23:50:33 +00004565 TerminatorInst *TI = LLVMBB->getTerminator();
Chris Lattner7a60d912005-01-07 07:47:53 +00004566
4567 // Emit constants only once even if used by multiple PHI nodes.
4568 std::map<Constant*, unsigned> ConstantsOut;
Chris Lattner707339a52006-09-07 01:59:34 +00004569
Chris Lattner84a03502006-10-27 23:50:33 +00004570 // Vector bool would be better, but vector<bool> is really slow.
4571 std::vector<unsigned char> SuccsHandled;
4572 if (TI->getNumSuccessors())
4573 SuccsHandled.resize(BB->getParent()->getNumBlockIDs());
4574
Chris Lattner7a60d912005-01-07 07:47:53 +00004575 // Check successor nodes PHI nodes that expect a constant to be available from
4576 // this block.
Chris Lattner7a60d912005-01-07 07:47:53 +00004577 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
4578 BasicBlock *SuccBB = TI->getSuccessor(succ);
Chris Lattner707339a52006-09-07 01:59:34 +00004579 if (!isa<PHINode>(SuccBB->begin())) continue;
Chris Lattner84a03502006-10-27 23:50:33 +00004580 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
Chris Lattner707339a52006-09-07 01:59:34 +00004581
Chris Lattner84a03502006-10-27 23:50:33 +00004582 // If this terminator has multiple identical successors (common for
4583 // switches), only handle each succ once.
4584 unsigned SuccMBBNo = SuccMBB->getNumber();
4585 if (SuccsHandled[SuccMBBNo]) continue;
4586 SuccsHandled[SuccMBBNo] = true;
4587
4588 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
Chris Lattner7a60d912005-01-07 07:47:53 +00004589 PHINode *PN;
4590
4591 // At this point we know that there is a 1-1 correspondence between LLVM PHI
4592 // nodes and Machine PHI nodes, but the incoming operands have not been
4593 // emitted yet.
4594 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner84a03502006-10-27 23:50:33 +00004595 (PN = dyn_cast<PHINode>(I)); ++I) {
4596 // Ignore dead phi's.
4597 if (PN->use_empty()) continue;
4598
4599 unsigned Reg;
4600 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
Chris Lattner90f42382006-11-29 01:12:32 +00004601
Chris Lattner84a03502006-10-27 23:50:33 +00004602 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
4603 unsigned &RegOut = ConstantsOut[C];
4604 if (RegOut == 0) {
4605 RegOut = FuncInfo.CreateRegForValue(C);
4606 UnorderedChains.push_back(
4607 SDL.CopyValueToVirtualRegister(C, RegOut));
Chris Lattner7a60d912005-01-07 07:47:53 +00004608 }
Chris Lattner84a03502006-10-27 23:50:33 +00004609 Reg = RegOut;
4610 } else {
4611 Reg = FuncInfo.ValueMap[PHIOp];
4612 if (Reg == 0) {
4613 assert(isa<AllocaInst>(PHIOp) &&
4614 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
4615 "Didn't codegen value into a register!??");
4616 Reg = FuncInfo.CreateRegForValue(PHIOp);
4617 UnorderedChains.push_back(
4618 SDL.CopyValueToVirtualRegister(PHIOp, Reg));
Chris Lattnerba380352006-03-31 02:12:18 +00004619 }
Chris Lattner7a60d912005-01-07 07:47:53 +00004620 }
Chris Lattner84a03502006-10-27 23:50:33 +00004621
4622 // Remember that this register needs to added to the machine PHI node as
4623 // the input for this MBB.
4624 MVT::ValueType VT = TLI.getValueType(PN->getType());
Dan Gohmana8665142007-06-25 16:23:39 +00004625 unsigned NumRegisters = TLI.getNumRegisters(VT);
Dan Gohman04deef32007-06-21 14:42:22 +00004626 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
Chris Lattner84a03502006-10-27 23:50:33 +00004627 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
4628 }
Chris Lattner7a60d912005-01-07 07:47:53 +00004629 }
4630 ConstantsOut.clear();
4631
Chris Lattner718b5c22005-01-13 17:59:43 +00004632 // Turn all of the unordered chains into one factored node.
Chris Lattner24516842005-01-13 19:53:14 +00004633 if (!UnorderedChains.empty()) {
Chris Lattnerb7cad902005-11-09 05:03:03 +00004634 SDOperand Root = SDL.getRoot();
4635 if (Root.getOpcode() != ISD::EntryToken) {
4636 unsigned i = 0, e = UnorderedChains.size();
4637 for (; i != e; ++i) {
4638 assert(UnorderedChains[i].Val->getNumOperands() > 1);
4639 if (UnorderedChains[i].Val->getOperand(0) == Root)
4640 break; // Don't add the root if we already indirectly depend on it.
4641 }
4642
4643 if (i == e)
4644 UnorderedChains.push_back(Root);
4645 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +00004646 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
4647 &UnorderedChains[0], UnorderedChains.size()));
Chris Lattner718b5c22005-01-13 17:59:43 +00004648 }
4649
Chris Lattner7a60d912005-01-07 07:47:53 +00004650 // Lower the terminator after the copies are emitted.
Duncan Sands97f72362007-06-13 05:51:31 +00004651 SDL.visit(*LLVMBB->getTerminator());
Chris Lattner4108bb02005-01-17 19:43:36 +00004652
Nate Begemaned728c12006-03-27 01:32:24 +00004653 // Copy over any CaseBlock records that may now exist due to SwitchInst
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004654 // lowering, as well as any jump table information.
Nate Begemaned728c12006-03-27 01:32:24 +00004655 SwitchCases.clear();
4656 SwitchCases = SDL.SwitchCases;
Anton Korobeynikov70378262007-03-25 15:07:15 +00004657 JTCases.clear();
4658 JTCases = SDL.JTCases;
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00004659 BitTestCases.clear();
4660 BitTestCases = SDL.BitTestCases;
4661
Chris Lattner4108bb02005-01-17 19:43:36 +00004662 // Make sure the root of the DAG is up-to-date.
4663 DAG.setRoot(SDL.getRoot());
Chris Lattner7a60d912005-01-07 07:47:53 +00004664}
4665
Nate Begemaned728c12006-03-27 01:32:24 +00004666void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
Jim Laskeydcb2b832006-10-16 20:52:31 +00004667 // Get alias analysis for load/store combining.
4668 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
4669
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00004670 // Run the DAG combiner in pre-legalize mode.
Jim Laskeydcb2b832006-10-16 20:52:31 +00004671 DAG.Combine(false, AA);
Nate Begeman007c6502005-09-07 00:15:36 +00004672
Bill Wendling22e978a2006-12-07 20:04:42 +00004673 DOUT << "Lowered selection DAG:\n";
Chris Lattner7a60d912005-01-07 07:47:53 +00004674 DEBUG(DAG.dump());
Nate Begemaned728c12006-03-27 01:32:24 +00004675
Chris Lattner7a60d912005-01-07 07:47:53 +00004676 // Second step, hack on the DAG until it only uses operations and types that
4677 // the target supports.
Chris Lattnerffcb0ae2005-01-23 04:36:26 +00004678 DAG.Legalize();
Nate Begemaned728c12006-03-27 01:32:24 +00004679
Bill Wendling22e978a2006-12-07 20:04:42 +00004680 DOUT << "Legalized selection DAG:\n";
Chris Lattner7a60d912005-01-07 07:47:53 +00004681 DEBUG(DAG.dump());
Nate Begemaned728c12006-03-27 01:32:24 +00004682
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00004683 // Run the DAG combiner in post-legalize mode.
Jim Laskeydcb2b832006-10-16 20:52:31 +00004684 DAG.Combine(true, AA);
Nate Begeman007c6502005-09-07 00:15:36 +00004685
Evan Cheng739a6a42006-01-21 02:32:06 +00004686 if (ViewISelDAGs) DAG.viewGraph();
Evan Cheng51ab4492006-04-28 02:09:19 +00004687
Chris Lattner5ca31d92005-03-30 01:10:47 +00004688 // Third, instruction select all of the operations to machine code, adding the
4689 // code to the MachineBasicBlock.
Chris Lattner7a60d912005-01-07 07:47:53 +00004690 InstructionSelectBasicBlock(DAG);
Nate Begemaned728c12006-03-27 01:32:24 +00004691
Bill Wendling22e978a2006-12-07 20:04:42 +00004692 DOUT << "Selected machine code:\n";
Chris Lattner7a60d912005-01-07 07:47:53 +00004693 DEBUG(BB->dump());
Nate Begemaned728c12006-03-27 01:32:24 +00004694}
Chris Lattner7a60d912005-01-07 07:47:53 +00004695
Nate Begemaned728c12006-03-27 01:32:24 +00004696void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
4697 FunctionLoweringInfo &FuncInfo) {
4698 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
4699 {
Jim Laskeyc56315c2007-01-26 21:22:28 +00004700 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
Nate Begemaned728c12006-03-27 01:32:24 +00004701 CurDAG = &DAG;
4702
4703 // First step, lower LLVM code to some DAG. This DAG may use operations and
4704 // types that are not supported by the target.
4705 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
4706
4707 // Second step, emit the lowered DAG as machine code.
4708 CodeGenAndEmitDAG(DAG);
4709 }
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00004710
4711 DOUT << "Total amount of phi nodes to update: "
4712 << PHINodesToUpdate.size() << "\n";
4713 DEBUG(for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i)
4714 DOUT << "Node " << i << " : (" << PHINodesToUpdate[i].first
4715 << ", " << PHINodesToUpdate[i].second << ")\n";);
Nate Begemaned728c12006-03-27 01:32:24 +00004716
Chris Lattner5ca31d92005-03-30 01:10:47 +00004717 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner7a60d912005-01-07 07:47:53 +00004718 // PHI nodes in successors.
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00004719 if (SwitchCases.empty() && JTCases.empty() && BitTestCases.empty()) {
Nate Begemaned728c12006-03-27 01:32:24 +00004720 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4721 MachineInstr *PHI = PHINodesToUpdate[i].first;
4722 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4723 "This is not a machine PHI node that we are updating!");
Chris Lattneraf23f9b2006-09-05 02:31:13 +00004724 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
Nate Begemaned728c12006-03-27 01:32:24 +00004725 PHI->addMachineBasicBlockOperand(BB);
4726 }
4727 return;
Chris Lattner7a60d912005-01-07 07:47:53 +00004728 }
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00004729
4730 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i) {
4731 // Lower header first, if it wasn't already lowered
4732 if (!BitTestCases[i].Emitted) {
4733 SelectionDAG HSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4734 CurDAG = &HSDAG;
4735 SelectionDAGLowering HSDL(HSDAG, TLI, FuncInfo);
4736 // Set the current basic block to the mbb we wish to insert the code into
4737 BB = BitTestCases[i].Parent;
4738 HSDL.setCurrentBasicBlock(BB);
4739 // Emit the code
4740 HSDL.visitBitTestHeader(BitTestCases[i]);
4741 HSDAG.setRoot(HSDL.getRoot());
4742 CodeGenAndEmitDAG(HSDAG);
4743 }
4744
4745 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
4746 SelectionDAG BSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4747 CurDAG = &BSDAG;
4748 SelectionDAGLowering BSDL(BSDAG, TLI, FuncInfo);
4749 // Set the current basic block to the mbb we wish to insert the code into
4750 BB = BitTestCases[i].Cases[j].ThisBB;
4751 BSDL.setCurrentBasicBlock(BB);
4752 // Emit the code
4753 if (j+1 != ej)
4754 BSDL.visitBitTestCase(BitTestCases[i].Cases[j+1].ThisBB,
4755 BitTestCases[i].Reg,
4756 BitTestCases[i].Cases[j]);
4757 else
4758 BSDL.visitBitTestCase(BitTestCases[i].Default,
4759 BitTestCases[i].Reg,
4760 BitTestCases[i].Cases[j]);
4761
4762
4763 BSDAG.setRoot(BSDL.getRoot());
4764 CodeGenAndEmitDAG(BSDAG);
4765 }
4766
4767 // Update PHI Nodes
4768 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
4769 MachineInstr *PHI = PHINodesToUpdate[pi].first;
4770 MachineBasicBlock *PHIBB = PHI->getParent();
4771 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4772 "This is not a machine PHI node that we are updating!");
4773 // This is "default" BB. We have two jumps to it. From "header" BB and
4774 // from last "case" BB.
4775 if (PHIBB == BitTestCases[i].Default) {
4776 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
4777 PHI->addMachineBasicBlockOperand(BitTestCases[i].Parent);
Anton Korobeynikove2880402007-04-13 06:53:51 +00004778 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00004779 PHI->addMachineBasicBlockOperand(BitTestCases[i].Cases.back().ThisBB);
4780 }
4781 // One of "cases" BB.
4782 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
4783 MachineBasicBlock* cBB = BitTestCases[i].Cases[j].ThisBB;
4784 if (cBB->succ_end() !=
4785 std::find(cBB->succ_begin(),cBB->succ_end(), PHIBB)) {
4786 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
4787 PHI->addMachineBasicBlockOperand(cBB);
4788 }
4789 }
4790 }
4791 }
4792
Nate Begeman866b4b42006-04-23 06:26:20 +00004793 // If the JumpTable record is filled in, then we need to emit a jump table.
4794 // Updating the PHI nodes is tricky in this case, since we need to determine
4795 // whether the PHI is a successor of the range check MBB or the jump table MBB
Anton Korobeynikov70378262007-03-25 15:07:15 +00004796 for (unsigned i = 0, e = JTCases.size(); i != e; ++i) {
4797 // Lower header first, if it wasn't already lowered
4798 if (!JTCases[i].first.Emitted) {
4799 SelectionDAG HSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4800 CurDAG = &HSDAG;
4801 SelectionDAGLowering HSDL(HSDAG, TLI, FuncInfo);
4802 // Set the current basic block to the mbb we wish to insert the code into
4803 BB = JTCases[i].first.HeaderBB;
4804 HSDL.setCurrentBasicBlock(BB);
4805 // Emit the code
4806 HSDL.visitJumpTableHeader(JTCases[i].second, JTCases[i].first);
4807 HSDAG.setRoot(HSDL.getRoot());
4808 CodeGenAndEmitDAG(HSDAG);
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00004809 }
Anton Korobeynikov70378262007-03-25 15:07:15 +00004810
4811 SelectionDAG JSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4812 CurDAG = &JSDAG;
4813 SelectionDAGLowering JSDL(JSDAG, TLI, FuncInfo);
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004814 // Set the current basic block to the mbb we wish to insert the code into
Anton Korobeynikov70378262007-03-25 15:07:15 +00004815 BB = JTCases[i].second.MBB;
4816 JSDL.setCurrentBasicBlock(BB);
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004817 // Emit the code
Anton Korobeynikov70378262007-03-25 15:07:15 +00004818 JSDL.visitJumpTable(JTCases[i].second);
4819 JSDAG.setRoot(JSDL.getRoot());
4820 CodeGenAndEmitDAG(JSDAG);
4821
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004822 // Update PHI Nodes
4823 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
4824 MachineInstr *PHI = PHINodesToUpdate[pi].first;
4825 MachineBasicBlock *PHIBB = PHI->getParent();
4826 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4827 "This is not a machine PHI node that we are updating!");
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00004828 // "default" BB. We can go there only from header BB.
Anton Korobeynikov70378262007-03-25 15:07:15 +00004829 if (PHIBB == JTCases[i].second.Default) {
Chris Lattneraf23f9b2006-09-05 02:31:13 +00004830 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Anton Korobeynikov70378262007-03-25 15:07:15 +00004831 PHI->addMachineBasicBlockOperand(JTCases[i].first.HeaderBB);
Nate Begemandf488392006-05-03 03:48:02 +00004832 }
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00004833 // JT BB. Just iterate over successors here
Nate Begemandf488392006-05-03 03:48:02 +00004834 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
Chris Lattneraf23f9b2006-09-05 02:31:13 +00004835 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Nate Begemandf488392006-05-03 03:48:02 +00004836 PHI->addMachineBasicBlockOperand(BB);
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004837 }
4838 }
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004839 }
4840
Chris Lattner76a7bc82006-10-22 23:00:53 +00004841 // If the switch block involved a branch to one of the actual successors, we
4842 // need to update PHI nodes in that block.
4843 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4844 MachineInstr *PHI = PHINodesToUpdate[i].first;
4845 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4846 "This is not a machine PHI node that we are updating!");
4847 if (BB->isSuccessor(PHI->getParent())) {
4848 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
4849 PHI->addMachineBasicBlockOperand(BB);
4850 }
4851 }
4852
Nate Begemaned728c12006-03-27 01:32:24 +00004853 // If we generated any switch lowering information, build and codegen any
4854 // additional DAGs necessary.
Chris Lattner707339a52006-09-07 01:59:34 +00004855 for (unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
Jim Laskeyc56315c2007-01-26 21:22:28 +00004856 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
Nate Begemaned728c12006-03-27 01:32:24 +00004857 CurDAG = &SDAG;
4858 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
Chris Lattner707339a52006-09-07 01:59:34 +00004859
Nate Begemaned728c12006-03-27 01:32:24 +00004860 // Set the current basic block to the mbb we wish to insert the code into
4861 BB = SwitchCases[i].ThisBB;
4862 SDL.setCurrentBasicBlock(BB);
Chris Lattner707339a52006-09-07 01:59:34 +00004863
Nate Begemaned728c12006-03-27 01:32:24 +00004864 // Emit the code
4865 SDL.visitSwitchCase(SwitchCases[i]);
4866 SDAG.setRoot(SDL.getRoot());
4867 CodeGenAndEmitDAG(SDAG);
Chris Lattner707339a52006-09-07 01:59:34 +00004868
4869 // Handle any PHI nodes in successors of this chunk, as if we were coming
4870 // from the original BB before switch expansion. Note that PHI nodes can
4871 // occur multiple times in PHINodesToUpdate. We have to be very careful to
4872 // handle them the right number of times.
Chris Lattner963ddad2006-10-24 17:57:59 +00004873 while ((BB = SwitchCases[i].TrueBB)) { // Handle LHS and RHS.
Chris Lattner707339a52006-09-07 01:59:34 +00004874 for (MachineBasicBlock::iterator Phi = BB->begin();
4875 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
4876 // This value for this PHI node is recorded in PHINodesToUpdate, get it.
4877 for (unsigned pn = 0; ; ++pn) {
4878 assert(pn != PHINodesToUpdate.size() && "Didn't find PHI entry!");
4879 if (PHINodesToUpdate[pn].first == Phi) {
4880 Phi->addRegOperand(PHINodesToUpdate[pn].second, false);
4881 Phi->addMachineBasicBlockOperand(SwitchCases[i].ThisBB);
4882 break;
4883 }
4884 }
Nate Begemaned728c12006-03-27 01:32:24 +00004885 }
Chris Lattner707339a52006-09-07 01:59:34 +00004886
4887 // Don't process RHS if same block as LHS.
Chris Lattner963ddad2006-10-24 17:57:59 +00004888 if (BB == SwitchCases[i].FalseBB)
4889 SwitchCases[i].FalseBB = 0;
Chris Lattner707339a52006-09-07 01:59:34 +00004890
4891 // If we haven't handled the RHS, do so now. Otherwise, we're done.
Chris Lattner61bcf912006-10-24 18:07:37 +00004892 SwitchCases[i].TrueBB = SwitchCases[i].FalseBB;
Chris Lattner963ddad2006-10-24 17:57:59 +00004893 SwitchCases[i].FalseBB = 0;
Nate Begemaned728c12006-03-27 01:32:24 +00004894 }
Chris Lattner963ddad2006-10-24 17:57:59 +00004895 assert(SwitchCases[i].TrueBB == 0 && SwitchCases[i].FalseBB == 0);
Chris Lattner5ca31d92005-03-30 01:10:47 +00004896 }
Chris Lattner7a60d912005-01-07 07:47:53 +00004897}
Evan Cheng739a6a42006-01-21 02:32:06 +00004898
Jim Laskey95eda5b2006-08-01 14:21:23 +00004899
Evan Cheng739a6a42006-01-21 02:32:06 +00004900//===----------------------------------------------------------------------===//
4901/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
4902/// target node in the graph.
4903void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
4904 if (ViewSchedDAGs) DAG.viewGraph();
Evan Chengc1e1d972006-01-23 07:01:07 +00004905
Jim Laskey29e635d2006-08-02 12:30:23 +00004906 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
Jim Laskey95eda5b2006-08-01 14:21:23 +00004907
4908 if (!Ctor) {
Jim Laskey29e635d2006-08-02 12:30:23 +00004909 Ctor = ISHeuristic;
Jim Laskey17c67ef2006-08-01 19:14:14 +00004910 RegisterScheduler::setDefault(Ctor);
Evan Chengc1e1d972006-01-23 07:01:07 +00004911 }
Jim Laskey95eda5b2006-08-01 14:21:23 +00004912
Jim Laskey03593f72006-08-01 18:29:48 +00004913 ScheduleDAG *SL = Ctor(this, &DAG, BB);
Chris Lattnere23928c2006-01-21 19:12:11 +00004914 BB = SL->Run();
Evan Chengf9adce92006-02-04 06:49:00 +00004915 delete SL;
Evan Cheng739a6a42006-01-21 02:32:06 +00004916}
Chris Lattnerdcf785b2006-02-24 02:13:54 +00004917
Chris Lattner47639db2006-03-06 00:22:00 +00004918
Jim Laskey03593f72006-08-01 18:29:48 +00004919HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
4920 return new HazardRecognizer();
4921}
4922
Chris Lattner6df34962006-10-11 03:58:02 +00004923//===----------------------------------------------------------------------===//
4924// Helper functions used by the generated instruction selector.
4925//===----------------------------------------------------------------------===//
4926// Calls to these methods are generated by tblgen.
4927
4928/// CheckAndMask - The isel is trying to match something like (and X, 255). If
4929/// the dag combiner simplified the 255, we still want to match. RHS is the
4930/// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
4931/// specified in the .td file (e.g. 255).
4932bool SelectionDAGISel::CheckAndMask(SDOperand LHS, ConstantSDNode *RHS,
4933 int64_t DesiredMaskS) {
4934 uint64_t ActualMask = RHS->getValue();
4935 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4936
4937 // If the actual mask exactly matches, success!
4938 if (ActualMask == DesiredMask)
4939 return true;
4940
4941 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4942 if (ActualMask & ~DesiredMask)
4943 return false;
4944
4945 // Otherwise, the DAG Combiner may have proven that the value coming in is
4946 // either already zero or is not demanded. Check for known zero input bits.
4947 uint64_t NeededMask = DesiredMask & ~ActualMask;
Dan Gohman309d3d52007-06-22 14:59:07 +00004948 if (CurDAG->MaskedValueIsZero(LHS, NeededMask))
Chris Lattner6df34962006-10-11 03:58:02 +00004949 return true;
4950
4951 // TODO: check to see if missing bits are just not demanded.
4952
4953 // Otherwise, this pattern doesn't match.
4954 return false;
4955}
4956
4957/// CheckOrMask - The isel is trying to match something like (or X, 255). If
4958/// the dag combiner simplified the 255, we still want to match. RHS is the
4959/// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
4960/// specified in the .td file (e.g. 255).
4961bool SelectionDAGISel::CheckOrMask(SDOperand LHS, ConstantSDNode *RHS,
4962 int64_t DesiredMaskS) {
4963 uint64_t ActualMask = RHS->getValue();
4964 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4965
4966 // If the actual mask exactly matches, success!
4967 if (ActualMask == DesiredMask)
4968 return true;
4969
4970 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4971 if (ActualMask & ~DesiredMask)
4972 return false;
4973
4974 // Otherwise, the DAG Combiner may have proven that the value coming in is
4975 // either already zero or is not demanded. Check for known zero input bits.
4976 uint64_t NeededMask = DesiredMask & ~ActualMask;
4977
4978 uint64_t KnownZero, KnownOne;
Dan Gohman309d3d52007-06-22 14:59:07 +00004979 CurDAG->ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
Chris Lattner6df34962006-10-11 03:58:02 +00004980
4981 // If all the missing bits in the or are already known to be set, match!
4982 if ((NeededMask & KnownOne) == NeededMask)
4983 return true;
4984
4985 // TODO: check to see if missing bits are just not demanded.
4986
4987 // Otherwise, this pattern doesn't match.
4988 return false;
4989}
4990
Jim Laskey03593f72006-08-01 18:29:48 +00004991
Chris Lattnerdcf785b2006-02-24 02:13:54 +00004992/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
4993/// by tblgen. Others should not call it.
4994void SelectionDAGISel::
4995SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
4996 std::vector<SDOperand> InOps;
4997 std::swap(InOps, Ops);
4998
4999 Ops.push_back(InOps[0]); // input chain.
5000 Ops.push_back(InOps[1]); // input asm string.
5001
Chris Lattnerdcf785b2006-02-24 02:13:54 +00005002 unsigned i = 2, e = InOps.size();
5003 if (InOps[e-1].getValueType() == MVT::Flag)
5004 --e; // Don't process a flag operand if it is here.
5005
5006 while (i != e) {
5007 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
5008 if ((Flags & 7) != 4 /*MEM*/) {
5009 // Just skip over this operand, copying the operands verbatim.
5010 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
5011 i += (Flags >> 3) + 1;
5012 } else {
5013 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
5014 // Otherwise, this is a memory operand. Ask the target to select it.
5015 std::vector<SDOperand> SelOps;
5016 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
Bill Wendling22e978a2006-12-07 20:04:42 +00005017 cerr << "Could not match memory address. Inline asm failure!\n";
Chris Lattnerdcf785b2006-02-24 02:13:54 +00005018 exit(1);
5019 }
5020
5021 // Add this to the output node.
Chris Lattnerb49917d2007-04-09 00:33:58 +00005022 MVT::ValueType IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
Chris Lattner9bd5ed62006-12-16 21:14:48 +00005023 Ops.push_back(DAG.getTargetConstant(4/*MEM*/ | (SelOps.size() << 3),
Chris Lattnerb49917d2007-04-09 00:33:58 +00005024 IntPtrTy));
Chris Lattnerdcf785b2006-02-24 02:13:54 +00005025 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
5026 i += 2;
5027 }
5028 }
5029
5030 // Add the flag input back if present.
5031 if (e != InOps.size())
5032 Ops.push_back(InOps.back());
5033}
Devang Patel09f162c2007-05-01 21:15:47 +00005034
Devang Patel8c78a0b2007-05-03 01:11:54 +00005035char SelectionDAGISel::ID = 0;