blob: 10754669ea980b742a6db750290367528d812aa0 [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
Dan Gohman7139a482007-06-27 14:34:07 +0000309 unsigned NumRegisters;
310 MVT::ValueType RegisterVT;
Dan Gohmana8665142007-06-25 16:23:39 +0000311 if (MVT::isVector(VT)) {
Dan Gohman7139a482007-06-27 14:34:07 +0000312 MVT::ValueType ElementVT;
313 NumRegisters = TLI.getVectorTypeBreakdown(VT, ElementVT, RegisterVT);
314 } else {
315 RegisterVT = TLI.getTypeToTransformTo(VT);
316 NumRegisters = TLI.getNumRegisters(VT);
Chris Lattner49409cb2006-03-16 19:51:18 +0000317 }
Bill Wendling47917b62007-04-24 21:13:23 +0000318
Dan Gohman7139a482007-06-27 14:34:07 +0000319 unsigned R = MakeReg(RegisterVT);
320 for (unsigned i = 1; i != NumRegisters; ++i)
321 MakeReg(RegisterVT);
322
Chris Lattner49409cb2006-03-16 19:51:18 +0000323 return R;
324}
Chris Lattner7a60d912005-01-07 07:47:53 +0000325
326//===----------------------------------------------------------------------===//
327/// SelectionDAGLowering - This is the common target-independent lowering
328/// implementation that is parameterized by a TargetLowering object.
329/// Also, targets can overload any lowering method.
330///
331namespace llvm {
332class SelectionDAGLowering {
333 MachineBasicBlock *CurMBB;
334
Chris Lattner79084302007-02-04 01:31:47 +0000335 DenseMap<const Value*, SDOperand> NodeMap;
Chris Lattner7a60d912005-01-07 07:47:53 +0000336
Chris Lattner4d9651c2005-01-17 22:19:26 +0000337 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
338 /// them up and then emit token factor nodes when possible. This allows us to
339 /// get simple disambiguation between loads without worrying about alias
340 /// analysis.
341 std::vector<SDOperand> PendingLoads;
342
Anton Korobeynikov915e6172007-04-04 21:14:49 +0000343 /// Case - A struct to record the Value for a switch case, and the
344 /// case's target basic block.
345 struct Case {
346 Constant* Low;
347 Constant* High;
348 MachineBasicBlock* BB;
349
350 Case() : Low(0), High(0), BB(0) { }
351 Case(Constant* low, Constant* high, MachineBasicBlock* bb) :
352 Low(low), High(high), BB(bb) { }
353 uint64_t size() const {
354 uint64_t rHigh = cast<ConstantInt>(High)->getSExtValue();
355 uint64_t rLow = cast<ConstantInt>(Low)->getSExtValue();
356 return (rHigh - rLow + 1ULL);
357 }
358 };
359
Anton Korobeynikov506eaf72007-04-09 12:31:58 +0000360 struct CaseBits {
361 uint64_t Mask;
362 MachineBasicBlock* BB;
363 unsigned Bits;
364
365 CaseBits(uint64_t mask, MachineBasicBlock* bb, unsigned bits):
366 Mask(mask), BB(bb), Bits(bits) { }
367 };
368
Anton Korobeynikov915e6172007-04-04 21:14:49 +0000369 typedef std::vector<Case> CaseVector;
Anton Korobeynikov506eaf72007-04-09 12:31:58 +0000370 typedef std::vector<CaseBits> CaseBitsVector;
Anton Korobeynikov915e6172007-04-04 21:14:49 +0000371 typedef CaseVector::iterator CaseItr;
372 typedef std::pair<CaseItr, CaseItr> CaseRange;
Nate Begemaned728c12006-03-27 01:32:24 +0000373
374 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
375 /// of conditional branches.
376 struct CaseRec {
377 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
378 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
379
380 /// CaseBB - The MBB in which to emit the compare and branch
381 MachineBasicBlock *CaseBB;
382 /// LT, GE - If nonzero, we know the current case value must be less-than or
383 /// greater-than-or-equal-to these Constants.
384 Constant *LT;
385 Constant *GE;
386 /// Range - A pair of iterators representing the range of case values to be
387 /// processed at this point in the binary search tree.
388 CaseRange Range;
389 };
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +0000390
391 typedef std::vector<CaseRec> CaseRecVector;
Anton Korobeynikov915e6172007-04-04 21:14:49 +0000392
393 /// The comparison function for sorting the switch case values in the vector.
394 /// WARNING: Case ranges should be disjoint!
Nate Begemaned728c12006-03-27 01:32:24 +0000395 struct CaseCmp {
Anton Korobeynikov506eaf72007-04-09 12:31:58 +0000396 bool operator () (const Case& C1, const Case& C2) {
Anton Korobeynikov915e6172007-04-04 21:14:49 +0000397 assert(isa<ConstantInt>(C1.Low) && isa<ConstantInt>(C2.High));
398 const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
399 const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
400 return CI1->getValue().slt(CI2->getValue());
Nate Begemaned728c12006-03-27 01:32:24 +0000401 }
402 };
Anton Korobeynikov915e6172007-04-04 21:14:49 +0000403
Anton Korobeynikov506eaf72007-04-09 12:31:58 +0000404 struct CaseBitsCmp {
405 bool operator () (const CaseBits& C1, const CaseBits& C2) {
406 return C1.Bits > C2.Bits;
407 }
408 };
409
Anton Korobeynikov915e6172007-04-04 21:14:49 +0000410 unsigned Clusterify(CaseVector& Cases, const SwitchInst &SI);
Nate Begemaned728c12006-03-27 01:32:24 +0000411
Chris Lattner7a60d912005-01-07 07:47:53 +0000412public:
413 // TLI - This is information that describes the available target features we
414 // need for lowering. This indicates when operations are unavailable,
415 // implemented with a libcall, etc.
416 TargetLowering &TLI;
417 SelectionDAG &DAG;
Owen Anderson20a631f2006-05-03 01:29:57 +0000418 const TargetData *TD;
Chris Lattner7a60d912005-01-07 07:47:53 +0000419
Nate Begemaned728c12006-03-27 01:32:24 +0000420 /// SwitchCases - Vector of CaseBlock structures used to communicate
421 /// SwitchInst code generation information.
422 std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
Anton Korobeynikov70378262007-03-25 15:07:15 +0000423 /// JTCases - Vector of JumpTable structures used to communicate
424 /// SwitchInst code generation information.
425 std::vector<SelectionDAGISel::JumpTableBlock> JTCases;
Anton Korobeynikov506eaf72007-04-09 12:31:58 +0000426 std::vector<SelectionDAGISel::BitTestBlock> BitTestCases;
Nate Begemaned728c12006-03-27 01:32:24 +0000427
Chris Lattner7a60d912005-01-07 07:47:53 +0000428 /// FuncInfo - Information about the function as a whole.
429 ///
430 FunctionLoweringInfo &FuncInfo;
431
432 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Misha Brukman835702a2005-04-21 22:36:52 +0000433 FunctionLoweringInfo &funcinfo)
Chris Lattner7a60d912005-01-07 07:47:53 +0000434 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
Anton Korobeynikov70378262007-03-25 15:07:15 +0000435 FuncInfo(funcinfo) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000436 }
437
Chris Lattner4108bb02005-01-17 19:43:36 +0000438 /// getRoot - Return the current virtual root of the Selection DAG.
439 ///
440 SDOperand getRoot() {
Chris Lattner4d9651c2005-01-17 22:19:26 +0000441 if (PendingLoads.empty())
442 return DAG.getRoot();
Misha Brukman835702a2005-04-21 22:36:52 +0000443
Chris Lattner4d9651c2005-01-17 22:19:26 +0000444 if (PendingLoads.size() == 1) {
445 SDOperand Root = PendingLoads[0];
446 DAG.setRoot(Root);
447 PendingLoads.clear();
448 return Root;
449 }
450
451 // Otherwise, we have to make a token factor node.
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000452 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
453 &PendingLoads[0], PendingLoads.size());
Chris Lattner4d9651c2005-01-17 22:19:26 +0000454 PendingLoads.clear();
455 DAG.setRoot(Root);
456 return Root;
Chris Lattner4108bb02005-01-17 19:43:36 +0000457 }
458
Chris Lattnered0110b2006-10-27 21:36:01 +0000459 SDOperand CopyValueToVirtualRegister(Value *V, unsigned Reg);
460
Chris Lattner7a60d912005-01-07 07:47:53 +0000461 void visit(Instruction &I) { visit(I.getOpcode(), I); }
462
463 void visit(unsigned Opcode, User &I) {
Chris Lattnerd5e604d2006-11-10 04:41:34 +0000464 // Note: this doesn't use InstVisitor, because it has to work with
465 // ConstantExpr's in addition to instructions.
Chris Lattner7a60d912005-01-07 07:47:53 +0000466 switch (Opcode) {
467 default: assert(0 && "Unknown instruction type encountered!");
468 abort();
469 // Build the switch statement using the Instruction.def file.
470#define HANDLE_INST(NUM, OPCODE, CLASS) \
471 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
472#include "llvm/Instruction.def"
473 }
474 }
475
476 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
477
Chris Lattner4024c002006-03-15 22:19:46 +0000478 SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Chenge71fe34d2006-10-09 20:57:25 +0000479 const Value *SV, SDOperand Root,
Christopher Lamb8af6d582007-04-22 23:15:30 +0000480 bool isVolatile, unsigned Alignment);
Chris Lattner7a60d912005-01-07 07:47:53 +0000481
482 SDOperand getIntPtrConstant(uint64_t Val) {
483 return DAG.getConstant(Val, TLI.getPointerTy());
484 }
485
Chris Lattner8471b152006-03-16 19:57:50 +0000486 SDOperand getValue(const Value *V);
Chris Lattner7a60d912005-01-07 07:47:53 +0000487
Chris Lattner79084302007-02-04 01:31:47 +0000488 void setValue(const Value *V, SDOperand NewN) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000489 SDOperand &N = NodeMap[V];
490 assert(N.Val == 0 && "Already set a value for this node!");
Chris Lattner79084302007-02-04 01:31:47 +0000491 N = NewN;
Chris Lattner7a60d912005-01-07 07:47:53 +0000492 }
Chris Lattner1558fc62006-02-01 18:59:47 +0000493
Chris Lattner8cfd33b2007-04-30 21:11:17 +0000494 void GetRegistersForValue(AsmOperandInfo &OpInfo, bool HasEarlyClobber,
495 std::set<unsigned> &OutputRegs,
496 std::set<unsigned> &InputRegs);
Nate Begemaned728c12006-03-27 01:32:24 +0000497
Chris Lattnered0110b2006-10-27 21:36:01 +0000498 void FindMergedConditions(Value *Cond, MachineBasicBlock *TBB,
499 MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
500 unsigned Opc);
Chris Lattner84a03502006-10-27 23:50:33 +0000501 bool isExportableFromCurrentBlock(Value *V, const BasicBlock *FromBB);
Chris Lattnered0110b2006-10-27 21:36:01 +0000502 void ExportFromCurrentBlock(Value *V);
Jim Laskey31fef782007-02-23 21:45:01 +0000503 void LowerCallTo(Instruction &I,
504 const Type *CalledValueTy, unsigned CallingConv,
Anton Korobeynikov3b327822007-05-23 11:08:31 +0000505 bool IsTailCall, SDOperand Callee, unsigned OpIdx,
506 MachineBasicBlock *LandingPad = NULL);
507
Chris Lattner7a60d912005-01-07 07:47:53 +0000508 // Terminator instructions.
509 void visitRet(ReturnInst &I);
510 void visitBr(BranchInst &I);
Nate Begemaned728c12006-03-27 01:32:24 +0000511 void visitSwitch(SwitchInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000512 void visitUnreachable(UnreachableInst &I) { /* noop */ }
513
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +0000514 // Helpers for visitSwitch
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +0000515 bool handleSmallSwitchRange(CaseRec& CR,
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +0000516 CaseRecVector& WorkList,
517 Value* SV,
518 MachineBasicBlock* Default);
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +0000519 bool handleJTSwitchCase(CaseRec& CR,
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +0000520 CaseRecVector& WorkList,
521 Value* SV,
522 MachineBasicBlock* Default);
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +0000523 bool handleBTSplitSwitchCase(CaseRec& CR,
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +0000524 CaseRecVector& WorkList,
525 Value* SV,
526 MachineBasicBlock* Default);
Anton Korobeynikov506eaf72007-04-09 12:31:58 +0000527 bool handleBitTestsSwitchCase(CaseRec& CR,
528 CaseRecVector& WorkList,
529 Value* SV,
530 MachineBasicBlock* Default);
Nate Begemaned728c12006-03-27 01:32:24 +0000531 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
Anton Korobeynikov506eaf72007-04-09 12:31:58 +0000532 void visitBitTestHeader(SelectionDAGISel::BitTestBlock &B);
533 void visitBitTestCase(MachineBasicBlock* NextMBB,
534 unsigned Reg,
535 SelectionDAGISel::BitTestCase &B);
Nate Begeman4ca2ea52006-04-22 18:53:45 +0000536 void visitJumpTable(SelectionDAGISel::JumpTable &JT);
Anton Korobeynikov70378262007-03-25 15:07:15 +0000537 void visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
538 SelectionDAGISel::JumpTableHeader &JTH);
Nate Begemaned728c12006-03-27 01:32:24 +0000539
Chris Lattner7a60d912005-01-07 07:47:53 +0000540 // These all get lowered before this pass.
Jim Laskey4b37a4c2007-02-21 22:53:45 +0000541 void visitInvoke(InvokeInst &I);
542 void visitUnwind(UnwindInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000543
Dan Gohmana8665142007-06-25 16:23:39 +0000544 void visitBinary(User &I, unsigned OpCode);
Nate Begeman127321b2005-11-18 07:42:56 +0000545 void visitShift(User &I, unsigned Opcode);
Nate Begemanb2e089c2005-11-19 00:36:38 +0000546 void visitAdd(User &I) {
Dan Gohmana8665142007-06-25 16:23:39 +0000547 if (I.getType()->isFPOrFPVector())
548 visitBinary(I, ISD::FADD);
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000549 else
Dan Gohmana8665142007-06-25 16:23:39 +0000550 visitBinary(I, ISD::ADD);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000551 }
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000552 void visitSub(User &I);
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000553 void visitMul(User &I) {
Dan Gohmana8665142007-06-25 16:23:39 +0000554 if (I.getType()->isFPOrFPVector())
555 visitBinary(I, ISD::FMUL);
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000556 else
Dan Gohmana8665142007-06-25 16:23:39 +0000557 visitBinary(I, ISD::MUL);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000558 }
Dan Gohmana8665142007-06-25 16:23:39 +0000559 void visitURem(User &I) { visitBinary(I, ISD::UREM); }
560 void visitSRem(User &I) { visitBinary(I, ISD::SREM); }
561 void visitFRem(User &I) { visitBinary(I, ISD::FREM); }
562 void visitUDiv(User &I) { visitBinary(I, ISD::UDIV); }
563 void visitSDiv(User &I) { visitBinary(I, ISD::SDIV); }
564 void visitFDiv(User &I) { visitBinary(I, ISD::FDIV); }
565 void visitAnd (User &I) { visitBinary(I, ISD::AND); }
566 void visitOr (User &I) { visitBinary(I, ISD::OR); }
567 void visitXor (User &I) { visitBinary(I, ISD::XOR); }
Reid Spencer2eadb532007-01-21 00:29:26 +0000568 void visitShl (User &I) { visitShift(I, ISD::SHL); }
Reid Spencerfdff9382006-11-08 06:47:33 +0000569 void visitLShr(User &I) { visitShift(I, ISD::SRL); }
570 void visitAShr(User &I) { visitShift(I, ISD::SRA); }
Reid Spencerd9436b62006-11-20 01:22:35 +0000571 void visitICmp(User &I);
572 void visitFCmp(User &I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000573 // Visit the conversion instructions
574 void visitTrunc(User &I);
575 void visitZExt(User &I);
576 void visitSExt(User &I);
577 void visitFPTrunc(User &I);
578 void visitFPExt(User &I);
579 void visitFPToUI(User &I);
580 void visitFPToSI(User &I);
581 void visitUIToFP(User &I);
582 void visitSIToFP(User &I);
583 void visitPtrToInt(User &I);
584 void visitIntToPtr(User &I);
585 void visitBitCast(User &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000586
Chris Lattner67271862006-03-29 00:11:43 +0000587 void visitExtractElement(User &I);
588 void visitInsertElement(User &I);
Chris Lattner098c01e2006-04-08 04:15:24 +0000589 void visitShuffleVector(User &I);
Chris Lattner32206f52006-03-18 01:44:44 +0000590
Chris Lattner7a60d912005-01-07 07:47:53 +0000591 void visitGetElementPtr(User &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000592 void visitSelect(User &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000593
594 void visitMalloc(MallocInst &I);
595 void visitFree(FreeInst &I);
596 void visitAlloca(AllocaInst &I);
597 void visitLoad(LoadInst &I);
598 void visitStore(StoreInst &I);
599 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
600 void visitCall(CallInst &I);
Chris Lattner476e67b2006-01-26 22:24:51 +0000601 void visitInlineAsm(CallInst &I);
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000602 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattnerd96b09a2006-03-24 02:22:33 +0000603 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
Chris Lattner7a60d912005-01-07 07:47:53 +0000604
Chris Lattner7a60d912005-01-07 07:47:53 +0000605 void visitVAStart(CallInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000606 void visitVAArg(VAArgInst &I);
607 void visitVAEnd(CallInst &I);
608 void visitVACopy(CallInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000609
Chris Lattner875def92005-01-11 05:56:49 +0000610 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner7a60d912005-01-07 07:47:53 +0000611
612 void visitUserOp1(Instruction &I) {
613 assert(0 && "UserOp1 should not exist at instruction selection time!");
614 abort();
615 }
616 void visitUserOp2(Instruction &I) {
617 assert(0 && "UserOp2 should not exist at instruction selection time!");
618 abort();
619 }
620};
621} // end namespace llvm
622
Chris Lattner8471b152006-03-16 19:57:50 +0000623SDOperand SelectionDAGLowering::getValue(const Value *V) {
624 SDOperand &N = NodeMap[V];
625 if (N.Val) return N;
626
627 const Type *VTy = V->getType();
628 MVT::ValueType VT = TLI.getValueType(VTy);
629 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
630 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
631 visit(CE->getOpcode(), *CE);
Chris Lattner79084302007-02-04 01:31:47 +0000632 SDOperand N1 = NodeMap[V];
633 assert(N1.Val && "visit didn't populate the ValueMap!");
634 return N1;
Chris Lattner8471b152006-03-16 19:57:50 +0000635 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
636 return N = DAG.getGlobalAddress(GV, VT);
637 } else if (isa<ConstantPointerNull>(C)) {
638 return N = DAG.getConstant(0, TLI.getPointerTy());
639 } else if (isa<UndefValue>(C)) {
Reid Spencerd84d35b2007-02-15 02:26:10 +0000640 if (!isa<VectorType>(VTy))
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000641 return N = DAG.getNode(ISD::UNDEF, VT);
642
Dan Gohmana8665142007-06-25 16:23:39 +0000643 // Create a BUILD_VECTOR of undef nodes.
Reid Spencerd84d35b2007-02-15 02:26:10 +0000644 const VectorType *PTy = cast<VectorType>(VTy);
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000645 unsigned NumElements = PTy->getNumElements();
646 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
647
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000648 SmallVector<SDOperand, 8> Ops;
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000649 Ops.assign(NumElements, DAG.getNode(ISD::UNDEF, PVT));
650
651 // Create a VConstant node with generic Vector type.
Dan Gohmana8665142007-06-25 16:23:39 +0000652 MVT::ValueType VT = MVT::getVectorType(PVT, NumElements);
653 return N = DAG.getNode(ISD::BUILD_VECTOR, VT,
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000654 &Ops[0], Ops.size());
Chris Lattner8471b152006-03-16 19:57:50 +0000655 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
656 return N = DAG.getConstantFP(CFP->getValue(), VT);
Reid Spencerd84d35b2007-02-15 02:26:10 +0000657 } else if (const VectorType *PTy = dyn_cast<VectorType>(VTy)) {
Chris Lattner8471b152006-03-16 19:57:50 +0000658 unsigned NumElements = PTy->getNumElements();
659 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Chris Lattner8471b152006-03-16 19:57:50 +0000660
661 // Now that we know the number and type of the elements, push a
662 // Constant or ConstantFP node onto the ops list for each element of
663 // the packed constant.
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000664 SmallVector<SDOperand, 8> Ops;
Reid Spencerd84d35b2007-02-15 02:26:10 +0000665 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
Chris Lattner67271862006-03-29 00:11:43 +0000666 for (unsigned i = 0; i != NumElements; ++i)
667 Ops.push_back(getValue(CP->getOperand(i)));
Chris Lattner8471b152006-03-16 19:57:50 +0000668 } else {
669 assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
670 SDOperand Op;
671 if (MVT::isFloatingPoint(PVT))
672 Op = DAG.getConstantFP(0, PVT);
673 else
674 Op = DAG.getConstant(0, PVT);
675 Ops.assign(NumElements, Op);
676 }
677
Dan Gohmana8665142007-06-25 16:23:39 +0000678 // Create a BUILD_VECTOR node.
679 MVT::ValueType VT = MVT::getVectorType(PVT, NumElements);
680 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0],
Chris Lattner79084302007-02-04 01:31:47 +0000681 Ops.size());
Chris Lattner8471b152006-03-16 19:57:50 +0000682 } else {
683 // Canonicalize all constant ints to be unsigned.
Zhou Sheng75b871f2007-01-11 12:24:14 +0000684 return N = DAG.getConstant(cast<ConstantInt>(C)->getZExtValue(),VT);
Chris Lattner8471b152006-03-16 19:57:50 +0000685 }
686 }
687
688 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
689 std::map<const AllocaInst*, int>::iterator SI =
690 FuncInfo.StaticAllocaMap.find(AI);
691 if (SI != FuncInfo.StaticAllocaMap.end())
692 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
693 }
694
Chris Lattner8c504cf2007-02-25 18:40:32 +0000695 unsigned InReg = FuncInfo.ValueMap[V];
696 assert(InReg && "Value not in map!");
Chris Lattner8471b152006-03-16 19:57:50 +0000697
698 // If this type is not legal, make it so now.
Dan Gohmana8665142007-06-25 16:23:39 +0000699 if (!MVT::isVector(VT)) {
Evan Cheng22cf8992006-12-13 20:57:08 +0000700 if (TLI.getTypeAction(VT) == TargetLowering::Expand) {
Chris Lattner5fe1f542006-03-31 02:06:56 +0000701 // Source must be expanded. This input value is actually coming from the
Chris Lattner8c504cf2007-02-25 18:40:32 +0000702 // register pair InReg and InReg+1.
Evan Cheng22cf8992006-12-13 20:57:08 +0000703 MVT::ValueType DestVT = TLI.getTypeToExpandTo(VT);
Dan Gohman04deef32007-06-21 14:42:22 +0000704 unsigned NumVals = TLI.getNumRegisters(VT);
Evan Cheng22cf8992006-12-13 20:57:08 +0000705 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
706 if (NumVals == 1)
707 N = DAG.getNode(ISD::BIT_CONVERT, VT, N);
708 else {
709 assert(NumVals == 2 && "1 to 4 (and more) expansion not implemented!");
710 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
Dan Gohmana8665142007-06-25 16:23:39 +0000711 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
Evan Cheng22cf8992006-12-13 20:57:08 +0000712 }
713 } else {
714 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
715 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
716 if (TLI.getTypeAction(VT) == TargetLowering::Promote) // Promotion case
717 N = MVT::isFloatingPoint(VT)
718 ? DAG.getNode(ISD::FP_ROUND, VT, N)
719 : DAG.getNode(ISD::TRUNCATE, VT, N);
Chris Lattner8471b152006-03-16 19:57:50 +0000720 }
Chris Lattner5fe1f542006-03-31 02:06:56 +0000721 } else {
Dan Gohmana8665142007-06-25 16:23:39 +0000722 // Otherwise, if this is a vector, make it available as a vector
Chris Lattner5fe1f542006-03-31 02:06:56 +0000723 // here.
Dan Gohmana8665142007-06-25 16:23:39 +0000724 MVT::ValueType ElementVT, LegalElementVT;
725 unsigned NE = TLI.getVectorTypeBreakdown(VT, ElementVT,
726 LegalElementVT);
Chris Lattner5fe1f542006-03-31 02:06:56 +0000727
Dan Gohmana8665142007-06-25 16:23:39 +0000728 // Build a BUILD_VECTOR or CONCAT_VECTORS with the input registers.
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000729 SmallVector<SDOperand, 8> Ops;
Dan Gohmana8665142007-06-25 16:23:39 +0000730 if (ElementVT == LegalElementVT) {
731 // If the value types are legal, just BUILD the CopyFromReg nodes.
Chris Lattner5fe1f542006-03-31 02:06:56 +0000732 for (unsigned i = 0; i != NE; ++i)
733 Ops.push_back(DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
Dan Gohmana8665142007-06-25 16:23:39 +0000734 ElementVT));
735 } else if (ElementVT < LegalElementVT) {
Dan Gohman30978072007-05-24 14:36:04 +0000736 // If the register was promoted, use TRUNCATE or FP_ROUND as appropriate.
Chris Lattner5fe1f542006-03-31 02:06:56 +0000737 for (unsigned i = 0; i != NE; ++i) {
738 SDOperand Op = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
Dan Gohmana8665142007-06-25 16:23:39 +0000739 LegalElementVT);
740 if (MVT::isFloatingPoint(ElementVT))
741 Op = DAG.getNode(ISD::FP_ROUND, ElementVT, Op);
Chris Lattner5fe1f542006-03-31 02:06:56 +0000742 else
Dan Gohmana8665142007-06-25 16:23:39 +0000743 Op = DAG.getNode(ISD::TRUNCATE, ElementVT, Op);
Chris Lattner5fe1f542006-03-31 02:06:56 +0000744 Ops.push_back(Op);
745 }
746 } else {
747 // If the register was expanded, use BUILD_PAIR.
748 assert((NE & 1) == 0 && "Must expand into a multiple of 2 elements!");
Dan Gohmancbd51c82007-06-13 14:55:16 +0000749 for (unsigned i = 0; i != NE; ++i) {
Chris Lattner5fe1f542006-03-31 02:06:56 +0000750 SDOperand Op0 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
Dan Gohmana8665142007-06-25 16:23:39 +0000751 LegalElementVT);
Chris Lattner5fe1f542006-03-31 02:06:56 +0000752 SDOperand Op1 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
Dan Gohmana8665142007-06-25 16:23:39 +0000753 LegalElementVT);
754 Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, ElementVT, Op0, Op1));
Chris Lattner5fe1f542006-03-31 02:06:56 +0000755 }
756 }
757
Dan Gohmana8665142007-06-25 16:23:39 +0000758 if (MVT::isVector(ElementVT)) {
759 N = DAG.getNode(ISD::CONCAT_VECTORS,
760 MVT::getVectorType(MVT::getVectorElementType(ElementVT),
761 NE * MVT::getVectorNumElements(ElementVT)),
762 &Ops[0], Ops.size());
Dan Gohman26455c42007-06-13 15:12:02 +0000763 } else {
Dan Gohmana8665142007-06-25 16:23:39 +0000764 N = DAG.getNode(ISD::BUILD_VECTOR,
765 MVT::getVectorType(ElementVT, NE),
766 &Ops[0], Ops.size());
Dan Gohman26455c42007-06-13 15:12:02 +0000767 }
Chris Lattner8471b152006-03-16 19:57:50 +0000768 }
769
770 return N;
771}
772
773
Chris Lattner7a60d912005-01-07 07:47:53 +0000774void SelectionDAGLowering::visitRet(ReturnInst &I) {
775 if (I.getNumOperands() == 0) {
Chris Lattner4108bb02005-01-17 19:43:36 +0000776 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
Chris Lattner7a60d912005-01-07 07:47:53 +0000777 return;
778 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000779 SmallVector<SDOperand, 8> NewValues;
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000780 NewValues.push_back(getRoot());
781 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
782 SDOperand RetOp = getValue(I.getOperand(i));
783
784 // If this is an integer return value, we need to promote it ourselves to
785 // the full width of a register, since LegalizeOp will use ANY_EXTEND rather
786 // than sign/zero.
Evan Chenga2e99532006-05-26 23:09:09 +0000787 // FIXME: C calling convention requires the return type to be promoted to
788 // at least 32-bit. But this is not necessary for non-C calling conventions.
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000789 if (MVT::isInteger(RetOp.getValueType()) &&
790 RetOp.getValueType() < MVT::i64) {
791 MVT::ValueType TmpVT;
792 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
793 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
794 else
795 TmpVT = MVT::i32;
Reid Spencere63b6512006-12-31 05:55:36 +0000796 const FunctionType *FTy = I.getParent()->getParent()->getFunctionType();
Reid Spencer71b79e32007-04-09 06:17:21 +0000797 const ParamAttrsList *Attrs = FTy->getParamAttrs();
Reid Spencere6f81872007-01-03 16:49:33 +0000798 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
Reid Spencera472f662007-04-11 02:44:20 +0000799 if (Attrs && Attrs->paramHasAttr(0, ParamAttr::SExt))
Reid Spencer0917adf2007-01-03 04:25:33 +0000800 ExtendKind = ISD::SIGN_EXTEND;
Reid Spencera472f662007-04-11 02:44:20 +0000801 if (Attrs && Attrs->paramHasAttr(0, ParamAttr::ZExt))
Reid Spencere63b6512006-12-31 05:55:36 +0000802 ExtendKind = ISD::ZERO_EXTEND;
Reid Spencer2a34b912007-01-03 05:03:05 +0000803 RetOp = DAG.getNode(ExtendKind, TmpVT, RetOp);
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000804 }
805 NewValues.push_back(RetOp);
Reid Spencere63b6512006-12-31 05:55:36 +0000806 NewValues.push_back(DAG.getConstant(false, MVT::i32));
Chris Lattner7a60d912005-01-07 07:47:53 +0000807 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000808 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
809 &NewValues[0], NewValues.size()));
Chris Lattner7a60d912005-01-07 07:47:53 +0000810}
811
Chris Lattnered0110b2006-10-27 21:36:01 +0000812/// ExportFromCurrentBlock - If this condition isn't known to be exported from
813/// the current basic block, add it to ValueMap now so that we'll get a
814/// CopyTo/FromReg.
815void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
816 // No need to export constants.
817 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
818
819 // Already exported?
820 if (FuncInfo.isExportedInst(V)) return;
821
822 unsigned Reg = FuncInfo.InitializeRegForValue(V);
823 PendingLoads.push_back(CopyValueToVirtualRegister(V, Reg));
824}
825
Chris Lattner84a03502006-10-27 23:50:33 +0000826bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
827 const BasicBlock *FromBB) {
828 // The operands of the setcc have to be in this block. We don't know
829 // how to export them from some other block.
830 if (Instruction *VI = dyn_cast<Instruction>(V)) {
831 // Can export from current BB.
832 if (VI->getParent() == FromBB)
833 return true;
834
835 // Is already exported, noop.
836 return FuncInfo.isExportedInst(V);
837 }
838
839 // If this is an argument, we can export it if the BB is the entry block or
840 // if it is already exported.
841 if (isa<Argument>(V)) {
842 if (FromBB == &FromBB->getParent()->getEntryBlock())
843 return true;
844
845 // Otherwise, can only export this if it is already exported.
846 return FuncInfo.isExportedInst(V);
847 }
848
849 // Otherwise, constants can always be exported.
850 return true;
851}
852
Chris Lattnere60ae822006-10-29 21:01:20 +0000853static bool InBlock(const Value *V, const BasicBlock *BB) {
854 if (const Instruction *I = dyn_cast<Instruction>(V))
855 return I->getParent() == BB;
856 return true;
857}
858
Chris Lattnered0110b2006-10-27 21:36:01 +0000859/// FindMergedConditions - If Cond is an expression like
860void SelectionDAGLowering::FindMergedConditions(Value *Cond,
861 MachineBasicBlock *TBB,
862 MachineBasicBlock *FBB,
863 MachineBasicBlock *CurBB,
864 unsigned Opc) {
Chris Lattnered0110b2006-10-27 21:36:01 +0000865 // If this node is not part of the or/and tree, emit it as a branch.
Reid Spencer266e42b2006-12-23 06:05:41 +0000866 Instruction *BOp = dyn_cast<Instruction>(Cond);
Chris Lattnered0110b2006-10-27 21:36:01 +0000867
Reid Spencer266e42b2006-12-23 06:05:41 +0000868 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
869 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
Chris Lattnere60ae822006-10-29 21:01:20 +0000870 BOp->getParent() != CurBB->getBasicBlock() ||
871 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
872 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
Chris Lattnered0110b2006-10-27 21:36:01 +0000873 const BasicBlock *BB = CurBB->getBasicBlock();
874
Reid Spencer266e42b2006-12-23 06:05:41 +0000875 // If the leaf of the tree is a comparison, merge the condition into
876 // the caseblock.
877 if ((isa<ICmpInst>(Cond) || isa<FCmpInst>(Cond)) &&
878 // The operands of the cmp have to be in this block. We don't know
Chris Lattnerf31b9ef2006-10-29 18:23:37 +0000879 // how to export them from some other block. If this is the first block
880 // of the sequence, no exporting is needed.
881 (CurBB == CurMBB ||
882 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
883 isExportableFromCurrentBlock(BOp->getOperand(1), BB)))) {
Reid Spencer266e42b2006-12-23 06:05:41 +0000884 BOp = cast<Instruction>(Cond);
885 ISD::CondCode Condition;
886 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
887 switch (IC->getPredicate()) {
888 default: assert(0 && "Unknown icmp predicate opcode!");
889 case ICmpInst::ICMP_EQ: Condition = ISD::SETEQ; break;
890 case ICmpInst::ICMP_NE: Condition = ISD::SETNE; break;
891 case ICmpInst::ICMP_SLE: Condition = ISD::SETLE; break;
892 case ICmpInst::ICMP_ULE: Condition = ISD::SETULE; break;
893 case ICmpInst::ICMP_SGE: Condition = ISD::SETGE; break;
894 case ICmpInst::ICMP_UGE: Condition = ISD::SETUGE; break;
895 case ICmpInst::ICMP_SLT: Condition = ISD::SETLT; break;
896 case ICmpInst::ICMP_ULT: Condition = ISD::SETULT; break;
897 case ICmpInst::ICMP_SGT: Condition = ISD::SETGT; break;
898 case ICmpInst::ICMP_UGT: Condition = ISD::SETUGT; break;
899 }
900 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
901 ISD::CondCode FPC, FOC;
902 switch (FC->getPredicate()) {
903 default: assert(0 && "Unknown fcmp predicate opcode!");
904 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
905 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
906 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
907 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
908 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
909 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
910 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
911 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
912 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
913 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
914 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
915 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
916 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
917 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
918 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
919 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
920 }
921 if (FiniteOnlyFPMath())
922 Condition = FOC;
923 else
924 Condition = FPC;
925 } else {
Chris Lattner79084302007-02-04 01:31:47 +0000926 Condition = ISD::SETEQ; // silence warning.
Reid Spencer266e42b2006-12-23 06:05:41 +0000927 assert(0 && "Unknown compare instruction");
Chris Lattnered0110b2006-10-27 21:36:01 +0000928 }
929
Chris Lattnered0110b2006-10-27 21:36:01 +0000930 SelectionDAGISel::CaseBlock CB(Condition, BOp->getOperand(0),
Anton Korobeynikov915e6172007-04-04 21:14:49 +0000931 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
Chris Lattnered0110b2006-10-27 21:36:01 +0000932 SwitchCases.push_back(CB);
933 return;
934 }
935
936 // Create a CaseBlock record representing this branch.
Zhou Sheng75b871f2007-01-11 12:24:14 +0000937 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
Anton Korobeynikov915e6172007-04-04 21:14:49 +0000938 NULL, TBB, FBB, CurBB);
Chris Lattnered0110b2006-10-27 21:36:01 +0000939 SwitchCases.push_back(CB);
Chris Lattnered0110b2006-10-27 21:36:01 +0000940 return;
941 }
942
Chris Lattnerf1b54fd2006-10-27 21:54:23 +0000943
944 // Create TmpBB after CurBB.
Chris Lattnered0110b2006-10-27 21:36:01 +0000945 MachineFunction::iterator BBI = CurBB;
946 MachineBasicBlock *TmpBB = new MachineBasicBlock(CurBB->getBasicBlock());
947 CurBB->getParent()->getBasicBlockList().insert(++BBI, TmpBB);
948
Chris Lattnerf1b54fd2006-10-27 21:54:23 +0000949 if (Opc == Instruction::Or) {
950 // Codegen X | Y as:
951 // jmp_if_X TBB
952 // jmp TmpBB
953 // TmpBB:
954 // jmp_if_Y TBB
955 // jmp FBB
956 //
Chris Lattnered0110b2006-10-27 21:36:01 +0000957
Chris Lattnerf1b54fd2006-10-27 21:54:23 +0000958 // Emit the LHS condition.
959 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
960
961 // Emit the RHS condition into TmpBB.
962 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
963 } else {
964 assert(Opc == Instruction::And && "Unknown merge op!");
965 // Codegen X & Y as:
966 // jmp_if_X TmpBB
967 // jmp FBB
968 // TmpBB:
969 // jmp_if_Y TBB
970 // jmp FBB
971 //
972 // This requires creation of TmpBB after CurBB.
973
974 // Emit the LHS condition.
975 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
976
977 // Emit the RHS condition into TmpBB.
978 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
979 }
Chris Lattnered0110b2006-10-27 21:36:01 +0000980}
981
Chris Lattner427301f2006-10-31 22:37:42 +0000982/// If the set of cases should be emitted as a series of branches, return true.
983/// If we should emit this as a bunch of and/or'd together conditions, return
984/// false.
985static bool
986ShouldEmitAsBranches(const std::vector<SelectionDAGISel::CaseBlock> &Cases) {
987 if (Cases.size() != 2) return true;
988
Chris Lattnerfe43bef2006-10-31 23:06:00 +0000989 // If this is two comparisons of the same values or'd or and'd together, they
990 // will get folded into a single comparison, so don't emit two blocks.
991 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
992 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
993 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
994 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
995 return false;
996 }
997
Chris Lattner427301f2006-10-31 22:37:42 +0000998 return true;
999}
1000
Chris Lattner7a60d912005-01-07 07:47:53 +00001001void SelectionDAGLowering::visitBr(BranchInst &I) {
1002 // Update machine-CFG edges.
1003 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner7a60d912005-01-07 07:47:53 +00001004
1005 // Figure out which block is immediately after the current one.
1006 MachineBasicBlock *NextBlock = 0;
1007 MachineFunction::iterator BBI = CurMBB;
1008 if (++BBI != CurMBB->getParent()->end())
1009 NextBlock = BBI;
1010
1011 if (I.isUnconditional()) {
1012 // If this is not a fall-through branch, emit the branch.
1013 if (Succ0MBB != NextBlock)
Chris Lattner4108bb02005-01-17 19:43:36 +00001014 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +00001015 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +00001016
Chris Lattner963ddad2006-10-24 17:57:59 +00001017 // Update machine-CFG edges.
1018 CurMBB->addSuccessor(Succ0MBB);
1019
1020 return;
1021 }
1022
1023 // If this condition is one of the special cases we handle, do special stuff
1024 // now.
1025 Value *CondVal = I.getCondition();
Chris Lattner963ddad2006-10-24 17:57:59 +00001026 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattnered0110b2006-10-27 21:36:01 +00001027
1028 // If this is a series of conditions that are or'd or and'd together, emit
1029 // this as a sequence of branches instead of setcc's with and/or operations.
1030 // For example, instead of something like:
1031 // cmp A, B
1032 // C = seteq
1033 // cmp D, E
1034 // F = setle
1035 // or C, F
1036 // jnz foo
1037 // Emit:
1038 // cmp A, B
1039 // je foo
1040 // cmp D, E
1041 // jle foo
1042 //
1043 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1044 if (BOp->hasOneUse() &&
Chris Lattnerf1b54fd2006-10-27 21:54:23 +00001045 (BOp->getOpcode() == Instruction::And ||
Chris Lattnered0110b2006-10-27 21:36:01 +00001046 BOp->getOpcode() == Instruction::Or)) {
1047 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
Chris Lattnerfe43bef2006-10-31 23:06:00 +00001048 // If the compares in later blocks need to use values not currently
1049 // exported from this block, export them now. This block should always
1050 // be the first entry.
1051 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1052
Chris Lattner427301f2006-10-31 22:37:42 +00001053 // Allow some cases to be rejected.
1054 if (ShouldEmitAsBranches(SwitchCases)) {
Chris Lattner427301f2006-10-31 22:37:42 +00001055 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1056 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1057 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1058 }
1059
1060 // Emit the branch for this block.
1061 visitSwitchCase(SwitchCases[0]);
1062 SwitchCases.erase(SwitchCases.begin());
1063 return;
Chris Lattnerf31b9ef2006-10-29 18:23:37 +00001064 }
1065
Chris Lattnerfe43bef2006-10-31 23:06:00 +00001066 // Okay, we decided not to do this, remove any inserted MBB's and clear
1067 // SwitchCases.
1068 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1069 CurMBB->getParent()->getBasicBlockList().erase(SwitchCases[i].ThisBB);
1070
Chris Lattner427301f2006-10-31 22:37:42 +00001071 SwitchCases.clear();
Chris Lattnered0110b2006-10-27 21:36:01 +00001072 }
1073 }
Chris Lattner61bcf912006-10-24 18:07:37 +00001074
1075 // Create a CaseBlock record representing this branch.
Zhou Sheng75b871f2007-01-11 12:24:14 +00001076 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001077 NULL, Succ0MBB, Succ1MBB, CurMBB);
Chris Lattner61bcf912006-10-24 18:07:37 +00001078 // Use visitSwitchCase to actually insert the fast branch sequence for this
1079 // cond branch.
1080 visitSwitchCase(CB);
Chris Lattner7a60d912005-01-07 07:47:53 +00001081}
1082
Nate Begemaned728c12006-03-27 01:32:24 +00001083/// visitSwitchCase - Emits the necessary code to represent a single node in
1084/// the binary search tree resulting from lowering a switch instruction.
1085void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
Chris Lattner963ddad2006-10-24 17:57:59 +00001086 SDOperand Cond;
1087 SDOperand CondLHS = getValue(CB.CmpLHS);
1088
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001089 // Build the setcc now.
1090 if (CB.CmpMHS == NULL) {
1091 // Fold "(X == true)" to X and "(X == false)" to !X to
1092 // handle common cases produced by branch lowering.
1093 if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
1094 Cond = CondLHS;
1095 else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
1096 SDOperand True = DAG.getConstant(1, CondLHS.getValueType());
1097 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1098 } else
1099 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1100 } else {
1101 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
Anton Korobeynikov70378262007-03-25 15:07:15 +00001102
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001103 uint64_t Low = cast<ConstantInt>(CB.CmpLHS)->getSExtValue();
1104 uint64_t High = cast<ConstantInt>(CB.CmpRHS)->getSExtValue();
1105
1106 SDOperand CmpOp = getValue(CB.CmpMHS);
1107 MVT::ValueType VT = CmpOp.getValueType();
1108
1109 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1110 Cond = DAG.getSetCC(MVT::i1, CmpOp, DAG.getConstant(High, VT), ISD::SETLE);
1111 } else {
1112 SDOperand SUB = DAG.getNode(ISD::SUB, VT, CmpOp, DAG.getConstant(Low, VT));
1113 Cond = DAG.getSetCC(MVT::i1, SUB,
1114 DAG.getConstant(High-Low, VT), ISD::SETULE);
1115 }
1116
1117 }
1118
Nate Begemaned728c12006-03-27 01:32:24 +00001119 // Set NextBlock to be the MBB immediately after the current one, if any.
1120 // This is used to avoid emitting unnecessary branches to the next block.
1121 MachineBasicBlock *NextBlock = 0;
1122 MachineFunction::iterator BBI = CurMBB;
1123 if (++BBI != CurMBB->getParent()->end())
1124 NextBlock = BBI;
1125
1126 // If the lhs block is the next block, invert the condition so that we can
1127 // fall through to the lhs instead of the rhs block.
Chris Lattner963ddad2006-10-24 17:57:59 +00001128 if (CB.TrueBB == NextBlock) {
1129 std::swap(CB.TrueBB, CB.FalseBB);
Nate Begemaned728c12006-03-27 01:32:24 +00001130 SDOperand True = DAG.getConstant(1, Cond.getValueType());
1131 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1132 }
1133 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
Chris Lattner963ddad2006-10-24 17:57:59 +00001134 DAG.getBasicBlock(CB.TrueBB));
1135 if (CB.FalseBB == NextBlock)
Nate Begemaned728c12006-03-27 01:32:24 +00001136 DAG.setRoot(BrCond);
1137 else
1138 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
Chris Lattner963ddad2006-10-24 17:57:59 +00001139 DAG.getBasicBlock(CB.FalseBB)));
Nate Begemaned728c12006-03-27 01:32:24 +00001140 // Update successor info
Chris Lattner963ddad2006-10-24 17:57:59 +00001141 CurMBB->addSuccessor(CB.TrueBB);
1142 CurMBB->addSuccessor(CB.FalseBB);
Nate Begemaned728c12006-03-27 01:32:24 +00001143}
1144
Anton Korobeynikov70378262007-03-25 15:07:15 +00001145/// visitJumpTable - Emit JumpTable node in the current MBB
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001146void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001147 // Emit the code for the jump table
Scott Michel4cfa6162007-04-24 01:24:20 +00001148 assert(JT.Reg != -1U && "Should lower JT Header first!");
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001149 MVT::ValueType PTy = TLI.getPointerTy();
Evan Cheng84a28d42006-10-30 08:00:44 +00001150 SDOperand Index = DAG.getCopyFromReg(getRoot(), JT.Reg, PTy);
1151 SDOperand Table = DAG.getJumpTable(JT.JTI, PTy);
1152 DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1153 Table, Index));
1154 return;
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001155}
1156
Anton Korobeynikov70378262007-03-25 15:07:15 +00001157/// visitJumpTableHeader - This function emits necessary code to produce index
1158/// in the JumpTable from switch case.
1159void SelectionDAGLowering::visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
1160 SelectionDAGISel::JumpTableHeader &JTH) {
1161 // Subtract the lowest switch case value from the value being switched on
1162 // and conditional branch to default mbb if the result is greater than the
1163 // difference between smallest and largest cases.
1164 SDOperand SwitchOp = getValue(JTH.SValue);
1165 MVT::ValueType VT = SwitchOp.getValueType();
1166 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1167 DAG.getConstant(JTH.First, VT));
1168
1169 // The SDNode we just created, which holds the value being switched on
1170 // minus the the smallest case value, needs to be copied to a virtual
1171 // register so it can be used as an index into the jump table in a
1172 // subsequent basic block. This value may be smaller or larger than the
1173 // target's pointer type, and therefore require extension or truncating.
Dan Gohmana8665142007-06-25 16:23:39 +00001174 if (MVT::getSizeInBits(VT) > MVT::getSizeInBits(TLI.getPointerTy()))
Anton Korobeynikov70378262007-03-25 15:07:15 +00001175 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1176 else
1177 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
1178
1179 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1180 SDOperand CopyTo = DAG.getCopyToReg(getRoot(), JumpTableReg, SwitchOp);
1181 JT.Reg = JumpTableReg;
1182
1183 // Emit the range check for the jump table, and branch to the default
1184 // block for the switch statement if the value being switched on exceeds
1185 // the largest case in the switch.
1186 SDOperand CMP = DAG.getSetCC(TLI.getSetCCResultTy(), SUB,
1187 DAG.getConstant(JTH.Last-JTH.First,VT),
1188 ISD::SETUGT);
1189
1190 // Set NextBlock to be the MBB immediately after the current one, if any.
1191 // This is used to avoid emitting unnecessary branches to the next block.
1192 MachineBasicBlock *NextBlock = 0;
1193 MachineFunction::iterator BBI = CurMBB;
1194 if (++BBI != CurMBB->getParent()->end())
1195 NextBlock = BBI;
1196
1197 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
1198 DAG.getBasicBlock(JT.Default));
1199
1200 if (JT.MBB == NextBlock)
1201 DAG.setRoot(BrCond);
1202 else
1203 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001204 DAG.getBasicBlock(JT.MBB)));
1205
1206 return;
Anton Korobeynikov70378262007-03-25 15:07:15 +00001207}
1208
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001209/// visitBitTestHeader - This function emits necessary code to produce value
1210/// suitable for "bit tests"
1211void SelectionDAGLowering::visitBitTestHeader(SelectionDAGISel::BitTestBlock &B) {
1212 // Subtract the minimum value
1213 SDOperand SwitchOp = getValue(B.SValue);
1214 MVT::ValueType VT = SwitchOp.getValueType();
1215 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1216 DAG.getConstant(B.First, VT));
1217
1218 // Check range
1219 SDOperand RangeCmp = DAG.getSetCC(TLI.getSetCCResultTy(), SUB,
1220 DAG.getConstant(B.Range, VT),
1221 ISD::SETUGT);
1222
1223 SDOperand ShiftOp;
Dan Gohmana8665142007-06-25 16:23:39 +00001224 if (MVT::getSizeInBits(VT) > MVT::getSizeInBits(TLI.getShiftAmountTy()))
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001225 ShiftOp = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), SUB);
1226 else
1227 ShiftOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getShiftAmountTy(), SUB);
1228
1229 // Make desired shift
1230 SDOperand SwitchVal = DAG.getNode(ISD::SHL, TLI.getPointerTy(),
1231 DAG.getConstant(1, TLI.getPointerTy()),
1232 ShiftOp);
1233
1234 unsigned SwitchReg = FuncInfo.MakeReg(TLI.getPointerTy());
1235 SDOperand CopyTo = DAG.getCopyToReg(getRoot(), SwitchReg, SwitchVal);
1236 B.Reg = SwitchReg;
1237
1238 SDOperand BrRange = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, RangeCmp,
1239 DAG.getBasicBlock(B.Default));
1240
1241 // Set NextBlock to be the MBB immediately after the current one, if any.
1242 // This is used to avoid emitting unnecessary branches to the next block.
1243 MachineBasicBlock *NextBlock = 0;
1244 MachineFunction::iterator BBI = CurMBB;
1245 if (++BBI != CurMBB->getParent()->end())
1246 NextBlock = BBI;
1247
1248 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1249 if (MBB == NextBlock)
1250 DAG.setRoot(BrRange);
1251 else
1252 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, CopyTo,
1253 DAG.getBasicBlock(MBB)));
1254
1255 CurMBB->addSuccessor(B.Default);
1256 CurMBB->addSuccessor(MBB);
1257
1258 return;
1259}
1260
1261/// visitBitTestCase - this function produces one "bit test"
1262void SelectionDAGLowering::visitBitTestCase(MachineBasicBlock* NextMBB,
1263 unsigned Reg,
1264 SelectionDAGISel::BitTestCase &B) {
1265 // Emit bit tests and jumps
1266 SDOperand SwitchVal = DAG.getCopyFromReg(getRoot(), Reg, TLI.getPointerTy());
1267
1268 SDOperand AndOp = DAG.getNode(ISD::AND, TLI.getPointerTy(),
1269 SwitchVal,
1270 DAG.getConstant(B.Mask,
1271 TLI.getPointerTy()));
1272 SDOperand AndCmp = DAG.getSetCC(TLI.getSetCCResultTy(), AndOp,
1273 DAG.getConstant(0, TLI.getPointerTy()),
1274 ISD::SETNE);
1275 SDOperand BrAnd = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
1276 AndCmp, DAG.getBasicBlock(B.TargetBB));
1277
1278 // Set NextBlock to be the MBB immediately after the current one, if any.
1279 // This is used to avoid emitting unnecessary branches to the next block.
1280 MachineBasicBlock *NextBlock = 0;
1281 MachineFunction::iterator BBI = CurMBB;
1282 if (++BBI != CurMBB->getParent()->end())
1283 NextBlock = BBI;
1284
1285 if (NextMBB == NextBlock)
1286 DAG.setRoot(BrAnd);
1287 else
1288 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrAnd,
1289 DAG.getBasicBlock(NextMBB)));
1290
1291 CurMBB->addSuccessor(B.TargetBB);
1292 CurMBB->addSuccessor(NextMBB);
1293
1294 return;
1295}
Anton Korobeynikov70378262007-03-25 15:07:15 +00001296
Jim Laskey4b37a4c2007-02-21 22:53:45 +00001297void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
1298 // Retrieve successors.
1299 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
Duncan Sands97f72362007-06-13 05:51:31 +00001300 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
Duncan Sands61166502007-06-06 10:05:18 +00001301
Duncan Sands97f72362007-06-13 05:51:31 +00001302 LowerCallTo(I, I.getCalledValue()->getType(),
1303 I.getCallingConv(),
1304 false,
1305 getValue(I.getOperand(0)),
1306 3, LandingPad);
Duncan Sands61166502007-06-06 10:05:18 +00001307
Duncan Sands97f72362007-06-13 05:51:31 +00001308 // If the value of the invoke is used outside of its defining block, make it
1309 // available as a virtual register.
1310 if (!I.use_empty()) {
1311 DenseMap<const Value*, unsigned>::iterator VMI = FuncInfo.ValueMap.find(&I);
1312 if (VMI != FuncInfo.ValueMap.end())
1313 DAG.setRoot(CopyValueToVirtualRegister(&I, VMI->second));
Jim Laskey14059d92007-02-25 21:43:59 +00001314 }
Duncan Sands97f72362007-06-13 05:51:31 +00001315
1316 // Drop into normal successor.
1317 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
1318 DAG.getBasicBlock(Return)));
1319
1320 // Update successor info
1321 CurMBB->addSuccessor(Return);
1322 CurMBB->addSuccessor(LandingPad);
Jim Laskey4b37a4c2007-02-21 22:53:45 +00001323}
1324
1325void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1326}
1327
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001328/// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001329/// small case ranges).
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001330bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR,
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001331 CaseRecVector& WorkList,
1332 Value* SV,
1333 MachineBasicBlock* Default) {
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001334 Case& BackCase = *(CR.Range.second-1);
1335
1336 // Size is the number of Cases represented by this range.
1337 unsigned Size = CR.Range.second - CR.Range.first;
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001338 if (Size > 3)
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001339 return false;
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001340
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001341 // Get the MachineFunction which holds the current MBB. This is used when
1342 // inserting any additional MBBs necessary to represent the switch.
1343 MachineFunction *CurMF = CurMBB->getParent();
1344
1345 // Figure out which block is immediately after the current one.
1346 MachineBasicBlock *NextBlock = 0;
1347 MachineFunction::iterator BBI = CR.CaseBB;
1348
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001349 if (++BBI != CurMBB->getParent()->end())
1350 NextBlock = BBI;
1351
1352 // TODO: If any two of the cases has the same destination, and if one value
1353 // is the same as the other, but has one bit unset that the other has set,
1354 // use bit manipulation to do two compares at once. For example:
1355 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1356
1357 // Rearrange the case blocks so that the last one falls through if possible.
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001358 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001359 // The last case block won't fall through into 'NextBlock' if we emit the
1360 // branches in this order. See if rearranging a case value would help.
1361 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001362 if (I->BB == NextBlock) {
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001363 std::swap(*I, BackCase);
1364 break;
1365 }
1366 }
1367 }
1368
1369 // Create a CaseBlock record representing a conditional branch to
1370 // the Case's target mbb if the value being switched on SV is equal
1371 // to C.
1372 MachineBasicBlock *CurBlock = CR.CaseBB;
1373 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1374 MachineBasicBlock *FallThrough;
1375 if (I != E-1) {
1376 FallThrough = new MachineBasicBlock(CurBlock->getBasicBlock());
1377 CurMF->getBasicBlockList().insert(BBI, FallThrough);
1378 } else {
1379 // If the last case doesn't match, go to the default block.
1380 FallThrough = Default;
1381 }
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001382
1383 Value *RHS, *LHS, *MHS;
1384 ISD::CondCode CC;
1385 if (I->High == I->Low) {
1386 // This is just small small case range :) containing exactly 1 case
1387 CC = ISD::SETEQ;
1388 LHS = SV; RHS = I->High; MHS = NULL;
1389 } else {
1390 CC = ISD::SETLE;
1391 LHS = I->Low; MHS = SV; RHS = I->High;
1392 }
1393 SelectionDAGISel::CaseBlock CB(CC, LHS, RHS, MHS,
1394 I->BB, FallThrough, CurBlock);
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001395
1396 // If emitting the first comparison, just call visitSwitchCase to emit the
1397 // code into the current block. Otherwise, push the CaseBlock onto the
1398 // vector to be later processed by SDISel, and insert the node's MBB
1399 // before the next MBB.
1400 if (CurBlock == CurMBB)
1401 visitSwitchCase(CB);
1402 else
1403 SwitchCases.push_back(CB);
1404
1405 CurBlock = FallThrough;
1406 }
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001407
1408 return true;
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001409}
1410
Anton Korobeynikov192d09c2007-05-09 20:07:08 +00001411static inline bool areJTsAllowed(const TargetLowering &TLI) {
1412 return (TLI.isOperationLegal(ISD::BR_JT, MVT::Other) ||
1413 TLI.isOperationLegal(ISD::BRIND, MVT::Other));
1414}
1415
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001416/// handleJTSwitchCase - Emit jumptable for current switch case range
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001417bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR,
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001418 CaseRecVector& WorkList,
1419 Value* SV,
1420 MachineBasicBlock* Default) {
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001421 Case& FrontCase = *CR.Range.first;
1422 Case& BackCase = *(CR.Range.second-1);
1423
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001424 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1425 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
1426
1427 uint64_t TSize = 0;
1428 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1429 I!=E; ++I)
1430 TSize += I->size();
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001431
Anton Korobeynikov192d09c2007-05-09 20:07:08 +00001432 if (!areJTsAllowed(TLI) || TSize <= 3)
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001433 return false;
1434
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001435 double Density = (double)TSize / (double)((Last - First) + 1ULL);
1436 if (Density < 0.4)
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001437 return false;
1438
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001439 DOUT << "Lowering jump table\n"
1440 << "First entry: " << First << ". Last entry: " << Last << "\n"
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001441 << "Size: " << TSize << ". Density: " << Density << "\n\n";
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001442
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001443 // Get the MachineFunction which holds the current MBB. This is used when
1444 // inserting any additional MBBs necessary to represent the switch.
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001445 MachineFunction *CurMF = CurMBB->getParent();
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001446
1447 // Figure out which block is immediately after the current one.
1448 MachineBasicBlock *NextBlock = 0;
1449 MachineFunction::iterator BBI = CR.CaseBB;
1450
1451 if (++BBI != CurMBB->getParent()->end())
1452 NextBlock = BBI;
1453
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001454 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1455
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001456 // Create a new basic block to hold the code for loading the address
1457 // of the jump table, and jumping to it. Update successor information;
1458 // we will either branch to the default case for the switch, or the jump
1459 // table.
1460 MachineBasicBlock *JumpTableBB = new MachineBasicBlock(LLVMBB);
1461 CurMF->getBasicBlockList().insert(BBI, JumpTableBB);
1462 CR.CaseBB->addSuccessor(Default);
1463 CR.CaseBB->addSuccessor(JumpTableBB);
1464
1465 // Build a vector of destination BBs, corresponding to each target
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001466 // of the jump table. If the value of the jump table slot corresponds to
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001467 // a case statement, push the case's BB onto the vector, otherwise, push
1468 // the default BB.
1469 std::vector<MachineBasicBlock*> DestBBs;
1470 int64_t TEI = First;
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001471 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
1472 int64_t Low = cast<ConstantInt>(I->Low)->getSExtValue();
1473 int64_t High = cast<ConstantInt>(I->High)->getSExtValue();
1474
1475 if ((Low <= TEI) && (TEI <= High)) {
1476 DestBBs.push_back(I->BB);
1477 if (TEI==High)
1478 ++I;
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001479 } else {
1480 DestBBs.push_back(Default);
1481 }
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001482 }
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001483
1484 // Update successor info. Add one edge to each unique successor.
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001485 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001486 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
1487 E = DestBBs.end(); I != E; ++I) {
1488 if (!SuccsHandled[(*I)->getNumber()]) {
1489 SuccsHandled[(*I)->getNumber()] = true;
1490 JumpTableBB->addSuccessor(*I);
1491 }
1492 }
1493
1494 // Create a jump table index for this jump table, or return an existing
1495 // one.
1496 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1497
1498 // Set the jump table information so that we can codegen it as a second
1499 // MachineBasicBlock
Scott Michel4cfa6162007-04-24 01:24:20 +00001500 SelectionDAGISel::JumpTable JT(-1U, JTI, JumpTableBB, Default);
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001501 SelectionDAGISel::JumpTableHeader JTH(First, Last, SV, CR.CaseBB,
1502 (CR.CaseBB == CurMBB));
1503 if (CR.CaseBB == CurMBB)
1504 visitJumpTableHeader(JT, JTH);
1505
1506 JTCases.push_back(SelectionDAGISel::JumpTableBlock(JTH, JT));
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001507
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001508 return true;
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001509}
1510
1511/// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1512/// 2 subtrees.
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001513bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR,
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001514 CaseRecVector& WorkList,
1515 Value* SV,
1516 MachineBasicBlock* Default) {
1517 // Get the MachineFunction which holds the current MBB. This is used when
1518 // inserting any additional MBBs necessary to represent the switch.
1519 MachineFunction *CurMF = CurMBB->getParent();
1520
1521 // Figure out which block is immediately after the current one.
1522 MachineBasicBlock *NextBlock = 0;
1523 MachineFunction::iterator BBI = CR.CaseBB;
1524
1525 if (++BBI != CurMBB->getParent()->end())
1526 NextBlock = BBI;
1527
1528 Case& FrontCase = *CR.Range.first;
1529 Case& BackCase = *(CR.Range.second-1);
1530 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1531
1532 // Size is the number of Cases represented by this range.
1533 unsigned Size = CR.Range.second - CR.Range.first;
1534
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001535 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1536 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001537 double FMetric = 0;
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001538 CaseItr Pivot = CR.Range.first + Size/2;
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001539
1540 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
1541 // (heuristically) allow us to emit JumpTable's later.
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001542 uint64_t TSize = 0;
1543 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1544 I!=E; ++I)
1545 TSize += I->size();
1546
1547 uint64_t LSize = FrontCase.size();
1548 uint64_t RSize = TSize-LSize;
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001549 DOUT << "Selecting best pivot: \n"
1550 << "First: " << First << ", Last: " << Last <<"\n"
1551 << "LSize: " << LSize << ", RSize: " << RSize << "\n";
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001552 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001553 J!=E; ++I, ++J) {
1554 int64_t LEnd = cast<ConstantInt>(I->High)->getSExtValue();
1555 int64_t RBegin = cast<ConstantInt>(J->Low)->getSExtValue();
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001556 assert((RBegin-LEnd>=1) && "Invalid case distance");
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001557 double LDensity = (double)LSize / (double)((LEnd - First) + 1ULL);
1558 double RDensity = (double)RSize / (double)((Last - RBegin) + 1ULL);
Anton Korobeynikovda964a22007-04-09 21:57:03 +00001559 double Metric = Log2_64(RBegin-LEnd)*(LDensity+RDensity);
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001560 // Should always split in some non-trivial place
1561 DOUT <<"=>Step\n"
1562 << "LEnd: " << LEnd << ", RBegin: " << RBegin << "\n"
1563 << "LDensity: " << LDensity << ", RDensity: " << RDensity << "\n"
1564 << "Metric: " << Metric << "\n";
1565 if (FMetric < Metric) {
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001566 Pivot = J;
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001567 FMetric = Metric;
1568 DOUT << "Current metric set to: " << FMetric << "\n";
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001569 }
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001570
1571 LSize += J->size();
1572 RSize -= J->size();
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001573 }
Anton Korobeynikov192d09c2007-05-09 20:07:08 +00001574 if (areJTsAllowed(TLI)) {
1575 // If our case is dense we *really* should handle it earlier!
1576 assert((FMetric > 0) && "Should handle dense range earlier!");
1577 } else {
1578 Pivot = CR.Range.first + Size/2;
1579 }
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001580
1581 CaseRange LHSR(CR.Range.first, Pivot);
1582 CaseRange RHSR(Pivot, CR.Range.second);
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001583 Constant *C = Pivot->Low;
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001584 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
1585
1586 // We know that we branch to the LHS if the Value being switched on is
1587 // less than the Pivot value, C. We use this to optimize our binary
1588 // tree a bit, by recognizing that if SV is greater than or equal to the
1589 // LHS's Case Value, and that Case Value is exactly one less than the
1590 // Pivot's Value, then we can branch directly to the LHS's Target,
1591 // rather than creating a leaf node for it.
1592 if ((LHSR.second - LHSR.first) == 1 &&
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001593 LHSR.first->High == CR.GE &&
1594 cast<ConstantInt>(C)->getSExtValue() ==
1595 (cast<ConstantInt>(CR.GE)->getSExtValue() + 1LL)) {
1596 TrueBB = LHSR.first->BB;
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001597 } else {
1598 TrueBB = new MachineBasicBlock(LLVMBB);
1599 CurMF->getBasicBlockList().insert(BBI, TrueBB);
1600 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
1601 }
1602
1603 // Similar to the optimization above, if the Value being switched on is
1604 // known to be less than the Constant CR.LT, and the current Case Value
1605 // is CR.LT - 1, then we can branch directly to the target block for
1606 // the current Case Value, rather than emitting a RHS leaf node for it.
1607 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001608 cast<ConstantInt>(RHSR.first->Low)->getSExtValue() ==
1609 (cast<ConstantInt>(CR.LT)->getSExtValue() - 1LL)) {
1610 FalseBB = RHSR.first->BB;
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001611 } else {
1612 FalseBB = new MachineBasicBlock(LLVMBB);
1613 CurMF->getBasicBlockList().insert(BBI, FalseBB);
1614 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
1615 }
1616
1617 // Create a CaseBlock record representing a conditional branch to
1618 // the LHS node if the value being switched on SV is less than C.
1619 // Otherwise, branch to LHS.
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001620 SelectionDAGISel::CaseBlock CB(ISD::SETLT, SV, C, NULL,
1621 TrueBB, FalseBB, CR.CaseBB);
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001622
1623 if (CR.CaseBB == CurMBB)
1624 visitSwitchCase(CB);
1625 else
1626 SwitchCases.push_back(CB);
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001627
1628 return true;
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001629}
1630
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001631/// handleBitTestsSwitchCase - if current case range has few destination and
1632/// range span less, than machine word bitwidth, encode case range into series
1633/// of masks and emit bit tests with these masks.
1634bool SelectionDAGLowering::handleBitTestsSwitchCase(CaseRec& CR,
1635 CaseRecVector& WorkList,
1636 Value* SV,
Chris Lattner7196f092007-04-14 02:26:56 +00001637 MachineBasicBlock* Default){
Dan Gohman1796f1f2007-05-18 17:52:13 +00001638 unsigned IntPtrBits = MVT::getSizeInBits(TLI.getPointerTy());
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001639
1640 Case& FrontCase = *CR.Range.first;
1641 Case& BackCase = *(CR.Range.second-1);
1642
1643 // Get the MachineFunction which holds the current MBB. This is used when
1644 // inserting any additional MBBs necessary to represent the switch.
1645 MachineFunction *CurMF = CurMBB->getParent();
1646
1647 unsigned numCmps = 0;
1648 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1649 I!=E; ++I) {
1650 // Single case counts one, case range - two.
1651 if (I->Low == I->High)
1652 numCmps +=1;
1653 else
1654 numCmps +=2;
1655 }
1656
1657 // Count unique destinations
1658 SmallSet<MachineBasicBlock*, 4> Dests;
1659 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1660 Dests.insert(I->BB);
1661 if (Dests.size() > 3)
1662 // Don't bother the code below, if there are too much unique destinations
1663 return false;
1664 }
1665 DOUT << "Total number of unique destinations: " << Dests.size() << "\n"
1666 << "Total number of comparisons: " << numCmps << "\n";
1667
1668 // Compute span of values.
1669 Constant* minValue = FrontCase.Low;
1670 Constant* maxValue = BackCase.High;
1671 uint64_t range = cast<ConstantInt>(maxValue)->getSExtValue() -
1672 cast<ConstantInt>(minValue)->getSExtValue();
1673 DOUT << "Compare range: " << range << "\n"
1674 << "Low bound: " << cast<ConstantInt>(minValue)->getSExtValue() << "\n"
1675 << "High bound: " << cast<ConstantInt>(maxValue)->getSExtValue() << "\n";
1676
Anton Korobeynikovd7ae7f12007-04-26 20:44:04 +00001677 if (range>=IntPtrBits ||
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001678 (!(Dests.size() == 1 && numCmps >= 3) &&
1679 !(Dests.size() == 2 && numCmps >= 5) &&
1680 !(Dests.size() >= 3 && numCmps >= 6)))
1681 return false;
1682
1683 DOUT << "Emitting bit tests\n";
1684 int64_t lowBound = 0;
1685
1686 // Optimize the case where all the case values fit in a
1687 // word without having to subtract minValue. In this case,
1688 // we can optimize away the subtraction.
1689 if (cast<ConstantInt>(minValue)->getSExtValue() >= 0 &&
Anton Korobeynikov8a1a84f2007-04-14 13:25:55 +00001690 cast<ConstantInt>(maxValue)->getSExtValue() < IntPtrBits) {
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001691 range = cast<ConstantInt>(maxValue)->getSExtValue();
1692 } else {
1693 lowBound = cast<ConstantInt>(minValue)->getSExtValue();
1694 }
1695
1696 CaseBitsVector CasesBits;
1697 unsigned i, count = 0;
1698
1699 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1700 MachineBasicBlock* Dest = I->BB;
1701 for (i = 0; i < count; ++i)
1702 if (Dest == CasesBits[i].BB)
1703 break;
1704
1705 if (i == count) {
1706 assert((count < 3) && "Too much destinations to test!");
1707 CasesBits.push_back(CaseBits(0, Dest, 0));
1708 count++;
1709 }
1710
1711 uint64_t lo = cast<ConstantInt>(I->Low)->getSExtValue() - lowBound;
1712 uint64_t hi = cast<ConstantInt>(I->High)->getSExtValue() - lowBound;
1713
1714 for (uint64_t j = lo; j <= hi; j++) {
Anton Korobeynikov8a1a84f2007-04-14 13:25:55 +00001715 CasesBits[i].Mask |= 1ULL << j;
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001716 CasesBits[i].Bits++;
1717 }
1718
1719 }
1720 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
1721
1722 SelectionDAGISel::BitTestInfo BTC;
1723
1724 // Figure out which block is immediately after the current one.
1725 MachineFunction::iterator BBI = CR.CaseBB;
1726 ++BBI;
1727
1728 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1729
1730 DOUT << "Cases:\n";
1731 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
1732 DOUT << "Mask: " << CasesBits[i].Mask << ", Bits: " << CasesBits[i].Bits
1733 << ", BB: " << CasesBits[i].BB << "\n";
1734
1735 MachineBasicBlock *CaseBB = new MachineBasicBlock(LLVMBB);
1736 CurMF->getBasicBlockList().insert(BBI, CaseBB);
1737 BTC.push_back(SelectionDAGISel::BitTestCase(CasesBits[i].Mask,
1738 CaseBB,
1739 CasesBits[i].BB));
1740 }
1741
1742 SelectionDAGISel::BitTestBlock BTB(lowBound, range, SV,
Jeff Cohen0475f3b2007-04-09 14:32:59 +00001743 -1U, (CR.CaseBB == CurMBB),
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001744 CR.CaseBB, Default, BTC);
1745
1746 if (CR.CaseBB == CurMBB)
1747 visitBitTestHeader(BTB);
1748
1749 BitTestCases.push_back(BTB);
1750
1751 return true;
1752}
1753
1754
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001755// Clusterify - Transform simple list of Cases into list of CaseRange's
1756unsigned SelectionDAGLowering::Clusterify(CaseVector& Cases,
1757 const SwitchInst& SI) {
1758 unsigned numCmps = 0;
1759
1760 // Start with "simple" cases
1761 for (unsigned i = 1; i < SI.getNumSuccessors(); ++i) {
1762 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
1763 Cases.push_back(Case(SI.getSuccessorValue(i),
1764 SI.getSuccessorValue(i),
1765 SMBB));
1766 }
1767 sort(Cases.begin(), Cases.end(), CaseCmp());
1768
1769 // Merge case into clusters
1770 if (Cases.size()>=2)
1771 for (CaseItr I=Cases.begin(), J=++(Cases.begin()), E=Cases.end(); J!=E; ) {
1772 int64_t nextValue = cast<ConstantInt>(J->Low)->getSExtValue();
1773 int64_t currentValue = cast<ConstantInt>(I->High)->getSExtValue();
1774 MachineBasicBlock* nextBB = J->BB;
1775 MachineBasicBlock* currentBB = I->BB;
1776
1777 // If the two neighboring cases go to the same destination, merge them
1778 // into a single case.
1779 if ((nextValue-currentValue==1) && (currentBB == nextBB)) {
1780 I->High = J->High;
1781 J = Cases.erase(J);
1782 } else {
1783 I = J++;
1784 }
1785 }
1786
1787 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
1788 if (I->Low != I->High)
1789 // A range counts double, since it requires two compares.
1790 ++numCmps;
1791 }
1792
1793 return numCmps;
1794}
1795
1796void SelectionDAGLowering::visitSwitch(SwitchInst &SI) {
Nate Begemaned728c12006-03-27 01:32:24 +00001797 // Figure out which block is immediately after the current one.
1798 MachineBasicBlock *NextBlock = 0;
1799 MachineFunction::iterator BBI = CurMBB;
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001800
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001801 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
Chris Lattner6d6fc262006-10-22 21:36:53 +00001802
Nate Begemaned728c12006-03-27 01:32:24 +00001803 // If there is only the default destination, branch to it if it is not the
1804 // next basic block. Otherwise, just fall through.
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001805 if (SI.getNumOperands() == 2) {
Nate Begemaned728c12006-03-27 01:32:24 +00001806 // Update machine-CFG edges.
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001807
Nate Begemaned728c12006-03-27 01:32:24 +00001808 // If this is not a fall-through branch, emit the branch.
Chris Lattner6d6fc262006-10-22 21:36:53 +00001809 if (Default != NextBlock)
Nate Begemaned728c12006-03-27 01:32:24 +00001810 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Chris Lattner6d6fc262006-10-22 21:36:53 +00001811 DAG.getBasicBlock(Default)));
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001812
Chris Lattner6d6fc262006-10-22 21:36:53 +00001813 CurMBB->addSuccessor(Default);
Nate Begemaned728c12006-03-27 01:32:24 +00001814 return;
1815 }
1816
1817 // If there are any non-default case statements, create a vector of Cases
1818 // representing each one, and sort the vector so that we can efficiently
1819 // create a binary search tree from them.
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001820 CaseVector Cases;
1821 unsigned numCmps = Clusterify(Cases, SI);
1822 DOUT << "Clusterify finished. Total clusters: " << Cases.size()
1823 << ". Total compares: " << numCmps << "\n";
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001824
Nate Begemaned728c12006-03-27 01:32:24 +00001825 // Get the Value to be switched on and default basic blocks, which will be
1826 // inserted into CaseBlock records, representing basic blocks in the binary
1827 // search tree.
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001828 Value *SV = SI.getOperand(0);
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001829
Nate Begemaned728c12006-03-27 01:32:24 +00001830 // Push the initial CaseRec onto the worklist
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001831 CaseRecVector WorkList;
Anton Korobeynikov70378262007-03-25 15:07:15 +00001832 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
1833
1834 while (!WorkList.empty()) {
Nate Begemaned728c12006-03-27 01:32:24 +00001835 // Grab a record representing a case range to process off the worklist
Anton Korobeynikov70378262007-03-25 15:07:15 +00001836 CaseRec CR = WorkList.back();
1837 WorkList.pop_back();
Anton Korobeynikov70378262007-03-25 15:07:15 +00001838
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001839 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
1840 continue;
1841
Anton Korobeynikov70378262007-03-25 15:07:15 +00001842 // If the range has few cases (two or less) emit a series of specific
1843 // tests.
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001844 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
1845 continue;
1846
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001847 // If the switch has more than 5 blocks, and at least 40% dense, and the
Anton Korobeynikov70378262007-03-25 15:07:15 +00001848 // target supports indirect branches, then emit a jump table rather than
1849 // lowering the switch to a binary tree of conditional branches.
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001850 if (handleJTSwitchCase(CR, WorkList, SV, Default))
1851 continue;
1852
1853 // Emit binary tree. We need to pick a pivot, and push left and right ranges
1854 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
1855 handleBTSplitSwitchCase(CR, WorkList, SV, Default);
Nate Begemaned728c12006-03-27 01:32:24 +00001856 }
1857}
1858
Anton Korobeynikov70378262007-03-25 15:07:15 +00001859
Chris Lattnerf68fd0b2005-04-02 05:04:50 +00001860void SelectionDAGLowering::visitSub(User &I) {
1861 // -0.0 - X --> fneg
Reid Spencer2eadb532007-01-21 00:29:26 +00001862 const Type *Ty = I.getType();
Reid Spencerd84d35b2007-02-15 02:26:10 +00001863 if (isa<VectorType>(Ty)) {
Dan Gohmana8665142007-06-25 16:23:39 +00001864 if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
1865 const VectorType *DestTy = cast<VectorType>(I.getType());
1866 const Type *ElTy = DestTy->getElementType();
1867 unsigned VL = DestTy->getNumElements();
1868 std::vector<Constant*> NZ(VL, ConstantFP::get(ElTy, -0.0));
1869 Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
1870 if (CV == CNZ) {
1871 SDOperand Op2 = getValue(I.getOperand(1));
1872 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
1873 return;
1874 }
1875 }
1876 }
1877 if (Ty->isFloatingPoint()) {
Chris Lattner6f3b5772005-09-28 22:28:18 +00001878 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
1879 if (CFP->isExactlyValue(-0.0)) {
1880 SDOperand Op2 = getValue(I.getOperand(1));
1881 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
1882 return;
1883 }
Dan Gohmana8665142007-06-25 16:23:39 +00001884 }
1885
1886 visitBinary(I, Ty->isFPOrFPVector() ? ISD::FSUB : ISD::SUB);
Chris Lattnerf68fd0b2005-04-02 05:04:50 +00001887}
1888
Dan Gohmana8665142007-06-25 16:23:39 +00001889void SelectionDAGLowering::visitBinary(User &I, unsigned OpCode) {
Chris Lattner7a60d912005-01-07 07:47:53 +00001890 SDOperand Op1 = getValue(I.getOperand(0));
1891 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencer2eadb532007-01-21 00:29:26 +00001892
1893 setValue(&I, DAG.getNode(OpCode, Op1.getValueType(), Op1, Op2));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001894}
1895
Nate Begeman127321b2005-11-18 07:42:56 +00001896void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
1897 SDOperand Op1 = getValue(I.getOperand(0));
1898 SDOperand Op2 = getValue(I.getOperand(1));
1899
Dan Gohmana8665142007-06-25 16:23:39 +00001900 if (MVT::getSizeInBits(TLI.getShiftAmountTy()) <
1901 MVT::getSizeInBits(Op2.getValueType()))
Reid Spencer2341c222007-02-02 02:16:23 +00001902 Op2 = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), Op2);
1903 else if (TLI.getShiftAmountTy() > Op2.getValueType())
1904 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
Nate Begeman127321b2005-11-18 07:42:56 +00001905
Chris Lattner7a60d912005-01-07 07:47:53 +00001906 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
1907}
1908
Reid Spencerd9436b62006-11-20 01:22:35 +00001909void SelectionDAGLowering::visitICmp(User &I) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001910 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
1911 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
1912 predicate = IC->getPredicate();
1913 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
1914 predicate = ICmpInst::Predicate(IC->getPredicate());
1915 SDOperand Op1 = getValue(I.getOperand(0));
1916 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencerd9436b62006-11-20 01:22:35 +00001917 ISD::CondCode Opcode;
Reid Spencer266e42b2006-12-23 06:05:41 +00001918 switch (predicate) {
Reid Spencerd9436b62006-11-20 01:22:35 +00001919 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
1920 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
1921 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
1922 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
1923 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
1924 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
1925 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
1926 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
1927 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
1928 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
1929 default:
1930 assert(!"Invalid ICmp predicate value");
1931 Opcode = ISD::SETEQ;
1932 break;
1933 }
1934 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
1935}
1936
1937void SelectionDAGLowering::visitFCmp(User &I) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001938 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
1939 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
1940 predicate = FC->getPredicate();
1941 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
1942 predicate = FCmpInst::Predicate(FC->getPredicate());
Chris Lattner7a60d912005-01-07 07:47:53 +00001943 SDOperand Op1 = getValue(I.getOperand(0));
1944 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencer266e42b2006-12-23 06:05:41 +00001945 ISD::CondCode Condition, FOC, FPC;
1946 switch (predicate) {
1947 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1948 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1949 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1950 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1951 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1952 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1953 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
1954 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
1955 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
1956 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1957 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1958 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1959 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1960 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1961 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1962 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
1963 default:
1964 assert(!"Invalid FCmp predicate value");
1965 FOC = FPC = ISD::SETFALSE;
1966 break;
1967 }
1968 if (FiniteOnlyFPMath())
1969 Condition = FOC;
1970 else
1971 Condition = FPC;
1972 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Condition));
Chris Lattner7a60d912005-01-07 07:47:53 +00001973}
1974
1975void SelectionDAGLowering::visitSelect(User &I) {
1976 SDOperand Cond = getValue(I.getOperand(0));
1977 SDOperand TrueVal = getValue(I.getOperand(1));
1978 SDOperand FalseVal = getValue(I.getOperand(2));
Dan Gohmana8665142007-06-25 16:23:39 +00001979 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
1980 TrueVal, FalseVal));
Chris Lattner7a60d912005-01-07 07:47:53 +00001981}
1982
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001983
1984void SelectionDAGLowering::visitTrunc(User &I) {
1985 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
1986 SDOperand N = getValue(I.getOperand(0));
1987 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1988 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
1989}
1990
1991void SelectionDAGLowering::visitZExt(User &I) {
1992 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
1993 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
1994 SDOperand N = getValue(I.getOperand(0));
1995 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1996 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
1997}
1998
1999void SelectionDAGLowering::visitSExt(User &I) {
2000 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2001 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2002 SDOperand N = getValue(I.getOperand(0));
2003 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2004 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
2005}
2006
2007void SelectionDAGLowering::visitFPTrunc(User &I) {
2008 // FPTrunc is never a no-op cast, no need to check
2009 SDOperand N = getValue(I.getOperand(0));
2010 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2011 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N));
2012}
2013
2014void SelectionDAGLowering::visitFPExt(User &I){
2015 // FPTrunc is never a no-op cast, no need to check
2016 SDOperand N = getValue(I.getOperand(0));
2017 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2018 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
2019}
2020
2021void SelectionDAGLowering::visitFPToUI(User &I) {
2022 // FPToUI is never a no-op cast, no need to check
2023 SDOperand N = getValue(I.getOperand(0));
2024 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2025 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
2026}
2027
2028void SelectionDAGLowering::visitFPToSI(User &I) {
2029 // FPToSI is never a no-op cast, no need to check
2030 SDOperand N = getValue(I.getOperand(0));
2031 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2032 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
2033}
2034
2035void SelectionDAGLowering::visitUIToFP(User &I) {
2036 // UIToFP is never a no-op cast, no need to check
2037 SDOperand N = getValue(I.getOperand(0));
2038 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2039 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
2040}
2041
2042void SelectionDAGLowering::visitSIToFP(User &I){
2043 // UIToFP is never a no-op cast, no need to check
2044 SDOperand N = getValue(I.getOperand(0));
2045 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2046 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
2047}
2048
2049void SelectionDAGLowering::visitPtrToInt(User &I) {
2050 // What to do depends on the size of the integer and the size of the pointer.
2051 // We can either truncate, zero extend, or no-op, accordingly.
Chris Lattner7a60d912005-01-07 07:47:53 +00002052 SDOperand N = getValue(I.getOperand(0));
Chris Lattner2f4119a2006-03-22 20:09:35 +00002053 MVT::ValueType SrcVT = N.getValueType();
Chris Lattner4024c002006-03-15 22:19:46 +00002054 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002055 SDOperand Result;
2056 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
2057 Result = DAG.getNode(ISD::TRUNCATE, DestVT, N);
2058 else
2059 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2060 Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N);
2061 setValue(&I, Result);
2062}
Chris Lattner7a60d912005-01-07 07:47:53 +00002063
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002064void SelectionDAGLowering::visitIntToPtr(User &I) {
2065 // What to do depends on the size of the integer and the size of the pointer.
2066 // We can either truncate, zero extend, or no-op, accordingly.
2067 SDOperand N = getValue(I.getOperand(0));
2068 MVT::ValueType SrcVT = N.getValueType();
2069 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2070 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
2071 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2072 else
2073 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2074 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2075}
2076
2077void SelectionDAGLowering::visitBitCast(User &I) {
2078 SDOperand N = getValue(I.getOperand(0));
2079 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002080
2081 // BitCast assures us that source and destination are the same size so this
2082 // is either a BIT_CONVERT or a no-op.
2083 if (DestVT != N.getValueType())
2084 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types
2085 else
2086 setValue(&I, N); // noop cast.
Chris Lattner7a60d912005-01-07 07:47:53 +00002087}
2088
Chris Lattner67271862006-03-29 00:11:43 +00002089void SelectionDAGLowering::visitInsertElement(User &I) {
Chris Lattner32206f52006-03-18 01:44:44 +00002090 SDOperand InVec = getValue(I.getOperand(0));
2091 SDOperand InVal = getValue(I.getOperand(1));
2092 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2093 getValue(I.getOperand(2)));
2094
Dan Gohmana8665142007-06-25 16:23:39 +00002095 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT,
2096 TLI.getValueType(I.getType()),
2097 InVec, InVal, InIdx));
Chris Lattner32206f52006-03-18 01:44:44 +00002098}
2099
Chris Lattner67271862006-03-29 00:11:43 +00002100void SelectionDAGLowering::visitExtractElement(User &I) {
Chris Lattner7c0cd8c2006-03-21 20:44:12 +00002101 SDOperand InVec = getValue(I.getOperand(0));
2102 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2103 getValue(I.getOperand(1)));
Dan Gohmana8665142007-06-25 16:23:39 +00002104 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
Chris Lattner7c0cd8c2006-03-21 20:44:12 +00002105 TLI.getValueType(I.getType()), InVec, InIdx));
2106}
Chris Lattner32206f52006-03-18 01:44:44 +00002107
Chris Lattner098c01e2006-04-08 04:15:24 +00002108void SelectionDAGLowering::visitShuffleVector(User &I) {
2109 SDOperand V1 = getValue(I.getOperand(0));
2110 SDOperand V2 = getValue(I.getOperand(1));
2111 SDOperand Mask = getValue(I.getOperand(2));
2112
Dan Gohmana8665142007-06-25 16:23:39 +00002113 setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE,
2114 TLI.getValueType(I.getType()),
2115 V1, V2, Mask));
Chris Lattner098c01e2006-04-08 04:15:24 +00002116}
2117
2118
Chris Lattner7a60d912005-01-07 07:47:53 +00002119void SelectionDAGLowering::visitGetElementPtr(User &I) {
2120 SDOperand N = getValue(I.getOperand(0));
2121 const Type *Ty = I.getOperand(0)->getType();
Chris Lattner7a60d912005-01-07 07:47:53 +00002122
2123 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2124 OI != E; ++OI) {
2125 Value *Idx = *OI;
Chris Lattner35397782005-12-05 07:10:48 +00002126 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002127 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
Chris Lattner7a60d912005-01-07 07:47:53 +00002128 if (Field) {
2129 // N = N + Offset
Chris Lattnerc473d8e2007-02-10 19:55:17 +00002130 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
Chris Lattner7a60d912005-01-07 07:47:53 +00002131 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Misha Brukman77451162005-04-22 04:01:18 +00002132 getIntPtrConstant(Offset));
Chris Lattner7a60d912005-01-07 07:47:53 +00002133 }
2134 Ty = StTy->getElementType(Field);
2135 } else {
2136 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner19a83992005-01-07 21:56:57 +00002137
Chris Lattner43535a12005-11-09 04:45:33 +00002138 // If this is a constant subscript, handle it quickly.
2139 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002140 if (CI->getZExtValue() == 0) continue;
Reid Spencere63b6512006-12-31 05:55:36 +00002141 uint64_t Offs =
Evan Cheng8ec52832007-01-05 01:46:20 +00002142 TD->getTypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
Chris Lattner43535a12005-11-09 04:45:33 +00002143 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
2144 continue;
Chris Lattner7a60d912005-01-07 07:47:53 +00002145 }
Chris Lattner43535a12005-11-09 04:45:33 +00002146
2147 // N = N + Idx * ElementSize;
Owen Anderson20a631f2006-05-03 01:29:57 +00002148 uint64_t ElementSize = TD->getTypeSize(Ty);
Chris Lattner43535a12005-11-09 04:45:33 +00002149 SDOperand IdxN = getValue(Idx);
2150
2151 // If the index is smaller or larger than intptr_t, truncate or extend
2152 // it.
2153 if (IdxN.getValueType() < N.getValueType()) {
Reid Spencere63b6512006-12-31 05:55:36 +00002154 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
Chris Lattner43535a12005-11-09 04:45:33 +00002155 } else if (IdxN.getValueType() > N.getValueType())
2156 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
2157
2158 // If this is a multiply by a power of two, turn it into a shl
2159 // immediately. This is a very common case.
2160 if (isPowerOf2_64(ElementSize)) {
2161 unsigned Amt = Log2_64(ElementSize);
2162 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner41fd6d52005-11-09 16:50:40 +00002163 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner43535a12005-11-09 04:45:33 +00002164 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
2165 continue;
2166 }
2167
2168 SDOperand Scale = getIntPtrConstant(ElementSize);
2169 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
2170 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner7a60d912005-01-07 07:47:53 +00002171 }
2172 }
2173 setValue(&I, N);
2174}
2175
2176void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
2177 // If this is a fixed sized alloca in the entry block of the function,
2178 // allocate it statically on the stack.
2179 if (FuncInfo.StaticAllocaMap.count(&I))
2180 return; // getValue will auto-populate this.
2181
2182 const Type *Ty = I.getAllocatedType();
Owen Anderson20a631f2006-05-03 01:29:57 +00002183 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
Chris Lattner50ee0e42007-01-20 22:35:55 +00002184 unsigned Align =
Chris Lattner945e4372007-02-14 05:52:17 +00002185 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
Chris Lattner50ee0e42007-01-20 22:35:55 +00002186 I.getAlignment());
Chris Lattner7a60d912005-01-07 07:47:53 +00002187
2188 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattnereccb73d2005-01-22 23:04:37 +00002189 MVT::ValueType IntPtr = TLI.getPointerTy();
2190 if (IntPtr < AllocSize.getValueType())
2191 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
2192 else if (IntPtr > AllocSize.getValueType())
2193 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner7a60d912005-01-07 07:47:53 +00002194
Chris Lattnereccb73d2005-01-22 23:04:37 +00002195 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner7a60d912005-01-07 07:47:53 +00002196 getIntPtrConstant(TySize));
2197
2198 // Handle alignment. If the requested alignment is less than or equal to the
2199 // stack alignment, ignore it and round the size of the allocation up to the
2200 // stack alignment size. If the size is greater than the stack alignment, we
2201 // note this in the DYNAMIC_STACKALLOC node.
2202 unsigned StackAlign =
2203 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
2204 if (Align <= StackAlign) {
2205 Align = 0;
2206 // Add SA-1 to the size.
2207 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
2208 getIntPtrConstant(StackAlign-1));
2209 // Mask out the low bits for alignment purposes.
2210 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
2211 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
2212 }
2213
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002214 SDOperand Ops[] = { getRoot(), AllocSize, getIntPtrConstant(Align) };
Chris Lattnerbd887772006-08-14 23:53:35 +00002215 const MVT::ValueType *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
2216 MVT::Other);
2217 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
Chris Lattner79084302007-02-04 01:31:47 +00002218 setValue(&I, DSA);
2219 DAG.setRoot(DSA.getValue(1));
Chris Lattner7a60d912005-01-07 07:47:53 +00002220
2221 // Inform the Frame Information that we have just allocated a variable-sized
2222 // object.
2223 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
2224}
2225
Chris Lattner7a60d912005-01-07 07:47:53 +00002226void SelectionDAGLowering::visitLoad(LoadInst &I) {
2227 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukman835702a2005-04-21 22:36:52 +00002228
Chris Lattner4d9651c2005-01-17 22:19:26 +00002229 SDOperand Root;
2230 if (I.isVolatile())
2231 Root = getRoot();
2232 else {
2233 // Do not serialize non-volatile loads against each other.
2234 Root = DAG.getRoot();
2235 }
Chris Lattner4024c002006-03-15 22:19:46 +00002236
Evan Chenge71fe34d2006-10-09 20:57:25 +00002237 setValue(&I, getLoadFrom(I.getType(), Ptr, I.getOperand(0),
Christopher Lamb8af6d582007-04-22 23:15:30 +00002238 Root, I.isVolatile(), I.getAlignment()));
Chris Lattner4024c002006-03-15 22:19:46 +00002239}
2240
2241SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Chenge71fe34d2006-10-09 20:57:25 +00002242 const Value *SV, SDOperand Root,
Christopher Lamb8af6d582007-04-22 23:15:30 +00002243 bool isVolatile,
2244 unsigned Alignment) {
Dan Gohmana8665142007-06-25 16:23:39 +00002245 SDOperand L =
2246 DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SV, 0,
2247 isVolatile, Alignment);
Chris Lattner4d9651c2005-01-17 22:19:26 +00002248
Chris Lattner4024c002006-03-15 22:19:46 +00002249 if (isVolatile)
Chris Lattner4d9651c2005-01-17 22:19:26 +00002250 DAG.setRoot(L.getValue(1));
2251 else
2252 PendingLoads.push_back(L.getValue(1));
Chris Lattner4024c002006-03-15 22:19:46 +00002253
2254 return L;
Chris Lattner7a60d912005-01-07 07:47:53 +00002255}
2256
2257
2258void SelectionDAGLowering::visitStore(StoreInst &I) {
2259 Value *SrcV = I.getOperand(0);
2260 SDOperand Src = getValue(SrcV);
2261 SDOperand Ptr = getValue(I.getOperand(1));
Evan Cheng258657e2006-12-20 01:27:29 +00002262 DAG.setRoot(DAG.getStore(getRoot(), Src, Ptr, I.getOperand(1), 0,
Christopher Lamb8af6d582007-04-22 23:15:30 +00002263 I.isVolatile(), I.getAlignment()));
Chris Lattner7a60d912005-01-07 07:47:53 +00002264}
2265
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002266/// IntrinsicCannotAccessMemory - Return true if the specified intrinsic cannot
2267/// access memory and has no other side effects at all.
2268static bool IntrinsicCannotAccessMemory(unsigned IntrinsicID) {
2269#define GET_NO_MEMORY_INTRINSICS
2270#include "llvm/Intrinsics.gen"
2271#undef GET_NO_MEMORY_INTRINSICS
2272 return false;
2273}
2274
Chris Lattnera9c59156b2006-04-02 03:41:14 +00002275// IntrinsicOnlyReadsMemory - Return true if the specified intrinsic doesn't
2276// have any side-effects or if it only reads memory.
2277static bool IntrinsicOnlyReadsMemory(unsigned IntrinsicID) {
2278#define GET_SIDE_EFFECT_INFO
2279#include "llvm/Intrinsics.gen"
2280#undef GET_SIDE_EFFECT_INFO
2281 return false;
2282}
2283
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002284/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2285/// node.
2286void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
2287 unsigned Intrinsic) {
Chris Lattner313229c2006-03-24 22:49:42 +00002288 bool HasChain = !IntrinsicCannotAccessMemory(Intrinsic);
Chris Lattnera9c59156b2006-04-02 03:41:14 +00002289 bool OnlyLoad = HasChain && IntrinsicOnlyReadsMemory(Intrinsic);
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002290
2291 // Build the operand list.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002292 SmallVector<SDOperand, 8> Ops;
Chris Lattnera9c59156b2006-04-02 03:41:14 +00002293 if (HasChain) { // If this intrinsic has side-effects, chainify it.
2294 if (OnlyLoad) {
2295 // We don't need to serialize loads against other loads.
2296 Ops.push_back(DAG.getRoot());
2297 } else {
2298 Ops.push_back(getRoot());
2299 }
2300 }
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002301
2302 // Add the intrinsic ID as an integer operand.
2303 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
2304
2305 // Add all operands of the call to the operand list.
2306 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2307 SDOperand Op = getValue(I.getOperand(i));
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002308 assert(TLI.isTypeLegal(Op.getValueType()) &&
2309 "Intrinsic uses a non-legal type?");
2310 Ops.push_back(Op);
2311 }
2312
2313 std::vector<MVT::ValueType> VTs;
2314 if (I.getType() != Type::VoidTy) {
2315 MVT::ValueType VT = TLI.getValueType(I.getType());
Dan Gohmana8665142007-06-25 16:23:39 +00002316 if (MVT::isVector(VT)) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00002317 const VectorType *DestTy = cast<VectorType>(I.getType());
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002318 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
2319
2320 VT = MVT::getVectorType(EltVT, DestTy->getNumElements());
2321 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
2322 }
2323
2324 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
2325 VTs.push_back(VT);
2326 }
2327 if (HasChain)
2328 VTs.push_back(MVT::Other);
2329
Chris Lattnerbd887772006-08-14 23:53:35 +00002330 const MVT::ValueType *VTList = DAG.getNodeValueTypes(VTs);
2331
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002332 // Create the node.
Chris Lattnere55d1712006-03-28 00:40:33 +00002333 SDOperand Result;
2334 if (!HasChain)
Chris Lattnerbd887772006-08-14 23:53:35 +00002335 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
2336 &Ops[0], Ops.size());
Chris Lattnere55d1712006-03-28 00:40:33 +00002337 else if (I.getType() != Type::VoidTy)
Chris Lattnerbd887772006-08-14 23:53:35 +00002338 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
2339 &Ops[0], Ops.size());
Chris Lattnere55d1712006-03-28 00:40:33 +00002340 else
Chris Lattnerbd887772006-08-14 23:53:35 +00002341 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
2342 &Ops[0], Ops.size());
Chris Lattnere55d1712006-03-28 00:40:33 +00002343
Chris Lattnera9c59156b2006-04-02 03:41:14 +00002344 if (HasChain) {
2345 SDOperand Chain = Result.getValue(Result.Val->getNumValues()-1);
2346 if (OnlyLoad)
2347 PendingLoads.push_back(Chain);
2348 else
2349 DAG.setRoot(Chain);
2350 }
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002351 if (I.getType() != Type::VoidTy) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00002352 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
Dan Gohmana8665142007-06-25 16:23:39 +00002353 MVT::ValueType VT = TLI.getValueType(PTy);
2354 Result = DAG.getNode(ISD::BIT_CONVERT, VT, Result);
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002355 }
2356 setValue(&I, Result);
2357 }
2358}
2359
Duncan Sands4cb9eb82007-05-04 17:12:26 +00002360/// ExtractGlobalVariable - If C is a global variable, or a bitcast of one
2361/// (possibly constant folded), return it. Otherwise return NULL.
2362static GlobalVariable *ExtractGlobalVariable (Constant *C) {
2363 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
2364 return GV;
2365 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2366 if (CE->getOpcode() == Instruction::BitCast)
2367 return dyn_cast<GlobalVariable>(CE->getOperand(0));
2368 else if (CE->getOpcode() == Instruction::GetElementPtr) {
2369 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
2370 if (!CE->getOperand(i)->isNullValue())
2371 return NULL;
2372 return dyn_cast<GlobalVariable>(CE->getOperand(0));
2373 }
2374 }
2375 return NULL;
2376}
2377
Duncan Sands92bf2c62007-06-15 19:04:19 +00002378/// addCatchInfo - Extract the personality and type infos from an eh.selector
2379/// or eh.filter call, and add them to the specified machine basic block.
2380static void addCatchInfo(CallInst &I, MachineModuleInfo *MMI,
2381 MachineBasicBlock *MBB) {
2382 // Inform the MachineModuleInfo of the personality for this landing pad.
2383 ConstantExpr *CE = cast<ConstantExpr>(I.getOperand(2));
2384 assert(CE->getOpcode() == Instruction::BitCast &&
2385 isa<Function>(CE->getOperand(0)) &&
2386 "Personality should be a function");
2387 MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0)));
2388
2389 // Gather all the type infos for this landing pad and pass them along to
2390 // MachineModuleInfo.
2391 std::vector<GlobalVariable *> TyInfo;
2392 for (unsigned i = 3, N = I.getNumOperands(); i < N; ++i) {
2393 Constant *C = cast<Constant>(I.getOperand(i));
2394 GlobalVariable *GV = ExtractGlobalVariable(C);
2395 assert (GV || isa<ConstantPointerNull>(C) &&
2396 "TypeInfo must be a global variable or NULL");
2397 TyInfo.push_back(GV);
2398 }
2399 if (I.getCalledFunction()->getIntrinsicID() == Intrinsic::eh_filter)
2400 MMI->addFilterTypeInfo(MBB, TyInfo);
2401 else
2402 MMI->addCatchTypeInfo(MBB, TyInfo);
2403}
2404
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002405/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
2406/// we want to emit this as a call to a named external function, return the name
2407/// otherwise lower it and return null.
2408const char *
2409SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
2410 switch (Intrinsic) {
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002411 default:
2412 // By default, turn this into a target intrinsic node.
2413 visitTargetIntrinsic(I, Intrinsic);
2414 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002415 case Intrinsic::vastart: visitVAStart(I); return 0;
2416 case Intrinsic::vaend: visitVAEnd(I); return 0;
2417 case Intrinsic::vacopy: visitVACopy(I); return 0;
Nate Begemaneda59972007-01-29 22:58:52 +00002418 case Intrinsic::returnaddress:
2419 setValue(&I, DAG.getNode(ISD::RETURNADDR, TLI.getPointerTy(),
2420 getValue(I.getOperand(1))));
2421 return 0;
2422 case Intrinsic::frameaddress:
2423 setValue(&I, DAG.getNode(ISD::FRAMEADDR, TLI.getPointerTy(),
2424 getValue(I.getOperand(1))));
2425 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002426 case Intrinsic::setjmp:
Anton Korobeynikov3b7c2572006-12-10 23:12:42 +00002427 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002428 break;
2429 case Intrinsic::longjmp:
Anton Korobeynikov3b7c2572006-12-10 23:12:42 +00002430 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002431 break;
Chris Lattner093c1592006-03-03 00:00:25 +00002432 case Intrinsic::memcpy_i32:
2433 case Intrinsic::memcpy_i64:
2434 visitMemIntrinsic(I, ISD::MEMCPY);
2435 return 0;
2436 case Intrinsic::memset_i32:
2437 case Intrinsic::memset_i64:
2438 visitMemIntrinsic(I, ISD::MEMSET);
2439 return 0;
2440 case Intrinsic::memmove_i32:
2441 case Intrinsic::memmove_i64:
2442 visitMemIntrinsic(I, ISD::MEMMOVE);
2443 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002444
Chris Lattner5d4e61d2005-12-13 17:40:33 +00002445 case Intrinsic::dbg_stoppoint: {
Jim Laskeyc56315c2007-01-26 21:22:28 +00002446 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskeya8bdac82006-03-23 18:06:46 +00002447 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Jim Laskeyc56315c2007-01-26 21:22:28 +00002448 if (MMI && SPI.getContext() && MMI->Verify(SPI.getContext())) {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002449 SDOperand Ops[5];
Chris Lattner435b4022005-11-29 06:21:05 +00002450
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002451 Ops[0] = getRoot();
2452 Ops[1] = getValue(SPI.getLineValue());
2453 Ops[2] = getValue(SPI.getColumnValue());
Chris Lattner435b4022005-11-29 06:21:05 +00002454
Jim Laskeyc56315c2007-01-26 21:22:28 +00002455 DebugInfoDesc *DD = MMI->getDescFor(SPI.getContext());
Jim Laskey5995d012006-02-11 01:01:30 +00002456 assert(DD && "Not a debug information descriptor");
Jim Laskeya8bdac82006-03-23 18:06:46 +00002457 CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
2458
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002459 Ops[3] = DAG.getString(CompileUnit->getFileName());
2460 Ops[4] = DAG.getString(CompileUnit->getDirectory());
Jim Laskey5995d012006-02-11 01:01:30 +00002461
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002462 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops, 5));
Chris Lattner5d4e61d2005-12-13 17:40:33 +00002463 }
Jim Laskeya8bdac82006-03-23 18:06:46 +00002464
Chris Lattnerf2b62f32005-11-16 07:22:30 +00002465 return 0;
Chris Lattner435b4022005-11-29 06:21:05 +00002466 }
Jim Laskeya8bdac82006-03-23 18:06:46 +00002467 case Intrinsic::dbg_region_start: {
Jim Laskeyc56315c2007-01-26 21:22:28 +00002468 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskeya8bdac82006-03-23 18:06:46 +00002469 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
Jim Laskeyc56315c2007-01-26 21:22:28 +00002470 if (MMI && RSI.getContext() && MMI->Verify(RSI.getContext())) {
2471 unsigned LabelID = MMI->RecordRegionStart(RSI.getContext());
Jim Laskeyf9e54452007-01-26 14:34:52 +00002472 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002473 DAG.getConstant(LabelID, MVT::i32)));
Jim Laskeya8bdac82006-03-23 18:06:46 +00002474 }
2475
Chris Lattnerf2b62f32005-11-16 07:22:30 +00002476 return 0;
Jim Laskeya8bdac82006-03-23 18:06:46 +00002477 }
2478 case Intrinsic::dbg_region_end: {
Jim Laskeyc56315c2007-01-26 21:22:28 +00002479 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskeya8bdac82006-03-23 18:06:46 +00002480 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
Jim Laskeyc56315c2007-01-26 21:22:28 +00002481 if (MMI && REI.getContext() && MMI->Verify(REI.getContext())) {
2482 unsigned LabelID = MMI->RecordRegionEnd(REI.getContext());
Jim Laskeyf9e54452007-01-26 14:34:52 +00002483 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other,
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002484 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
Jim Laskeya8bdac82006-03-23 18:06:46 +00002485 }
2486
Chris Lattnerf2b62f32005-11-16 07:22:30 +00002487 return 0;
Jim Laskeya8bdac82006-03-23 18:06:46 +00002488 }
2489 case Intrinsic::dbg_func_start: {
Jim Laskeyc56315c2007-01-26 21:22:28 +00002490 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskeya8bdac82006-03-23 18:06:46 +00002491 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
Jim Laskeyc56315c2007-01-26 21:22:28 +00002492 if (MMI && FSI.getSubprogram() &&
2493 MMI->Verify(FSI.getSubprogram())) {
2494 unsigned LabelID = MMI->RecordRegionStart(FSI.getSubprogram());
Jim Laskeyf9e54452007-01-26 14:34:52 +00002495 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other,
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002496 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
Jim Laskeya8bdac82006-03-23 18:06:46 +00002497 }
2498
Chris Lattnerf2b62f32005-11-16 07:22:30 +00002499 return 0;
Jim Laskeya8bdac82006-03-23 18:06:46 +00002500 }
2501 case Intrinsic::dbg_declare: {
Jim Laskeyc56315c2007-01-26 21:22:28 +00002502 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskeya8bdac82006-03-23 18:06:46 +00002503 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
Jim Laskeyc56315c2007-01-26 21:22:28 +00002504 if (MMI && DI.getVariable() && MMI->Verify(DI.getVariable())) {
Jim Laskey53f1ecc2006-03-24 09:50:27 +00002505 SDOperand AddressOp = getValue(DI.getAddress());
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002506 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(AddressOp))
Jim Laskeyc56315c2007-01-26 21:22:28 +00002507 MMI->RecordVariable(DI.getVariable(), FI->getIndex());
Jim Laskeya8bdac82006-03-23 18:06:46 +00002508 }
2509
2510 return 0;
2511 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002512
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002513 case Intrinsic::eh_exception: {
2514 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2515
Duncan Sands74137362007-06-13 16:53:21 +00002516 if (ExceptionHandling && MMI) {
Jim Laskey504e9942007-02-22 15:38:06 +00002517 // Mark exception register as live in.
2518 unsigned Reg = TLI.getExceptionAddressRegister();
2519 if (Reg) CurMBB->addLiveIn(Reg);
Duncan Sands61166502007-06-06 10:05:18 +00002520
Jim Laskey504e9942007-02-22 15:38:06 +00002521 // Insert the EXCEPTIONADDR instruction.
2522 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
2523 SDOperand Ops[1];
2524 Ops[0] = DAG.getRoot();
2525 SDOperand Op = DAG.getNode(ISD::EXCEPTIONADDR, VTs, Ops, 1);
2526 setValue(&I, Op);
2527 DAG.setRoot(Op.getValue(1));
Jim Laskeye1d1c052007-02-24 09:45:44 +00002528 } else {
Jim Laskeycf465fc2007-02-28 18:37:04 +00002529 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
Jim Laskey504e9942007-02-22 15:38:06 +00002530 }
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002531 return 0;
2532 }
2533
Jim Laskeyd5453d72007-03-01 20:24:30 +00002534 case Intrinsic::eh_selector:
2535 case Intrinsic::eh_filter:{
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002536 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002537
Duncan Sands92bf2c62007-06-15 19:04:19 +00002538 if (ExceptionHandling && MMI) {
2539 if (CurMBB->isLandingPad())
2540 addCatchInfo(I, MMI, CurMBB);
2541#ifndef NDEBUG
Duncan Sandsc063f5f2007-06-02 16:53:42 +00002542 else
Duncan Sands92bf2c62007-06-15 19:04:19 +00002543 FuncInfo.CatchInfoLost.insert(&I);
2544#endif
Duncan Sands61166502007-06-06 10:05:18 +00002545
Jim Laskey504e9942007-02-22 15:38:06 +00002546 // Mark exception selector register as live in.
2547 unsigned Reg = TLI.getExceptionSelectorRegister();
2548 if (Reg) CurMBB->addLiveIn(Reg);
2549
2550 // Insert the EHSELECTION instruction.
Anton Korobeynikov11940fb2007-05-02 22:15:48 +00002551 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
Jim Laskey504e9942007-02-22 15:38:06 +00002552 SDOperand Ops[2];
2553 Ops[0] = getValue(I.getOperand(1));
2554 Ops[1] = getRoot();
2555 SDOperand Op = DAG.getNode(ISD::EHSELECTION, VTs, Ops, 2);
2556 setValue(&I, Op);
2557 DAG.setRoot(Op.getValue(1));
Jim Laskeye1d1c052007-02-24 09:45:44 +00002558 } else {
Anton Korobeynikov11940fb2007-05-02 22:15:48 +00002559 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
Jim Laskey504e9942007-02-22 15:38:06 +00002560 }
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002561
2562 return 0;
2563 }
2564
2565 case Intrinsic::eh_typeid_for: {
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002566 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002567
Jim Laskey504e9942007-02-22 15:38:06 +00002568 if (MMI) {
2569 // Find the type id for the given typeinfo.
Duncan Sands4cb9eb82007-05-04 17:12:26 +00002570 Constant *C = cast<Constant>(I.getOperand(1));
2571 GlobalVariable *GV = ExtractGlobalVariable(C);
Duncan Sands706421e2007-06-01 08:18:30 +00002572 assert (GV || isa<ConstantPointerNull>(C) &&
Duncan Sands4cb9eb82007-05-04 17:12:26 +00002573 "TypeInfo must be a global variable or NULL");
2574
Jim Laskey504e9942007-02-22 15:38:06 +00002575 unsigned TypeID = MMI->getTypeIDFor(GV);
2576 setValue(&I, DAG.getConstant(TypeID, MVT::i32));
Jim Laskeye1d1c052007-02-24 09:45:44 +00002577 } else {
2578 setValue(&I, DAG.getConstant(0, MVT::i32));
Jim Laskey504e9942007-02-22 15:38:06 +00002579 }
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002580
2581 return 0;
2582 }
2583
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00002584 case Intrinsic::sqrt_f32:
2585 case Intrinsic::sqrt_f64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002586 setValue(&I, DAG.getNode(ISD::FSQRT,
2587 getValue(I.getOperand(1)).getValueType(),
2588 getValue(I.getOperand(1))));
2589 return 0;
Chris Lattnerf0359b32006-09-09 06:03:30 +00002590 case Intrinsic::powi_f32:
2591 case Intrinsic::powi_f64:
2592 setValue(&I, DAG.getNode(ISD::FPOWI,
2593 getValue(I.getOperand(1)).getValueType(),
2594 getValue(I.getOperand(1)),
2595 getValue(I.getOperand(2))));
2596 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002597 case Intrinsic::pcmarker: {
2598 SDOperand Tmp = getValue(I.getOperand(1));
2599 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
2600 return 0;
2601 }
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00002602 case Intrinsic::readcyclecounter: {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002603 SDOperand Op = getRoot();
Chris Lattnerbd887772006-08-14 23:53:35 +00002604 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
2605 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
2606 &Op, 1);
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00002607 setValue(&I, Tmp);
2608 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth01aa5632005-11-11 16:47:30 +00002609 return 0;
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00002610 }
Chris Lattnerf269d842007-04-10 03:20:39 +00002611 case Intrinsic::part_select: {
Reid Spencer85460ac2007-04-05 01:20:18 +00002612 // Currently not implemented: just abort
Reid Spencerc6251a72007-04-12 02:48:46 +00002613 assert(0 && "part_select intrinsic not implemented");
2614 abort();
2615 }
2616 case Intrinsic::part_set: {
2617 // Currently not implemented: just abort
2618 assert(0 && "part_set intrinsic not implemented");
Reid Spencer85460ac2007-04-05 01:20:18 +00002619 abort();
Reid Spencercce90f52007-04-04 23:48:25 +00002620 }
Reid Spencer3a0843e2007-04-01 07:34:11 +00002621 case Intrinsic::bswap:
Nate Begeman2fba8a32006-01-14 03:14:10 +00002622 setValue(&I, DAG.getNode(ISD::BSWAP,
2623 getValue(I.getOperand(1)).getValueType(),
2624 getValue(I.getOperand(1))));
2625 return 0;
Reid Spencer3a0843e2007-04-01 07:34:11 +00002626 case Intrinsic::cttz: {
2627 SDOperand Arg = getValue(I.getOperand(1));
2628 MVT::ValueType Ty = Arg.getValueType();
2629 SDOperand result = DAG.getNode(ISD::CTTZ, Ty, Arg);
2630 if (Ty < MVT::i32)
2631 result = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, result);
2632 else if (Ty > MVT::i32)
2633 result = DAG.getNode(ISD::TRUNCATE, MVT::i32, result);
2634 setValue(&I, result);
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002635 return 0;
Reid Spencer3a0843e2007-04-01 07:34:11 +00002636 }
2637 case Intrinsic::ctlz: {
2638 SDOperand Arg = getValue(I.getOperand(1));
2639 MVT::ValueType Ty = Arg.getValueType();
2640 SDOperand result = DAG.getNode(ISD::CTLZ, Ty, Arg);
2641 if (Ty < MVT::i32)
2642 result = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, result);
2643 else if (Ty > MVT::i32)
2644 result = DAG.getNode(ISD::TRUNCATE, MVT::i32, result);
2645 setValue(&I, result);
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002646 return 0;
Reid Spencer3a0843e2007-04-01 07:34:11 +00002647 }
2648 case Intrinsic::ctpop: {
2649 SDOperand Arg = getValue(I.getOperand(1));
2650 MVT::ValueType Ty = Arg.getValueType();
2651 SDOperand result = DAG.getNode(ISD::CTPOP, Ty, Arg);
2652 if (Ty < MVT::i32)
2653 result = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, result);
2654 else if (Ty > MVT::i32)
2655 result = DAG.getNode(ISD::TRUNCATE, MVT::i32, result);
2656 setValue(&I, result);
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002657 return 0;
Reid Spencer3a0843e2007-04-01 07:34:11 +00002658 }
Chris Lattnerb3266452006-01-13 02:50:02 +00002659 case Intrinsic::stacksave: {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002660 SDOperand Op = getRoot();
Chris Lattnerbd887772006-08-14 23:53:35 +00002661 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE,
2662 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
Chris Lattnerb3266452006-01-13 02:50:02 +00002663 setValue(&I, Tmp);
2664 DAG.setRoot(Tmp.getValue(1));
2665 return 0;
2666 }
Chris Lattnerdeda32a2006-01-23 05:22:07 +00002667 case Intrinsic::stackrestore: {
2668 SDOperand Tmp = getValue(I.getOperand(1));
2669 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
Chris Lattnerb3266452006-01-13 02:50:02 +00002670 return 0;
Chris Lattnerdeda32a2006-01-23 05:22:07 +00002671 }
Chris Lattner9e8b6332005-12-12 22:51:16 +00002672 case Intrinsic::prefetch:
2673 // FIXME: Currently discarding prefetches.
2674 return 0;
Tanya Lattnere199f972007-06-15 22:26:58 +00002675
2676 case Intrinsic::var_annotation:
2677 // Discard annotate attributes
2678 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002679 }
2680}
2681
2682
Jim Laskey31fef782007-02-23 21:45:01 +00002683void SelectionDAGLowering::LowerCallTo(Instruction &I,
2684 const Type *CalledValueTy,
2685 unsigned CallingConv,
2686 bool IsTailCall,
Anton Korobeynikov3b327822007-05-23 11:08:31 +00002687 SDOperand Callee, unsigned OpIdx,
2688 MachineBasicBlock *LandingPad) {
Jim Laskey31fef782007-02-23 21:45:01 +00002689 const PointerType *PT = cast<PointerType>(CalledValueTy);
Jim Laskey504e9942007-02-22 15:38:06 +00002690 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Reid Spencer71b79e32007-04-09 06:17:21 +00002691 const ParamAttrsList *Attrs = FTy->getParamAttrs();
Anton Korobeynikov3b327822007-05-23 11:08:31 +00002692 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2693 unsigned BeginLabel = 0, EndLabel = 0;
2694
Jim Laskey504e9942007-02-22 15:38:06 +00002695 TargetLowering::ArgListTy Args;
2696 TargetLowering::ArgListEntry Entry;
2697 Args.reserve(I.getNumOperands());
2698 for (unsigned i = OpIdx, e = I.getNumOperands(); i != e; ++i) {
2699 Value *Arg = I.getOperand(i);
2700 SDOperand ArgNode = getValue(Arg);
2701 Entry.Node = ArgNode; Entry.Ty = Arg->getType();
Duncan Sands671e8c42007-05-07 20:49:28 +00002702
2703 unsigned attrInd = i - OpIdx + 1;
2704 Entry.isSExt = Attrs && Attrs->paramHasAttr(attrInd, ParamAttr::SExt);
2705 Entry.isZExt = Attrs && Attrs->paramHasAttr(attrInd, ParamAttr::ZExt);
2706 Entry.isInReg = Attrs && Attrs->paramHasAttr(attrInd, ParamAttr::InReg);
2707 Entry.isSRet = Attrs && Attrs->paramHasAttr(attrInd, ParamAttr::StructRet);
Jim Laskey504e9942007-02-22 15:38:06 +00002708 Args.push_back(Entry);
2709 }
2710
Duncan Sands61166502007-06-06 10:05:18 +00002711 if (ExceptionHandling && MMI) {
Anton Korobeynikov3b327822007-05-23 11:08:31 +00002712 // Insert a label before the invoke call to mark the try range. This can be
2713 // used to detect deletion of the invoke via the MachineModuleInfo.
2714 BeginLabel = MMI->NextLabelID();
2715 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
2716 DAG.getConstant(BeginLabel, MVT::i32)));
2717 }
2718
Jim Laskey504e9942007-02-22 15:38:06 +00002719 std::pair<SDOperand,SDOperand> Result =
2720 TLI.LowerCallTo(getRoot(), I.getType(),
Reid Spencera472f662007-04-11 02:44:20 +00002721 Attrs && Attrs->paramHasAttr(0, ParamAttr::SExt),
Jim Laskey31fef782007-02-23 21:45:01 +00002722 FTy->isVarArg(), CallingConv, IsTailCall,
Jim Laskey504e9942007-02-22 15:38:06 +00002723 Callee, Args, DAG);
2724 if (I.getType() != Type::VoidTy)
2725 setValue(&I, Result.first);
2726 DAG.setRoot(Result.second);
Anton Korobeynikov3b327822007-05-23 11:08:31 +00002727
Duncan Sands61166502007-06-06 10:05:18 +00002728 if (ExceptionHandling && MMI) {
Anton Korobeynikov3b327822007-05-23 11:08:31 +00002729 // Insert a label at the end of the invoke call to mark the try range. This
2730 // can be used to detect deletion of the invoke via the MachineModuleInfo.
2731 EndLabel = MMI->NextLabelID();
2732 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
2733 DAG.getConstant(EndLabel, MVT::i32)));
2734
2735 // Inform MachineModuleInfo of range.
2736 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
2737 }
Jim Laskey504e9942007-02-22 15:38:06 +00002738}
2739
2740
Chris Lattner7a60d912005-01-07 07:47:53 +00002741void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner18d2b342005-01-08 22:48:57 +00002742 const char *RenameFn = 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002743 if (Function *F = I.getCalledFunction()) {
Reid Spencer5301e7c2007-01-30 20:08:39 +00002744 if (F->isDeclaration())
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002745 if (unsigned IID = F->getIntrinsicID()) {
2746 RenameFn = visitIntrinsicCall(I, IID);
2747 if (!RenameFn)
2748 return;
2749 } else { // Not an LLVM intrinsic.
2750 const std::string &Name = F->getName();
Chris Lattner5c1ba2a2006-03-05 05:09:38 +00002751 if (Name[0] == 'c' && (Name == "copysign" || Name == "copysignf")) {
2752 if (I.getNumOperands() == 3 && // Basic sanity checks.
2753 I.getOperand(1)->getType()->isFloatingPoint() &&
2754 I.getType() == I.getOperand(1)->getType() &&
2755 I.getType() == I.getOperand(2)->getType()) {
2756 SDOperand LHS = getValue(I.getOperand(1));
2757 SDOperand RHS = getValue(I.getOperand(2));
2758 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
2759 LHS, RHS));
2760 return;
2761 }
2762 } else if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
Chris Lattner0c140002005-04-02 05:26:53 +00002763 if (I.getNumOperands() == 2 && // Basic sanity checks.
2764 I.getOperand(1)->getType()->isFloatingPoint() &&
2765 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002766 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner0c140002005-04-02 05:26:53 +00002767 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
2768 return;
2769 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002770 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
Chris Lattner80026402005-04-30 04:43:14 +00002771 if (I.getNumOperands() == 2 && // Basic sanity checks.
2772 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner1784a9d22006-02-14 05:39:35 +00002773 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002774 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +00002775 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
2776 return;
2777 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002778 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
Chris Lattner80026402005-04-30 04:43:14 +00002779 if (I.getNumOperands() == 2 && // Basic sanity checks.
2780 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner1784a9d22006-02-14 05:39:35 +00002781 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002782 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +00002783 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
2784 return;
2785 }
2786 }
Chris Lattnere4f71d02005-05-14 13:56:55 +00002787 }
Chris Lattner476e67b2006-01-26 22:24:51 +00002788 } else if (isa<InlineAsm>(I.getOperand(0))) {
2789 visitInlineAsm(I);
2790 return;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002791 }
Misha Brukman835702a2005-04-21 22:36:52 +00002792
Chris Lattner18d2b342005-01-08 22:48:57 +00002793 SDOperand Callee;
2794 if (!RenameFn)
2795 Callee = getValue(I.getOperand(0));
2796 else
2797 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Anton Korobeynikov3b327822007-05-23 11:08:31 +00002798
Jim Laskey31fef782007-02-23 21:45:01 +00002799 LowerCallTo(I, I.getCalledValue()->getType(),
Anton Korobeynikov3b327822007-05-23 11:08:31 +00002800 I.getCallingConv(),
2801 I.isTailCall(),
2802 Callee,
2803 1);
Chris Lattner7a60d912005-01-07 07:47:53 +00002804}
2805
Jim Laskey504e9942007-02-22 15:38:06 +00002806
Chris Lattner6f87d182006-02-22 22:37:12 +00002807SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002808 SDOperand &Chain, SDOperand &Flag)const{
Chris Lattner6f87d182006-02-22 22:37:12 +00002809 SDOperand Val = DAG.getCopyFromReg(Chain, Regs[0], RegVT, Flag);
2810 Chain = Val.getValue(1);
2811 Flag = Val.getValue(2);
2812
2813 // If the result was expanded, copy from the top part.
2814 if (Regs.size() > 1) {
2815 assert(Regs.size() == 2 &&
2816 "Cannot expand to more than 2 elts yet!");
2817 SDOperand Hi = DAG.getCopyFromReg(Chain, Regs[1], RegVT, Flag);
Evan Chengf80dfa82006-10-04 22:23:53 +00002818 Chain = Hi.getValue(1);
2819 Flag = Hi.getValue(2);
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002820 if (DAG.getTargetLoweringInfo().isLittleEndian())
2821 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi);
2822 else
2823 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Hi, Val);
Chris Lattner6f87d182006-02-22 22:37:12 +00002824 }
Chris Lattner1558fc62006-02-01 18:59:47 +00002825
Chris Lattner705948d2006-06-08 18:22:48 +00002826 // Otherwise, if the return value was promoted or extended, truncate it to the
Chris Lattner6f87d182006-02-22 22:37:12 +00002827 // appropriate type.
2828 if (RegVT == ValueVT)
2829 return Val;
2830
Chris Lattner77f04792007-03-25 05:00:54 +00002831 if (MVT::isVector(RegVT)) {
Dan Gohmana8665142007-06-25 16:23:39 +00002832 assert(MVT::isVector(ValueVT) && "Unknown vector conversion!");
2833 return DAG.getNode(ISD::BIT_CONVERT, RegVT, Val);
Chris Lattner77f04792007-03-25 05:00:54 +00002834 }
2835
Chris Lattner705948d2006-06-08 18:22:48 +00002836 if (MVT::isInteger(RegVT)) {
2837 if (ValueVT < RegVT)
2838 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
2839 else
2840 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
Chris Lattner705948d2006-06-08 18:22:48 +00002841 }
Chris Lattner77f04792007-03-25 05:00:54 +00002842
2843 assert(MVT::isFloatingPoint(RegVT) && MVT::isFloatingPoint(ValueVT));
2844 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
Chris Lattner6f87d182006-02-22 22:37:12 +00002845}
2846
Chris Lattner571d9642006-02-23 19:21:04 +00002847/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
2848/// specified value into the registers specified by this object. This uses
2849/// Chain/Flag as the input and updates them for the output Chain/Flag.
2850void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Evan Chengef9e07d2006-06-15 08:11:54 +00002851 SDOperand &Chain, SDOperand &Flag,
2852 MVT::ValueType PtrVT) const {
Chris Lattner571d9642006-02-23 19:21:04 +00002853 if (Regs.size() == 1) {
2854 // If there is a single register and the types differ, this must be
2855 // a promotion.
2856 if (RegVT != ValueVT) {
Chris Lattner77f04792007-03-25 05:00:54 +00002857 if (MVT::isVector(RegVT)) {
Dan Gohmana8665142007-06-25 16:23:39 +00002858 assert(MVT::isVector(Val.getValueType()) &&
2859 "Not a vector-vector cast?");
2860 Val = DAG.getNode(ISD::BIT_CONVERT, RegVT, Val);
Chris Lattner7b2decf2007-04-09 05:31:20 +00002861 } else if (MVT::isInteger(RegVT) && MVT::isInteger(Val.getValueType())) {
Chris Lattnerc03a9252006-06-08 18:27:11 +00002862 if (RegVT < ValueVT)
2863 Val = DAG.getNode(ISD::TRUNCATE, RegVT, Val);
2864 else
2865 Val = DAG.getNode(ISD::ANY_EXTEND, RegVT, Val);
Chris Lattner7b2decf2007-04-09 05:31:20 +00002866 } else if (MVT::isFloatingPoint(RegVT) &&
2867 MVT::isFloatingPoint(Val.getValueType())) {
Chris Lattner571d9642006-02-23 19:21:04 +00002868 Val = DAG.getNode(ISD::FP_EXTEND, RegVT, Val);
Chris Lattner7b2decf2007-04-09 05:31:20 +00002869 } else if (MVT::getSizeInBits(RegVT) ==
2870 MVT::getSizeInBits(Val.getValueType())) {
2871 Val = DAG.getNode(ISD::BIT_CONVERT, RegVT, Val);
2872 } else {
2873 assert(0 && "Unknown mismatch!");
2874 }
Chris Lattner571d9642006-02-23 19:21:04 +00002875 }
2876 Chain = DAG.getCopyToReg(Chain, Regs[0], Val, Flag);
2877 Flag = Chain.getValue(1);
2878 } else {
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002879 std::vector<unsigned> R(Regs);
2880 if (!DAG.getTargetLoweringInfo().isLittleEndian())
2881 std::reverse(R.begin(), R.end());
2882
2883 for (unsigned i = 0, e = R.size(); i != e; ++i) {
Chris Lattner571d9642006-02-23 19:21:04 +00002884 SDOperand Part = DAG.getNode(ISD::EXTRACT_ELEMENT, RegVT, Val,
Evan Chengef9e07d2006-06-15 08:11:54 +00002885 DAG.getConstant(i, PtrVT));
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002886 Chain = DAG.getCopyToReg(Chain, R[i], Part, Flag);
Chris Lattner571d9642006-02-23 19:21:04 +00002887 Flag = Chain.getValue(1);
2888 }
2889 }
2890}
Chris Lattner6f87d182006-02-22 22:37:12 +00002891
Chris Lattner571d9642006-02-23 19:21:04 +00002892/// AddInlineAsmOperands - Add this value to the specified inlineasm node
2893/// operand list. This adds the code marker and includes the number of
2894/// values added into it.
2895void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002896 std::vector<SDOperand> &Ops) const {
Chris Lattnerb49917d2007-04-09 00:33:58 +00002897 MVT::ValueType IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
2898 Ops.push_back(DAG.getTargetConstant(Code | (Regs.size() << 3), IntPtrTy));
Chris Lattner571d9642006-02-23 19:21:04 +00002899 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
2900 Ops.push_back(DAG.getRegister(Regs[i], RegVT));
2901}
Chris Lattner6f87d182006-02-22 22:37:12 +00002902
2903/// isAllocatableRegister - If the specified register is safe to allocate,
2904/// i.e. it isn't a stack pointer or some other special register, return the
2905/// register class for the register. Otherwise, return null.
2906static const TargetRegisterClass *
Chris Lattnerb1124f32006-02-22 23:09:03 +00002907isAllocatableRegister(unsigned Reg, MachineFunction &MF,
2908 const TargetLowering &TLI, const MRegisterInfo *MRI) {
Chris Lattnerbec582f2006-04-02 00:24:45 +00002909 MVT::ValueType FoundVT = MVT::Other;
2910 const TargetRegisterClass *FoundRC = 0;
Chris Lattnerb1124f32006-02-22 23:09:03 +00002911 for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
2912 E = MRI->regclass_end(); RCI != E; ++RCI) {
Chris Lattnerbec582f2006-04-02 00:24:45 +00002913 MVT::ValueType ThisVT = MVT::Other;
2914
Chris Lattnerb1124f32006-02-22 23:09:03 +00002915 const TargetRegisterClass *RC = *RCI;
2916 // If none of the the value types for this register class are valid, we
2917 // can't use it. For example, 64-bit reg classes on 32-bit targets.
Chris Lattnerb1124f32006-02-22 23:09:03 +00002918 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
2919 I != E; ++I) {
2920 if (TLI.isTypeLegal(*I)) {
Chris Lattnerbec582f2006-04-02 00:24:45 +00002921 // If we have already found this register in a different register class,
2922 // choose the one with the largest VT specified. For example, on
2923 // PowerPC, we favor f64 register classes over f32.
2924 if (FoundVT == MVT::Other ||
2925 MVT::getSizeInBits(FoundVT) < MVT::getSizeInBits(*I)) {
2926 ThisVT = *I;
2927 break;
2928 }
Chris Lattnerb1124f32006-02-22 23:09:03 +00002929 }
2930 }
2931
Chris Lattnerbec582f2006-04-02 00:24:45 +00002932 if (ThisVT == MVT::Other) continue;
Chris Lattnerb1124f32006-02-22 23:09:03 +00002933
Chris Lattner6f87d182006-02-22 22:37:12 +00002934 // NOTE: This isn't ideal. In particular, this might allocate the
2935 // frame pointer in functions that need it (due to them not being taken
2936 // out of allocation, because a variable sized allocation hasn't been seen
2937 // yet). This is a slight code pessimization, but should still work.
Chris Lattnerb1124f32006-02-22 23:09:03 +00002938 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
2939 E = RC->allocation_order_end(MF); I != E; ++I)
Chris Lattnerbec582f2006-04-02 00:24:45 +00002940 if (*I == Reg) {
2941 // We found a matching register class. Keep looking at others in case
2942 // we find one with larger registers that this physreg is also in.
2943 FoundRC = RC;
2944 FoundVT = ThisVT;
2945 break;
2946 }
Chris Lattner1558fc62006-02-01 18:59:47 +00002947 }
Chris Lattnerbec582f2006-04-02 00:24:45 +00002948 return FoundRC;
Chris Lattner6f87d182006-02-22 22:37:12 +00002949}
2950
Chris Lattner1558fc62006-02-01 18:59:47 +00002951
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00002952namespace {
2953/// AsmOperandInfo - This contains information for each constraint that we are
2954/// lowering.
2955struct AsmOperandInfo : public InlineAsm::ConstraintInfo {
2956 /// ConstraintCode - This contains the actual string for the code, like "m".
2957 std::string ConstraintCode;
Chris Lattnerb2e55562007-04-28 21:01:43 +00002958
2959 /// ConstraintType - Information about the constraint code, e.g. Register,
2960 /// RegisterClass, Memory, Other, Unknown.
2961 TargetLowering::ConstraintType ConstraintType;
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00002962
2963 /// CallOperand/CallOperandval - If this is the result output operand or a
2964 /// clobber, this is null, otherwise it is the incoming operand to the
2965 /// CallInst. This gets modified as the asm is processed.
2966 SDOperand CallOperand;
2967 Value *CallOperandVal;
2968
2969 /// ConstraintVT - The ValueType for the operand value.
2970 MVT::ValueType ConstraintVT;
2971
Chris Lattner8cfd33b2007-04-30 21:11:17 +00002972 /// AssignedRegs - If this is a register or register class operand, this
2973 /// contains the set of register corresponding to the operand.
2974 RegsForValue AssignedRegs;
2975
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00002976 AsmOperandInfo(const InlineAsm::ConstraintInfo &info)
Chris Lattnerb2e55562007-04-28 21:01:43 +00002977 : InlineAsm::ConstraintInfo(info),
2978 ConstraintType(TargetLowering::C_Unknown),
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00002979 CallOperand(0,0), CallOperandVal(0), ConstraintVT(MVT::Other) {
2980 }
Chris Lattneref073322007-04-30 17:16:27 +00002981
2982 void ComputeConstraintToUse(const TargetLowering &TLI);
Chris Lattner8cfd33b2007-04-30 21:11:17 +00002983
2984 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
2985 /// busy in OutputRegs/InputRegs.
2986 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
2987 std::set<unsigned> &OutputRegs,
2988 std::set<unsigned> &InputRegs) const {
2989 if (isOutReg)
2990 OutputRegs.insert(AssignedRegs.Regs.begin(), AssignedRegs.Regs.end());
2991 if (isInReg)
2992 InputRegs.insert(AssignedRegs.Regs.begin(), AssignedRegs.Regs.end());
2993 }
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00002994};
2995} // end anon namespace.
Chris Lattner6f87d182006-02-22 22:37:12 +00002996
Chris Lattneref073322007-04-30 17:16:27 +00002997/// getConstraintGenerality - Return an integer indicating how general CT is.
2998static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT) {
2999 switch (CT) {
3000 default: assert(0 && "Unknown constraint type!");
3001 case TargetLowering::C_Other:
3002 case TargetLowering::C_Unknown:
3003 return 0;
3004 case TargetLowering::C_Register:
3005 return 1;
3006 case TargetLowering::C_RegisterClass:
3007 return 2;
3008 case TargetLowering::C_Memory:
3009 return 3;
3010 }
3011}
3012
3013void AsmOperandInfo::ComputeConstraintToUse(const TargetLowering &TLI) {
3014 assert(!Codes.empty() && "Must have at least one constraint");
3015
3016 std::string *Current = &Codes[0];
3017 TargetLowering::ConstraintType CurType = TLI.getConstraintType(*Current);
3018 if (Codes.size() == 1) { // Single-letter constraints ('r') are very common.
3019 ConstraintCode = *Current;
3020 ConstraintType = CurType;
3021 return;
3022 }
3023
3024 unsigned CurGenerality = getConstraintGenerality(CurType);
3025
3026 // If we have multiple constraints, try to pick the most general one ahead
3027 // of time. This isn't a wonderful solution, but handles common cases.
3028 for (unsigned j = 1, e = Codes.size(); j != e; ++j) {
3029 TargetLowering::ConstraintType ThisType = TLI.getConstraintType(Codes[j]);
3030 unsigned ThisGenerality = getConstraintGenerality(ThisType);
3031 if (ThisGenerality > CurGenerality) {
3032 // This constraint letter is more general than the previous one,
3033 // use it.
3034 CurType = ThisType;
3035 Current = &Codes[j];
3036 CurGenerality = ThisGenerality;
3037 }
3038 }
3039
3040 ConstraintCode = *Current;
3041 ConstraintType = CurType;
3042}
3043
3044
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003045void SelectionDAGLowering::
3046GetRegistersForValue(AsmOperandInfo &OpInfo, bool HasEarlyClobber,
Chris Lattner4333f8b2007-04-30 17:29:31 +00003047 std::set<unsigned> &OutputRegs,
3048 std::set<unsigned> &InputRegs) {
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003049 // Compute whether this value requires an input register, an output register,
3050 // or both.
3051 bool isOutReg = false;
3052 bool isInReg = false;
3053 switch (OpInfo.Type) {
3054 case InlineAsm::isOutput:
3055 isOutReg = true;
3056
3057 // If this is an early-clobber output, or if there is an input
3058 // constraint that matches this, we need to reserve the input register
3059 // so no other inputs allocate to it.
3060 isInReg = OpInfo.isEarlyClobber || OpInfo.hasMatchingInput;
3061 break;
3062 case InlineAsm::isInput:
3063 isInReg = true;
3064 isOutReg = false;
3065 break;
3066 case InlineAsm::isClobber:
3067 isOutReg = true;
3068 isInReg = true;
3069 break;
3070 }
3071
3072
3073 MachineFunction &MF = DAG.getMachineFunction();
Chris Lattner4333f8b2007-04-30 17:29:31 +00003074 std::vector<unsigned> Regs;
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003075
3076 // If this is a constraint for a single physreg, or a constraint for a
3077 // register class, find it.
3078 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
3079 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
3080 OpInfo.ConstraintVT);
Chris Lattner4333f8b2007-04-30 17:29:31 +00003081
3082 unsigned NumRegs = 1;
3083 if (OpInfo.ConstraintVT != MVT::Other)
Dan Gohman04deef32007-06-21 14:42:22 +00003084 NumRegs = TLI.getNumRegisters(OpInfo.ConstraintVT);
Chris Lattner4333f8b2007-04-30 17:29:31 +00003085 MVT::ValueType RegVT;
3086 MVT::ValueType ValueVT = OpInfo.ConstraintVT;
3087
Chris Lattner4333f8b2007-04-30 17:29:31 +00003088
3089 // If this is a constraint for a specific physical register, like {r17},
3090 // assign it now.
3091 if (PhysReg.first) {
3092 if (OpInfo.ConstraintVT == MVT::Other)
3093 ValueVT = *PhysReg.second->vt_begin();
3094
3095 // Get the actual register value type. This is important, because the user
3096 // may have asked for (e.g.) the AX register in i32 type. We need to
3097 // remember that AX is actually i16 to get the right extension.
3098 RegVT = *PhysReg.second->vt_begin();
3099
3100 // This is a explicit reference to a physical register.
3101 Regs.push_back(PhysReg.first);
3102
3103 // If this is an expanded reference, add the rest of the regs to Regs.
3104 if (NumRegs != 1) {
3105 TargetRegisterClass::iterator I = PhysReg.second->begin();
3106 TargetRegisterClass::iterator E = PhysReg.second->end();
3107 for (; *I != PhysReg.first; ++I)
3108 assert(I != E && "Didn't find reg!");
3109
3110 // Already added the first reg.
3111 --NumRegs; ++I;
3112 for (; NumRegs; --NumRegs, ++I) {
3113 assert(I != E && "Ran out of registers to allocate!");
3114 Regs.push_back(*I);
3115 }
3116 }
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003117 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
3118 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs);
3119 return;
Chris Lattner4333f8b2007-04-30 17:29:31 +00003120 }
3121
3122 // Otherwise, if this was a reference to an LLVM register class, create vregs
3123 // for this reference.
3124 std::vector<unsigned> RegClassRegs;
Chris Lattnerf852e332007-06-15 19:11:01 +00003125 const TargetRegisterClass *RC = PhysReg.second;
3126 if (RC) {
Chris Lattner4333f8b2007-04-30 17:29:31 +00003127 // If this is an early clobber or tied register, our regalloc doesn't know
3128 // how to maintain the constraint. If it isn't, go ahead and create vreg
3129 // and let the regalloc do the right thing.
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003130 if (!OpInfo.hasMatchingInput && !OpInfo.isEarlyClobber &&
3131 // If there is some other early clobber and this is an input register,
3132 // then we are forced to pre-allocate the input reg so it doesn't
3133 // conflict with the earlyclobber.
3134 !(OpInfo.Type == InlineAsm::isInput && HasEarlyClobber)) {
Chris Lattner4333f8b2007-04-30 17:29:31 +00003135 RegVT = *PhysReg.second->vt_begin();
3136
3137 if (OpInfo.ConstraintVT == MVT::Other)
3138 ValueVT = RegVT;
3139
3140 // Create the appropriate number of virtual registers.
3141 SSARegMap *RegMap = MF.getSSARegMap();
3142 for (; NumRegs; --NumRegs)
3143 Regs.push_back(RegMap->createVirtualRegister(PhysReg.second));
3144
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003145 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
3146 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs);
3147 return;
Chris Lattner4333f8b2007-04-30 17:29:31 +00003148 }
3149
3150 // Otherwise, we can't allocate it. Let the code below figure out how to
3151 // maintain these constraints.
3152 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
3153
3154 } else {
3155 // This is a reference to a register class that doesn't directly correspond
3156 // to an LLVM register class. Allocate NumRegs consecutive, available,
3157 // registers from the class.
3158 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
3159 OpInfo.ConstraintVT);
3160 }
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003161
Chris Lattner4333f8b2007-04-30 17:29:31 +00003162 const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
3163 unsigned NumAllocated = 0;
3164 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
3165 unsigned Reg = RegClassRegs[i];
3166 // See if this register is available.
3167 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
3168 (isInReg && InputRegs.count(Reg))) { // Already used.
3169 // Make sure we find consecutive registers.
3170 NumAllocated = 0;
3171 continue;
3172 }
3173
3174 // Check to see if this register is allocatable (i.e. don't give out the
3175 // stack pointer).
Chris Lattnerf852e332007-06-15 19:11:01 +00003176 if (RC == 0) {
3177 RC = isAllocatableRegister(Reg, MF, TLI, MRI);
3178 if (!RC) { // Couldn't allocate this register.
3179 // Reset NumAllocated to make sure we return consecutive registers.
3180 NumAllocated = 0;
3181 continue;
3182 }
Chris Lattner4333f8b2007-04-30 17:29:31 +00003183 }
3184
3185 // Okay, this register is good, we can use it.
3186 ++NumAllocated;
3187
3188 // If we allocated enough consecutive registers, succeed.
3189 if (NumAllocated == NumRegs) {
3190 unsigned RegStart = (i-NumAllocated)+1;
3191 unsigned RegEnd = i+1;
3192 // Mark all of the allocated registers used.
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003193 for (unsigned i = RegStart; i != RegEnd; ++i)
3194 Regs.push_back(RegClassRegs[i]);
Chris Lattner4333f8b2007-04-30 17:29:31 +00003195
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003196 OpInfo.AssignedRegs = RegsForValue(Regs, *RC->vt_begin(),
3197 OpInfo.ConstraintVT);
3198 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs);
3199 return;
Chris Lattner4333f8b2007-04-30 17:29:31 +00003200 }
3201 }
3202
3203 // Otherwise, we couldn't allocate enough registers for this.
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003204 return;
Chris Lattner4333f8b2007-04-30 17:29:31 +00003205}
3206
3207
Chris Lattner476e67b2006-01-26 22:24:51 +00003208/// visitInlineAsm - Handle a call to an InlineAsm object.
3209///
3210void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
3211 InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
Chris Lattner476e67b2006-01-26 22:24:51 +00003212
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003213 /// ConstraintOperands - Information about all of the constraints.
3214 std::vector<AsmOperandInfo> ConstraintOperands;
Chris Lattner476e67b2006-01-26 22:24:51 +00003215
3216 SDOperand Chain = getRoot();
3217 SDOperand Flag;
3218
Chris Lattner1558fc62006-02-01 18:59:47 +00003219 std::set<unsigned> OutputRegs, InputRegs;
Chris Lattner7ad77df2006-02-22 00:56:39 +00003220
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003221 // Do a prepass over the constraints, canonicalizing them, and building up the
3222 // ConstraintOperands list.
3223 std::vector<InlineAsm::ConstraintInfo>
3224 ConstraintInfos = IA->ParseConstraints();
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003225
3226 // SawEarlyClobber - Keep track of whether we saw an earlyclobber output
3227 // constraint. If so, we can't let the register allocator allocate any input
3228 // registers, because it will not know to avoid the earlyclobbered output reg.
3229 bool SawEarlyClobber = false;
3230
3231 unsigned OpNo = 1; // OpNo - The operand of the CallInst.
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003232 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
3233 ConstraintOperands.push_back(AsmOperandInfo(ConstraintInfos[i]));
3234 AsmOperandInfo &OpInfo = ConstraintOperands.back();
3235
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003236 MVT::ValueType OpVT = MVT::Other;
3237
3238 // Compute the value type for each operand.
3239 switch (OpInfo.Type) {
Chris Lattner7ad77df2006-02-22 00:56:39 +00003240 case InlineAsm::isOutput:
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003241 if (!OpInfo.isIndirect) {
3242 // The return value of the call is this value. As such, there is no
3243 // corresponding argument.
Chris Lattner7ad77df2006-02-22 00:56:39 +00003244 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
3245 OpVT = TLI.getValueType(I.getType());
3246 } else {
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003247 OpInfo.CallOperandVal = I.getOperand(OpNo++);
Chris Lattner7ad77df2006-02-22 00:56:39 +00003248 }
3249 break;
3250 case InlineAsm::isInput:
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003251 OpInfo.CallOperandVal = I.getOperand(OpNo++);
Chris Lattner7ad77df2006-02-22 00:56:39 +00003252 break;
3253 case InlineAsm::isClobber:
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003254 // Nothing to do.
Chris Lattner7ad77df2006-02-22 00:56:39 +00003255 break;
3256 }
Chris Lattner7ad77df2006-02-22 00:56:39 +00003257
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003258 // If this is an input or an indirect output, process the call argument.
3259 if (OpInfo.CallOperandVal) {
3260 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
3261 const Type *OpTy = OpInfo.CallOperandVal->getType();
Chris Lattner412d61a2007-04-29 18:58:03 +00003262 // If this is an indirect operand, the operand is a pointer to the
3263 // accessed type.
3264 if (OpInfo.isIndirect)
3265 OpTy = cast<PointerType>(OpTy)->getElementType();
3266
3267 // If OpTy is not a first-class value, it may be a struct/union that we
3268 // can tile with integers.
3269 if (!OpTy->isFirstClassType() && OpTy->isSized()) {
3270 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
3271 switch (BitSize) {
3272 default: break;
3273 case 1:
3274 case 8:
3275 case 16:
3276 case 32:
3277 case 64:
3278 OpTy = IntegerType::get(BitSize);
3279 break;
3280 }
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003281 }
Chris Lattner412d61a2007-04-29 18:58:03 +00003282
3283 OpVT = TLI.getValueType(OpTy, true);
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003284 }
3285
3286 OpInfo.ConstraintVT = OpVT;
Chris Lattnerb2e55562007-04-28 21:01:43 +00003287
Chris Lattneref073322007-04-30 17:16:27 +00003288 // Compute the constraint code and ConstraintType to use.
3289 OpInfo.ComputeConstraintToUse(TLI);
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003290
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003291 // Keep track of whether we see an earlyclobber.
3292 SawEarlyClobber |= OpInfo.isEarlyClobber;
Chris Lattner401d8db2007-04-28 21:12:06 +00003293
3294 // If this is a memory input, and if the operand is not indirect, do what we
3295 // need to to provide an address for the memory input.
3296 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
3297 !OpInfo.isIndirect) {
3298 assert(OpInfo.Type == InlineAsm::isInput &&
3299 "Can only indirectify direct input operands!");
3300
3301 // Memory operands really want the address of the value. If we don't have
3302 // an indirect input, put it in the constpool if we can, otherwise spill
3303 // it to a stack slot.
3304
3305 // If the operand is a float, integer, or vector constant, spill to a
3306 // constant pool entry to get its address.
3307 Value *OpVal = OpInfo.CallOperandVal;
3308 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
3309 isa<ConstantVector>(OpVal)) {
3310 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
3311 TLI.getPointerTy());
3312 } else {
3313 // Otherwise, create a stack slot and emit a store to it before the
3314 // asm.
3315 const Type *Ty = OpVal->getType();
3316 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
3317 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
3318 MachineFunction &MF = DAG.getMachineFunction();
3319 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align);
3320 SDOperand StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
3321 Chain = DAG.getStore(Chain, OpInfo.CallOperand, StackSlot, NULL, 0);
3322 OpInfo.CallOperand = StackSlot;
3323 }
3324
3325 // There is no longer a Value* corresponding to this operand.
3326 OpInfo.CallOperandVal = 0;
3327 // It is now an indirect operand.
3328 OpInfo.isIndirect = true;
3329 }
3330
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003331 // If this constraint is for a specific register, allocate it before
3332 // anything else.
3333 if (OpInfo.ConstraintType == TargetLowering::C_Register)
3334 GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003335 }
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003336 ConstraintInfos.clear();
3337
3338
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003339 // Second pass - Loop over all of the operands, assigning virtual or physregs
3340 // to registerclass operands.
3341 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
3342 AsmOperandInfo &OpInfo = ConstraintOperands[i];
3343
3344 // C_Register operands have already been allocated, Other/Memory don't need
3345 // to be.
3346 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
3347 GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
3348 }
3349
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003350 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
3351 std::vector<SDOperand> AsmNodeOperands;
3352 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
3353 AsmNodeOperands.push_back(
3354 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), MVT::Other));
3355
Chris Lattner3a5ed552006-02-01 01:28:23 +00003356
Chris Lattner5c79f982006-02-21 23:12:12 +00003357 // Loop over all of the inputs, copying the operand values into the
3358 // appropriate registers and processing the output regs.
Chris Lattner6f87d182006-02-22 22:37:12 +00003359 RegsForValue RetValRegs;
Chris Lattner5c79f982006-02-21 23:12:12 +00003360
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003361 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
3362 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
3363
3364 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
3365 AsmOperandInfo &OpInfo = ConstraintOperands[i];
Chris Lattner7ad77df2006-02-22 00:56:39 +00003366
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003367 switch (OpInfo.Type) {
Chris Lattner3a5ed552006-02-01 01:28:23 +00003368 case InlineAsm::isOutput: {
Chris Lattnerde339fa2007-04-28 21:03:16 +00003369 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
3370 OpInfo.ConstraintType != TargetLowering::C_Register) {
Chris Lattnerd102ed02007-04-28 06:08:13 +00003371 // Memory output, or 'other' output (e.g. 'X' constraint).
Chris Lattner401d8db2007-04-28 21:12:06 +00003372 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
Chris Lattner9fed5b62006-02-27 23:45:39 +00003373
Chris Lattner9fed5b62006-02-27 23:45:39 +00003374 // Add information to the INLINEASM node to know about this output.
3375 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
Chris Lattnerc7596ef2007-05-15 01:33:58 +00003376 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
3377 TLI.getPointerTy()));
Chris Lattner401d8db2007-04-28 21:12:06 +00003378 AsmNodeOperands.push_back(OpInfo.CallOperand);
Chris Lattner9fed5b62006-02-27 23:45:39 +00003379 break;
3380 }
3381
Chris Lattnerb2e55562007-04-28 21:01:43 +00003382 // Otherwise, this is a register or register class output.
Chris Lattner9fed5b62006-02-27 23:45:39 +00003383
Chris Lattner6f87d182006-02-22 22:37:12 +00003384 // Copy the output from the appropriate register. Find a register that
Chris Lattner7ad77df2006-02-22 00:56:39 +00003385 // we can use.
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003386 if (OpInfo.AssignedRegs.Regs.empty()) {
Bill Wendling22e978a2006-12-07 20:04:42 +00003387 cerr << "Couldn't allocate output reg for contraint '"
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003388 << OpInfo.ConstraintCode << "'!\n";
Chris Lattner968f8032006-10-31 07:33:13 +00003389 exit(1);
3390 }
Chris Lattner7ad77df2006-02-22 00:56:39 +00003391
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003392 if (!OpInfo.isIndirect) {
3393 // This is the result value of the call.
Chris Lattner6f87d182006-02-22 22:37:12 +00003394 assert(RetValRegs.Regs.empty() &&
Chris Lattner3a5ed552006-02-01 01:28:23 +00003395 "Cannot have multiple output constraints yet!");
Chris Lattner3a5ed552006-02-01 01:28:23 +00003396 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003397 RetValRegs = OpInfo.AssignedRegs;
Chris Lattner3a5ed552006-02-01 01:28:23 +00003398 } else {
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003399 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003400 OpInfo.CallOperandVal));
Chris Lattner3a5ed552006-02-01 01:28:23 +00003401 }
Chris Lattner2e56e892006-01-31 02:03:41 +00003402
3403 // Add information to the INLINEASM node to know that this register is
3404 // set.
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003405 OpInfo.AssignedRegs.AddInlineAsmOperands(2 /*REGDEF*/, DAG,
3406 AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00003407 break;
3408 }
3409 case InlineAsm::isInput: {
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003410 SDOperand InOperandVal = OpInfo.CallOperand;
Chris Lattner65ad53f2006-02-04 02:16:44 +00003411
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003412 if (isdigit(OpInfo.ConstraintCode[0])) { // Matching constraint?
Chris Lattner7f5880b2006-02-02 00:25:23 +00003413 // If this is required to match an output register we have already set,
3414 // just use its register.
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003415 unsigned OperandNo = atoi(OpInfo.ConstraintCode.c_str());
Chris Lattner65ad53f2006-02-04 02:16:44 +00003416
Chris Lattner571d9642006-02-23 19:21:04 +00003417 // Scan until we find the definition we already emitted of this operand.
3418 // When we find it, create a RegsForValue operand.
3419 unsigned CurOp = 2; // The first operand.
3420 for (; OperandNo; --OperandNo) {
3421 // Advance to the next operand.
3422 unsigned NumOps =
3423 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattnerb0305322006-07-20 19:02:21 +00003424 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
3425 (NumOps & 7) == 4 /*MEM*/) &&
Chris Lattner571d9642006-02-23 19:21:04 +00003426 "Skipped past definitions?");
3427 CurOp += (NumOps>>3)+1;
3428 }
3429
3430 unsigned NumOps =
3431 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattnere3eeb242007-02-01 01:21:12 +00003432 if ((NumOps & 7) == 2 /*REGDEF*/) {
3433 // Add NumOps>>3 registers to MatchedRegs.
3434 RegsForValue MatchedRegs;
3435 MatchedRegs.ValueVT = InOperandVal.getValueType();
3436 MatchedRegs.RegVT = AsmNodeOperands[CurOp+1].getValueType();
3437 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
3438 unsigned Reg =
3439 cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
3440 MatchedRegs.Regs.push_back(Reg);
3441 }
Chris Lattner571d9642006-02-23 19:21:04 +00003442
Chris Lattnere3eeb242007-02-01 01:21:12 +00003443 // Use the produced MatchedRegs object to
3444 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag,
3445 TLI.getPointerTy());
3446 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
3447 break;
3448 } else {
3449 assert((NumOps & 7) == 4/*MEM*/ && "Unknown matching constraint!");
3450 assert(0 && "matching constraints for memory operands unimp");
Chris Lattner571d9642006-02-23 19:21:04 +00003451 }
Chris Lattner7f5880b2006-02-02 00:25:23 +00003452 }
Chris Lattner7ef7a642006-02-24 01:11:24 +00003453
Chris Lattnerb2e55562007-04-28 21:01:43 +00003454 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003455 assert(!OpInfo.isIndirect &&
Chris Lattner1deacd62007-04-28 06:42:38 +00003456 "Don't know how to handle indirect other inputs yet!");
3457
Chris Lattner6f043b92006-10-31 19:41:18 +00003458 InOperandVal = TLI.isOperandValidForConstraint(InOperandVal,
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003459 OpInfo.ConstraintCode[0],
3460 DAG);
Chris Lattner6f043b92006-10-31 19:41:18 +00003461 if (!InOperandVal.Val) {
Bill Wendling22e978a2006-12-07 20:04:42 +00003462 cerr << "Invalid operand for inline asm constraint '"
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003463 << OpInfo.ConstraintCode << "'!\n";
Chris Lattner6f043b92006-10-31 19:41:18 +00003464 exit(1);
3465 }
Chris Lattner7ef7a642006-02-24 01:11:24 +00003466
3467 // Add information to the INLINEASM node to know about this input.
3468 unsigned ResOpType = 3 /*IMM*/ | (1 << 3);
Chris Lattnerc7596ef2007-05-15 01:33:58 +00003469 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
3470 TLI.getPointerTy()));
Chris Lattner7ef7a642006-02-24 01:11:24 +00003471 AsmNodeOperands.push_back(InOperandVal);
3472 break;
Chris Lattnerb2e55562007-04-28 21:01:43 +00003473 } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
Chris Lattner401d8db2007-04-28 21:12:06 +00003474 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
Chris Lattner1deacd62007-04-28 06:42:38 +00003475 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
3476 "Memory operands expect pointer values");
3477
Chris Lattner7ef7a642006-02-24 01:11:24 +00003478 // Add information to the INLINEASM node to know about this input.
3479 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
Chris Lattnerc7596ef2007-05-15 01:33:58 +00003480 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
3481 TLI.getPointerTy()));
Chris Lattner7ef7a642006-02-24 01:11:24 +00003482 AsmNodeOperands.push_back(InOperandVal);
3483 break;
3484 }
3485
Chris Lattnerb2e55562007-04-28 21:01:43 +00003486 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
3487 OpInfo.ConstraintType == TargetLowering::C_Register) &&
3488 "Unknown constraint type!");
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003489 assert(!OpInfo.isIndirect &&
Chris Lattner1deacd62007-04-28 06:42:38 +00003490 "Don't know how to handle indirect register inputs yet!");
Chris Lattner7ef7a642006-02-24 01:11:24 +00003491
3492 // Copy the input into the appropriate registers.
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003493 assert(!OpInfo.AssignedRegs.Regs.empty() &&
3494 "Couldn't allocate input reg!");
Chris Lattner7ef7a642006-02-24 01:11:24 +00003495
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003496 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag,
3497 TLI.getPointerTy());
Chris Lattner7ef7a642006-02-24 01:11:24 +00003498
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003499 OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG,
3500 AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00003501 break;
3502 }
Chris Lattner571d9642006-02-23 19:21:04 +00003503 case InlineAsm::isClobber: {
Chris Lattner571d9642006-02-23 19:21:04 +00003504 // Add the clobbered value to the operand list, so that the register
3505 // allocator is aware that the physreg got clobbered.
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003506 if (!OpInfo.AssignedRegs.Regs.empty())
3507 OpInfo.AssignedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG,
3508 AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00003509 break;
3510 }
Chris Lattner571d9642006-02-23 19:21:04 +00003511 }
Chris Lattner2e56e892006-01-31 02:03:41 +00003512 }
Chris Lattner476e67b2006-01-26 22:24:51 +00003513
3514 // Finish up input operands.
3515 AsmNodeOperands[0] = Chain;
3516 if (Flag.Val) AsmNodeOperands.push_back(Flag);
3517
Chris Lattnerbd887772006-08-14 23:53:35 +00003518 Chain = DAG.getNode(ISD::INLINEASM,
3519 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003520 &AsmNodeOperands[0], AsmNodeOperands.size());
Chris Lattner476e67b2006-01-26 22:24:51 +00003521 Flag = Chain.getValue(1);
3522
Chris Lattner2e56e892006-01-31 02:03:41 +00003523 // If this asm returns a register value, copy the result from that register
3524 // and set it as the value of the call.
Chris Lattner51114992007-04-12 06:00:20 +00003525 if (!RetValRegs.Regs.empty()) {
3526 SDOperand Val = RetValRegs.getCopyFromRegs(DAG, Chain, Flag);
3527
3528 // If the result of the inline asm is a vector, it may have the wrong
3529 // width/num elts. Make sure to convert it to the right type with
Dan Gohmana8665142007-06-25 16:23:39 +00003530 // bit_convert.
3531 if (MVT::isVector(Val.getValueType())) {
Chris Lattner51114992007-04-12 06:00:20 +00003532 const VectorType *VTy = cast<VectorType>(I.getType());
Dan Gohmana8665142007-06-25 16:23:39 +00003533 MVT::ValueType DesiredVT = TLI.getValueType(VTy);
Chris Lattner51114992007-04-12 06:00:20 +00003534
Dan Gohmana8665142007-06-25 16:23:39 +00003535 Val = DAG.getNode(ISD::BIT_CONVERT, DesiredVT, Val);
Chris Lattner51114992007-04-12 06:00:20 +00003536 }
3537
3538 setValue(&I, Val);
3539 }
Chris Lattner476e67b2006-01-26 22:24:51 +00003540
Chris Lattner2e56e892006-01-31 02:03:41 +00003541 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
3542
3543 // Process indirect outputs, first output all of the flagged copies out of
3544 // physregs.
3545 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
Chris Lattner6f87d182006-02-22 22:37:12 +00003546 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Chris Lattner2e56e892006-01-31 02:03:41 +00003547 Value *Ptr = IndirectStoresToEmit[i].second;
Chris Lattner6f87d182006-02-22 22:37:12 +00003548 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, Flag);
3549 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner2e56e892006-01-31 02:03:41 +00003550 }
3551
3552 // Emit the non-flagged stores from the physregs.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003553 SmallVector<SDOperand, 8> OutChains;
Chris Lattner2e56e892006-01-31 02:03:41 +00003554 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003555 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
Chris Lattner2e56e892006-01-31 02:03:41 +00003556 getValue(StoresToEmit[i].second),
Evan Chengab51cf22006-10-13 21:14:26 +00003557 StoresToEmit[i].second, 0));
Chris Lattner2e56e892006-01-31 02:03:41 +00003558 if (!OutChains.empty())
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003559 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
3560 &OutChains[0], OutChains.size());
Chris Lattner476e67b2006-01-26 22:24:51 +00003561 DAG.setRoot(Chain);
3562}
3563
3564
Chris Lattner7a60d912005-01-07 07:47:53 +00003565void SelectionDAGLowering::visitMalloc(MallocInst &I) {
3566 SDOperand Src = getValue(I.getOperand(0));
3567
3568 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnereccb73d2005-01-22 23:04:37 +00003569
3570 if (IntPtr < Src.getValueType())
3571 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
3572 else if (IntPtr > Src.getValueType())
3573 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner7a60d912005-01-07 07:47:53 +00003574
3575 // Scale the source by the type size.
Owen Anderson20a631f2006-05-03 01:29:57 +00003576 uint64_t ElementSize = TD->getTypeSize(I.getType()->getElementType());
Chris Lattner7a60d912005-01-07 07:47:53 +00003577 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
3578 Src, getIntPtrConstant(ElementSize));
3579
Reid Spencere63b6512006-12-31 05:55:36 +00003580 TargetLowering::ArgListTy Args;
3581 TargetLowering::ArgListEntry Entry;
3582 Entry.Node = Src;
3583 Entry.Ty = TLI.getTargetData()->getIntPtrType();
Reid Spencere63b6512006-12-31 05:55:36 +00003584 Args.push_back(Entry);
Chris Lattner1f45cd72005-01-08 19:26:18 +00003585
3586 std::pair<SDOperand,SDOperand> Result =
Reid Spencere63b6512006-12-31 05:55:36 +00003587 TLI.LowerCallTo(getRoot(), I.getType(), false, false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00003588 DAG.getExternalSymbol("malloc", IntPtr),
3589 Args, DAG);
3590 setValue(&I, Result.first); // Pointers always fit in registers
3591 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00003592}
3593
3594void SelectionDAGLowering::visitFree(FreeInst &I) {
Reid Spencere63b6512006-12-31 05:55:36 +00003595 TargetLowering::ArgListTy Args;
3596 TargetLowering::ArgListEntry Entry;
3597 Entry.Node = getValue(I.getOperand(0));
3598 Entry.Ty = TLI.getTargetData()->getIntPtrType();
Reid Spencere63b6512006-12-31 05:55:36 +00003599 Args.push_back(Entry);
Chris Lattner7a60d912005-01-07 07:47:53 +00003600 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner1f45cd72005-01-08 19:26:18 +00003601 std::pair<SDOperand,SDOperand> Result =
Reid Spencere63b6512006-12-31 05:55:36 +00003602 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00003603 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
3604 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00003605}
3606
Chris Lattner13d7c252005-08-26 20:54:47 +00003607// InsertAtEndOfBasicBlock - This method should be implemented by targets that
3608// mark instructions with the 'usesCustomDAGSchedInserter' flag. These
3609// instructions are special in various ways, which require special support to
3610// insert. The specified MachineInstr is created but not inserted into any
3611// basic blocks, and the scheduler passes ownership of it to this method.
3612MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
3613 MachineBasicBlock *MBB) {
Bill Wendling22e978a2006-12-07 20:04:42 +00003614 cerr << "If a target marks an instruction with "
3615 << "'usesCustomDAGSchedInserter', it must implement "
3616 << "TargetLowering::InsertAtEndOfBasicBlock!\n";
Chris Lattner13d7c252005-08-26 20:54:47 +00003617 abort();
3618 return 0;
3619}
3620
Chris Lattner58cfd792005-01-09 00:00:49 +00003621void SelectionDAGLowering::visitVAStart(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00003622 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
3623 getValue(I.getOperand(1)),
3624 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner58cfd792005-01-09 00:00:49 +00003625}
3626
3627void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00003628 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
3629 getValue(I.getOperand(0)),
3630 DAG.getSrcValue(I.getOperand(0)));
3631 setValue(&I, V);
3632 DAG.setRoot(V.getValue(1));
Chris Lattner7a60d912005-01-07 07:47:53 +00003633}
3634
3635void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00003636 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
3637 getValue(I.getOperand(1)),
3638 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner7a60d912005-01-07 07:47:53 +00003639}
3640
3641void SelectionDAGLowering::visitVACopy(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00003642 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
3643 getValue(I.getOperand(1)),
3644 getValue(I.getOperand(2)),
3645 DAG.getSrcValue(I.getOperand(1)),
3646 DAG.getSrcValue(I.getOperand(2))));
Chris Lattner7a60d912005-01-07 07:47:53 +00003647}
3648
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003649/// ExpandScalarFormalArgs - Recursively expand the formal_argument node, either
3650/// bit_convert it or join a pair of them with a BUILD_PAIR when appropriate.
3651static SDOperand ExpandScalarFormalArgs(MVT::ValueType VT, SDNode *Arg,
3652 unsigned &i, SelectionDAG &DAG,
3653 TargetLowering &TLI) {
3654 if (TLI.getTypeAction(VT) != TargetLowering::Expand)
3655 return SDOperand(Arg, i++);
3656
3657 MVT::ValueType EVT = TLI.getTypeToTransformTo(VT);
3658 unsigned NumVals = MVT::getSizeInBits(VT) / MVT::getSizeInBits(EVT);
3659 if (NumVals == 1) {
3660 return DAG.getNode(ISD::BIT_CONVERT, VT,
3661 ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI));
3662 } else if (NumVals == 2) {
3663 SDOperand Lo = ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI);
3664 SDOperand Hi = ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI);
3665 if (!TLI.isLittleEndian())
3666 std::swap(Lo, Hi);
3667 return DAG.getNode(ISD::BUILD_PAIR, VT, Lo, Hi);
3668 } else {
3669 // Value scalarized into many values. Unimp for now.
3670 assert(0 && "Cannot expand i64 -> i16 yet!");
3671 }
3672 return SDOperand();
3673}
3674
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003675/// TargetLowering::LowerArguments - This is the default LowerArguments
3676/// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
Chris Lattneraaa23d92006-05-16 22:53:20 +00003677/// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
3678/// integrated into SDISel.
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003679std::vector<SDOperand>
3680TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003681 const FunctionType *FTy = F.getFunctionType();
Reid Spencer71b79e32007-04-09 06:17:21 +00003682 const ParamAttrsList *Attrs = FTy->getParamAttrs();
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003683 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
3684 std::vector<SDOperand> Ops;
Chris Lattner3d826992006-05-16 06:45:34 +00003685 Ops.push_back(DAG.getRoot());
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003686 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
3687 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
3688
3689 // Add one result value for each formal argument.
3690 std::vector<MVT::ValueType> RetVals;
Anton Korobeynikov06f7d4b2007-01-28 18:01:49 +00003691 unsigned j = 1;
Anton Korobeynikov9fa38392007-01-28 16:04:40 +00003692 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
3693 I != E; ++I, ++j) {
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003694 MVT::ValueType VT = getValueType(I->getType());
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003695 unsigned Flags = ISD::ParamFlags::NoFlagSet;
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003696 unsigned OriginalAlignment =
Chris Lattner945e4372007-02-14 05:52:17 +00003697 getTargetData()->getABITypeAlignment(I->getType());
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003698
Chris Lattnerab5d0ac2007-02-26 02:56:58 +00003699 // FIXME: Distinguish between a formal with no [sz]ext attribute from one
3700 // that is zero extended!
Reid Spencera472f662007-04-11 02:44:20 +00003701 if (Attrs && Attrs->paramHasAttr(j, ParamAttr::ZExt))
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003702 Flags &= ~(ISD::ParamFlags::SExt);
Reid Spencera472f662007-04-11 02:44:20 +00003703 if (Attrs && Attrs->paramHasAttr(j, ParamAttr::SExt))
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003704 Flags |= ISD::ParamFlags::SExt;
Reid Spencera472f662007-04-11 02:44:20 +00003705 if (Attrs && Attrs->paramHasAttr(j, ParamAttr::InReg))
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003706 Flags |= ISD::ParamFlags::InReg;
Reid Spencera472f662007-04-11 02:44:20 +00003707 if (Attrs && Attrs->paramHasAttr(j, ParamAttr::StructRet))
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003708 Flags |= ISD::ParamFlags::StructReturn;
3709 Flags |= (OriginalAlignment << ISD::ParamFlags::OrigAlignmentOffs);
Chris Lattnerab5d0ac2007-02-26 02:56:58 +00003710
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003711 switch (getTypeAction(VT)) {
3712 default: assert(0 && "Unknown type action!");
3713 case Legal:
3714 RetVals.push_back(VT);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003715 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003716 break;
3717 case Promote:
3718 RetVals.push_back(getTypeToTransformTo(VT));
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003719 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003720 break;
3721 case Expand:
Dan Gohmana8665142007-06-25 16:23:39 +00003722 if (!MVT::isVector(VT)) {
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003723 // If this is a large integer, it needs to be broken up into small
3724 // integers. Figure out what the destination type is and how many small
3725 // integers it turns into.
Evan Cheng22cf8992006-12-13 20:57:08 +00003726 MVT::ValueType NVT = getTypeToExpandTo(VT);
Dan Gohman04deef32007-06-21 14:42:22 +00003727 unsigned NumVals = getNumRegisters(VT);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003728 for (unsigned i = 0; i != NumVals; ++i) {
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003729 RetVals.push_back(NVT);
Lauro Ramos Venancioabde3cc2007-02-13 18:10:13 +00003730 // if it isn't first piece, alignment must be 1
Anton Korobeynikovf0b93162007-03-06 06:10:33 +00003731 if (i > 0)
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003732 Flags = (Flags & (~ISD::ParamFlags::OrigAlignment)) |
3733 (1 << ISD::ParamFlags::OrigAlignmentOffs);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003734 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
3735 }
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003736 } else {
3737 // Otherwise, this is a vector type. We only support legal vectors
3738 // right now.
Reid Spencerd84d35b2007-02-15 02:26:10 +00003739 unsigned NumElems = cast<VectorType>(I->getType())->getNumElements();
3740 const Type *EltTy = cast<VectorType>(I->getType())->getElementType();
Evan Cheng3784f3c52006-04-27 08:29:42 +00003741
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003742 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencer09575ba2007-02-15 03:39:18 +00003743 // type. If so, convert to the vector type.
Dan Gohmana8665142007-06-25 16:23:39 +00003744 MVT::ValueType TVT =
3745 MVT::getVectorType(getValueType(EltTy), NumElems);
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003746 if (TVT != MVT::Other && isTypeLegal(TVT)) {
3747 RetVals.push_back(TVT);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003748 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003749 } else {
3750 assert(0 && "Don't support illegal by-val vector arguments yet!");
3751 }
3752 }
3753 break;
3754 }
3755 }
Evan Cheng9618df12006-04-25 23:03:35 +00003756
Chris Lattner3d826992006-05-16 06:45:34 +00003757 RetVals.push_back(MVT::Other);
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003758
3759 // Create the node.
Chris Lattnerbd887772006-08-14 23:53:35 +00003760 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
3761 DAG.getNodeValueTypes(RetVals), RetVals.size(),
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003762 &Ops[0], Ops.size()).Val;
Chris Lattner3d826992006-05-16 06:45:34 +00003763
3764 DAG.setRoot(SDOperand(Result, Result->getNumValues()-1));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003765
3766 // Set up the return result vector.
3767 Ops.clear();
3768 unsigned i = 0;
Reid Spencere63b6512006-12-31 05:55:36 +00003769 unsigned Idx = 1;
3770 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
3771 ++I, ++Idx) {
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003772 MVT::ValueType VT = getValueType(I->getType());
3773
3774 switch (getTypeAction(VT)) {
3775 default: assert(0 && "Unknown type action!");
3776 case Legal:
3777 Ops.push_back(SDOperand(Result, i++));
3778 break;
3779 case Promote: {
3780 SDOperand Op(Result, i++);
3781 if (MVT::isInteger(VT)) {
Reid Spencera472f662007-04-11 02:44:20 +00003782 if (Attrs && Attrs->paramHasAttr(Idx, ParamAttr::SExt))
Chris Lattner96035be2007-01-04 22:22:37 +00003783 Op = DAG.getNode(ISD::AssertSext, Op.getValueType(), Op,
3784 DAG.getValueType(VT));
Reid Spencera472f662007-04-11 02:44:20 +00003785 else if (Attrs && Attrs->paramHasAttr(Idx, ParamAttr::ZExt))
Chris Lattner96035be2007-01-04 22:22:37 +00003786 Op = DAG.getNode(ISD::AssertZext, Op.getValueType(), Op,
3787 DAG.getValueType(VT));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003788 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
3789 } else {
3790 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
3791 Op = DAG.getNode(ISD::FP_ROUND, VT, Op);
3792 }
3793 Ops.push_back(Op);
3794 break;
3795 }
3796 case Expand:
Dan Gohmana8665142007-06-25 16:23:39 +00003797 if (!MVT::isVector(VT)) {
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003798 // If this is a large integer or a floating point node that needs to be
3799 // expanded, it needs to be reassembled from small integers. Figure out
3800 // what the source elt type is and how many small integers it is.
3801 Ops.push_back(ExpandScalarFormalArgs(VT, Result, i, DAG, *this));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003802 } else {
3803 // Otherwise, this is a vector type. We only support legal vectors
3804 // right now.
Reid Spencerd84d35b2007-02-15 02:26:10 +00003805 const VectorType *PTy = cast<VectorType>(I->getType());
Evan Chengd43c5c62006-04-28 05:25:15 +00003806 unsigned NumElems = PTy->getNumElements();
3807 const Type *EltTy = PTy->getElementType();
Evan Cheng3784f3c52006-04-27 08:29:42 +00003808
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003809 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencer09575ba2007-02-15 03:39:18 +00003810 // type. If so, convert to the vector type.
Dan Gohmana8665142007-06-25 16:23:39 +00003811 MVT::ValueType TVT =
3812 MVT::getVectorType(getValueType(EltTy), NumElems);
Chris Lattner7949c2e2006-05-17 20:49:36 +00003813 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Evan Chengd43c5c62006-04-28 05:25:15 +00003814 SDOperand N = SDOperand(Result, i++);
Dan Gohmana8665142007-06-25 16:23:39 +00003815 // Handle copies from vectors to registers.
3816 N = DAG.getNode(ISD::BIT_CONVERT, TVT, N);
Chris Lattner7949c2e2006-05-17 20:49:36 +00003817 Ops.push_back(N);
3818 } else {
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003819 assert(0 && "Don't support illegal by-val vector arguments yet!");
Chris Lattnerb77ba732006-05-16 23:39:44 +00003820 abort();
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003821 }
3822 }
3823 break;
3824 }
3825 }
3826 return Ops;
3827}
3828
Chris Lattneraaa23d92006-05-16 22:53:20 +00003829
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003830/// ExpandScalarCallArgs - Recursively expand call argument node by
3831/// bit_converting it or extract a pair of elements from the larger node.
3832static void ExpandScalarCallArgs(MVT::ValueType VT, SDOperand Arg,
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003833 unsigned Flags,
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003834 SmallVector<SDOperand, 32> &Ops,
3835 SelectionDAG &DAG,
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003836 TargetLowering &TLI,
3837 bool isFirst = true) {
3838
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003839 if (TLI.getTypeAction(VT) != TargetLowering::Expand) {
Lauro Ramos Venancioabde3cc2007-02-13 18:10:13 +00003840 // if it isn't first piece, alignment must be 1
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003841 if (!isFirst)
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003842 Flags = (Flags & (~ISD::ParamFlags::OrigAlignment)) |
3843 (1 << ISD::ParamFlags::OrigAlignmentOffs);
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003844 Ops.push_back(Arg);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003845 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003846 return;
3847 }
3848
3849 MVT::ValueType EVT = TLI.getTypeToTransformTo(VT);
3850 unsigned NumVals = MVT::getSizeInBits(VT) / MVT::getSizeInBits(EVT);
3851 if (NumVals == 1) {
3852 Arg = DAG.getNode(ISD::BIT_CONVERT, EVT, Arg);
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003853 ExpandScalarCallArgs(EVT, Arg, Flags, Ops, DAG, TLI, isFirst);
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003854 } else if (NumVals == 2) {
3855 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, EVT, Arg,
3856 DAG.getConstant(0, TLI.getPointerTy()));
3857 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, EVT, Arg,
3858 DAG.getConstant(1, TLI.getPointerTy()));
3859 if (!TLI.isLittleEndian())
3860 std::swap(Lo, Hi);
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003861 ExpandScalarCallArgs(EVT, Lo, Flags, Ops, DAG, TLI, isFirst);
3862 ExpandScalarCallArgs(EVT, Hi, Flags, Ops, DAG, TLI, false);
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003863 } else {
3864 // Value scalarized into many values. Unimp for now.
3865 assert(0 && "Cannot expand i64 -> i16 yet!");
3866 }
3867}
3868
Chris Lattneraaa23d92006-05-16 22:53:20 +00003869/// TargetLowering::LowerCallTo - This is the default LowerCallTo
3870/// implementation, which just inserts an ISD::CALL node, which is later custom
3871/// lowered by the target to something concrete. FIXME: When all targets are
3872/// migrated to using ISD::CALL, this hook should be integrated into SDISel.
3873std::pair<SDOperand, SDOperand>
Reid Spencere63b6512006-12-31 05:55:36 +00003874TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy,
3875 bool RetTyIsSigned, bool isVarArg,
Chris Lattneraaa23d92006-05-16 22:53:20 +00003876 unsigned CallingConv, bool isTailCall,
3877 SDOperand Callee,
3878 ArgListTy &Args, SelectionDAG &DAG) {
Chris Lattner65879ca2006-08-16 22:57:46 +00003879 SmallVector<SDOperand, 32> Ops;
Chris Lattneraaa23d92006-05-16 22:53:20 +00003880 Ops.push_back(Chain); // Op#0 - Chain
3881 Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
3882 Ops.push_back(DAG.getConstant(isVarArg, getPointerTy())); // Op#2 - VarArg
3883 Ops.push_back(DAG.getConstant(isTailCall, getPointerTy())); // Op#3 - Tail
3884 Ops.push_back(Callee);
3885
3886 // Handle all of the outgoing arguments.
3887 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
Reid Spencere63b6512006-12-31 05:55:36 +00003888 MVT::ValueType VT = getValueType(Args[i].Ty);
3889 SDOperand Op = Args[i].Node;
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003890 unsigned Flags = ISD::ParamFlags::NoFlagSet;
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003891 unsigned OriginalAlignment =
Chris Lattner945e4372007-02-14 05:52:17 +00003892 getTargetData()->getABITypeAlignment(Args[i].Ty);
Anton Korobeynikovf0b93162007-03-06 06:10:33 +00003893
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003894 if (Args[i].isSExt)
3895 Flags |= ISD::ParamFlags::SExt;
3896 if (Args[i].isZExt)
3897 Flags |= ISD::ParamFlags::ZExt;
Anton Korobeynikovf0b93162007-03-06 06:10:33 +00003898 if (Args[i].isInReg)
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003899 Flags |= ISD::ParamFlags::InReg;
Anton Korobeynikovf0b93162007-03-06 06:10:33 +00003900 if (Args[i].isSRet)
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003901 Flags |= ISD::ParamFlags::StructReturn;
3902 Flags |= OriginalAlignment << ISD::ParamFlags::OrigAlignmentOffs;
Anton Korobeynikovf0b93162007-03-06 06:10:33 +00003903
Chris Lattneraaa23d92006-05-16 22:53:20 +00003904 switch (getTypeAction(VT)) {
3905 default: assert(0 && "Unknown type action!");
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003906 case Legal:
Chris Lattneraaa23d92006-05-16 22:53:20 +00003907 Ops.push_back(Op);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003908 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattneraaa23d92006-05-16 22:53:20 +00003909 break;
3910 case Promote:
3911 if (MVT::isInteger(VT)) {
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003912 unsigned ExtOp;
3913 if (Args[i].isSExt)
3914 ExtOp = ISD::SIGN_EXTEND;
3915 else if (Args[i].isZExt)
3916 ExtOp = ISD::ZERO_EXTEND;
3917 else
3918 ExtOp = ISD::ANY_EXTEND;
Chris Lattneraaa23d92006-05-16 22:53:20 +00003919 Op = DAG.getNode(ExtOp, getTypeToTransformTo(VT), Op);
3920 } else {
3921 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
Dale Johannesen9a4d9872007-06-07 21:07:15 +00003922 // A true promotion would change the size of the argument.
3923 // Instead, pretend this is an int. If FP objects are not
3924 // passed the same as ints, the original type should be Legal
3925 // and we should not get here.
3926 Op = DAG.getNode(ISD::BIT_CONVERT,
3927 VT==MVT::f32 ? MVT::i32 :
3928 (VT==MVT::f64 ? MVT::i64 :
3929 MVT::Other),
3930 Op);
Chris Lattneraaa23d92006-05-16 22:53:20 +00003931 }
3932 Ops.push_back(Op);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003933 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattneraaa23d92006-05-16 22:53:20 +00003934 break;
3935 case Expand:
Dan Gohmana8665142007-06-25 16:23:39 +00003936 if (!MVT::isVector(VT)) {
Chris Lattneraaa23d92006-05-16 22:53:20 +00003937 // If this is a large integer, it needs to be broken down into small
3938 // integers. Figure out what the source elt type is and how many small
3939 // integers it is.
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003940 ExpandScalarCallArgs(VT, Op, Flags, Ops, DAG, *this);
Chris Lattneraaa23d92006-05-16 22:53:20 +00003941 } else {
Chris Lattnerb77ba732006-05-16 23:39:44 +00003942 // Otherwise, this is a vector type. We only support legal vectors
3943 // right now.
Reid Spencerd84d35b2007-02-15 02:26:10 +00003944 const VectorType *PTy = cast<VectorType>(Args[i].Ty);
Chris Lattnerb77ba732006-05-16 23:39:44 +00003945 unsigned NumElems = PTy->getNumElements();
3946 const Type *EltTy = PTy->getElementType();
3947
3948 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencer09575ba2007-02-15 03:39:18 +00003949 // type. If so, convert to the vector type.
Dan Gohmana8665142007-06-25 16:23:39 +00003950 MVT::ValueType TVT =
3951 MVT::getVectorType(getValueType(EltTy), NumElems);
Chris Lattner938155c2006-05-17 20:43:21 +00003952 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Dan Gohmana8665142007-06-25 16:23:39 +00003953 // Insert a BIT_CONVERT of the original type to the vector type.
3954 Op = DAG.getNode(ISD::BIT_CONVERT, TVT, Op);
Chris Lattner938155c2006-05-17 20:43:21 +00003955 Ops.push_back(Op);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003956 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattner938155c2006-05-17 20:43:21 +00003957 } else {
Chris Lattnerb77ba732006-05-16 23:39:44 +00003958 assert(0 && "Don't support illegal by-val vector call args yet!");
3959 abort();
3960 }
Chris Lattneraaa23d92006-05-16 22:53:20 +00003961 }
3962 break;
3963 }
3964 }
3965
3966 // Figure out the result value types.
Chris Lattner65879ca2006-08-16 22:57:46 +00003967 SmallVector<MVT::ValueType, 4> RetTys;
Chris Lattneraaa23d92006-05-16 22:53:20 +00003968
3969 if (RetTy != Type::VoidTy) {
3970 MVT::ValueType VT = getValueType(RetTy);
3971 switch (getTypeAction(VT)) {
3972 default: assert(0 && "Unknown type action!");
3973 case Legal:
3974 RetTys.push_back(VT);
3975 break;
3976 case Promote:
3977 RetTys.push_back(getTypeToTransformTo(VT));
3978 break;
3979 case Expand:
Dan Gohmana8665142007-06-25 16:23:39 +00003980 if (!MVT::isVector(VT)) {
Chris Lattneraaa23d92006-05-16 22:53:20 +00003981 // If this is a large integer, it needs to be reassembled from small
3982 // integers. Figure out what the source elt type is and how many small
3983 // integers it is.
Evan Cheng22cf8992006-12-13 20:57:08 +00003984 MVT::ValueType NVT = getTypeToExpandTo(VT);
Dan Gohman04deef32007-06-21 14:42:22 +00003985 unsigned NumVals = getNumRegisters(VT);
Chris Lattneraaa23d92006-05-16 22:53:20 +00003986 for (unsigned i = 0; i != NumVals; ++i)
3987 RetTys.push_back(NVT);
3988 } else {
Chris Lattnerb77ba732006-05-16 23:39:44 +00003989 // Otherwise, this is a vector type. We only support legal vectors
3990 // right now.
Reid Spencerd84d35b2007-02-15 02:26:10 +00003991 const VectorType *PTy = cast<VectorType>(RetTy);
Chris Lattnerb77ba732006-05-16 23:39:44 +00003992 unsigned NumElems = PTy->getNumElements();
3993 const Type *EltTy = PTy->getElementType();
3994
3995 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencer09575ba2007-02-15 03:39:18 +00003996 // type. If so, convert to the vector type.
Dan Gohmana8665142007-06-25 16:23:39 +00003997 MVT::ValueType TVT =
3998 MVT::getVectorType(getValueType(EltTy), NumElems);
Chris Lattnerb77ba732006-05-16 23:39:44 +00003999 if (TVT != MVT::Other && isTypeLegal(TVT)) {
4000 RetTys.push_back(TVT);
4001 } else {
4002 assert(0 && "Don't support illegal by-val vector call results yet!");
4003 abort();
4004 }
Chris Lattneraaa23d92006-05-16 22:53:20 +00004005 }
4006 }
4007 }
4008
4009 RetTys.push_back(MVT::Other); // Always has a chain.
4010
4011 // Finally, create the CALL node.
Chris Lattner65879ca2006-08-16 22:57:46 +00004012 SDOperand Res = DAG.getNode(ISD::CALL,
4013 DAG.getVTList(&RetTys[0], RetTys.size()),
4014 &Ops[0], Ops.size());
Chris Lattneraaa23d92006-05-16 22:53:20 +00004015
4016 // This returns a pair of operands. The first element is the
4017 // return value for the function (if RetTy is not VoidTy). The second
4018 // element is the outgoing token chain.
4019 SDOperand ResVal;
4020 if (RetTys.size() != 1) {
4021 MVT::ValueType VT = getValueType(RetTy);
4022 if (RetTys.size() == 2) {
4023 ResVal = Res;
4024
4025 // If this value was promoted, truncate it down.
4026 if (ResVal.getValueType() != VT) {
Dan Gohmana8665142007-06-25 16:23:39 +00004027 if (MVT::isVector(VT)) {
4028 // Insert a BIT_CONVERT to convert from the packed result type to the
4029 // new vector type.
Reid Spencerd84d35b2007-02-15 02:26:10 +00004030 unsigned NumElems = cast<VectorType>(RetTy)->getNumElements();
4031 const Type *EltTy = cast<VectorType>(RetTy)->getElementType();
Chris Lattnerb77ba732006-05-16 23:39:44 +00004032
4033 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencer09575ba2007-02-15 03:39:18 +00004034 // type. If so, convert to the vector type.
Dan Gohmana8665142007-06-25 16:23:39 +00004035 MVT::ValueType TVT =
4036 MVT::getVectorType(getValueType(EltTy),NumElems);
Chris Lattnerb77ba732006-05-16 23:39:44 +00004037 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Dan Gohmana8665142007-06-25 16:23:39 +00004038 // Insert a BIT_CONVERT of the FORMAL_ARGUMENTS to a
4039 // "N x PTyElementVT" vector type.
4040 ResVal = DAG.getNode(ISD::BIT_CONVERT, TVT, ResVal);
Chris Lattnerb77ba732006-05-16 23:39:44 +00004041 } else {
4042 abort();
4043 }
4044 } else if (MVT::isInteger(VT)) {
Reid Spencere63b6512006-12-31 05:55:36 +00004045 unsigned AssertOp = ISD::AssertSext;
4046 if (!RetTyIsSigned)
4047 AssertOp = ISD::AssertZext;
Chris Lattneraaa23d92006-05-16 22:53:20 +00004048 ResVal = DAG.getNode(AssertOp, ResVal.getValueType(), ResVal,
4049 DAG.getValueType(VT));
4050 ResVal = DAG.getNode(ISD::TRUNCATE, VT, ResVal);
4051 } else {
4052 assert(MVT::isFloatingPoint(VT));
Evan Cheng4eee7242006-12-09 02:42:38 +00004053 if (getTypeAction(VT) == Expand)
4054 ResVal = DAG.getNode(ISD::BIT_CONVERT, VT, ResVal);
4055 else
4056 ResVal = DAG.getNode(ISD::FP_ROUND, VT, ResVal);
Chris Lattneraaa23d92006-05-16 22:53:20 +00004057 }
4058 }
4059 } else if (RetTys.size() == 3) {
4060 ResVal = DAG.getNode(ISD::BUILD_PAIR, VT,
4061 Res.getValue(0), Res.getValue(1));
4062
4063 } else {
4064 assert(0 && "Case not handled yet!");
4065 }
4066 }
4067
4068 return std::make_pair(ResVal, Res.getValue(Res.Val->getNumValues()-1));
4069}
4070
Chris Lattner29dcc712005-05-14 05:50:48 +00004071SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner897cd7d2005-01-16 07:28:41 +00004072 assert(0 && "LowerOperation not implemented for this target!");
4073 abort();
Misha Brukman73e929f2005-02-17 21:39:27 +00004074 return SDOperand();
Chris Lattner897cd7d2005-01-16 07:28:41 +00004075}
4076
Nate Begeman595ec732006-01-28 03:14:31 +00004077SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
4078 SelectionDAG &DAG) {
4079 assert(0 && "CustomPromoteOperation not implemented for this target!");
4080 abort();
4081 return SDOperand();
4082}
4083
Evan Cheng6781b6e2006-02-15 21:59:04 +00004084/// getMemsetValue - Vectorized representation of the memset value
Evan Cheng81fcea82006-02-14 08:22:34 +00004085/// operand.
4086static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
Evan Cheng93e48652006-02-15 22:12:35 +00004087 SelectionDAG &DAG) {
Evan Cheng81fcea82006-02-14 08:22:34 +00004088 MVT::ValueType CurVT = VT;
4089 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
4090 uint64_t Val = C->getValue() & 255;
4091 unsigned Shift = 8;
4092 while (CurVT != MVT::i8) {
4093 Val = (Val << Shift) | Val;
4094 Shift <<= 1;
4095 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00004096 }
4097 return DAG.getConstant(Val, VT);
4098 } else {
4099 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
4100 unsigned Shift = 8;
4101 while (CurVT != MVT::i8) {
4102 Value =
4103 DAG.getNode(ISD::OR, VT,
4104 DAG.getNode(ISD::SHL, VT, Value,
4105 DAG.getConstant(Shift, MVT::i8)), Value);
4106 Shift <<= 1;
4107 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00004108 }
4109
4110 return Value;
4111 }
4112}
4113
Evan Cheng6781b6e2006-02-15 21:59:04 +00004114/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
4115/// used when a memcpy is turned into a memset when the source is a constant
4116/// string ptr.
4117static SDOperand getMemsetStringVal(MVT::ValueType VT,
4118 SelectionDAG &DAG, TargetLowering &TLI,
4119 std::string &Str, unsigned Offset) {
Evan Cheng6781b6e2006-02-15 21:59:04 +00004120 uint64_t Val = 0;
Dan Gohman1796f1f2007-05-18 17:52:13 +00004121 unsigned MSB = MVT::getSizeInBits(VT) / 8;
Evan Cheng6781b6e2006-02-15 21:59:04 +00004122 if (TLI.isLittleEndian())
4123 Offset = Offset + MSB - 1;
4124 for (unsigned i = 0; i != MSB; ++i) {
Evan Cheng6e12a052006-11-29 01:38:07 +00004125 Val = (Val << 8) | (unsigned char)Str[Offset];
Evan Cheng6781b6e2006-02-15 21:59:04 +00004126 Offset += TLI.isLittleEndian() ? -1 : 1;
4127 }
4128 return DAG.getConstant(Val, VT);
4129}
4130
Evan Cheng81fcea82006-02-14 08:22:34 +00004131/// getMemBasePlusOffset - Returns base and offset node for the
4132static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
4133 SelectionDAG &DAG, TargetLowering &TLI) {
4134 MVT::ValueType VT = Base.getValueType();
4135 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
4136}
4137
Evan Chengdb2a7a72006-02-14 20:12:38 +00004138/// MeetsMaxMemopRequirement - Determines if the number of memory ops required
Evan Chengd5026102006-02-14 09:11:59 +00004139/// to replace the memset / memcpy is below the threshold. It also returns the
4140/// types of the sequence of memory ops to perform memset / memcpy.
Evan Chengdb2a7a72006-02-14 20:12:38 +00004141static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
4142 unsigned Limit, uint64_t Size,
4143 unsigned Align, TargetLowering &TLI) {
Evan Cheng81fcea82006-02-14 08:22:34 +00004144 MVT::ValueType VT;
4145
4146 if (TLI.allowsUnalignedMemoryAccesses()) {
4147 VT = MVT::i64;
4148 } else {
4149 switch (Align & 7) {
4150 case 0:
4151 VT = MVT::i64;
4152 break;
4153 case 4:
4154 VT = MVT::i32;
4155 break;
4156 case 2:
4157 VT = MVT::i16;
4158 break;
4159 default:
4160 VT = MVT::i8;
4161 break;
4162 }
4163 }
4164
Evan Chengd5026102006-02-14 09:11:59 +00004165 MVT::ValueType LVT = MVT::i64;
4166 while (!TLI.isTypeLegal(LVT))
4167 LVT = (MVT::ValueType)((unsigned)LVT - 1);
4168 assert(MVT::isInteger(LVT));
Evan Cheng81fcea82006-02-14 08:22:34 +00004169
Evan Chengd5026102006-02-14 09:11:59 +00004170 if (VT > LVT)
4171 VT = LVT;
4172
Evan Cheng04514992006-02-14 23:05:54 +00004173 unsigned NumMemOps = 0;
Evan Cheng81fcea82006-02-14 08:22:34 +00004174 while (Size != 0) {
Dan Gohman1796f1f2007-05-18 17:52:13 +00004175 unsigned VTSize = MVT::getSizeInBits(VT) / 8;
Evan Cheng81fcea82006-02-14 08:22:34 +00004176 while (VTSize > Size) {
4177 VT = (MVT::ValueType)((unsigned)VT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00004178 VTSize >>= 1;
4179 }
Evan Chengd5026102006-02-14 09:11:59 +00004180 assert(MVT::isInteger(VT));
4181
4182 if (++NumMemOps > Limit)
4183 return false;
Evan Cheng81fcea82006-02-14 08:22:34 +00004184 MemOps.push_back(VT);
4185 Size -= VTSize;
4186 }
Evan Chengd5026102006-02-14 09:11:59 +00004187
4188 return true;
Evan Cheng81fcea82006-02-14 08:22:34 +00004189}
4190
Chris Lattner875def92005-01-11 05:56:49 +00004191void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
Evan Cheng81fcea82006-02-14 08:22:34 +00004192 SDOperand Op1 = getValue(I.getOperand(1));
4193 SDOperand Op2 = getValue(I.getOperand(2));
4194 SDOperand Op3 = getValue(I.getOperand(3));
4195 SDOperand Op4 = getValue(I.getOperand(4));
4196 unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
4197 if (Align == 0) Align = 1;
4198
4199 if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
4200 std::vector<MVT::ValueType> MemOps;
Evan Cheng81fcea82006-02-14 08:22:34 +00004201
4202 // Expand memset / memcpy to a series of load / store ops
4203 // if the size operand falls below a certain threshold.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00004204 SmallVector<SDOperand, 8> OutChains;
Evan Cheng81fcea82006-02-14 08:22:34 +00004205 switch (Op) {
Evan Cheng038521e2006-02-14 19:45:56 +00004206 default: break; // Do nothing for now.
Evan Cheng81fcea82006-02-14 08:22:34 +00004207 case ISD::MEMSET: {
Evan Chengdb2a7a72006-02-14 20:12:38 +00004208 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
4209 Size->getValue(), Align, TLI)) {
Evan Chengd5026102006-02-14 09:11:59 +00004210 unsigned NumMemOps = MemOps.size();
Evan Cheng81fcea82006-02-14 08:22:34 +00004211 unsigned Offset = 0;
4212 for (unsigned i = 0; i < NumMemOps; i++) {
4213 MVT::ValueType VT = MemOps[i];
Dan Gohman1796f1f2007-05-18 17:52:13 +00004214 unsigned VTSize = MVT::getSizeInBits(VT) / 8;
Evan Cheng93e48652006-02-15 22:12:35 +00004215 SDOperand Value = getMemsetValue(Op2, VT, DAG);
Evan Chengdf9ac472006-10-05 23:01:46 +00004216 SDOperand Store = DAG.getStore(getRoot(), Value,
Chris Lattner6f87d182006-02-22 22:37:12 +00004217 getMemBasePlusOffset(Op1, Offset, DAG, TLI),
Evan Chengab51cf22006-10-13 21:14:26 +00004218 I.getOperand(1), Offset);
Evan Chenge2038bd2006-02-15 01:54:51 +00004219 OutChains.push_back(Store);
Evan Cheng81fcea82006-02-14 08:22:34 +00004220 Offset += VTSize;
4221 }
Evan Cheng81fcea82006-02-14 08:22:34 +00004222 }
Evan Chenge2038bd2006-02-15 01:54:51 +00004223 break;
Evan Cheng81fcea82006-02-14 08:22:34 +00004224 }
Evan Chenge2038bd2006-02-15 01:54:51 +00004225 case ISD::MEMCPY: {
4226 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
4227 Size->getValue(), Align, TLI)) {
4228 unsigned NumMemOps = MemOps.size();
Evan Chengc3dcf5a2006-02-16 23:11:42 +00004229 unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
Evan Cheng6781b6e2006-02-15 21:59:04 +00004230 GlobalAddressSDNode *G = NULL;
4231 std::string Str;
Evan Chengc3dcf5a2006-02-16 23:11:42 +00004232 bool CopyFromStr = false;
Evan Cheng6781b6e2006-02-15 21:59:04 +00004233
4234 if (Op2.getOpcode() == ISD::GlobalAddress)
4235 G = cast<GlobalAddressSDNode>(Op2);
4236 else if (Op2.getOpcode() == ISD::ADD &&
4237 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
4238 Op2.getOperand(1).getOpcode() == ISD::Constant) {
4239 G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
Evan Chengc3dcf5a2006-02-16 23:11:42 +00004240 SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
Evan Cheng6781b6e2006-02-15 21:59:04 +00004241 }
4242 if (G) {
4243 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
Evan Chengfeba5072006-11-29 01:58:12 +00004244 if (GV && GV->isConstant()) {
Evan Cheng38280c02006-03-10 23:52:03 +00004245 Str = GV->getStringValue(false);
Evan Chengc3dcf5a2006-02-16 23:11:42 +00004246 if (!Str.empty()) {
4247 CopyFromStr = true;
4248 SrcOff += SrcDelta;
4249 }
4250 }
Evan Cheng6781b6e2006-02-15 21:59:04 +00004251 }
4252
Evan Chenge2038bd2006-02-15 01:54:51 +00004253 for (unsigned i = 0; i < NumMemOps; i++) {
4254 MVT::ValueType VT = MemOps[i];
Dan Gohman1796f1f2007-05-18 17:52:13 +00004255 unsigned VTSize = MVT::getSizeInBits(VT) / 8;
Evan Cheng6781b6e2006-02-15 21:59:04 +00004256 SDOperand Value, Chain, Store;
4257
Evan Chengc3dcf5a2006-02-16 23:11:42 +00004258 if (CopyFromStr) {
Evan Cheng6781b6e2006-02-15 21:59:04 +00004259 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
4260 Chain = getRoot();
4261 Store =
Evan Chengdf9ac472006-10-05 23:01:46 +00004262 DAG.getStore(Chain, Value,
4263 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
Evan Chengab51cf22006-10-13 21:14:26 +00004264 I.getOperand(1), DstOff);
Evan Cheng6781b6e2006-02-15 21:59:04 +00004265 } else {
4266 Value = DAG.getLoad(VT, getRoot(),
4267 getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
Evan Chenge71fe34d2006-10-09 20:57:25 +00004268 I.getOperand(2), SrcOff);
Evan Cheng6781b6e2006-02-15 21:59:04 +00004269 Chain = Value.getValue(1);
4270 Store =
Evan Chengdf9ac472006-10-05 23:01:46 +00004271 DAG.getStore(Chain, Value,
4272 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
Evan Chengab51cf22006-10-13 21:14:26 +00004273 I.getOperand(1), DstOff);
Evan Cheng6781b6e2006-02-15 21:59:04 +00004274 }
Evan Chenge2038bd2006-02-15 01:54:51 +00004275 OutChains.push_back(Store);
Evan Cheng6781b6e2006-02-15 21:59:04 +00004276 SrcOff += VTSize;
4277 DstOff += VTSize;
Evan Chenge2038bd2006-02-15 01:54:51 +00004278 }
4279 }
4280 break;
4281 }
4282 }
4283
4284 if (!OutChains.empty()) {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00004285 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
4286 &OutChains[0], OutChains.size()));
Evan Chenge2038bd2006-02-15 01:54:51 +00004287 return;
Evan Cheng81fcea82006-02-14 08:22:34 +00004288 }
4289 }
4290
Chris Lattnerc24a1d32006-08-08 02:23:42 +00004291 DAG.setRoot(DAG.getNode(Op, MVT::Other, getRoot(), Op1, Op2, Op3, Op4));
Chris Lattner7a60d912005-01-07 07:47:53 +00004292}
4293
Chris Lattner875def92005-01-11 05:56:49 +00004294//===----------------------------------------------------------------------===//
4295// SelectionDAGISel code
4296//===----------------------------------------------------------------------===//
Chris Lattner7a60d912005-01-07 07:47:53 +00004297
4298unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
4299 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
4300}
4301
Chris Lattnerc9950c12005-08-17 06:37:43 +00004302void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Jim Laskeydcb2b832006-10-16 20:52:31 +00004303 AU.addRequired<AliasAnalysis>();
Chris Lattnerf6a6d3c2007-03-31 04:18:03 +00004304 AU.setPreservesAll();
Chris Lattnerc9950c12005-08-17 06:37:43 +00004305}
Chris Lattner7a60d912005-01-07 07:47:53 +00004306
Chris Lattner35397782005-12-05 07:10:48 +00004307
Chris Lattnerbba52192006-10-28 19:22:10 +00004308
Chris Lattner7a60d912005-01-07 07:47:53 +00004309bool SelectionDAGISel::runOnFunction(Function &Fn) {
4310 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
4311 RegMap = MF.getSSARegMap();
Bill Wendling22e978a2006-12-07 20:04:42 +00004312 DOUT << "\n\n\n=== " << Fn.getName() << "\n";
Chris Lattner7a60d912005-01-07 07:47:53 +00004313
4314 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
4315
Duncan Sands74137362007-06-13 16:53:21 +00004316 if (ExceptionHandling)
4317 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
4318 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(I->getTerminator()))
4319 // Mark landing pad.
4320 FuncInfo.MBBMap[Invoke->getSuccessor(1)]->setIsLandingPad();
Duncan Sands61166502007-06-06 10:05:18 +00004321
4322 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
Chris Lattner7a60d912005-01-07 07:47:53 +00004323 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukman835702a2005-04-21 22:36:52 +00004324
Evan Cheng276b44b2007-02-10 02:43:39 +00004325 // Add function live-ins to entry block live-in set.
4326 BasicBlock *EntryBB = &Fn.getEntryBlock();
4327 BB = FuncInfo.MBBMap[EntryBB];
4328 if (!MF.livein_empty())
4329 for (MachineFunction::livein_iterator I = MF.livein_begin(),
4330 E = MF.livein_end(); I != E; ++I)
4331 BB->addLiveIn(I->first);
4332
Duncan Sands92bf2c62007-06-15 19:04:19 +00004333#ifndef NDEBUG
4334 assert(FuncInfo.CatchInfoFound.size() == FuncInfo.CatchInfoLost.size() &&
4335 "Not all catch info was assigned to a landing pad!");
4336#endif
4337
Chris Lattner7a60d912005-01-07 07:47:53 +00004338 return true;
4339}
4340
Chris Lattnered0110b2006-10-27 21:36:01 +00004341SDOperand SelectionDAGLowering::CopyValueToVirtualRegister(Value *V,
4342 unsigned Reg) {
4343 SDOperand Op = getValue(V);
Chris Lattnere727af02005-01-13 20:50:02 +00004344 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattner33182322005-08-16 21:55:35 +00004345 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattnere727af02005-01-13 20:50:02 +00004346 "Copy from a reg to the same reg!");
Chris Lattner33182322005-08-16 21:55:35 +00004347
4348 // If this type is not legal, we must make sure to not create an invalid
4349 // register use.
4350 MVT::ValueType SrcVT = Op.getValueType();
4351 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
Chris Lattner33182322005-08-16 21:55:35 +00004352 if (SrcVT == DestVT) {
Chris Lattnered0110b2006-10-27 21:36:01 +00004353 return DAG.getCopyToReg(getRoot(), Reg, Op);
Dan Gohmana8665142007-06-25 16:23:39 +00004354 } else if (MVT::isVector(SrcVT)) {
Chris Lattner5fe1f542006-03-31 02:06:56 +00004355 // Handle copies from generic vectors to registers.
Dan Gohmana8665142007-06-25 16:23:39 +00004356 MVT::ValueType ElementVT, LegalElementVT;
4357 unsigned NE = TLI.getVectorTypeBreakdown(SrcVT,
4358 ElementVT, LegalElementVT);
4359 uint64_t SrcVL = MVT::getVectorNumElements(SrcVT);
Chris Lattner672a42d2006-03-21 19:20:37 +00004360
Chris Lattner5fe1f542006-03-31 02:06:56 +00004361 // Loop over all of the elements of the resultant vector,
Dan Gohmana8665142007-06-25 16:23:39 +00004362 // EXTRACT_VECTOR_ELT'ing or EXTRACT_SUBVECTOR'ing them, converting them
4363 // to LegalElementVT, then copying them into output registers.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00004364 SmallVector<SDOperand, 8> OutChains;
Chris Lattnered0110b2006-10-27 21:36:01 +00004365 SDOperand Root = getRoot();
Chris Lattner5fe1f542006-03-31 02:06:56 +00004366 for (unsigned i = 0; i != NE; ++i) {
Dan Gohmana8665142007-06-25 16:23:39 +00004367 SDOperand Elt = MVT::isVector(ElementVT) ?
4368 DAG.getNode(ISD::EXTRACT_SUBVECTOR, ElementVT,
Dan Gohman26455c42007-06-13 15:12:02 +00004369 Op, DAG.getConstant(i * (SrcVL / NE), TLI.getPointerTy())) :
Dan Gohmana8665142007-06-25 16:23:39 +00004370 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, ElementVT,
Dan Gohman26455c42007-06-13 15:12:02 +00004371 Op, DAG.getConstant(i, TLI.getPointerTy()));
Dan Gohmana8665142007-06-25 16:23:39 +00004372 if (ElementVT == LegalElementVT) {
Chris Lattner5fe1f542006-03-31 02:06:56 +00004373 // Elements are legal.
4374 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
Dan Gohmana8665142007-06-25 16:23:39 +00004375 } else if (LegalElementVT > ElementVT) {
Chris Lattner5fe1f542006-03-31 02:06:56 +00004376 // Elements are promoted.
Dan Gohmana8665142007-06-25 16:23:39 +00004377 if (MVT::isFloatingPoint(LegalElementVT))
4378 Elt = DAG.getNode(ISD::FP_EXTEND, LegalElementVT, Elt);
Chris Lattner5fe1f542006-03-31 02:06:56 +00004379 else
Dan Gohmana8665142007-06-25 16:23:39 +00004380 Elt = DAG.getNode(ISD::ANY_EXTEND, LegalElementVT, Elt);
Chris Lattner5fe1f542006-03-31 02:06:56 +00004381 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
4382 } else {
4383 // Elements are expanded.
4384 // The src value is expanded into multiple registers.
Dan Gohmana8665142007-06-25 16:23:39 +00004385 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, LegalElementVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00004386 Elt, DAG.getConstant(0, TLI.getPointerTy()));
Dan Gohmana8665142007-06-25 16:23:39 +00004387 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, LegalElementVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00004388 Elt, DAG.getConstant(1, TLI.getPointerTy()));
Chris Lattner5fe1f542006-03-31 02:06:56 +00004389 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Lo));
4390 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Hi));
4391 }
Chris Lattner672a42d2006-03-21 19:20:37 +00004392 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +00004393 return DAG.getNode(ISD::TokenFactor, MVT::Other,
4394 &OutChains[0], OutChains.size());
Evan Cheng22cf8992006-12-13 20:57:08 +00004395 } else if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote) {
Chris Lattner33182322005-08-16 21:55:35 +00004396 // The src value is promoted to the register.
Chris Lattnerba28c272005-08-17 06:06:25 +00004397 if (MVT::isFloatingPoint(SrcVT))
4398 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
4399 else
Chris Lattnera66403d2005-09-02 00:19:37 +00004400 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
Chris Lattnered0110b2006-10-27 21:36:01 +00004401 return DAG.getCopyToReg(getRoot(), Reg, Op);
Chris Lattner33182322005-08-16 21:55:35 +00004402 } else {
Evan Cheng22cf8992006-12-13 20:57:08 +00004403 DestVT = TLI.getTypeToExpandTo(SrcVT);
Dan Gohman04deef32007-06-21 14:42:22 +00004404 unsigned NumVals = TLI.getNumRegisters(SrcVT);
Evan Cheng22cf8992006-12-13 20:57:08 +00004405 if (NumVals == 1)
4406 return DAG.getCopyToReg(getRoot(), Reg,
4407 DAG.getNode(ISD::BIT_CONVERT, DestVT, Op));
4408 assert(NumVals == 2 && "1 to 4 (and more) expansion not implemented!");
Chris Lattner33182322005-08-16 21:55:35 +00004409 // The src value is expanded into multiple registers.
4410 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00004411 Op, DAG.getConstant(0, TLI.getPointerTy()));
Chris Lattner33182322005-08-16 21:55:35 +00004412 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00004413 Op, DAG.getConstant(1, TLI.getPointerTy()));
Chris Lattnered0110b2006-10-27 21:36:01 +00004414 Op = DAG.getCopyToReg(getRoot(), Reg, Lo);
Chris Lattner33182322005-08-16 21:55:35 +00004415 return DAG.getCopyToReg(Op, Reg+1, Hi);
4416 }
Chris Lattner7a60d912005-01-07 07:47:53 +00004417}
4418
Chris Lattner16f64df2005-01-17 17:15:02 +00004419void SelectionDAGISel::
Evan Chengde608342007-02-10 01:08:18 +00004420LowerArguments(BasicBlock *LLVMBB, SelectionDAGLowering &SDL,
Chris Lattner16f64df2005-01-17 17:15:02 +00004421 std::vector<SDOperand> &UnorderedChains) {
4422 // If this is the entry block, emit arguments.
Evan Chengde608342007-02-10 01:08:18 +00004423 Function &F = *LLVMBB->getParent();
Chris Lattnere3c2cf42005-01-17 17:55:19 +00004424 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattner6871b232005-10-30 19:42:35 +00004425 SDOperand OldRoot = SDL.DAG.getRoot();
4426 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner16f64df2005-01-17 17:15:02 +00004427
Chris Lattner6871b232005-10-30 19:42:35 +00004428 unsigned a = 0;
4429 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
4430 AI != E; ++AI, ++a)
4431 if (!AI->use_empty()) {
4432 SDL.setValue(AI, Args[a]);
Evan Cheng3784f3c52006-04-27 08:29:42 +00004433
Chris Lattner6871b232005-10-30 19:42:35 +00004434 // If this argument is live outside of the entry block, insert a copy from
4435 // whereever we got it to the vreg that other BB's will reference it as.
Chris Lattner8c504cf2007-02-25 18:40:32 +00004436 DenseMap<const Value*, unsigned>::iterator VMI=FuncInfo.ValueMap.find(AI);
4437 if (VMI != FuncInfo.ValueMap.end()) {
4438 SDOperand Copy = SDL.CopyValueToVirtualRegister(AI, VMI->second);
Chris Lattner6871b232005-10-30 19:42:35 +00004439 UnorderedChains.push_back(Copy);
4440 }
Chris Lattnere3c2cf42005-01-17 17:55:19 +00004441 }
Chris Lattner6871b232005-10-30 19:42:35 +00004442
Chris Lattner6871b232005-10-30 19:42:35 +00004443 // Finally, if the target has anything special to do, allow it to do so.
Chris Lattner957cb672006-05-16 06:10:58 +00004444 // FIXME: this should insert code into the DAG!
Chris Lattner6871b232005-10-30 19:42:35 +00004445 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner16f64df2005-01-17 17:15:02 +00004446}
4447
Duncan Sands92bf2c62007-06-15 19:04:19 +00004448static void copyCatchInfo(BasicBlock *SrcBB, BasicBlock *DestBB,
4449 MachineModuleInfo *MMI, FunctionLoweringInfo &FLI) {
4450 assert(!FLI.MBBMap[SrcBB]->isLandingPad() &&
4451 "Copying catch info out of a landing pad!");
4452 for (BasicBlock::iterator I = SrcBB->begin(), E = --SrcBB->end(); I != E; ++I)
4453 if (isFilterOrSelector(I)) {
4454 // Apply the catch info to DestBB.
4455 addCatchInfo(cast<CallInst>(*I), MMI, FLI.MBBMap[DestBB]);
4456#ifndef NDEBUG
4457 FLI.CatchInfoFound.insert(I);
4458#endif
4459 }
4460}
4461
Chris Lattner7a60d912005-01-07 07:47:53 +00004462void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
4463 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
Nate Begemaned728c12006-03-27 01:32:24 +00004464 FunctionLoweringInfo &FuncInfo) {
Chris Lattner7a60d912005-01-07 07:47:53 +00004465 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattner718b5c22005-01-13 17:59:43 +00004466
4467 std::vector<SDOperand> UnorderedChains;
Misha Brukman835702a2005-04-21 22:36:52 +00004468
Chris Lattner6871b232005-10-30 19:42:35 +00004469 // Lower any arguments needed in this block if this is the entry block.
Dan Gohmandcb291f2007-03-22 16:38:57 +00004470 if (LLVMBB == &LLVMBB->getParent()->getEntryBlock())
Chris Lattner6871b232005-10-30 19:42:35 +00004471 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner7a60d912005-01-07 07:47:53 +00004472
4473 BB = FuncInfo.MBBMap[LLVMBB];
4474 SDL.setCurrentBasicBlock(BB);
4475
Duncan Sands92bf2c62007-06-15 19:04:19 +00004476 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Duncan Sands61166502007-06-06 10:05:18 +00004477
Duncan Sands92bf2c62007-06-15 19:04:19 +00004478 if (ExceptionHandling && MMI && BB->isLandingPad()) {
4479 // Add a label to mark the beginning of the landing pad. Deletion of the
4480 // landing pad can thus be detected via the MachineModuleInfo.
4481 unsigned LabelID = MMI->addLandingPad(BB);
4482 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, DAG.getEntryNode(),
4483 DAG.getConstant(LabelID, MVT::i32)));
4484
4485 // FIXME: Hack around an exception handling flaw (PR1508): the personality
4486 // function and list of typeids logically belong to the invoke (or, if you
4487 // like, the basic block containing the invoke), and need to be associated
4488 // with it in the dwarf exception handling tables. Currently however the
4489 // information is provided by intrinsics (eh.filter and eh.selector) that
4490 // can be moved to unexpected places by the optimizers: if the unwind edge
4491 // is critical, then breaking it can result in the intrinsics being in the
4492 // successor of the landing pad, not the landing pad itself. This results
4493 // in exceptions not being caught because no typeids are associated with
4494 // the invoke. This may not be the only way things can go wrong, but it
4495 // is the only way we try to work around for the moment.
4496 BranchInst *Br = dyn_cast<BranchInst>(LLVMBB->getTerminator());
4497
4498 if (Br && Br->isUnconditional()) { // Critical edge?
4499 BasicBlock::iterator I, E;
4500 for (I = LLVMBB->begin(), E = --LLVMBB->end(); I != E; ++I)
4501 if (isFilterOrSelector(I))
4502 break;
4503
4504 if (I == E)
4505 // No catch info found - try to extract some from the successor.
4506 copyCatchInfo(Br->getSuccessor(0), LLVMBB, MMI, FuncInfo);
Duncan Sands61166502007-06-06 10:05:18 +00004507 }
4508 }
4509
Chris Lattner7a60d912005-01-07 07:47:53 +00004510 // Lower all of the non-terminator instructions.
4511 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
4512 I != E; ++I)
4513 SDL.visit(*I);
Duncan Sands97f72362007-06-13 05:51:31 +00004514
Chris Lattner7a60d912005-01-07 07:47:53 +00004515 // Ensure that all instructions which are used outside of their defining
Duncan Sands97f72362007-06-13 05:51:31 +00004516 // blocks are available as virtual registers. Invoke is handled elsewhere.
Chris Lattner7a60d912005-01-07 07:47:53 +00004517 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Duncan Sands97f72362007-06-13 05:51:31 +00004518 if (!I->use_empty() && !isa<PHINode>(I) && !isa<InvokeInst>(I)) {
Chris Lattner289aa442007-02-04 01:35:11 +00004519 DenseMap<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner7a60d912005-01-07 07:47:53 +00004520 if (VMI != FuncInfo.ValueMap.end())
Chris Lattner718b5c22005-01-13 17:59:43 +00004521 UnorderedChains.push_back(
Chris Lattnered0110b2006-10-27 21:36:01 +00004522 SDL.CopyValueToVirtualRegister(I, VMI->second));
Chris Lattner7a60d912005-01-07 07:47:53 +00004523 }
4524
4525 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
4526 // ensure constants are generated when needed. Remember the virtual registers
4527 // that need to be added to the Machine PHI nodes as input. We cannot just
4528 // directly add them, because expansion might result in multiple MBB's for one
4529 // BB. As such, the start of the BB might correspond to a different MBB than
4530 // the end.
Misha Brukman835702a2005-04-21 22:36:52 +00004531 //
Chris Lattner84a03502006-10-27 23:50:33 +00004532 TerminatorInst *TI = LLVMBB->getTerminator();
Chris Lattner7a60d912005-01-07 07:47:53 +00004533
4534 // Emit constants only once even if used by multiple PHI nodes.
4535 std::map<Constant*, unsigned> ConstantsOut;
Chris Lattner707339a52006-09-07 01:59:34 +00004536
Chris Lattner84a03502006-10-27 23:50:33 +00004537 // Vector bool would be better, but vector<bool> is really slow.
4538 std::vector<unsigned char> SuccsHandled;
4539 if (TI->getNumSuccessors())
4540 SuccsHandled.resize(BB->getParent()->getNumBlockIDs());
4541
Chris Lattner7a60d912005-01-07 07:47:53 +00004542 // Check successor nodes PHI nodes that expect a constant to be available from
4543 // this block.
Chris Lattner7a60d912005-01-07 07:47:53 +00004544 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
4545 BasicBlock *SuccBB = TI->getSuccessor(succ);
Chris Lattner707339a52006-09-07 01:59:34 +00004546 if (!isa<PHINode>(SuccBB->begin())) continue;
Chris Lattner84a03502006-10-27 23:50:33 +00004547 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
Chris Lattner707339a52006-09-07 01:59:34 +00004548
Chris Lattner84a03502006-10-27 23:50:33 +00004549 // If this terminator has multiple identical successors (common for
4550 // switches), only handle each succ once.
4551 unsigned SuccMBBNo = SuccMBB->getNumber();
4552 if (SuccsHandled[SuccMBBNo]) continue;
4553 SuccsHandled[SuccMBBNo] = true;
4554
4555 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
Chris Lattner7a60d912005-01-07 07:47:53 +00004556 PHINode *PN;
4557
4558 // At this point we know that there is a 1-1 correspondence between LLVM PHI
4559 // nodes and Machine PHI nodes, but the incoming operands have not been
4560 // emitted yet.
4561 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner84a03502006-10-27 23:50:33 +00004562 (PN = dyn_cast<PHINode>(I)); ++I) {
4563 // Ignore dead phi's.
4564 if (PN->use_empty()) continue;
4565
4566 unsigned Reg;
4567 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
Chris Lattner90f42382006-11-29 01:12:32 +00004568
Chris Lattner84a03502006-10-27 23:50:33 +00004569 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
4570 unsigned &RegOut = ConstantsOut[C];
4571 if (RegOut == 0) {
4572 RegOut = FuncInfo.CreateRegForValue(C);
4573 UnorderedChains.push_back(
4574 SDL.CopyValueToVirtualRegister(C, RegOut));
Chris Lattner7a60d912005-01-07 07:47:53 +00004575 }
Chris Lattner84a03502006-10-27 23:50:33 +00004576 Reg = RegOut;
4577 } else {
4578 Reg = FuncInfo.ValueMap[PHIOp];
4579 if (Reg == 0) {
4580 assert(isa<AllocaInst>(PHIOp) &&
4581 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
4582 "Didn't codegen value into a register!??");
4583 Reg = FuncInfo.CreateRegForValue(PHIOp);
4584 UnorderedChains.push_back(
4585 SDL.CopyValueToVirtualRegister(PHIOp, Reg));
Chris Lattnerba380352006-03-31 02:12:18 +00004586 }
Chris Lattner7a60d912005-01-07 07:47:53 +00004587 }
Chris Lattner84a03502006-10-27 23:50:33 +00004588
4589 // Remember that this register needs to added to the machine PHI node as
4590 // the input for this MBB.
4591 MVT::ValueType VT = TLI.getValueType(PN->getType());
Dan Gohmana8665142007-06-25 16:23:39 +00004592 unsigned NumRegisters = TLI.getNumRegisters(VT);
Dan Gohman04deef32007-06-21 14:42:22 +00004593 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
Chris Lattner84a03502006-10-27 23:50:33 +00004594 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
4595 }
Chris Lattner7a60d912005-01-07 07:47:53 +00004596 }
4597 ConstantsOut.clear();
4598
Chris Lattner718b5c22005-01-13 17:59:43 +00004599 // Turn all of the unordered chains into one factored node.
Chris Lattner24516842005-01-13 19:53:14 +00004600 if (!UnorderedChains.empty()) {
Chris Lattnerb7cad902005-11-09 05:03:03 +00004601 SDOperand Root = SDL.getRoot();
4602 if (Root.getOpcode() != ISD::EntryToken) {
4603 unsigned i = 0, e = UnorderedChains.size();
4604 for (; i != e; ++i) {
4605 assert(UnorderedChains[i].Val->getNumOperands() > 1);
4606 if (UnorderedChains[i].Val->getOperand(0) == Root)
4607 break; // Don't add the root if we already indirectly depend on it.
4608 }
4609
4610 if (i == e)
4611 UnorderedChains.push_back(Root);
4612 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +00004613 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
4614 &UnorderedChains[0], UnorderedChains.size()));
Chris Lattner718b5c22005-01-13 17:59:43 +00004615 }
4616
Chris Lattner7a60d912005-01-07 07:47:53 +00004617 // Lower the terminator after the copies are emitted.
Duncan Sands97f72362007-06-13 05:51:31 +00004618 SDL.visit(*LLVMBB->getTerminator());
Chris Lattner4108bb02005-01-17 19:43:36 +00004619
Nate Begemaned728c12006-03-27 01:32:24 +00004620 // Copy over any CaseBlock records that may now exist due to SwitchInst
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004621 // lowering, as well as any jump table information.
Nate Begemaned728c12006-03-27 01:32:24 +00004622 SwitchCases.clear();
4623 SwitchCases = SDL.SwitchCases;
Anton Korobeynikov70378262007-03-25 15:07:15 +00004624 JTCases.clear();
4625 JTCases = SDL.JTCases;
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00004626 BitTestCases.clear();
4627 BitTestCases = SDL.BitTestCases;
4628
Chris Lattner4108bb02005-01-17 19:43:36 +00004629 // Make sure the root of the DAG is up-to-date.
4630 DAG.setRoot(SDL.getRoot());
Chris Lattner7a60d912005-01-07 07:47:53 +00004631}
4632
Nate Begemaned728c12006-03-27 01:32:24 +00004633void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
Jim Laskeydcb2b832006-10-16 20:52:31 +00004634 // Get alias analysis for load/store combining.
4635 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
4636
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00004637 // Run the DAG combiner in pre-legalize mode.
Jim Laskeydcb2b832006-10-16 20:52:31 +00004638 DAG.Combine(false, AA);
Nate Begeman007c6502005-09-07 00:15:36 +00004639
Bill Wendling22e978a2006-12-07 20:04:42 +00004640 DOUT << "Lowered selection DAG:\n";
Chris Lattner7a60d912005-01-07 07:47:53 +00004641 DEBUG(DAG.dump());
Nate Begemaned728c12006-03-27 01:32:24 +00004642
Chris Lattner7a60d912005-01-07 07:47:53 +00004643 // Second step, hack on the DAG until it only uses operations and types that
4644 // the target supports.
Chris Lattnerffcb0ae2005-01-23 04:36:26 +00004645 DAG.Legalize();
Nate Begemaned728c12006-03-27 01:32:24 +00004646
Bill Wendling22e978a2006-12-07 20:04:42 +00004647 DOUT << "Legalized selection DAG:\n";
Chris Lattner7a60d912005-01-07 07:47:53 +00004648 DEBUG(DAG.dump());
Nate Begemaned728c12006-03-27 01:32:24 +00004649
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00004650 // Run the DAG combiner in post-legalize mode.
Jim Laskeydcb2b832006-10-16 20:52:31 +00004651 DAG.Combine(true, AA);
Nate Begeman007c6502005-09-07 00:15:36 +00004652
Evan Cheng739a6a42006-01-21 02:32:06 +00004653 if (ViewISelDAGs) DAG.viewGraph();
Evan Cheng51ab4492006-04-28 02:09:19 +00004654
Chris Lattner5ca31d92005-03-30 01:10:47 +00004655 // Third, instruction select all of the operations to machine code, adding the
4656 // code to the MachineBasicBlock.
Chris Lattner7a60d912005-01-07 07:47:53 +00004657 InstructionSelectBasicBlock(DAG);
Nate Begemaned728c12006-03-27 01:32:24 +00004658
Bill Wendling22e978a2006-12-07 20:04:42 +00004659 DOUT << "Selected machine code:\n";
Chris Lattner7a60d912005-01-07 07:47:53 +00004660 DEBUG(BB->dump());
Nate Begemaned728c12006-03-27 01:32:24 +00004661}
Chris Lattner7a60d912005-01-07 07:47:53 +00004662
Nate Begemaned728c12006-03-27 01:32:24 +00004663void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
4664 FunctionLoweringInfo &FuncInfo) {
4665 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
4666 {
Jim Laskeyc56315c2007-01-26 21:22:28 +00004667 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
Nate Begemaned728c12006-03-27 01:32:24 +00004668 CurDAG = &DAG;
4669
4670 // First step, lower LLVM code to some DAG. This DAG may use operations and
4671 // types that are not supported by the target.
4672 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
4673
4674 // Second step, emit the lowered DAG as machine code.
4675 CodeGenAndEmitDAG(DAG);
4676 }
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00004677
4678 DOUT << "Total amount of phi nodes to update: "
4679 << PHINodesToUpdate.size() << "\n";
4680 DEBUG(for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i)
4681 DOUT << "Node " << i << " : (" << PHINodesToUpdate[i].first
4682 << ", " << PHINodesToUpdate[i].second << ")\n";);
Nate Begemaned728c12006-03-27 01:32:24 +00004683
Chris Lattner5ca31d92005-03-30 01:10:47 +00004684 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner7a60d912005-01-07 07:47:53 +00004685 // PHI nodes in successors.
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00004686 if (SwitchCases.empty() && JTCases.empty() && BitTestCases.empty()) {
Nate Begemaned728c12006-03-27 01:32:24 +00004687 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4688 MachineInstr *PHI = PHINodesToUpdate[i].first;
4689 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4690 "This is not a machine PHI node that we are updating!");
Chris Lattneraf23f9b2006-09-05 02:31:13 +00004691 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
Nate Begemaned728c12006-03-27 01:32:24 +00004692 PHI->addMachineBasicBlockOperand(BB);
4693 }
4694 return;
Chris Lattner7a60d912005-01-07 07:47:53 +00004695 }
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00004696
4697 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i) {
4698 // Lower header first, if it wasn't already lowered
4699 if (!BitTestCases[i].Emitted) {
4700 SelectionDAG HSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4701 CurDAG = &HSDAG;
4702 SelectionDAGLowering HSDL(HSDAG, TLI, FuncInfo);
4703 // Set the current basic block to the mbb we wish to insert the code into
4704 BB = BitTestCases[i].Parent;
4705 HSDL.setCurrentBasicBlock(BB);
4706 // Emit the code
4707 HSDL.visitBitTestHeader(BitTestCases[i]);
4708 HSDAG.setRoot(HSDL.getRoot());
4709 CodeGenAndEmitDAG(HSDAG);
4710 }
4711
4712 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
4713 SelectionDAG BSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4714 CurDAG = &BSDAG;
4715 SelectionDAGLowering BSDL(BSDAG, TLI, FuncInfo);
4716 // Set the current basic block to the mbb we wish to insert the code into
4717 BB = BitTestCases[i].Cases[j].ThisBB;
4718 BSDL.setCurrentBasicBlock(BB);
4719 // Emit the code
4720 if (j+1 != ej)
4721 BSDL.visitBitTestCase(BitTestCases[i].Cases[j+1].ThisBB,
4722 BitTestCases[i].Reg,
4723 BitTestCases[i].Cases[j]);
4724 else
4725 BSDL.visitBitTestCase(BitTestCases[i].Default,
4726 BitTestCases[i].Reg,
4727 BitTestCases[i].Cases[j]);
4728
4729
4730 BSDAG.setRoot(BSDL.getRoot());
4731 CodeGenAndEmitDAG(BSDAG);
4732 }
4733
4734 // Update PHI Nodes
4735 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
4736 MachineInstr *PHI = PHINodesToUpdate[pi].first;
4737 MachineBasicBlock *PHIBB = PHI->getParent();
4738 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4739 "This is not a machine PHI node that we are updating!");
4740 // This is "default" BB. We have two jumps to it. From "header" BB and
4741 // from last "case" BB.
4742 if (PHIBB == BitTestCases[i].Default) {
4743 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
4744 PHI->addMachineBasicBlockOperand(BitTestCases[i].Parent);
Anton Korobeynikove2880402007-04-13 06:53:51 +00004745 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00004746 PHI->addMachineBasicBlockOperand(BitTestCases[i].Cases.back().ThisBB);
4747 }
4748 // One of "cases" BB.
4749 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
4750 MachineBasicBlock* cBB = BitTestCases[i].Cases[j].ThisBB;
4751 if (cBB->succ_end() !=
4752 std::find(cBB->succ_begin(),cBB->succ_end(), PHIBB)) {
4753 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
4754 PHI->addMachineBasicBlockOperand(cBB);
4755 }
4756 }
4757 }
4758 }
4759
Nate Begeman866b4b42006-04-23 06:26:20 +00004760 // If the JumpTable record is filled in, then we need to emit a jump table.
4761 // Updating the PHI nodes is tricky in this case, since we need to determine
4762 // whether the PHI is a successor of the range check MBB or the jump table MBB
Anton Korobeynikov70378262007-03-25 15:07:15 +00004763 for (unsigned i = 0, e = JTCases.size(); i != e; ++i) {
4764 // Lower header first, if it wasn't already lowered
4765 if (!JTCases[i].first.Emitted) {
4766 SelectionDAG HSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4767 CurDAG = &HSDAG;
4768 SelectionDAGLowering HSDL(HSDAG, TLI, FuncInfo);
4769 // Set the current basic block to the mbb we wish to insert the code into
4770 BB = JTCases[i].first.HeaderBB;
4771 HSDL.setCurrentBasicBlock(BB);
4772 // Emit the code
4773 HSDL.visitJumpTableHeader(JTCases[i].second, JTCases[i].first);
4774 HSDAG.setRoot(HSDL.getRoot());
4775 CodeGenAndEmitDAG(HSDAG);
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00004776 }
Anton Korobeynikov70378262007-03-25 15:07:15 +00004777
4778 SelectionDAG JSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4779 CurDAG = &JSDAG;
4780 SelectionDAGLowering JSDL(JSDAG, TLI, FuncInfo);
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004781 // Set the current basic block to the mbb we wish to insert the code into
Anton Korobeynikov70378262007-03-25 15:07:15 +00004782 BB = JTCases[i].second.MBB;
4783 JSDL.setCurrentBasicBlock(BB);
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004784 // Emit the code
Anton Korobeynikov70378262007-03-25 15:07:15 +00004785 JSDL.visitJumpTable(JTCases[i].second);
4786 JSDAG.setRoot(JSDL.getRoot());
4787 CodeGenAndEmitDAG(JSDAG);
4788
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004789 // Update PHI Nodes
4790 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
4791 MachineInstr *PHI = PHINodesToUpdate[pi].first;
4792 MachineBasicBlock *PHIBB = PHI->getParent();
4793 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4794 "This is not a machine PHI node that we are updating!");
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00004795 // "default" BB. We can go there only from header BB.
Anton Korobeynikov70378262007-03-25 15:07:15 +00004796 if (PHIBB == JTCases[i].second.Default) {
Chris Lattneraf23f9b2006-09-05 02:31:13 +00004797 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Anton Korobeynikov70378262007-03-25 15:07:15 +00004798 PHI->addMachineBasicBlockOperand(JTCases[i].first.HeaderBB);
Nate Begemandf488392006-05-03 03:48:02 +00004799 }
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00004800 // JT BB. Just iterate over successors here
Nate Begemandf488392006-05-03 03:48:02 +00004801 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
Chris Lattneraf23f9b2006-09-05 02:31:13 +00004802 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Nate Begemandf488392006-05-03 03:48:02 +00004803 PHI->addMachineBasicBlockOperand(BB);
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004804 }
4805 }
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004806 }
4807
Chris Lattner76a7bc82006-10-22 23:00:53 +00004808 // If the switch block involved a branch to one of the actual successors, we
4809 // need to update PHI nodes in that block.
4810 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4811 MachineInstr *PHI = PHINodesToUpdate[i].first;
4812 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4813 "This is not a machine PHI node that we are updating!");
4814 if (BB->isSuccessor(PHI->getParent())) {
4815 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
4816 PHI->addMachineBasicBlockOperand(BB);
4817 }
4818 }
4819
Nate Begemaned728c12006-03-27 01:32:24 +00004820 // If we generated any switch lowering information, build and codegen any
4821 // additional DAGs necessary.
Chris Lattner707339a52006-09-07 01:59:34 +00004822 for (unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
Jim Laskeyc56315c2007-01-26 21:22:28 +00004823 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
Nate Begemaned728c12006-03-27 01:32:24 +00004824 CurDAG = &SDAG;
4825 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
Chris Lattner707339a52006-09-07 01:59:34 +00004826
Nate Begemaned728c12006-03-27 01:32:24 +00004827 // Set the current basic block to the mbb we wish to insert the code into
4828 BB = SwitchCases[i].ThisBB;
4829 SDL.setCurrentBasicBlock(BB);
Chris Lattner707339a52006-09-07 01:59:34 +00004830
Nate Begemaned728c12006-03-27 01:32:24 +00004831 // Emit the code
4832 SDL.visitSwitchCase(SwitchCases[i]);
4833 SDAG.setRoot(SDL.getRoot());
4834 CodeGenAndEmitDAG(SDAG);
Chris Lattner707339a52006-09-07 01:59:34 +00004835
4836 // Handle any PHI nodes in successors of this chunk, as if we were coming
4837 // from the original BB before switch expansion. Note that PHI nodes can
4838 // occur multiple times in PHINodesToUpdate. We have to be very careful to
4839 // handle them the right number of times.
Chris Lattner963ddad2006-10-24 17:57:59 +00004840 while ((BB = SwitchCases[i].TrueBB)) { // Handle LHS and RHS.
Chris Lattner707339a52006-09-07 01:59:34 +00004841 for (MachineBasicBlock::iterator Phi = BB->begin();
4842 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
4843 // This value for this PHI node is recorded in PHINodesToUpdate, get it.
4844 for (unsigned pn = 0; ; ++pn) {
4845 assert(pn != PHINodesToUpdate.size() && "Didn't find PHI entry!");
4846 if (PHINodesToUpdate[pn].first == Phi) {
4847 Phi->addRegOperand(PHINodesToUpdate[pn].second, false);
4848 Phi->addMachineBasicBlockOperand(SwitchCases[i].ThisBB);
4849 break;
4850 }
4851 }
Nate Begemaned728c12006-03-27 01:32:24 +00004852 }
Chris Lattner707339a52006-09-07 01:59:34 +00004853
4854 // Don't process RHS if same block as LHS.
Chris Lattner963ddad2006-10-24 17:57:59 +00004855 if (BB == SwitchCases[i].FalseBB)
4856 SwitchCases[i].FalseBB = 0;
Chris Lattner707339a52006-09-07 01:59:34 +00004857
4858 // If we haven't handled the RHS, do so now. Otherwise, we're done.
Chris Lattner61bcf912006-10-24 18:07:37 +00004859 SwitchCases[i].TrueBB = SwitchCases[i].FalseBB;
Chris Lattner963ddad2006-10-24 17:57:59 +00004860 SwitchCases[i].FalseBB = 0;
Nate Begemaned728c12006-03-27 01:32:24 +00004861 }
Chris Lattner963ddad2006-10-24 17:57:59 +00004862 assert(SwitchCases[i].TrueBB == 0 && SwitchCases[i].FalseBB == 0);
Chris Lattner5ca31d92005-03-30 01:10:47 +00004863 }
Chris Lattner7a60d912005-01-07 07:47:53 +00004864}
Evan Cheng739a6a42006-01-21 02:32:06 +00004865
Jim Laskey95eda5b2006-08-01 14:21:23 +00004866
Evan Cheng739a6a42006-01-21 02:32:06 +00004867//===----------------------------------------------------------------------===//
4868/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
4869/// target node in the graph.
4870void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
4871 if (ViewSchedDAGs) DAG.viewGraph();
Evan Chengc1e1d972006-01-23 07:01:07 +00004872
Jim Laskey29e635d2006-08-02 12:30:23 +00004873 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
Jim Laskey95eda5b2006-08-01 14:21:23 +00004874
4875 if (!Ctor) {
Jim Laskey29e635d2006-08-02 12:30:23 +00004876 Ctor = ISHeuristic;
Jim Laskey17c67ef2006-08-01 19:14:14 +00004877 RegisterScheduler::setDefault(Ctor);
Evan Chengc1e1d972006-01-23 07:01:07 +00004878 }
Jim Laskey95eda5b2006-08-01 14:21:23 +00004879
Jim Laskey03593f72006-08-01 18:29:48 +00004880 ScheduleDAG *SL = Ctor(this, &DAG, BB);
Chris Lattnere23928c2006-01-21 19:12:11 +00004881 BB = SL->Run();
Evan Chengf9adce92006-02-04 06:49:00 +00004882 delete SL;
Evan Cheng739a6a42006-01-21 02:32:06 +00004883}
Chris Lattnerdcf785b2006-02-24 02:13:54 +00004884
Chris Lattner47639db2006-03-06 00:22:00 +00004885
Jim Laskey03593f72006-08-01 18:29:48 +00004886HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
4887 return new HazardRecognizer();
4888}
4889
Chris Lattner6df34962006-10-11 03:58:02 +00004890//===----------------------------------------------------------------------===//
4891// Helper functions used by the generated instruction selector.
4892//===----------------------------------------------------------------------===//
4893// Calls to these methods are generated by tblgen.
4894
4895/// CheckAndMask - The isel is trying to match something like (and X, 255). If
4896/// the dag combiner simplified the 255, we still want to match. RHS is the
4897/// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
4898/// specified in the .td file (e.g. 255).
4899bool SelectionDAGISel::CheckAndMask(SDOperand LHS, ConstantSDNode *RHS,
4900 int64_t DesiredMaskS) {
4901 uint64_t ActualMask = RHS->getValue();
4902 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4903
4904 // If the actual mask exactly matches, success!
4905 if (ActualMask == DesiredMask)
4906 return true;
4907
4908 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4909 if (ActualMask & ~DesiredMask)
4910 return false;
4911
4912 // Otherwise, the DAG Combiner may have proven that the value coming in is
4913 // either already zero or is not demanded. Check for known zero input bits.
4914 uint64_t NeededMask = DesiredMask & ~ActualMask;
Dan Gohman309d3d52007-06-22 14:59:07 +00004915 if (CurDAG->MaskedValueIsZero(LHS, NeededMask))
Chris Lattner6df34962006-10-11 03:58:02 +00004916 return true;
4917
4918 // TODO: check to see if missing bits are just not demanded.
4919
4920 // Otherwise, this pattern doesn't match.
4921 return false;
4922}
4923
4924/// CheckOrMask - The isel is trying to match something like (or X, 255). If
4925/// the dag combiner simplified the 255, we still want to match. RHS is the
4926/// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
4927/// specified in the .td file (e.g. 255).
4928bool SelectionDAGISel::CheckOrMask(SDOperand LHS, ConstantSDNode *RHS,
4929 int64_t DesiredMaskS) {
4930 uint64_t ActualMask = RHS->getValue();
4931 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4932
4933 // If the actual mask exactly matches, success!
4934 if (ActualMask == DesiredMask)
4935 return true;
4936
4937 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4938 if (ActualMask & ~DesiredMask)
4939 return false;
4940
4941 // Otherwise, the DAG Combiner may have proven that the value coming in is
4942 // either already zero or is not demanded. Check for known zero input bits.
4943 uint64_t NeededMask = DesiredMask & ~ActualMask;
4944
4945 uint64_t KnownZero, KnownOne;
Dan Gohman309d3d52007-06-22 14:59:07 +00004946 CurDAG->ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
Chris Lattner6df34962006-10-11 03:58:02 +00004947
4948 // If all the missing bits in the or are already known to be set, match!
4949 if ((NeededMask & KnownOne) == NeededMask)
4950 return true;
4951
4952 // TODO: check to see if missing bits are just not demanded.
4953
4954 // Otherwise, this pattern doesn't match.
4955 return false;
4956}
4957
Jim Laskey03593f72006-08-01 18:29:48 +00004958
Chris Lattnerdcf785b2006-02-24 02:13:54 +00004959/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
4960/// by tblgen. Others should not call it.
4961void SelectionDAGISel::
4962SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
4963 std::vector<SDOperand> InOps;
4964 std::swap(InOps, Ops);
4965
4966 Ops.push_back(InOps[0]); // input chain.
4967 Ops.push_back(InOps[1]); // input asm string.
4968
Chris Lattnerdcf785b2006-02-24 02:13:54 +00004969 unsigned i = 2, e = InOps.size();
4970 if (InOps[e-1].getValueType() == MVT::Flag)
4971 --e; // Don't process a flag operand if it is here.
4972
4973 while (i != e) {
4974 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
4975 if ((Flags & 7) != 4 /*MEM*/) {
4976 // Just skip over this operand, copying the operands verbatim.
4977 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
4978 i += (Flags >> 3) + 1;
4979 } else {
4980 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
4981 // Otherwise, this is a memory operand. Ask the target to select it.
4982 std::vector<SDOperand> SelOps;
4983 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
Bill Wendling22e978a2006-12-07 20:04:42 +00004984 cerr << "Could not match memory address. Inline asm failure!\n";
Chris Lattnerdcf785b2006-02-24 02:13:54 +00004985 exit(1);
4986 }
4987
4988 // Add this to the output node.
Chris Lattnerb49917d2007-04-09 00:33:58 +00004989 MVT::ValueType IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
Chris Lattner9bd5ed62006-12-16 21:14:48 +00004990 Ops.push_back(DAG.getTargetConstant(4/*MEM*/ | (SelOps.size() << 3),
Chris Lattnerb49917d2007-04-09 00:33:58 +00004991 IntPtrTy));
Chris Lattnerdcf785b2006-02-24 02:13:54 +00004992 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
4993 i += 2;
4994 }
4995 }
4996
4997 // Add the flag input back if present.
4998 if (e != InOps.size())
4999 Ops.push_back(InOps.back());
5000}
Devang Patel09f162c2007-05-01 21:15:47 +00005001
Devang Patel8c78a0b2007-05-03 01:11:54 +00005002char SelectionDAGISel::ID = 0;