blob: 911f326ee033b58b26154fc2b7d6ad9fc347f16f [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"
Jim Laskeydcb2b832006-10-16 20:52:31 +000015#include "llvm/Analysis/AliasAnalysis.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000016#include "llvm/CodeGen/SelectionDAGISel.h"
Evan Cheng739a6a42006-01-21 02:32:06 +000017#include "llvm/CodeGen/ScheduleDAG.h"
Chris Lattner2e77db62005-05-13 18:50:42 +000018#include "llvm/CallingConv.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000019#include "llvm/Constants.h"
20#include "llvm/DerivedTypes.h"
21#include "llvm/Function.h"
Chris Lattner435b4022005-11-29 06:21:05 +000022#include "llvm/GlobalVariable.h"
Chris Lattner476e67b2006-01-26 22:24:51 +000023#include "llvm/InlineAsm.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000024#include "llvm/Instructions.h"
25#include "llvm/Intrinsics.h"
Jim Laskeya8bdac82006-03-23 18:06:46 +000026#include "llvm/IntrinsicInst.h"
Jim Laskey219d5592006-01-04 22:28:25 +000027#include "llvm/CodeGen/MachineDebugInfo.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000028#include "llvm/CodeGen/MachineFunction.h"
29#include "llvm/CodeGen/MachineFrameInfo.h"
Nate Begeman4ca2ea52006-04-22 18:53:45 +000030#include "llvm/CodeGen/MachineJumpTableInfo.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000031#include "llvm/CodeGen/MachineInstrBuilder.h"
Jim Laskey29e635d2006-08-02 12:30:23 +000032#include "llvm/CodeGen/SchedulerRegistry.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000033#include "llvm/CodeGen/SelectionDAG.h"
34#include "llvm/CodeGen/SSARegMap.h"
Chris Lattnerd4382f02005-09-13 19:30:54 +000035#include "llvm/Target/MRegisterInfo.h"
Chris Lattner90f42382006-11-29 01:12:32 +000036#include "llvm/Target/TargetAsmInfo.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000037#include "llvm/Target/TargetData.h"
38#include "llvm/Target/TargetFrameInfo.h"
39#include "llvm/Target/TargetInstrInfo.h"
40#include "llvm/Target/TargetLowering.h"
41#include "llvm/Target/TargetMachine.h"
Vladimir Prusdf1d4392006-05-23 13:43:15 +000042#include "llvm/Target/TargetOptions.h"
Chris Lattnerc9950c12005-08-17 06:37:43 +000043#include "llvm/Transforms/Utils/BasicBlockUtils.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///
64/// RegisterScheduler class - Track the registration of instruction schedulers.
65///
66//===---------------------------------------------------------------------===//
67MachinePassRegistry RegisterScheduler::Registry;
68
69//===---------------------------------------------------------------------===//
70///
71/// ISHeuristic command line option for instruction schedulers.
72///
73//===---------------------------------------------------------------------===//
Evan Chengc1e1d972006-01-23 07:01:07 +000074namespace {
Jim Laskey29e635d2006-08-02 12:30:23 +000075 cl::opt<RegisterScheduler::FunctionPassCtor, false,
76 RegisterPassParser<RegisterScheduler> >
Jim Laskey95eda5b2006-08-01 14:21:23 +000077 ISHeuristic("sched",
Chris Lattner524c1a22006-08-03 00:18:59 +000078 cl::init(&createDefaultScheduler),
Jim Laskey95eda5b2006-08-01 14:21:23 +000079 cl::desc("Instruction schedulers available:"));
80
Jim Laskey03593f72006-08-01 18:29:48 +000081 static RegisterScheduler
Jim Laskey17c67ef2006-08-01 19:14:14 +000082 defaultListDAGScheduler("default", " Best scheduler for the target",
83 createDefaultScheduler);
Evan Chengc1e1d972006-01-23 07:01:07 +000084} // namespace
85
Chris Lattner6f87d182006-02-22 22:37:12 +000086namespace {
87 /// RegsForValue - This struct represents the physical registers that a
88 /// particular value is assigned and the type information about the value.
89 /// This is needed because values can be promoted into larger registers and
90 /// expanded into multiple smaller registers than the value.
Chris Lattner996795b2006-06-28 23:17:24 +000091 struct VISIBILITY_HIDDEN RegsForValue {
Chris Lattner6f87d182006-02-22 22:37:12 +000092 /// Regs - This list hold the register (for legal and promoted values)
93 /// or register set (for expanded values) that the value should be assigned
94 /// to.
95 std::vector<unsigned> Regs;
96
97 /// RegVT - The value type of each register.
98 ///
99 MVT::ValueType RegVT;
100
101 /// ValueVT - The value type of the LLVM value, which may be promoted from
102 /// RegVT or made from merging the two expanded parts.
103 MVT::ValueType ValueVT;
104
105 RegsForValue() : RegVT(MVT::Other), ValueVT(MVT::Other) {}
106
107 RegsForValue(unsigned Reg, MVT::ValueType regvt, MVT::ValueType valuevt)
108 : RegVT(regvt), ValueVT(valuevt) {
109 Regs.push_back(Reg);
110 }
111 RegsForValue(const std::vector<unsigned> &regs,
112 MVT::ValueType regvt, MVT::ValueType valuevt)
113 : Regs(regs), RegVT(regvt), ValueVT(valuevt) {
114 }
115
116 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
117 /// this value and returns the result as a ValueVT value. This uses
118 /// Chain/Flag as the input and updates them for the output Chain/Flag.
119 SDOperand getCopyFromRegs(SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +0000120 SDOperand &Chain, SDOperand &Flag) const;
Chris Lattner571d9642006-02-23 19:21:04 +0000121
122 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
123 /// specified value into the registers specified by this object. This uses
124 /// Chain/Flag as the input and updates them for the output Chain/Flag.
125 void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Evan Chengef9e07d2006-06-15 08:11:54 +0000126 SDOperand &Chain, SDOperand &Flag,
127 MVT::ValueType PtrVT) const;
Chris Lattner571d9642006-02-23 19:21:04 +0000128
129 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
130 /// operand list. This adds the code marker and includes the number of
131 /// values added into it.
132 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +0000133 std::vector<SDOperand> &Ops) const;
Chris Lattner6f87d182006-02-22 22:37:12 +0000134 };
135}
Evan Chengc1e1d972006-01-23 07:01:07 +0000136
Chris Lattner7a60d912005-01-07 07:47:53 +0000137namespace llvm {
138 //===--------------------------------------------------------------------===//
Jim Laskey17c67ef2006-08-01 19:14:14 +0000139 /// createDefaultScheduler - This creates an instruction scheduler appropriate
140 /// for the target.
141 ScheduleDAG* createDefaultScheduler(SelectionDAGISel *IS,
142 SelectionDAG *DAG,
143 MachineBasicBlock *BB) {
144 TargetLowering &TLI = IS->getTargetLowering();
145
146 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency) {
147 return createTDListDAGScheduler(IS, DAG, BB);
148 } else {
149 assert(TLI.getSchedulingPreference() ==
150 TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
151 return createBURRListDAGScheduler(IS, DAG, BB);
152 }
153 }
154
155
156 //===--------------------------------------------------------------------===//
Chris Lattner7a60d912005-01-07 07:47:53 +0000157 /// FunctionLoweringInfo - This contains information that is global to a
158 /// function that is used when lowering a region of the function.
Chris Lattnerd0061952005-01-08 19:52:31 +0000159 class FunctionLoweringInfo {
160 public:
Chris Lattner7a60d912005-01-07 07:47:53 +0000161 TargetLowering &TLI;
162 Function &Fn;
163 MachineFunction &MF;
164 SSARegMap *RegMap;
165
166 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
167
168 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
169 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
170
171 /// ValueMap - Since we emit code for the function a basic block at a time,
172 /// we must remember which virtual registers hold the values for
173 /// cross-basic-block values.
174 std::map<const Value*, unsigned> ValueMap;
175
176 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
177 /// the entry block. This allows the allocas to be efficiently referenced
178 /// anywhere in the function.
179 std::map<const AllocaInst*, int> StaticAllocaMap;
180
181 unsigned MakeReg(MVT::ValueType VT) {
182 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
183 }
Chris Lattnered0110b2006-10-27 21:36:01 +0000184
185 /// isExportedInst - Return true if the specified value is an instruction
186 /// exported from its block.
187 bool isExportedInst(const Value *V) {
188 return ValueMap.count(V);
189 }
Misha Brukman835702a2005-04-21 22:36:52 +0000190
Chris Lattner49409cb2006-03-16 19:51:18 +0000191 unsigned CreateRegForValue(const Value *V);
192
Chris Lattner7a60d912005-01-07 07:47:53 +0000193 unsigned InitializeRegForValue(const Value *V) {
194 unsigned &R = ValueMap[V];
195 assert(R == 0 && "Already initialized this value register!");
196 return R = CreateRegForValue(V);
197 }
198 };
199}
200
201/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
Nate Begemaned728c12006-03-27 01:32:24 +0000202/// PHI nodes or outside of the basic block that defines it, or used by a
203/// switch instruction, which may expand to multiple basic blocks.
Chris Lattner7a60d912005-01-07 07:47:53 +0000204static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
205 if (isa<PHINode>(I)) return true;
206 BasicBlock *BB = I->getParent();
207 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
Nate Begemaned728c12006-03-27 01:32:24 +0000208 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
Chris Lattnered0110b2006-10-27 21:36:01 +0000209 // FIXME: Remove switchinst special case.
Nate Begemaned728c12006-03-27 01:32:24 +0000210 isa<SwitchInst>(*UI))
Chris Lattner7a60d912005-01-07 07:47:53 +0000211 return true;
212 return false;
213}
214
Chris Lattner6871b232005-10-30 19:42:35 +0000215/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
Nate Begemaned728c12006-03-27 01:32:24 +0000216/// entry block, return true. This includes arguments used by switches, since
217/// the switch may expand into multiple basic blocks.
Chris Lattner6871b232005-10-30 19:42:35 +0000218static bool isOnlyUsedInEntryBlock(Argument *A) {
219 BasicBlock *Entry = A->getParent()->begin();
220 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
Nate Begemaned728c12006-03-27 01:32:24 +0000221 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
Chris Lattner6871b232005-10-30 19:42:35 +0000222 return false; // Use not in entry block.
223 return true;
224}
225
Chris Lattner7a60d912005-01-07 07:47:53 +0000226FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
Misha Brukman835702a2005-04-21 22:36:52 +0000227 Function &fn, MachineFunction &mf)
Chris Lattner7a60d912005-01-07 07:47:53 +0000228 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
229
Chris Lattner6871b232005-10-30 19:42:35 +0000230 // Create a vreg for each argument register that is not dead and is used
231 // outside of the entry block for the function.
232 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
233 AI != E; ++AI)
234 if (!isOnlyUsedInEntryBlock(AI))
235 InitializeRegForValue(AI);
236
Chris Lattner7a60d912005-01-07 07:47:53 +0000237 // Initialize the mapping of values to registers. This is only set up for
238 // instruction values that are used outside of the block that defines
239 // them.
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000240 Function::iterator BB = Fn.begin(), EB = Fn.end();
Chris Lattner7a60d912005-01-07 07:47:53 +0000241 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
242 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
Reid Spencere0fc4df2006-10-20 07:07:24 +0000243 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000244 const Type *Ty = AI->getAllocatedType();
Owen Anderson20a631f2006-05-03 01:29:57 +0000245 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
Nate Begeman3ee3e692005-11-06 09:00:38 +0000246 unsigned Align =
Owen Anderson20a631f2006-05-03 01:29:57 +0000247 std::max((unsigned)TLI.getTargetData()->getTypeAlignment(Ty),
Nate Begeman3ee3e692005-11-06 09:00:38 +0000248 AI->getAlignment());
Chris Lattnercbefe722005-05-13 23:14:17 +0000249
Reid Spencere0fc4df2006-10-20 07:07:24 +0000250 // If the alignment of the value is smaller than the size of the
251 // value, and if the size of the value is particularly small
252 // (<= 8 bytes), round up to the size of the value for potentially
253 // better performance.
Chris Lattnercbefe722005-05-13 23:14:17 +0000254 //
255 // FIXME: This could be made better with a preferred alignment hook in
256 // TargetData. It serves primarily to 8-byte align doubles for X86.
257 if (Align < TySize && TySize <= 8) Align = TySize;
Reid Spencere0fc4df2006-10-20 07:07:24 +0000258 TySize *= CUI->getZExtValue(); // Get total allocated size.
Chris Lattner0a71a9a2005-10-18 22:14:06 +0000259 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
Chris Lattner7a60d912005-01-07 07:47:53 +0000260 StaticAllocaMap[AI] =
Chris Lattnerd0061952005-01-08 19:52:31 +0000261 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
Chris Lattner7a60d912005-01-07 07:47:53 +0000262 }
263
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000264 for (; BB != EB; ++BB)
265 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner7a60d912005-01-07 07:47:53 +0000266 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
267 if (!isa<AllocaInst>(I) ||
268 !StaticAllocaMap.count(cast<AllocaInst>(I)))
269 InitializeRegForValue(I);
270
271 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
272 // also creates the initial PHI MachineInstrs, though none of the input
273 // operands are populated.
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000274 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000275 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
276 MBBMap[BB] = MBB;
277 MF.getBasicBlockList().push_back(MBB);
278
279 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
280 // appropriate.
281 PHINode *PN;
Chris Lattner84a03502006-10-27 23:50:33 +0000282 for (BasicBlock::iterator I = BB->begin();(PN = dyn_cast<PHINode>(I)); ++I){
283 if (PN->use_empty()) continue;
284
285 MVT::ValueType VT = TLI.getValueType(PN->getType());
286 unsigned NumElements;
287 if (VT != MVT::Vector)
288 NumElements = TLI.getNumElements(VT);
289 else {
290 MVT::ValueType VT1,VT2;
291 NumElements =
292 TLI.getPackedTypeBreakdown(cast<PackedType>(PN->getType()),
293 VT1, VT2);
Chris Lattner8ea875f2005-01-07 21:34:19 +0000294 }
Chris Lattner84a03502006-10-27 23:50:33 +0000295 unsigned PHIReg = ValueMap[PN];
296 assert(PHIReg && "PHI node does not have an assigned virtual register!");
Evan Cheng20350c42006-11-27 23:37:22 +0000297 const TargetInstrInfo *TII = TLI.getTargetMachine().getInstrInfo();
Chris Lattner84a03502006-10-27 23:50:33 +0000298 for (unsigned i = 0; i != NumElements; ++i)
Evan Cheng20350c42006-11-27 23:37:22 +0000299 BuildMI(MBB, TII->get(TargetInstrInfo::PHI), PHIReg+i);
Chris Lattner84a03502006-10-27 23:50:33 +0000300 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000301 }
302}
303
Chris Lattner49409cb2006-03-16 19:51:18 +0000304/// CreateRegForValue - Allocate the appropriate number of virtual registers of
305/// the correctly promoted or expanded types. Assign these registers
306/// consecutive vreg numbers and return the first assigned number.
307unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
308 MVT::ValueType VT = TLI.getValueType(V->getType());
309
310 // The number of multiples of registers that we need, to, e.g., split up
311 // a <2 x int64> -> 4 x i32 registers.
312 unsigned NumVectorRegs = 1;
313
314 // If this is a packed type, figure out what type it will decompose into
315 // and how many of the elements it will use.
316 if (VT == MVT::Vector) {
317 const PackedType *PTy = cast<PackedType>(V->getType());
318 unsigned NumElts = PTy->getNumElements();
319 MVT::ValueType EltTy = TLI.getValueType(PTy->getElementType());
320
321 // Divide the input until we get to a supported size. This will always
322 // end with a scalar if the target doesn't support vectors.
323 while (NumElts > 1 && !TLI.isTypeLegal(getVectorType(EltTy, NumElts))) {
324 NumElts >>= 1;
325 NumVectorRegs <<= 1;
326 }
Chris Lattner7ececaa2006-03-16 23:05:19 +0000327 if (NumElts == 1)
328 VT = EltTy;
329 else
330 VT = getVectorType(EltTy, NumElts);
Chris Lattner49409cb2006-03-16 19:51:18 +0000331 }
332
333 // The common case is that we will only create one register for this
334 // value. If we have that case, create and return the virtual register.
335 unsigned NV = TLI.getNumElements(VT);
336 if (NV == 1) {
337 // If we are promoting this value, pick the next largest supported type.
338 MVT::ValueType PromotedType = TLI.getTypeToTransformTo(VT);
339 unsigned Reg = MakeReg(PromotedType);
340 // If this is a vector of supported or promoted types (e.g. 4 x i16),
341 // create all of the registers.
342 for (unsigned i = 1; i != NumVectorRegs; ++i)
343 MakeReg(PromotedType);
344 return Reg;
345 }
346
347 // If this value is represented with multiple target registers, make sure
348 // to create enough consecutive registers of the right (smaller) type.
Evan Cheng22cf8992006-12-13 20:57:08 +0000349 VT = TLI.getTypeToExpandTo(VT);
350 unsigned R = MakeReg(VT);
Chris Lattner49409cb2006-03-16 19:51:18 +0000351 for (unsigned i = 1; i != NV*NumVectorRegs; ++i)
Evan Cheng22cf8992006-12-13 20:57:08 +0000352 MakeReg(VT);
Chris Lattner49409cb2006-03-16 19:51:18 +0000353 return R;
354}
Chris Lattner7a60d912005-01-07 07:47:53 +0000355
356//===----------------------------------------------------------------------===//
357/// SelectionDAGLowering - This is the common target-independent lowering
358/// implementation that is parameterized by a TargetLowering object.
359/// Also, targets can overload any lowering method.
360///
361namespace llvm {
362class SelectionDAGLowering {
363 MachineBasicBlock *CurMBB;
364
365 std::map<const Value*, SDOperand> NodeMap;
366
Chris Lattner4d9651c2005-01-17 22:19:26 +0000367 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
368 /// them up and then emit token factor nodes when possible. This allows us to
369 /// get simple disambiguation between loads without worrying about alias
370 /// analysis.
371 std::vector<SDOperand> PendingLoads;
372
Nate Begemaned728c12006-03-27 01:32:24 +0000373 /// Case - A pair of values to record the Value for a switch case, and the
374 /// case's target basic block.
375 typedef std::pair<Constant*, MachineBasicBlock*> Case;
376 typedef std::vector<Case>::iterator CaseItr;
377 typedef std::pair<CaseItr, CaseItr> CaseRange;
378
379 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
380 /// of conditional branches.
381 struct CaseRec {
382 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
383 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
384
385 /// CaseBB - The MBB in which to emit the compare and branch
386 MachineBasicBlock *CaseBB;
387 /// LT, GE - If nonzero, we know the current case value must be less-than or
388 /// greater-than-or-equal-to these Constants.
389 Constant *LT;
390 Constant *GE;
391 /// Range - A pair of iterators representing the range of case values to be
392 /// processed at this point in the binary search tree.
393 CaseRange Range;
394 };
395
396 /// The comparison function for sorting Case values.
397 struct CaseCmp {
398 bool operator () (const Case& C1, const Case& C2) {
Reid Spencere0fc4df2006-10-20 07:07:24 +0000399 if (const ConstantInt* I1 = dyn_cast<const ConstantInt>(C1.first))
400 if (I1->getType()->isUnsigned())
401 return I1->getZExtValue() <
402 cast<const ConstantInt>(C2.first)->getZExtValue();
Nate Begemaned728c12006-03-27 01:32:24 +0000403
Reid Spencere0fc4df2006-10-20 07:07:24 +0000404 return cast<const ConstantInt>(C1.first)->getSExtValue() <
405 cast<const ConstantInt>(C2.first)->getSExtValue();
Nate Begemaned728c12006-03-27 01:32:24 +0000406 }
407 };
408
Chris Lattner7a60d912005-01-07 07:47:53 +0000409public:
410 // TLI - This is information that describes the available target features we
411 // need for lowering. This indicates when operations are unavailable,
412 // implemented with a libcall, etc.
413 TargetLowering &TLI;
414 SelectionDAG &DAG;
Owen Anderson20a631f2006-05-03 01:29:57 +0000415 const TargetData *TD;
Chris Lattner7a60d912005-01-07 07:47:53 +0000416
Nate Begemaned728c12006-03-27 01:32:24 +0000417 /// SwitchCases - Vector of CaseBlock structures used to communicate
418 /// SwitchInst code generation information.
419 std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
Nate Begeman4ca2ea52006-04-22 18:53:45 +0000420 SelectionDAGISel::JumpTable JT;
Nate Begemaned728c12006-03-27 01:32:24 +0000421
Chris Lattner7a60d912005-01-07 07:47:53 +0000422 /// FuncInfo - Information about the function as a whole.
423 ///
424 FunctionLoweringInfo &FuncInfo;
425
426 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Misha Brukman835702a2005-04-21 22:36:52 +0000427 FunctionLoweringInfo &funcinfo)
Chris Lattner7a60d912005-01-07 07:47:53 +0000428 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
Nate Begeman866b4b42006-04-23 06:26:20 +0000429 JT(0,0,0,0), FuncInfo(funcinfo) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000430 }
431
Chris Lattner4108bb02005-01-17 19:43:36 +0000432 /// getRoot - Return the current virtual root of the Selection DAG.
433 ///
434 SDOperand getRoot() {
Chris Lattner4d9651c2005-01-17 22:19:26 +0000435 if (PendingLoads.empty())
436 return DAG.getRoot();
Misha Brukman835702a2005-04-21 22:36:52 +0000437
Chris Lattner4d9651c2005-01-17 22:19:26 +0000438 if (PendingLoads.size() == 1) {
439 SDOperand Root = PendingLoads[0];
440 DAG.setRoot(Root);
441 PendingLoads.clear();
442 return Root;
443 }
444
445 // Otherwise, we have to make a token factor node.
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000446 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
447 &PendingLoads[0], PendingLoads.size());
Chris Lattner4d9651c2005-01-17 22:19:26 +0000448 PendingLoads.clear();
449 DAG.setRoot(Root);
450 return Root;
Chris Lattner4108bb02005-01-17 19:43:36 +0000451 }
452
Chris Lattnered0110b2006-10-27 21:36:01 +0000453 SDOperand CopyValueToVirtualRegister(Value *V, unsigned Reg);
454
Chris Lattner7a60d912005-01-07 07:47:53 +0000455 void visit(Instruction &I) { visit(I.getOpcode(), I); }
456
457 void visit(unsigned Opcode, User &I) {
Chris Lattnerd5e604d2006-11-10 04:41:34 +0000458 // Note: this doesn't use InstVisitor, because it has to work with
459 // ConstantExpr's in addition to instructions.
Chris Lattner7a60d912005-01-07 07:47:53 +0000460 switch (Opcode) {
461 default: assert(0 && "Unknown instruction type encountered!");
462 abort();
463 // Build the switch statement using the Instruction.def file.
464#define HANDLE_INST(NUM, OPCODE, CLASS) \
465 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
466#include "llvm/Instruction.def"
467 }
468 }
469
470 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
471
Chris Lattner4024c002006-03-15 22:19:46 +0000472 SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Chenge71fe34d2006-10-09 20:57:25 +0000473 const Value *SV, SDOperand Root,
Chris Lattner4024c002006-03-15 22:19:46 +0000474 bool isVolatile);
Chris Lattner7a60d912005-01-07 07:47:53 +0000475
476 SDOperand getIntPtrConstant(uint64_t Val) {
477 return DAG.getConstant(Val, TLI.getPointerTy());
478 }
479
Chris Lattner8471b152006-03-16 19:57:50 +0000480 SDOperand getValue(const Value *V);
Chris Lattner7a60d912005-01-07 07:47:53 +0000481
482 const SDOperand &setValue(const Value *V, SDOperand NewN) {
483 SDOperand &N = NodeMap[V];
484 assert(N.Val == 0 && "Already set a value for this node!");
485 return N = NewN;
486 }
Chris Lattner1558fc62006-02-01 18:59:47 +0000487
Chris Lattner6f87d182006-02-22 22:37:12 +0000488 RegsForValue GetRegistersForValue(const std::string &ConstrCode,
489 MVT::ValueType VT,
490 bool OutReg, bool InReg,
491 std::set<unsigned> &OutputRegs,
492 std::set<unsigned> &InputRegs);
Nate Begemaned728c12006-03-27 01:32:24 +0000493
Chris Lattnered0110b2006-10-27 21:36:01 +0000494 void FindMergedConditions(Value *Cond, MachineBasicBlock *TBB,
495 MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
496 unsigned Opc);
Chris Lattner84a03502006-10-27 23:50:33 +0000497 bool isExportableFromCurrentBlock(Value *V, const BasicBlock *FromBB);
Chris Lattnered0110b2006-10-27 21:36:01 +0000498 void ExportFromCurrentBlock(Value *V);
499
Chris Lattner7a60d912005-01-07 07:47:53 +0000500 // Terminator instructions.
501 void visitRet(ReturnInst &I);
502 void visitBr(BranchInst &I);
Nate Begemaned728c12006-03-27 01:32:24 +0000503 void visitSwitch(SwitchInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000504 void visitUnreachable(UnreachableInst &I) { /* noop */ }
505
Nate Begemaned728c12006-03-27 01:32:24 +0000506 // Helper for visitSwitch
507 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
Nate Begeman4ca2ea52006-04-22 18:53:45 +0000508 void visitJumpTable(SelectionDAGISel::JumpTable &JT);
Nate Begemaned728c12006-03-27 01:32:24 +0000509
Chris Lattner7a60d912005-01-07 07:47:53 +0000510 // These all get lowered before this pass.
Chris Lattner7a60d912005-01-07 07:47:53 +0000511 void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
512 void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
513
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000514 void visitIntBinary(User &I, unsigned IntOp, unsigned VecOp);
515 void visitFPBinary(User &I, unsigned FPOp, unsigned VecOp);
Nate Begeman127321b2005-11-18 07:42:56 +0000516 void visitShift(User &I, unsigned Opcode);
Nate Begemanb2e089c2005-11-19 00:36:38 +0000517 void visitAdd(User &I) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000518 if (I.getType()->isFloatingPoint())
519 visitFPBinary(I, ISD::FADD, ISD::VADD);
520 else
521 visitIntBinary(I, ISD::ADD, ISD::VADD);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000522 }
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000523 void visitSub(User &I);
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000524 void visitMul(User &I) {
525 if (I.getType()->isFloatingPoint())
526 visitFPBinary(I, ISD::FMUL, ISD::VMUL);
527 else
528 visitIntBinary(I, ISD::MUL, ISD::VMUL);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000529 }
Reid Spencer7eb55b32006-11-02 01:53:59 +0000530 void visitURem(User &I) { visitIntBinary(I, ISD::UREM, 0); }
531 void visitSRem(User &I) { visitIntBinary(I, ISD::SREM, 0); }
532 void visitFRem(User &I) { visitFPBinary (I, ISD::FREM, 0); }
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000533 void visitUDiv(User &I) { visitIntBinary(I, ISD::UDIV, ISD::VUDIV); }
534 void visitSDiv(User &I) { visitIntBinary(I, ISD::SDIV, ISD::VSDIV); }
Reid Spencer7eb55b32006-11-02 01:53:59 +0000535 void visitFDiv(User &I) { visitFPBinary (I, ISD::FDIV, ISD::VSDIV); }
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000536 void visitAnd(User &I) { visitIntBinary(I, ISD::AND, ISD::VAND); }
537 void visitOr (User &I) { visitIntBinary(I, ISD::OR, ISD::VOR); }
538 void visitXor(User &I) { visitIntBinary(I, ISD::XOR, ISD::VXOR); }
Nate Begeman127321b2005-11-18 07:42:56 +0000539 void visitShl(User &I) { visitShift(I, ISD::SHL); }
Reid Spencerfdff9382006-11-08 06:47:33 +0000540 void visitLShr(User &I) { visitShift(I, ISD::SRL); }
541 void visitAShr(User &I) { visitShift(I, ISD::SRA); }
Reid Spencerd9436b62006-11-20 01:22:35 +0000542 void visitICmp(User &I);
543 void visitFCmp(User &I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000544 // Visit the conversion instructions
545 void visitTrunc(User &I);
546 void visitZExt(User &I);
547 void visitSExt(User &I);
548 void visitFPTrunc(User &I);
549 void visitFPExt(User &I);
550 void visitFPToUI(User &I);
551 void visitFPToSI(User &I);
552 void visitUIToFP(User &I);
553 void visitSIToFP(User &I);
554 void visitPtrToInt(User &I);
555 void visitIntToPtr(User &I);
556 void visitBitCast(User &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000557
Chris Lattner67271862006-03-29 00:11:43 +0000558 void visitExtractElement(User &I);
559 void visitInsertElement(User &I);
Chris Lattner098c01e2006-04-08 04:15:24 +0000560 void visitShuffleVector(User &I);
Chris Lattner32206f52006-03-18 01:44:44 +0000561
Chris Lattner7a60d912005-01-07 07:47:53 +0000562 void visitGetElementPtr(User &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000563 void visitSelect(User &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000564
565 void visitMalloc(MallocInst &I);
566 void visitFree(FreeInst &I);
567 void visitAlloca(AllocaInst &I);
568 void visitLoad(LoadInst &I);
569 void visitStore(StoreInst &I);
570 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
571 void visitCall(CallInst &I);
Chris Lattner476e67b2006-01-26 22:24:51 +0000572 void visitInlineAsm(CallInst &I);
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000573 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattnerd96b09a2006-03-24 02:22:33 +0000574 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
Chris Lattner7a60d912005-01-07 07:47:53 +0000575
Chris Lattner7a60d912005-01-07 07:47:53 +0000576 void visitVAStart(CallInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000577 void visitVAArg(VAArgInst &I);
578 void visitVAEnd(CallInst &I);
579 void visitVACopy(CallInst &I);
Chris Lattner58cfd792005-01-09 00:00:49 +0000580 void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
Chris Lattner7a60d912005-01-07 07:47:53 +0000581
Chris Lattner875def92005-01-11 05:56:49 +0000582 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner7a60d912005-01-07 07:47:53 +0000583
584 void visitUserOp1(Instruction &I) {
585 assert(0 && "UserOp1 should not exist at instruction selection time!");
586 abort();
587 }
588 void visitUserOp2(Instruction &I) {
589 assert(0 && "UserOp2 should not exist at instruction selection time!");
590 abort();
591 }
592};
593} // end namespace llvm
594
Chris Lattner8471b152006-03-16 19:57:50 +0000595SDOperand SelectionDAGLowering::getValue(const Value *V) {
596 SDOperand &N = NodeMap[V];
597 if (N.Val) return N;
598
599 const Type *VTy = V->getType();
600 MVT::ValueType VT = TLI.getValueType(VTy);
601 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
602 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
603 visit(CE->getOpcode(), *CE);
604 assert(N.Val && "visit didn't populate the ValueMap!");
605 return N;
606 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
607 return N = DAG.getGlobalAddress(GV, VT);
608 } else if (isa<ConstantPointerNull>(C)) {
609 return N = DAG.getConstant(0, TLI.getPointerTy());
610 } else if (isa<UndefValue>(C)) {
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000611 if (!isa<PackedType>(VTy))
612 return N = DAG.getNode(ISD::UNDEF, VT);
613
Chris Lattnerf4e1a532006-03-19 00:52:58 +0000614 // Create a VBUILD_VECTOR of undef nodes.
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000615 const PackedType *PTy = cast<PackedType>(VTy);
616 unsigned NumElements = PTy->getNumElements();
617 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
618
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000619 SmallVector<SDOperand, 8> Ops;
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000620 Ops.assign(NumElements, DAG.getNode(ISD::UNDEF, PVT));
621
622 // Create a VConstant node with generic Vector type.
623 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
624 Ops.push_back(DAG.getValueType(PVT));
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000625 return N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector,
626 &Ops[0], Ops.size());
Chris Lattner8471b152006-03-16 19:57:50 +0000627 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
628 return N = DAG.getConstantFP(CFP->getValue(), VT);
629 } else if (const PackedType *PTy = dyn_cast<PackedType>(VTy)) {
630 unsigned NumElements = PTy->getNumElements();
631 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Chris Lattner8471b152006-03-16 19:57:50 +0000632
633 // Now that we know the number and type of the elements, push a
634 // Constant or ConstantFP node onto the ops list for each element of
635 // the packed constant.
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000636 SmallVector<SDOperand, 8> Ops;
Chris Lattner8471b152006-03-16 19:57:50 +0000637 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(C)) {
Chris Lattner67271862006-03-29 00:11:43 +0000638 for (unsigned i = 0; i != NumElements; ++i)
639 Ops.push_back(getValue(CP->getOperand(i)));
Chris Lattner8471b152006-03-16 19:57:50 +0000640 } else {
641 assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
642 SDOperand Op;
643 if (MVT::isFloatingPoint(PVT))
644 Op = DAG.getConstantFP(0, PVT);
645 else
646 Op = DAG.getConstant(0, PVT);
647 Ops.assign(NumElements, Op);
648 }
649
Chris Lattnerf4e1a532006-03-19 00:52:58 +0000650 // Create a VBUILD_VECTOR node with generic Vector type.
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000651 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
652 Ops.push_back(DAG.getValueType(PVT));
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000653 return N = DAG.getNode(ISD::VBUILD_VECTOR,MVT::Vector,&Ops[0],Ops.size());
Chris Lattner8471b152006-03-16 19:57:50 +0000654 } else {
655 // Canonicalize all constant ints to be unsigned.
Reid Spencere0fc4df2006-10-20 07:07:24 +0000656 return N = DAG.getConstant(cast<ConstantIntegral>(C)->getZExtValue(),VT);
Chris Lattner8471b152006-03-16 19:57:50 +0000657 }
658 }
659
660 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
661 std::map<const AllocaInst*, int>::iterator SI =
662 FuncInfo.StaticAllocaMap.find(AI);
663 if (SI != FuncInfo.StaticAllocaMap.end())
664 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
665 }
666
667 std::map<const Value*, unsigned>::const_iterator VMI =
668 FuncInfo.ValueMap.find(V);
669 assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
670
671 unsigned InReg = VMI->second;
672
673 // If this type is not legal, make it so now.
Chris Lattner5fe1f542006-03-31 02:06:56 +0000674 if (VT != MVT::Vector) {
Evan Cheng22cf8992006-12-13 20:57:08 +0000675 if (TLI.getTypeAction(VT) == TargetLowering::Expand) {
Chris Lattner5fe1f542006-03-31 02:06:56 +0000676 // Source must be expanded. This input value is actually coming from the
677 // register pair VMI->second and VMI->second+1.
Evan Cheng22cf8992006-12-13 20:57:08 +0000678 MVT::ValueType DestVT = TLI.getTypeToExpandTo(VT);
679 unsigned NumVals = TLI.getNumElements(VT);
680 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
681 if (NumVals == 1)
682 N = DAG.getNode(ISD::BIT_CONVERT, VT, N);
683 else {
684 assert(NumVals == 2 && "1 to 4 (and more) expansion not implemented!");
685 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
686 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
687 }
688 } else {
689 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
690 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
691 if (TLI.getTypeAction(VT) == TargetLowering::Promote) // Promotion case
692 N = MVT::isFloatingPoint(VT)
693 ? DAG.getNode(ISD::FP_ROUND, VT, N)
694 : DAG.getNode(ISD::TRUNCATE, VT, N);
Chris Lattner8471b152006-03-16 19:57:50 +0000695 }
Chris Lattner5fe1f542006-03-31 02:06:56 +0000696 } else {
697 // Otherwise, if this is a vector, make it available as a generic vector
698 // here.
699 MVT::ValueType PTyElementVT, PTyLegalElementVT;
Chris Lattner4a2413a2006-04-05 06:54:42 +0000700 const PackedType *PTy = cast<PackedType>(VTy);
701 unsigned NE = TLI.getPackedTypeBreakdown(PTy, PTyElementVT,
Chris Lattner5fe1f542006-03-31 02:06:56 +0000702 PTyLegalElementVT);
703
704 // Build a VBUILD_VECTOR with the input registers.
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000705 SmallVector<SDOperand, 8> Ops;
Chris Lattner5fe1f542006-03-31 02:06:56 +0000706 if (PTyElementVT == PTyLegalElementVT) {
707 // If the value types are legal, just VBUILD the CopyFromReg nodes.
708 for (unsigned i = 0; i != NE; ++i)
709 Ops.push_back(DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
710 PTyElementVT));
711 } else if (PTyElementVT < PTyLegalElementVT) {
712 // If the register was promoted, use TRUNCATE of FP_ROUND as appropriate.
713 for (unsigned i = 0; i != NE; ++i) {
714 SDOperand Op = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
715 PTyElementVT);
716 if (MVT::isFloatingPoint(PTyElementVT))
717 Op = DAG.getNode(ISD::FP_ROUND, PTyElementVT, Op);
718 else
719 Op = DAG.getNode(ISD::TRUNCATE, PTyElementVT, Op);
720 Ops.push_back(Op);
721 }
722 } else {
723 // If the register was expanded, use BUILD_PAIR.
724 assert((NE & 1) == 0 && "Must expand into a multiple of 2 elements!");
725 for (unsigned i = 0; i != NE/2; ++i) {
726 SDOperand Op0 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
727 PTyElementVT);
728 SDOperand Op1 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
729 PTyElementVT);
730 Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, VT, Op0, Op1));
731 }
732 }
733
734 Ops.push_back(DAG.getConstant(NE, MVT::i32));
735 Ops.push_back(DAG.getValueType(PTyLegalElementVT));
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000736 N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0], Ops.size());
Chris Lattner4a2413a2006-04-05 06:54:42 +0000737
738 // Finally, use a VBIT_CONVERT to make this available as the appropriate
739 // vector type.
740 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
741 DAG.getConstant(PTy->getNumElements(),
742 MVT::i32),
743 DAG.getValueType(TLI.getValueType(PTy->getElementType())));
Chris Lattner8471b152006-03-16 19:57:50 +0000744 }
745
746 return N;
747}
748
749
Chris Lattner7a60d912005-01-07 07:47:53 +0000750void SelectionDAGLowering::visitRet(ReturnInst &I) {
751 if (I.getNumOperands() == 0) {
Chris Lattner4108bb02005-01-17 19:43:36 +0000752 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
Chris Lattner7a60d912005-01-07 07:47:53 +0000753 return;
754 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000755 SmallVector<SDOperand, 8> NewValues;
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000756 NewValues.push_back(getRoot());
757 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
758 SDOperand RetOp = getValue(I.getOperand(i));
Evan Chenga2e99532006-05-26 23:09:09 +0000759 bool isSigned = I.getOperand(i)->getType()->isSigned();
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000760
761 // If this is an integer return value, we need to promote it ourselves to
762 // the full width of a register, since LegalizeOp will use ANY_EXTEND rather
763 // than sign/zero.
Evan Chenga2e99532006-05-26 23:09:09 +0000764 // FIXME: C calling convention requires the return type to be promoted to
765 // at least 32-bit. But this is not necessary for non-C calling conventions.
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000766 if (MVT::isInteger(RetOp.getValueType()) &&
767 RetOp.getValueType() < MVT::i64) {
768 MVT::ValueType TmpVT;
769 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
770 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
771 else
772 TmpVT = MVT::i32;
Chris Lattner7a60d912005-01-07 07:47:53 +0000773
Evan Chenga2e99532006-05-26 23:09:09 +0000774 if (isSigned)
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000775 RetOp = DAG.getNode(ISD::SIGN_EXTEND, TmpVT, RetOp);
776 else
777 RetOp = DAG.getNode(ISD::ZERO_EXTEND, TmpVT, RetOp);
778 }
779 NewValues.push_back(RetOp);
Evan Chenga2e99532006-05-26 23:09:09 +0000780 NewValues.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattner7a60d912005-01-07 07:47:53 +0000781 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000782 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
783 &NewValues[0], NewValues.size()));
Chris Lattner7a60d912005-01-07 07:47:53 +0000784}
785
Chris Lattnered0110b2006-10-27 21:36:01 +0000786/// ExportFromCurrentBlock - If this condition isn't known to be exported from
787/// the current basic block, add it to ValueMap now so that we'll get a
788/// CopyTo/FromReg.
789void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
790 // No need to export constants.
791 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
792
793 // Already exported?
794 if (FuncInfo.isExportedInst(V)) return;
795
796 unsigned Reg = FuncInfo.InitializeRegForValue(V);
797 PendingLoads.push_back(CopyValueToVirtualRegister(V, Reg));
798}
799
Chris Lattner84a03502006-10-27 23:50:33 +0000800bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
801 const BasicBlock *FromBB) {
802 // The operands of the setcc have to be in this block. We don't know
803 // how to export them from some other block.
804 if (Instruction *VI = dyn_cast<Instruction>(V)) {
805 // Can export from current BB.
806 if (VI->getParent() == FromBB)
807 return true;
808
809 // Is already exported, noop.
810 return FuncInfo.isExportedInst(V);
811 }
812
813 // If this is an argument, we can export it if the BB is the entry block or
814 // if it is already exported.
815 if (isa<Argument>(V)) {
816 if (FromBB == &FromBB->getParent()->getEntryBlock())
817 return true;
818
819 // Otherwise, can only export this if it is already exported.
820 return FuncInfo.isExportedInst(V);
821 }
822
823 // Otherwise, constants can always be exported.
824 return true;
825}
826
Chris Lattnere60ae822006-10-29 21:01:20 +0000827static bool InBlock(const Value *V, const BasicBlock *BB) {
828 if (const Instruction *I = dyn_cast<Instruction>(V))
829 return I->getParent() == BB;
830 return true;
831}
832
Chris Lattnered0110b2006-10-27 21:36:01 +0000833/// FindMergedConditions - If Cond is an expression like
834void SelectionDAGLowering::FindMergedConditions(Value *Cond,
835 MachineBasicBlock *TBB,
836 MachineBasicBlock *FBB,
837 MachineBasicBlock *CurBB,
838 unsigned Opc) {
Chris Lattnered0110b2006-10-27 21:36:01 +0000839 // If this node is not part of the or/and tree, emit it as a branch.
Reid Spencer266e42b2006-12-23 06:05:41 +0000840 Instruction *BOp = dyn_cast<Instruction>(Cond);
Chris Lattnered0110b2006-10-27 21:36:01 +0000841
Reid Spencer266e42b2006-12-23 06:05:41 +0000842 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
843 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
Chris Lattnere60ae822006-10-29 21:01:20 +0000844 BOp->getParent() != CurBB->getBasicBlock() ||
845 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
846 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
Chris Lattnered0110b2006-10-27 21:36:01 +0000847 const BasicBlock *BB = CurBB->getBasicBlock();
848
Chris Lattner427301f2006-10-31 22:37:42 +0000849 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Cond))
850 if ((II->getIntrinsicID() == Intrinsic::isunordered_f32 ||
851 II->getIntrinsicID() == Intrinsic::isunordered_f64) &&
852 // The operands of the setcc have to be in this block. We don't know
853 // how to export them from some other block. If this is the first
854 // block of the sequence, no exporting is needed.
855 (CurBB == CurMBB ||
856 (isExportableFromCurrentBlock(II->getOperand(1), BB) &&
857 isExportableFromCurrentBlock(II->getOperand(2), BB)))) {
858 SelectionDAGISel::CaseBlock CB(ISD::SETUO, II->getOperand(1),
859 II->getOperand(2), TBB, FBB, CurBB);
860 SwitchCases.push_back(CB);
861 return;
862 }
863
864
Reid Spencer266e42b2006-12-23 06:05:41 +0000865 // If the leaf of the tree is a comparison, merge the condition into
866 // the caseblock.
867 if ((isa<ICmpInst>(Cond) || isa<FCmpInst>(Cond)) &&
868 // The operands of the cmp have to be in this block. We don't know
Chris Lattnerf31b9ef2006-10-29 18:23:37 +0000869 // how to export them from some other block. If this is the first block
870 // of the sequence, no exporting is needed.
871 (CurBB == CurMBB ||
872 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
873 isExportableFromCurrentBlock(BOp->getOperand(1), BB)))) {
Reid Spencer266e42b2006-12-23 06:05:41 +0000874 BOp = cast<Instruction>(Cond);
875 ISD::CondCode Condition;
876 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
877 switch (IC->getPredicate()) {
878 default: assert(0 && "Unknown icmp predicate opcode!");
879 case ICmpInst::ICMP_EQ: Condition = ISD::SETEQ; break;
880 case ICmpInst::ICMP_NE: Condition = ISD::SETNE; break;
881 case ICmpInst::ICMP_SLE: Condition = ISD::SETLE; break;
882 case ICmpInst::ICMP_ULE: Condition = ISD::SETULE; break;
883 case ICmpInst::ICMP_SGE: Condition = ISD::SETGE; break;
884 case ICmpInst::ICMP_UGE: Condition = ISD::SETUGE; break;
885 case ICmpInst::ICMP_SLT: Condition = ISD::SETLT; break;
886 case ICmpInst::ICMP_ULT: Condition = ISD::SETULT; break;
887 case ICmpInst::ICMP_SGT: Condition = ISD::SETGT; break;
888 case ICmpInst::ICMP_UGT: Condition = ISD::SETUGT; break;
889 }
890 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
891 ISD::CondCode FPC, FOC;
892 switch (FC->getPredicate()) {
893 default: assert(0 && "Unknown fcmp predicate opcode!");
894 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
895 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
896 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
897 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
898 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
899 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
900 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
901 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
902 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
903 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
904 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
905 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
906 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
907 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
908 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
909 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
910 }
911 if (FiniteOnlyFPMath())
912 Condition = FOC;
913 else
914 Condition = FPC;
915 } else {
916 assert(0 && "Unknown compare instruction");
Chris Lattnered0110b2006-10-27 21:36:01 +0000917 }
918
Chris Lattnered0110b2006-10-27 21:36:01 +0000919 SelectionDAGISel::CaseBlock CB(Condition, BOp->getOperand(0),
920 BOp->getOperand(1), TBB, FBB, CurBB);
921 SwitchCases.push_back(CB);
922 return;
923 }
924
925 // Create a CaseBlock record representing this branch.
926 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, Cond, ConstantBool::getTrue(),
927 TBB, FBB, CurBB);
928 SwitchCases.push_back(CB);
Chris Lattnered0110b2006-10-27 21:36:01 +0000929 return;
930 }
931
Chris Lattnerf1b54fd2006-10-27 21:54:23 +0000932
933 // Create TmpBB after CurBB.
Chris Lattnered0110b2006-10-27 21:36:01 +0000934 MachineFunction::iterator BBI = CurBB;
935 MachineBasicBlock *TmpBB = new MachineBasicBlock(CurBB->getBasicBlock());
936 CurBB->getParent()->getBasicBlockList().insert(++BBI, TmpBB);
937
Chris Lattnerf1b54fd2006-10-27 21:54:23 +0000938 if (Opc == Instruction::Or) {
939 // Codegen X | Y as:
940 // jmp_if_X TBB
941 // jmp TmpBB
942 // TmpBB:
943 // jmp_if_Y TBB
944 // jmp FBB
945 //
Chris Lattnered0110b2006-10-27 21:36:01 +0000946
Chris Lattnerf1b54fd2006-10-27 21:54:23 +0000947 // Emit the LHS condition.
948 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
949
950 // Emit the RHS condition into TmpBB.
951 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
952 } else {
953 assert(Opc == Instruction::And && "Unknown merge op!");
954 // Codegen X & Y as:
955 // jmp_if_X TmpBB
956 // jmp FBB
957 // TmpBB:
958 // jmp_if_Y TBB
959 // jmp FBB
960 //
961 // This requires creation of TmpBB after CurBB.
962
963 // Emit the LHS condition.
964 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
965
966 // Emit the RHS condition into TmpBB.
967 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
968 }
Chris Lattnered0110b2006-10-27 21:36:01 +0000969}
970
Chris Lattner427301f2006-10-31 22:37:42 +0000971/// If the set of cases should be emitted as a series of branches, return true.
972/// If we should emit this as a bunch of and/or'd together conditions, return
973/// false.
974static bool
975ShouldEmitAsBranches(const std::vector<SelectionDAGISel::CaseBlock> &Cases) {
976 if (Cases.size() != 2) return true;
977
Chris Lattnerfe43bef2006-10-31 23:06:00 +0000978 // If this is two comparisons of the same values or'd or and'd together, they
979 // will get folded into a single comparison, so don't emit two blocks.
980 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
981 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
982 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
983 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
984 return false;
985 }
986
Chris Lattner427301f2006-10-31 22:37:42 +0000987 return true;
988}
989
Chris Lattner7a60d912005-01-07 07:47:53 +0000990void SelectionDAGLowering::visitBr(BranchInst &I) {
991 // Update machine-CFG edges.
992 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner7a60d912005-01-07 07:47:53 +0000993
994 // Figure out which block is immediately after the current one.
995 MachineBasicBlock *NextBlock = 0;
996 MachineFunction::iterator BBI = CurMBB;
997 if (++BBI != CurMBB->getParent()->end())
998 NextBlock = BBI;
999
1000 if (I.isUnconditional()) {
1001 // If this is not a fall-through branch, emit the branch.
1002 if (Succ0MBB != NextBlock)
Chris Lattner4108bb02005-01-17 19:43:36 +00001003 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +00001004 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +00001005
Chris Lattner963ddad2006-10-24 17:57:59 +00001006 // Update machine-CFG edges.
1007 CurMBB->addSuccessor(Succ0MBB);
1008
1009 return;
1010 }
1011
1012 // If this condition is one of the special cases we handle, do special stuff
1013 // now.
1014 Value *CondVal = I.getCondition();
Chris Lattner963ddad2006-10-24 17:57:59 +00001015 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattnered0110b2006-10-27 21:36:01 +00001016
1017 // If this is a series of conditions that are or'd or and'd together, emit
1018 // this as a sequence of branches instead of setcc's with and/or operations.
1019 // For example, instead of something like:
1020 // cmp A, B
1021 // C = seteq
1022 // cmp D, E
1023 // F = setle
1024 // or C, F
1025 // jnz foo
1026 // Emit:
1027 // cmp A, B
1028 // je foo
1029 // cmp D, E
1030 // jle foo
1031 //
1032 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1033 if (BOp->hasOneUse() &&
Chris Lattnerf1b54fd2006-10-27 21:54:23 +00001034 (BOp->getOpcode() == Instruction::And ||
Chris Lattnered0110b2006-10-27 21:36:01 +00001035 BOp->getOpcode() == Instruction::Or)) {
1036 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
Chris Lattnerfe43bef2006-10-31 23:06:00 +00001037 // If the compares in later blocks need to use values not currently
1038 // exported from this block, export them now. This block should always
1039 // be the first entry.
1040 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1041
Chris Lattner427301f2006-10-31 22:37:42 +00001042 // Allow some cases to be rejected.
1043 if (ShouldEmitAsBranches(SwitchCases)) {
Chris Lattner427301f2006-10-31 22:37:42 +00001044 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1045 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1046 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1047 }
1048
1049 // Emit the branch for this block.
1050 visitSwitchCase(SwitchCases[0]);
1051 SwitchCases.erase(SwitchCases.begin());
1052 return;
Chris Lattnerf31b9ef2006-10-29 18:23:37 +00001053 }
1054
Chris Lattnerfe43bef2006-10-31 23:06:00 +00001055 // Okay, we decided not to do this, remove any inserted MBB's and clear
1056 // SwitchCases.
1057 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1058 CurMBB->getParent()->getBasicBlockList().erase(SwitchCases[i].ThisBB);
1059
Chris Lattner427301f2006-10-31 22:37:42 +00001060 SwitchCases.clear();
Chris Lattnered0110b2006-10-27 21:36:01 +00001061 }
1062 }
Chris Lattner61bcf912006-10-24 18:07:37 +00001063
1064 // Create a CaseBlock record representing this branch.
Chris Lattnered0110b2006-10-27 21:36:01 +00001065 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, CondVal, ConstantBool::getTrue(),
Chris Lattner61bcf912006-10-24 18:07:37 +00001066 Succ0MBB, Succ1MBB, CurMBB);
1067 // Use visitSwitchCase to actually insert the fast branch sequence for this
1068 // cond branch.
1069 visitSwitchCase(CB);
Chris Lattner7a60d912005-01-07 07:47:53 +00001070}
1071
Nate Begemaned728c12006-03-27 01:32:24 +00001072/// visitSwitchCase - Emits the necessary code to represent a single node in
1073/// the binary search tree resulting from lowering a switch instruction.
1074void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
Chris Lattner963ddad2006-10-24 17:57:59 +00001075 SDOperand Cond;
1076 SDOperand CondLHS = getValue(CB.CmpLHS);
1077
Chris Lattnered0110b2006-10-27 21:36:01 +00001078 // Build the setcc now, fold "(X == true)" to X and "(X == false)" to !X to
1079 // handle common cases produced by branch lowering.
1080 if (CB.CmpRHS == ConstantBool::getTrue() && CB.CC == ISD::SETEQ)
Chris Lattner963ddad2006-10-24 17:57:59 +00001081 Cond = CondLHS;
Chris Lattnered0110b2006-10-27 21:36:01 +00001082 else if (CB.CmpRHS == ConstantBool::getFalse() && CB.CC == ISD::SETEQ) {
1083 SDOperand True = DAG.getConstant(1, CondLHS.getValueType());
1084 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1085 } else
1086 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
Nate Begemaned728c12006-03-27 01:32:24 +00001087
1088 // Set NextBlock to be the MBB immediately after the current one, if any.
1089 // This is used to avoid emitting unnecessary branches to the next block.
1090 MachineBasicBlock *NextBlock = 0;
1091 MachineFunction::iterator BBI = CurMBB;
1092 if (++BBI != CurMBB->getParent()->end())
1093 NextBlock = BBI;
1094
1095 // If the lhs block is the next block, invert the condition so that we can
1096 // fall through to the lhs instead of the rhs block.
Chris Lattner963ddad2006-10-24 17:57:59 +00001097 if (CB.TrueBB == NextBlock) {
1098 std::swap(CB.TrueBB, CB.FalseBB);
Nate Begemaned728c12006-03-27 01:32:24 +00001099 SDOperand True = DAG.getConstant(1, Cond.getValueType());
1100 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1101 }
1102 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
Chris Lattner963ddad2006-10-24 17:57:59 +00001103 DAG.getBasicBlock(CB.TrueBB));
1104 if (CB.FalseBB == NextBlock)
Nate Begemaned728c12006-03-27 01:32:24 +00001105 DAG.setRoot(BrCond);
1106 else
1107 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
Chris Lattner963ddad2006-10-24 17:57:59 +00001108 DAG.getBasicBlock(CB.FalseBB)));
Nate Begemaned728c12006-03-27 01:32:24 +00001109 // Update successor info
Chris Lattner963ddad2006-10-24 17:57:59 +00001110 CurMBB->addSuccessor(CB.TrueBB);
1111 CurMBB->addSuccessor(CB.FalseBB);
Nate Begemaned728c12006-03-27 01:32:24 +00001112}
1113
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001114void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001115 // Emit the code for the jump table
1116 MVT::ValueType PTy = TLI.getPointerTy();
Evan Cheng84a28d42006-10-30 08:00:44 +00001117 SDOperand Index = DAG.getCopyFromReg(getRoot(), JT.Reg, PTy);
1118 SDOperand Table = DAG.getJumpTable(JT.JTI, PTy);
1119 DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1120 Table, Index));
1121 return;
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001122}
1123
Nate Begemaned728c12006-03-27 01:32:24 +00001124void SelectionDAGLowering::visitSwitch(SwitchInst &I) {
1125 // Figure out which block is immediately after the current one.
1126 MachineBasicBlock *NextBlock = 0;
1127 MachineFunction::iterator BBI = CurMBB;
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001128
Nate Begemaned728c12006-03-27 01:32:24 +00001129 if (++BBI != CurMBB->getParent()->end())
1130 NextBlock = BBI;
1131
Chris Lattner6d6fc262006-10-22 21:36:53 +00001132 MachineBasicBlock *Default = FuncInfo.MBBMap[I.getDefaultDest()];
1133
Nate Begemaned728c12006-03-27 01:32:24 +00001134 // If there is only the default destination, branch to it if it is not the
1135 // next basic block. Otherwise, just fall through.
1136 if (I.getNumOperands() == 2) {
1137 // Update machine-CFG edges.
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001138
Nate Begemaned728c12006-03-27 01:32:24 +00001139 // If this is not a fall-through branch, emit the branch.
Chris Lattner6d6fc262006-10-22 21:36:53 +00001140 if (Default != NextBlock)
Nate Begemaned728c12006-03-27 01:32:24 +00001141 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Chris Lattner6d6fc262006-10-22 21:36:53 +00001142 DAG.getBasicBlock(Default)));
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001143
Chris Lattner6d6fc262006-10-22 21:36:53 +00001144 CurMBB->addSuccessor(Default);
Nate Begemaned728c12006-03-27 01:32:24 +00001145 return;
1146 }
1147
1148 // If there are any non-default case statements, create a vector of Cases
1149 // representing each one, and sort the vector so that we can efficiently
1150 // create a binary search tree from them.
1151 std::vector<Case> Cases;
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001152
Nate Begemaned728c12006-03-27 01:32:24 +00001153 for (unsigned i = 1; i < I.getNumSuccessors(); ++i) {
1154 MachineBasicBlock *SMBB = FuncInfo.MBBMap[I.getSuccessor(i)];
1155 Cases.push_back(Case(I.getSuccessorValue(i), SMBB));
1156 }
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001157
Nate Begemaned728c12006-03-27 01:32:24 +00001158 std::sort(Cases.begin(), Cases.end(), CaseCmp());
1159
1160 // Get the Value to be switched on and default basic blocks, which will be
1161 // inserted into CaseBlock records, representing basic blocks in the binary
1162 // search tree.
1163 Value *SV = I.getOperand(0);
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001164
1165 // Get the MachineFunction which holds the current MBB. This is used during
1166 // emission of jump tables, and when inserting any additional MBBs necessary
1167 // to represent the switch.
Nate Begemaned728c12006-03-27 01:32:24 +00001168 MachineFunction *CurMF = CurMBB->getParent();
1169 const BasicBlock *LLVMBB = CurMBB->getBasicBlock();
Chris Lattner6d6fc262006-10-22 21:36:53 +00001170
1171 // If the switch has few cases (two or less) emit a series of specific
1172 // tests.
Chris Lattner76a7bc82006-10-22 23:00:53 +00001173 if (Cases.size() < 3) {
Chris Lattner6d6fc262006-10-22 21:36:53 +00001174 // TODO: If any two of the cases has the same destination, and if one value
1175 // is the same as the other, but has one bit unset that the other has set,
1176 // use bit manipulation to do two compares at once. For example:
1177 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1178
Chris Lattner4c931502006-10-23 18:38:22 +00001179 // Rearrange the case blocks so that the last one falls through if possible.
1180 if (NextBlock && Default != NextBlock && Cases.back().second != NextBlock) {
1181 // The last case block won't fall through into 'NextBlock' if we emit the
1182 // branches in this order. See if rearranging a case value would help.
1183 for (unsigned i = 0, e = Cases.size()-1; i != e; ++i) {
1184 if (Cases[i].second == NextBlock) {
1185 std::swap(Cases[i], Cases.back());
1186 break;
1187 }
1188 }
1189 }
1190
Chris Lattner6d6fc262006-10-22 21:36:53 +00001191 // Create a CaseBlock record representing a conditional branch to
1192 // the Case's target mbb if the value being switched on SV is equal
1193 // to C.
1194 MachineBasicBlock *CurBlock = CurMBB;
1195 for (unsigned i = 0, e = Cases.size(); i != e; ++i) {
1196 MachineBasicBlock *FallThrough;
1197 if (i != e-1) {
1198 FallThrough = new MachineBasicBlock(CurMBB->getBasicBlock());
1199 CurMF->getBasicBlockList().insert(BBI, FallThrough);
1200 } else {
1201 // If the last case doesn't match, go to the default block.
1202 FallThrough = Default;
1203 }
1204
1205 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, SV, Cases[i].first,
1206 Cases[i].second, FallThrough, CurBlock);
1207
1208 // If emitting the first comparison, just call visitSwitchCase to emit the
1209 // code into the current block. Otherwise, push the CaseBlock onto the
1210 // vector to be later processed by SDISel, and insert the node's MBB
1211 // before the next MBB.
1212 if (CurBlock == CurMBB)
1213 visitSwitchCase(CB);
1214 else
1215 SwitchCases.push_back(CB);
1216
1217 CurBlock = FallThrough;
1218 }
1219 return;
1220 }
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001221
Nate Begemand7a19102006-05-08 16:51:36 +00001222 // If the switch has more than 5 blocks, and at least 31.25% dense, and the
1223 // target supports indirect branches, then emit a jump table rather than
1224 // lowering the switch to a binary tree of conditional branches.
Evan Cheng84a28d42006-10-30 08:00:44 +00001225 if ((TLI.isOperationLegal(ISD::BR_JT, MVT::Other) ||
1226 TLI.isOperationLegal(ISD::BRIND, MVT::Other)) &&
Nate Begemandf488392006-05-03 03:48:02 +00001227 Cases.size() > 5) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00001228 uint64_t First =cast<ConstantIntegral>(Cases.front().first)->getZExtValue();
1229 uint64_t Last = cast<ConstantIntegral>(Cases.back().first)->getZExtValue();
Nate Begemandf488392006-05-03 03:48:02 +00001230 double Density = (double)Cases.size() / (double)((Last - First) + 1ULL);
1231
Nate Begemand7a19102006-05-08 16:51:36 +00001232 if (Density >= 0.3125) {
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001233 // Create a new basic block to hold the code for loading the address
1234 // of the jump table, and jumping to it. Update successor information;
1235 // we will either branch to the default case for the switch, or the jump
1236 // table.
1237 MachineBasicBlock *JumpTableBB = new MachineBasicBlock(LLVMBB);
1238 CurMF->getBasicBlockList().insert(BBI, JumpTableBB);
1239 CurMBB->addSuccessor(Default);
1240 CurMBB->addSuccessor(JumpTableBB);
1241
1242 // Subtract the lowest switch case value from the value being switched on
1243 // and conditional branch to default mbb if the result is greater than the
1244 // difference between smallest and largest cases.
1245 SDOperand SwitchOp = getValue(SV);
1246 MVT::ValueType VT = SwitchOp.getValueType();
1247 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1248 DAG.getConstant(First, VT));
1249
1250 // The SDNode we just created, which holds the value being switched on
1251 // minus the the smallest case value, needs to be copied to a virtual
1252 // register so it can be used as an index into the jump table in a
1253 // subsequent basic block. This value may be smaller or larger than the
1254 // target's pointer type, and therefore require extension or truncating.
1255 if (VT > TLI.getPointerTy())
1256 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1257 else
1258 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001259
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001260 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1261 SDOperand CopyTo = DAG.getCopyToReg(getRoot(), JumpTableReg, SwitchOp);
1262
1263 // Emit the range check for the jump table, and branch to the default
1264 // block for the switch statement if the value being switched on exceeds
1265 // the largest case in the switch.
1266 SDOperand CMP = DAG.getSetCC(TLI.getSetCCResultTy(), SUB,
1267 DAG.getConstant(Last-First,VT), ISD::SETUGT);
1268 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
1269 DAG.getBasicBlock(Default)));
1270
Nate Begemandf488392006-05-03 03:48:02 +00001271 // Build a vector of destination BBs, corresponding to each target
1272 // of the jump table. If the value of the jump table slot corresponds to
1273 // a case statement, push the case's BB onto the vector, otherwise, push
1274 // the default BB.
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001275 std::vector<MachineBasicBlock*> DestBBs;
Nate Begemandf488392006-05-03 03:48:02 +00001276 uint64_t TEI = First;
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001277 for (CaseItr ii = Cases.begin(), ee = Cases.end(); ii != ee; ++TEI)
Reid Spencere0fc4df2006-10-20 07:07:24 +00001278 if (cast<ConstantIntegral>(ii->first)->getZExtValue() == TEI) {
Nate Begemandf488392006-05-03 03:48:02 +00001279 DestBBs.push_back(ii->second);
Nate Begemandf488392006-05-03 03:48:02 +00001280 ++ii;
1281 } else {
1282 DestBBs.push_back(Default);
Nate Begemandf488392006-05-03 03:48:02 +00001283 }
Nate Begemandf488392006-05-03 03:48:02 +00001284
Chris Lattner84a03502006-10-27 23:50:33 +00001285 // Update successor info. Add one edge to each unique successor.
1286 // Vector bool would be better, but vector<bool> is really slow.
1287 std::vector<unsigned char> SuccsHandled;
1288 SuccsHandled.resize(CurMBB->getParent()->getNumBlockIDs());
1289
Chris Lattner2e0dfb02006-09-10 06:36:57 +00001290 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
Chris Lattner84a03502006-10-27 23:50:33 +00001291 E = DestBBs.end(); I != E; ++I) {
1292 if (!SuccsHandled[(*I)->getNumber()]) {
1293 SuccsHandled[(*I)->getNumber()] = true;
1294 JumpTableBB->addSuccessor(*I);
1295 }
1296 }
Nate Begemandf488392006-05-03 03:48:02 +00001297
1298 // Create a jump table index for this jump table, or return an existing
1299 // one.
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001300 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1301
1302 // Set the jump table information so that we can codegen it as a second
1303 // MachineBasicBlock
1304 JT.Reg = JumpTableReg;
1305 JT.JTI = JTI;
1306 JT.MBB = JumpTableBB;
Nate Begeman866b4b42006-04-23 06:26:20 +00001307 JT.Default = Default;
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001308 return;
1309 }
1310 }
Nate Begemaned728c12006-03-27 01:32:24 +00001311
1312 // Push the initial CaseRec onto the worklist
1313 std::vector<CaseRec> CaseVec;
1314 CaseVec.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
1315
1316 while (!CaseVec.empty()) {
1317 // Grab a record representing a case range to process off the worklist
1318 CaseRec CR = CaseVec.back();
1319 CaseVec.pop_back();
1320
1321 // Size is the number of Cases represented by this range. If Size is 1,
1322 // then we are processing a leaf of the binary search tree. Otherwise,
1323 // we need to pick a pivot, and push left and right ranges onto the
1324 // worklist.
1325 unsigned Size = CR.Range.second - CR.Range.first;
1326
1327 if (Size == 1) {
1328 // Create a CaseBlock record representing a conditional branch to
1329 // the Case's target mbb if the value being switched on SV is equal
1330 // to C. Otherwise, branch to default.
1331 Constant *C = CR.Range.first->first;
1332 MachineBasicBlock *Target = CR.Range.first->second;
1333 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, SV, C, Target, Default,
1334 CR.CaseBB);
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001335
Nate Begemaned728c12006-03-27 01:32:24 +00001336 // If the MBB representing the leaf node is the current MBB, then just
1337 // call visitSwitchCase to emit the code into the current block.
1338 // Otherwise, push the CaseBlock onto the vector to be later processed
1339 // by SDISel, and insert the node's MBB before the next MBB.
1340 if (CR.CaseBB == CurMBB)
1341 visitSwitchCase(CB);
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001342 else
Nate Begemaned728c12006-03-27 01:32:24 +00001343 SwitchCases.push_back(CB);
Nate Begemaned728c12006-03-27 01:32:24 +00001344 } else {
1345 // split case range at pivot
1346 CaseItr Pivot = CR.Range.first + (Size / 2);
1347 CaseRange LHSR(CR.Range.first, Pivot);
1348 CaseRange RHSR(Pivot, CR.Range.second);
1349 Constant *C = Pivot->first;
Chris Lattner963ddad2006-10-24 17:57:59 +00001350 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001351
Nate Begemaned728c12006-03-27 01:32:24 +00001352 // We know that we branch to the LHS if the Value being switched on is
1353 // less than the Pivot value, C. We use this to optimize our binary
1354 // tree a bit, by recognizing that if SV is greater than or equal to the
1355 // LHS's Case Value, and that Case Value is exactly one less than the
1356 // Pivot's Value, then we can branch directly to the LHS's Target,
1357 // rather than creating a leaf node for it.
1358 if ((LHSR.second - LHSR.first) == 1 &&
1359 LHSR.first->first == CR.GE &&
Reid Spencere0fc4df2006-10-20 07:07:24 +00001360 cast<ConstantIntegral>(C)->getZExtValue() ==
1361 (cast<ConstantIntegral>(CR.GE)->getZExtValue() + 1ULL)) {
Chris Lattner963ddad2006-10-24 17:57:59 +00001362 TrueBB = LHSR.first->second;
Nate Begemaned728c12006-03-27 01:32:24 +00001363 } else {
Chris Lattner963ddad2006-10-24 17:57:59 +00001364 TrueBB = new MachineBasicBlock(LLVMBB);
1365 CurMF->getBasicBlockList().insert(BBI, TrueBB);
1366 CaseVec.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
Nate Begemaned728c12006-03-27 01:32:24 +00001367 }
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001368
Nate Begemaned728c12006-03-27 01:32:24 +00001369 // Similar to the optimization above, if the Value being switched on is
1370 // known to be less than the Constant CR.LT, and the current Case Value
1371 // is CR.LT - 1, then we can branch directly to the target block for
1372 // the current Case Value, rather than emitting a RHS leaf node for it.
1373 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
Reid Spencere0fc4df2006-10-20 07:07:24 +00001374 cast<ConstantIntegral>(RHSR.first->first)->getZExtValue() ==
1375 (cast<ConstantIntegral>(CR.LT)->getZExtValue() - 1ULL)) {
Chris Lattner963ddad2006-10-24 17:57:59 +00001376 FalseBB = RHSR.first->second;
Nate Begemaned728c12006-03-27 01:32:24 +00001377 } else {
Chris Lattner963ddad2006-10-24 17:57:59 +00001378 FalseBB = new MachineBasicBlock(LLVMBB);
1379 CurMF->getBasicBlockList().insert(BBI, FalseBB);
1380 CaseVec.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
Nate Begemaned728c12006-03-27 01:32:24 +00001381 }
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001382
Nate Begemaned728c12006-03-27 01:32:24 +00001383 // Create a CaseBlock record representing a conditional branch to
1384 // the LHS node if the value being switched on SV is less than C.
1385 // Otherwise, branch to LHS.
1386 ISD::CondCode CC = C->getType()->isSigned() ? ISD::SETLT : ISD::SETULT;
Chris Lattner963ddad2006-10-24 17:57:59 +00001387 SelectionDAGISel::CaseBlock CB(CC, SV, C, TrueBB, FalseBB, CR.CaseBB);
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001388
Nate Begemaned728c12006-03-27 01:32:24 +00001389 if (CR.CaseBB == CurMBB)
1390 visitSwitchCase(CB);
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001391 else
Nate Begemaned728c12006-03-27 01:32:24 +00001392 SwitchCases.push_back(CB);
Nate Begemaned728c12006-03-27 01:32:24 +00001393 }
1394 }
1395}
1396
Chris Lattnerf68fd0b2005-04-02 05:04:50 +00001397void SelectionDAGLowering::visitSub(User &I) {
1398 // -0.0 - X --> fneg
Chris Lattner6f3b5772005-09-28 22:28:18 +00001399 if (I.getType()->isFloatingPoint()) {
1400 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
1401 if (CFP->isExactlyValue(-0.0)) {
1402 SDOperand Op2 = getValue(I.getOperand(1));
1403 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
1404 return;
1405 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001406 visitFPBinary(I, ISD::FSUB, ISD::VSUB);
1407 } else
1408 visitIntBinary(I, ISD::SUB, ISD::VSUB);
Chris Lattnerf68fd0b2005-04-02 05:04:50 +00001409}
1410
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001411void
1412SelectionDAGLowering::visitIntBinary(User &I, unsigned IntOp, unsigned VecOp) {
Nate Begemanb2e089c2005-11-19 00:36:38 +00001413 const Type *Ty = I.getType();
Chris Lattner7a60d912005-01-07 07:47:53 +00001414 SDOperand Op1 = getValue(I.getOperand(0));
1415 SDOperand Op2 = getValue(I.getOperand(1));
Chris Lattner96c26752005-01-19 22:31:21 +00001416
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001417 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
Chris Lattner32206f52006-03-18 01:44:44 +00001418 SDOperand Num = DAG.getConstant(PTy->getNumElements(), MVT::i32);
1419 SDOperand Typ = DAG.getValueType(TLI.getValueType(PTy->getElementType()));
1420 setValue(&I, DAG.getNode(VecOp, MVT::Vector, Op1, Op2, Num, Typ));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001421 } else {
1422 setValue(&I, DAG.getNode(IntOp, Op1.getValueType(), Op1, Op2));
1423 }
1424}
1425
1426void
1427SelectionDAGLowering::visitFPBinary(User &I, unsigned FPOp, unsigned VecOp) {
1428 const Type *Ty = I.getType();
1429 SDOperand Op1 = getValue(I.getOperand(0));
1430 SDOperand Op2 = getValue(I.getOperand(1));
1431
1432 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
1433 SDOperand Num = DAG.getConstant(PTy->getNumElements(), MVT::i32);
1434 SDOperand Typ = DAG.getValueType(TLI.getValueType(PTy->getElementType()));
1435 setValue(&I, DAG.getNode(VecOp, MVT::Vector, Op1, Op2, Num, Typ));
1436 } else {
1437 setValue(&I, DAG.getNode(FPOp, Op1.getValueType(), Op1, Op2));
Nate Begemanb2e089c2005-11-19 00:36:38 +00001438 }
Nate Begeman127321b2005-11-18 07:42:56 +00001439}
Chris Lattner96c26752005-01-19 22:31:21 +00001440
Nate Begeman127321b2005-11-18 07:42:56 +00001441void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
1442 SDOperand Op1 = getValue(I.getOperand(0));
1443 SDOperand Op2 = getValue(I.getOperand(1));
1444
1445 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
1446
Chris Lattner7a60d912005-01-07 07:47:53 +00001447 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
1448}
1449
Reid Spencerd9436b62006-11-20 01:22:35 +00001450void SelectionDAGLowering::visitICmp(User &I) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001451 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
1452 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
1453 predicate = IC->getPredicate();
1454 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
1455 predicate = ICmpInst::Predicate(IC->getPredicate());
1456 SDOperand Op1 = getValue(I.getOperand(0));
1457 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencerd9436b62006-11-20 01:22:35 +00001458 ISD::CondCode Opcode;
Reid Spencer266e42b2006-12-23 06:05:41 +00001459 switch (predicate) {
Reid Spencerd9436b62006-11-20 01:22:35 +00001460 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
1461 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
1462 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
1463 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
1464 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
1465 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
1466 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
1467 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
1468 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
1469 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
1470 default:
1471 assert(!"Invalid ICmp predicate value");
1472 Opcode = ISD::SETEQ;
1473 break;
1474 }
1475 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
1476}
1477
1478void SelectionDAGLowering::visitFCmp(User &I) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001479 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
1480 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
1481 predicate = FC->getPredicate();
1482 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
1483 predicate = FCmpInst::Predicate(FC->getPredicate());
Chris Lattner7a60d912005-01-07 07:47:53 +00001484 SDOperand Op1 = getValue(I.getOperand(0));
1485 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencer266e42b2006-12-23 06:05:41 +00001486 ISD::CondCode Condition, FOC, FPC;
1487 switch (predicate) {
1488 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1489 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1490 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1491 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1492 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1493 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1494 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
1495 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
1496 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
1497 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1498 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1499 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1500 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1501 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1502 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1503 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
1504 default:
1505 assert(!"Invalid FCmp predicate value");
1506 FOC = FPC = ISD::SETFALSE;
1507 break;
1508 }
1509 if (FiniteOnlyFPMath())
1510 Condition = FOC;
1511 else
1512 Condition = FPC;
1513 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Condition));
Chris Lattner7a60d912005-01-07 07:47:53 +00001514}
1515
1516void SelectionDAGLowering::visitSelect(User &I) {
1517 SDOperand Cond = getValue(I.getOperand(0));
1518 SDOperand TrueVal = getValue(I.getOperand(1));
1519 SDOperand FalseVal = getValue(I.getOperand(2));
Chris Lattner02274a52006-04-08 22:22:57 +00001520 if (!isa<PackedType>(I.getType())) {
1521 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
1522 TrueVal, FalseVal));
1523 } else {
1524 setValue(&I, DAG.getNode(ISD::VSELECT, MVT::Vector, Cond, TrueVal, FalseVal,
1525 *(TrueVal.Val->op_end()-2),
1526 *(TrueVal.Val->op_end()-1)));
1527 }
Chris Lattner7a60d912005-01-07 07:47:53 +00001528}
1529
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001530
1531void SelectionDAGLowering::visitTrunc(User &I) {
1532 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
1533 SDOperand N = getValue(I.getOperand(0));
1534 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1535 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
1536}
1537
1538void SelectionDAGLowering::visitZExt(User &I) {
1539 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
1540 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
1541 SDOperand N = getValue(I.getOperand(0));
1542 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1543 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
1544}
1545
1546void SelectionDAGLowering::visitSExt(User &I) {
1547 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
1548 // SExt also can't be a cast to bool for same reason. So, nothing much to do
1549 SDOperand N = getValue(I.getOperand(0));
1550 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1551 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
1552}
1553
1554void SelectionDAGLowering::visitFPTrunc(User &I) {
1555 // FPTrunc is never a no-op cast, no need to check
1556 SDOperand N = getValue(I.getOperand(0));
1557 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1558 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N));
1559}
1560
1561void SelectionDAGLowering::visitFPExt(User &I){
1562 // FPTrunc is never a no-op cast, no need to check
1563 SDOperand N = getValue(I.getOperand(0));
1564 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1565 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
1566}
1567
1568void SelectionDAGLowering::visitFPToUI(User &I) {
1569 // FPToUI is never a no-op cast, no need to check
1570 SDOperand N = getValue(I.getOperand(0));
1571 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1572 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
1573}
1574
1575void SelectionDAGLowering::visitFPToSI(User &I) {
1576 // FPToSI is never a no-op cast, no need to check
1577 SDOperand N = getValue(I.getOperand(0));
1578 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1579 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
1580}
1581
1582void SelectionDAGLowering::visitUIToFP(User &I) {
1583 // UIToFP is never a no-op cast, no need to check
1584 SDOperand N = getValue(I.getOperand(0));
1585 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1586 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
1587}
1588
1589void SelectionDAGLowering::visitSIToFP(User &I){
1590 // UIToFP is never a no-op cast, no need to check
1591 SDOperand N = getValue(I.getOperand(0));
1592 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1593 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
1594}
1595
1596void SelectionDAGLowering::visitPtrToInt(User &I) {
1597 // What to do depends on the size of the integer and the size of the pointer.
1598 // We can either truncate, zero extend, or no-op, accordingly.
Chris Lattner7a60d912005-01-07 07:47:53 +00001599 SDOperand N = getValue(I.getOperand(0));
Chris Lattner2f4119a2006-03-22 20:09:35 +00001600 MVT::ValueType SrcVT = N.getValueType();
Chris Lattner4024c002006-03-15 22:19:46 +00001601 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001602 SDOperand Result;
1603 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
1604 Result = DAG.getNode(ISD::TRUNCATE, DestVT, N);
1605 else
1606 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
1607 Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N);
1608 setValue(&I, Result);
1609}
Chris Lattner7a60d912005-01-07 07:47:53 +00001610
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001611void SelectionDAGLowering::visitIntToPtr(User &I) {
1612 // What to do depends on the size of the integer and the size of the pointer.
1613 // We can either truncate, zero extend, or no-op, accordingly.
1614 SDOperand N = getValue(I.getOperand(0));
1615 MVT::ValueType SrcVT = N.getValueType();
1616 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1617 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
1618 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
1619 else
1620 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
1621 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
1622}
1623
1624void SelectionDAGLowering::visitBitCast(User &I) {
1625 SDOperand N = getValue(I.getOperand(0));
1626 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Chris Lattner2f4119a2006-03-22 20:09:35 +00001627 if (DestVT == MVT::Vector) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001628 // This is a cast to a vector from something else.
1629 // Get information about the output vector.
Chris Lattner2f4119a2006-03-22 20:09:35 +00001630 const PackedType *DestTy = cast<PackedType>(I.getType());
1631 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1632 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N,
1633 DAG.getConstant(DestTy->getNumElements(),MVT::i32),
1634 DAG.getValueType(EltVT)));
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001635 return;
1636 }
1637 MVT::ValueType SrcVT = N.getValueType();
1638 if (SrcVT == MVT::Vector) {
1639 // This is a cast from a vctor to something else.
1640 // Get information about the input vector.
Chris Lattner2f4119a2006-03-22 20:09:35 +00001641 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N));
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001642 return;
Chris Lattner7a60d912005-01-07 07:47:53 +00001643 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001644
1645 // BitCast assures us that source and destination are the same size so this
1646 // is either a BIT_CONVERT or a no-op.
1647 if (DestVT != N.getValueType())
1648 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types
1649 else
1650 setValue(&I, N); // noop cast.
Chris Lattner7a60d912005-01-07 07:47:53 +00001651}
1652
Chris Lattner67271862006-03-29 00:11:43 +00001653void SelectionDAGLowering::visitInsertElement(User &I) {
Chris Lattner32206f52006-03-18 01:44:44 +00001654 SDOperand InVec = getValue(I.getOperand(0));
1655 SDOperand InVal = getValue(I.getOperand(1));
1656 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1657 getValue(I.getOperand(2)));
1658
Chris Lattner29b23012006-03-19 01:17:20 +00001659 SDOperand Num = *(InVec.Val->op_end()-2);
1660 SDOperand Typ = *(InVec.Val->op_end()-1);
1661 setValue(&I, DAG.getNode(ISD::VINSERT_VECTOR_ELT, MVT::Vector,
1662 InVec, InVal, InIdx, Num, Typ));
Chris Lattner32206f52006-03-18 01:44:44 +00001663}
1664
Chris Lattner67271862006-03-29 00:11:43 +00001665void SelectionDAGLowering::visitExtractElement(User &I) {
Chris Lattner7c0cd8c2006-03-21 20:44:12 +00001666 SDOperand InVec = getValue(I.getOperand(0));
1667 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1668 getValue(I.getOperand(1)));
1669 SDOperand Typ = *(InVec.Val->op_end()-1);
1670 setValue(&I, DAG.getNode(ISD::VEXTRACT_VECTOR_ELT,
1671 TLI.getValueType(I.getType()), InVec, InIdx));
1672}
Chris Lattner32206f52006-03-18 01:44:44 +00001673
Chris Lattner098c01e2006-04-08 04:15:24 +00001674void SelectionDAGLowering::visitShuffleVector(User &I) {
1675 SDOperand V1 = getValue(I.getOperand(0));
1676 SDOperand V2 = getValue(I.getOperand(1));
1677 SDOperand Mask = getValue(I.getOperand(2));
1678
1679 SDOperand Num = *(V1.Val->op_end()-2);
1680 SDOperand Typ = *(V2.Val->op_end()-1);
1681 setValue(&I, DAG.getNode(ISD::VVECTOR_SHUFFLE, MVT::Vector,
1682 V1, V2, Mask, Num, Typ));
1683}
1684
1685
Chris Lattner7a60d912005-01-07 07:47:53 +00001686void SelectionDAGLowering::visitGetElementPtr(User &I) {
1687 SDOperand N = getValue(I.getOperand(0));
1688 const Type *Ty = I.getOperand(0)->getType();
Chris Lattner7a60d912005-01-07 07:47:53 +00001689
1690 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
1691 OI != E; ++OI) {
1692 Value *Idx = *OI;
Chris Lattner35397782005-12-05 07:10:48 +00001693 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00001694 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
Chris Lattner7a60d912005-01-07 07:47:53 +00001695 if (Field) {
1696 // N = N + Offset
Owen Anderson20a631f2006-05-03 01:29:57 +00001697 uint64_t Offset = TD->getStructLayout(StTy)->MemberOffsets[Field];
Chris Lattner7a60d912005-01-07 07:47:53 +00001698 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Misha Brukman77451162005-04-22 04:01:18 +00001699 getIntPtrConstant(Offset));
Chris Lattner7a60d912005-01-07 07:47:53 +00001700 }
1701 Ty = StTy->getElementType(Field);
1702 } else {
1703 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner19a83992005-01-07 21:56:57 +00001704
Chris Lattner43535a12005-11-09 04:45:33 +00001705 // If this is a constant subscript, handle it quickly.
1706 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00001707 if (CI->getZExtValue() == 0) continue;
Chris Lattner43535a12005-11-09 04:45:33 +00001708 uint64_t Offs;
Reid Spencere0fc4df2006-10-20 07:07:24 +00001709 if (CI->getType()->isSigned())
1710 Offs = (int64_t)
1711 TD->getTypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
Chris Lattner43535a12005-11-09 04:45:33 +00001712 else
Reid Spencere0fc4df2006-10-20 07:07:24 +00001713 Offs =
1714 TD->getTypeSize(Ty)*cast<ConstantInt>(CI)->getZExtValue();
Chris Lattner43535a12005-11-09 04:45:33 +00001715 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
1716 continue;
Chris Lattner7a60d912005-01-07 07:47:53 +00001717 }
Chris Lattner43535a12005-11-09 04:45:33 +00001718
1719 // N = N + Idx * ElementSize;
Owen Anderson20a631f2006-05-03 01:29:57 +00001720 uint64_t ElementSize = TD->getTypeSize(Ty);
Chris Lattner43535a12005-11-09 04:45:33 +00001721 SDOperand IdxN = getValue(Idx);
1722
1723 // If the index is smaller or larger than intptr_t, truncate or extend
1724 // it.
1725 if (IdxN.getValueType() < N.getValueType()) {
1726 if (Idx->getType()->isSigned())
1727 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
1728 else
1729 IdxN = DAG.getNode(ISD::ZERO_EXTEND, N.getValueType(), IdxN);
1730 } else if (IdxN.getValueType() > N.getValueType())
1731 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
1732
1733 // If this is a multiply by a power of two, turn it into a shl
1734 // immediately. This is a very common case.
1735 if (isPowerOf2_64(ElementSize)) {
1736 unsigned Amt = Log2_64(ElementSize);
1737 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner41fd6d52005-11-09 16:50:40 +00001738 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner43535a12005-11-09 04:45:33 +00001739 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
1740 continue;
1741 }
1742
1743 SDOperand Scale = getIntPtrConstant(ElementSize);
1744 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
1745 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner7a60d912005-01-07 07:47:53 +00001746 }
1747 }
1748 setValue(&I, N);
1749}
1750
1751void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
1752 // If this is a fixed sized alloca in the entry block of the function,
1753 // allocate it statically on the stack.
1754 if (FuncInfo.StaticAllocaMap.count(&I))
1755 return; // getValue will auto-populate this.
1756
1757 const Type *Ty = I.getAllocatedType();
Owen Anderson20a631f2006-05-03 01:29:57 +00001758 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
1759 unsigned Align = std::max((unsigned)TLI.getTargetData()->getTypeAlignment(Ty),
Nate Begeman3ee3e692005-11-06 09:00:38 +00001760 I.getAlignment());
Chris Lattner7a60d912005-01-07 07:47:53 +00001761
1762 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattnereccb73d2005-01-22 23:04:37 +00001763 MVT::ValueType IntPtr = TLI.getPointerTy();
1764 if (IntPtr < AllocSize.getValueType())
1765 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
1766 else if (IntPtr > AllocSize.getValueType())
1767 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner7a60d912005-01-07 07:47:53 +00001768
Chris Lattnereccb73d2005-01-22 23:04:37 +00001769 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner7a60d912005-01-07 07:47:53 +00001770 getIntPtrConstant(TySize));
1771
1772 // Handle alignment. If the requested alignment is less than or equal to the
1773 // stack alignment, ignore it and round the size of the allocation up to the
1774 // stack alignment size. If the size is greater than the stack alignment, we
1775 // note this in the DYNAMIC_STACKALLOC node.
1776 unsigned StackAlign =
1777 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
1778 if (Align <= StackAlign) {
1779 Align = 0;
1780 // Add SA-1 to the size.
1781 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
1782 getIntPtrConstant(StackAlign-1));
1783 // Mask out the low bits for alignment purposes.
1784 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
1785 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
1786 }
1787
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001788 SDOperand Ops[] = { getRoot(), AllocSize, getIntPtrConstant(Align) };
Chris Lattnerbd887772006-08-14 23:53:35 +00001789 const MVT::ValueType *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
1790 MVT::Other);
1791 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
Chris Lattner7a60d912005-01-07 07:47:53 +00001792 DAG.setRoot(setValue(&I, DSA).getValue(1));
1793
1794 // Inform the Frame Information that we have just allocated a variable-sized
1795 // object.
1796 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
1797}
1798
Chris Lattner7a60d912005-01-07 07:47:53 +00001799void SelectionDAGLowering::visitLoad(LoadInst &I) {
1800 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukman835702a2005-04-21 22:36:52 +00001801
Chris Lattner4d9651c2005-01-17 22:19:26 +00001802 SDOperand Root;
1803 if (I.isVolatile())
1804 Root = getRoot();
1805 else {
1806 // Do not serialize non-volatile loads against each other.
1807 Root = DAG.getRoot();
1808 }
Chris Lattner4024c002006-03-15 22:19:46 +00001809
Evan Chenge71fe34d2006-10-09 20:57:25 +00001810 setValue(&I, getLoadFrom(I.getType(), Ptr, I.getOperand(0),
Chris Lattner4024c002006-03-15 22:19:46 +00001811 Root, I.isVolatile()));
1812}
1813
1814SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Chenge71fe34d2006-10-09 20:57:25 +00001815 const Value *SV, SDOperand Root,
Chris Lattner4024c002006-03-15 22:19:46 +00001816 bool isVolatile) {
Nate Begemanb2e089c2005-11-19 00:36:38 +00001817 SDOperand L;
Nate Begeman41b1cdc2005-12-06 06:18:55 +00001818 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
Nate Begeman07890bb2005-11-22 01:29:36 +00001819 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Evan Chenge71fe34d2006-10-09 20:57:25 +00001820 L = DAG.getVecLoad(PTy->getNumElements(), PVT, Root, Ptr,
1821 DAG.getSrcValue(SV));
Nate Begemanb2e089c2005-11-19 00:36:38 +00001822 } else {
Evan Cheng258657e2006-12-20 01:27:29 +00001823 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SV, 0, isVolatile);
Nate Begemanb2e089c2005-11-19 00:36:38 +00001824 }
Chris Lattner4d9651c2005-01-17 22:19:26 +00001825
Chris Lattner4024c002006-03-15 22:19:46 +00001826 if (isVolatile)
Chris Lattner4d9651c2005-01-17 22:19:26 +00001827 DAG.setRoot(L.getValue(1));
1828 else
1829 PendingLoads.push_back(L.getValue(1));
Chris Lattner4024c002006-03-15 22:19:46 +00001830
1831 return L;
Chris Lattner7a60d912005-01-07 07:47:53 +00001832}
1833
1834
1835void SelectionDAGLowering::visitStore(StoreInst &I) {
1836 Value *SrcV = I.getOperand(0);
1837 SDOperand Src = getValue(SrcV);
1838 SDOperand Ptr = getValue(I.getOperand(1));
Evan Cheng258657e2006-12-20 01:27:29 +00001839 DAG.setRoot(DAG.getStore(getRoot(), Src, Ptr, I.getOperand(1), 0,
Evan Chengab51cf22006-10-13 21:14:26 +00001840 I.isVolatile()));
Chris Lattner7a60d912005-01-07 07:47:53 +00001841}
1842
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001843/// IntrinsicCannotAccessMemory - Return true if the specified intrinsic cannot
1844/// access memory and has no other side effects at all.
1845static bool IntrinsicCannotAccessMemory(unsigned IntrinsicID) {
1846#define GET_NO_MEMORY_INTRINSICS
1847#include "llvm/Intrinsics.gen"
1848#undef GET_NO_MEMORY_INTRINSICS
1849 return false;
1850}
1851
Chris Lattnera9c59156b2006-04-02 03:41:14 +00001852// IntrinsicOnlyReadsMemory - Return true if the specified intrinsic doesn't
1853// have any side-effects or if it only reads memory.
1854static bool IntrinsicOnlyReadsMemory(unsigned IntrinsicID) {
1855#define GET_SIDE_EFFECT_INFO
1856#include "llvm/Intrinsics.gen"
1857#undef GET_SIDE_EFFECT_INFO
1858 return false;
1859}
1860
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001861/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
1862/// node.
1863void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
1864 unsigned Intrinsic) {
Chris Lattner313229c2006-03-24 22:49:42 +00001865 bool HasChain = !IntrinsicCannotAccessMemory(Intrinsic);
Chris Lattnera9c59156b2006-04-02 03:41:14 +00001866 bool OnlyLoad = HasChain && IntrinsicOnlyReadsMemory(Intrinsic);
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001867
1868 // Build the operand list.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001869 SmallVector<SDOperand, 8> Ops;
Chris Lattnera9c59156b2006-04-02 03:41:14 +00001870 if (HasChain) { // If this intrinsic has side-effects, chainify it.
1871 if (OnlyLoad) {
1872 // We don't need to serialize loads against other loads.
1873 Ops.push_back(DAG.getRoot());
1874 } else {
1875 Ops.push_back(getRoot());
1876 }
1877 }
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001878
1879 // Add the intrinsic ID as an integer operand.
1880 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
1881
1882 // Add all operands of the call to the operand list.
1883 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1884 SDOperand Op = getValue(I.getOperand(i));
1885
1886 // If this is a vector type, force it to the right packed type.
1887 if (Op.getValueType() == MVT::Vector) {
1888 const PackedType *OpTy = cast<PackedType>(I.getOperand(i)->getType());
1889 MVT::ValueType EltVT = TLI.getValueType(OpTy->getElementType());
1890
1891 MVT::ValueType VVT = MVT::getVectorType(EltVT, OpTy->getNumElements());
1892 assert(VVT != MVT::Other && "Intrinsic uses a non-legal type?");
1893 Op = DAG.getNode(ISD::VBIT_CONVERT, VVT, Op);
1894 }
1895
1896 assert(TLI.isTypeLegal(Op.getValueType()) &&
1897 "Intrinsic uses a non-legal type?");
1898 Ops.push_back(Op);
1899 }
1900
1901 std::vector<MVT::ValueType> VTs;
1902 if (I.getType() != Type::VoidTy) {
1903 MVT::ValueType VT = TLI.getValueType(I.getType());
1904 if (VT == MVT::Vector) {
1905 const PackedType *DestTy = cast<PackedType>(I.getType());
1906 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1907
1908 VT = MVT::getVectorType(EltVT, DestTy->getNumElements());
1909 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
1910 }
1911
1912 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
1913 VTs.push_back(VT);
1914 }
1915 if (HasChain)
1916 VTs.push_back(MVT::Other);
1917
Chris Lattnerbd887772006-08-14 23:53:35 +00001918 const MVT::ValueType *VTList = DAG.getNodeValueTypes(VTs);
1919
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001920 // Create the node.
Chris Lattnere55d1712006-03-28 00:40:33 +00001921 SDOperand Result;
1922 if (!HasChain)
Chris Lattnerbd887772006-08-14 23:53:35 +00001923 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
1924 &Ops[0], Ops.size());
Chris Lattnere55d1712006-03-28 00:40:33 +00001925 else if (I.getType() != Type::VoidTy)
Chris Lattnerbd887772006-08-14 23:53:35 +00001926 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
1927 &Ops[0], Ops.size());
Chris Lattnere55d1712006-03-28 00:40:33 +00001928 else
Chris Lattnerbd887772006-08-14 23:53:35 +00001929 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
1930 &Ops[0], Ops.size());
Chris Lattnere55d1712006-03-28 00:40:33 +00001931
Chris Lattnera9c59156b2006-04-02 03:41:14 +00001932 if (HasChain) {
1933 SDOperand Chain = Result.getValue(Result.Val->getNumValues()-1);
1934 if (OnlyLoad)
1935 PendingLoads.push_back(Chain);
1936 else
1937 DAG.setRoot(Chain);
1938 }
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001939 if (I.getType() != Type::VoidTy) {
1940 if (const PackedType *PTy = dyn_cast<PackedType>(I.getType())) {
1941 MVT::ValueType EVT = TLI.getValueType(PTy->getElementType());
1942 Result = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Result,
1943 DAG.getConstant(PTy->getNumElements(), MVT::i32),
1944 DAG.getValueType(EVT));
1945 }
1946 setValue(&I, Result);
1947 }
1948}
1949
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001950/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
1951/// we want to emit this as a call to a named external function, return the name
1952/// otherwise lower it and return null.
1953const char *
1954SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
1955 switch (Intrinsic) {
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001956 default:
1957 // By default, turn this into a target intrinsic node.
1958 visitTargetIntrinsic(I, Intrinsic);
1959 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001960 case Intrinsic::vastart: visitVAStart(I); return 0;
1961 case Intrinsic::vaend: visitVAEnd(I); return 0;
1962 case Intrinsic::vacopy: visitVACopy(I); return 0;
1963 case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return 0;
1964 case Intrinsic::frameaddress: visitFrameReturnAddress(I, true); return 0;
1965 case Intrinsic::setjmp:
Anton Korobeynikov3b7c2572006-12-10 23:12:42 +00001966 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001967 break;
1968 case Intrinsic::longjmp:
Anton Korobeynikov3b7c2572006-12-10 23:12:42 +00001969 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001970 break;
Chris Lattner093c1592006-03-03 00:00:25 +00001971 case Intrinsic::memcpy_i32:
1972 case Intrinsic::memcpy_i64:
1973 visitMemIntrinsic(I, ISD::MEMCPY);
1974 return 0;
1975 case Intrinsic::memset_i32:
1976 case Intrinsic::memset_i64:
1977 visitMemIntrinsic(I, ISD::MEMSET);
1978 return 0;
1979 case Intrinsic::memmove_i32:
1980 case Intrinsic::memmove_i64:
1981 visitMemIntrinsic(I, ISD::MEMMOVE);
1982 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001983
Chris Lattner5d4e61d2005-12-13 17:40:33 +00001984 case Intrinsic::dbg_stoppoint: {
Jim Laskey5995d012006-02-11 01:01:30 +00001985 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
Jim Laskeya8bdac82006-03-23 18:06:46 +00001986 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Jim Laskey70928882006-03-26 22:46:27 +00001987 if (DebugInfo && SPI.getContext() && DebugInfo->Verify(SPI.getContext())) {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001988 SDOperand Ops[5];
Chris Lattner435b4022005-11-29 06:21:05 +00001989
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001990 Ops[0] = getRoot();
1991 Ops[1] = getValue(SPI.getLineValue());
1992 Ops[2] = getValue(SPI.getColumnValue());
Chris Lattner435b4022005-11-29 06:21:05 +00001993
Jim Laskeya8bdac82006-03-23 18:06:46 +00001994 DebugInfoDesc *DD = DebugInfo->getDescFor(SPI.getContext());
Jim Laskey5995d012006-02-11 01:01:30 +00001995 assert(DD && "Not a debug information descriptor");
Jim Laskeya8bdac82006-03-23 18:06:46 +00001996 CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
1997
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001998 Ops[3] = DAG.getString(CompileUnit->getFileName());
1999 Ops[4] = DAG.getString(CompileUnit->getDirectory());
Jim Laskey5995d012006-02-11 01:01:30 +00002000
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002001 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops, 5));
Chris Lattner5d4e61d2005-12-13 17:40:33 +00002002 }
Jim Laskeya8bdac82006-03-23 18:06:46 +00002003
Chris Lattnerf2b62f32005-11-16 07:22:30 +00002004 return 0;
Chris Lattner435b4022005-11-29 06:21:05 +00002005 }
Jim Laskeya8bdac82006-03-23 18:06:46 +00002006 case Intrinsic::dbg_region_start: {
2007 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
2008 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
Jim Laskey70928882006-03-26 22:46:27 +00002009 if (DebugInfo && RSI.getContext() && DebugInfo->Verify(RSI.getContext())) {
Jim Laskeya8bdac82006-03-23 18:06:46 +00002010 unsigned LabelID = DebugInfo->RecordRegionStart(RSI.getContext());
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002011 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other, getRoot(),
2012 DAG.getConstant(LabelID, MVT::i32)));
Jim Laskeya8bdac82006-03-23 18:06:46 +00002013 }
2014
Chris Lattnerf2b62f32005-11-16 07:22:30 +00002015 return 0;
Jim Laskeya8bdac82006-03-23 18:06:46 +00002016 }
2017 case Intrinsic::dbg_region_end: {
2018 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
2019 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
Jim Laskey70928882006-03-26 22:46:27 +00002020 if (DebugInfo && REI.getContext() && DebugInfo->Verify(REI.getContext())) {
Jim Laskeya8bdac82006-03-23 18:06:46 +00002021 unsigned LabelID = DebugInfo->RecordRegionEnd(REI.getContext());
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002022 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other,
2023 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
Jim Laskeya8bdac82006-03-23 18:06:46 +00002024 }
2025
Chris Lattnerf2b62f32005-11-16 07:22:30 +00002026 return 0;
Jim Laskeya8bdac82006-03-23 18:06:46 +00002027 }
2028 case Intrinsic::dbg_func_start: {
2029 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
2030 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
Jim Laskey70928882006-03-26 22:46:27 +00002031 if (DebugInfo && FSI.getSubprogram() &&
2032 DebugInfo->Verify(FSI.getSubprogram())) {
Jim Laskeya8bdac82006-03-23 18:06:46 +00002033 unsigned LabelID = DebugInfo->RecordRegionStart(FSI.getSubprogram());
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002034 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other,
2035 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
Jim Laskeya8bdac82006-03-23 18:06:46 +00002036 }
2037
Chris Lattnerf2b62f32005-11-16 07:22:30 +00002038 return 0;
Jim Laskeya8bdac82006-03-23 18:06:46 +00002039 }
2040 case Intrinsic::dbg_declare: {
2041 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
2042 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
Jim Laskey67a636c2006-03-28 13:45:20 +00002043 if (DebugInfo && DI.getVariable() && DebugInfo->Verify(DI.getVariable())) {
Jim Laskey53f1ecc2006-03-24 09:50:27 +00002044 SDOperand AddressOp = getValue(DI.getAddress());
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002045 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(AddressOp))
Jim Laskeya8bdac82006-03-23 18:06:46 +00002046 DebugInfo->RecordVariable(DI.getVariable(), FI->getIndex());
Jim Laskeya8bdac82006-03-23 18:06:46 +00002047 }
2048
2049 return 0;
2050 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002051
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00002052 case Intrinsic::isunordered_f32:
2053 case Intrinsic::isunordered_f64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002054 setValue(&I, DAG.getSetCC(MVT::i1,getValue(I.getOperand(1)),
2055 getValue(I.getOperand(2)), ISD::SETUO));
2056 return 0;
2057
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00002058 case Intrinsic::sqrt_f32:
2059 case Intrinsic::sqrt_f64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002060 setValue(&I, DAG.getNode(ISD::FSQRT,
2061 getValue(I.getOperand(1)).getValueType(),
2062 getValue(I.getOperand(1))));
2063 return 0;
Chris Lattnerf0359b32006-09-09 06:03:30 +00002064 case Intrinsic::powi_f32:
2065 case Intrinsic::powi_f64:
2066 setValue(&I, DAG.getNode(ISD::FPOWI,
2067 getValue(I.getOperand(1)).getValueType(),
2068 getValue(I.getOperand(1)),
2069 getValue(I.getOperand(2))));
2070 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002071 case Intrinsic::pcmarker: {
2072 SDOperand Tmp = getValue(I.getOperand(1));
2073 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
2074 return 0;
2075 }
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00002076 case Intrinsic::readcyclecounter: {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002077 SDOperand Op = getRoot();
Chris Lattnerbd887772006-08-14 23:53:35 +00002078 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
2079 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
2080 &Op, 1);
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00002081 setValue(&I, Tmp);
2082 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth01aa5632005-11-11 16:47:30 +00002083 return 0;
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00002084 }
Nate Begeman2fba8a32006-01-14 03:14:10 +00002085 case Intrinsic::bswap_i16:
Nate Begeman2fba8a32006-01-14 03:14:10 +00002086 case Intrinsic::bswap_i32:
Nate Begeman2fba8a32006-01-14 03:14:10 +00002087 case Intrinsic::bswap_i64:
2088 setValue(&I, DAG.getNode(ISD::BSWAP,
2089 getValue(I.getOperand(1)).getValueType(),
2090 getValue(I.getOperand(1))));
2091 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00002092 case Intrinsic::cttz_i8:
2093 case Intrinsic::cttz_i16:
2094 case Intrinsic::cttz_i32:
2095 case Intrinsic::cttz_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002096 setValue(&I, DAG.getNode(ISD::CTTZ,
2097 getValue(I.getOperand(1)).getValueType(),
2098 getValue(I.getOperand(1))));
2099 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00002100 case Intrinsic::ctlz_i8:
2101 case Intrinsic::ctlz_i16:
2102 case Intrinsic::ctlz_i32:
2103 case Intrinsic::ctlz_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002104 setValue(&I, DAG.getNode(ISD::CTLZ,
2105 getValue(I.getOperand(1)).getValueType(),
2106 getValue(I.getOperand(1))));
2107 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00002108 case Intrinsic::ctpop_i8:
2109 case Intrinsic::ctpop_i16:
2110 case Intrinsic::ctpop_i32:
2111 case Intrinsic::ctpop_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002112 setValue(&I, DAG.getNode(ISD::CTPOP,
2113 getValue(I.getOperand(1)).getValueType(),
2114 getValue(I.getOperand(1))));
2115 return 0;
Chris Lattnerb3266452006-01-13 02:50:02 +00002116 case Intrinsic::stacksave: {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002117 SDOperand Op = getRoot();
Chris Lattnerbd887772006-08-14 23:53:35 +00002118 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE,
2119 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
Chris Lattnerb3266452006-01-13 02:50:02 +00002120 setValue(&I, Tmp);
2121 DAG.setRoot(Tmp.getValue(1));
2122 return 0;
2123 }
Chris Lattnerdeda32a2006-01-23 05:22:07 +00002124 case Intrinsic::stackrestore: {
2125 SDOperand Tmp = getValue(I.getOperand(1));
2126 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
Chris Lattnerb3266452006-01-13 02:50:02 +00002127 return 0;
Chris Lattnerdeda32a2006-01-23 05:22:07 +00002128 }
Chris Lattner9e8b6332005-12-12 22:51:16 +00002129 case Intrinsic::prefetch:
2130 // FIXME: Currently discarding prefetches.
2131 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002132 }
2133}
2134
2135
Chris Lattner7a60d912005-01-07 07:47:53 +00002136void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner18d2b342005-01-08 22:48:57 +00002137 const char *RenameFn = 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002138 if (Function *F = I.getCalledFunction()) {
Chris Lattner0c140002005-04-02 05:26:53 +00002139 if (F->isExternal())
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002140 if (unsigned IID = F->getIntrinsicID()) {
2141 RenameFn = visitIntrinsicCall(I, IID);
2142 if (!RenameFn)
2143 return;
2144 } else { // Not an LLVM intrinsic.
2145 const std::string &Name = F->getName();
Chris Lattner5c1ba2a2006-03-05 05:09:38 +00002146 if (Name[0] == 'c' && (Name == "copysign" || Name == "copysignf")) {
2147 if (I.getNumOperands() == 3 && // Basic sanity checks.
2148 I.getOperand(1)->getType()->isFloatingPoint() &&
2149 I.getType() == I.getOperand(1)->getType() &&
2150 I.getType() == I.getOperand(2)->getType()) {
2151 SDOperand LHS = getValue(I.getOperand(1));
2152 SDOperand RHS = getValue(I.getOperand(2));
2153 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
2154 LHS, RHS));
2155 return;
2156 }
2157 } else if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
Chris Lattner0c140002005-04-02 05:26:53 +00002158 if (I.getNumOperands() == 2 && // Basic sanity checks.
2159 I.getOperand(1)->getType()->isFloatingPoint() &&
2160 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002161 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner0c140002005-04-02 05:26:53 +00002162 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
2163 return;
2164 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002165 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
Chris Lattner80026402005-04-30 04:43:14 +00002166 if (I.getNumOperands() == 2 && // Basic sanity checks.
2167 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner1784a9d22006-02-14 05:39:35 +00002168 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002169 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +00002170 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
2171 return;
2172 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002173 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
Chris Lattner80026402005-04-30 04:43:14 +00002174 if (I.getNumOperands() == 2 && // Basic sanity checks.
2175 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner1784a9d22006-02-14 05:39:35 +00002176 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002177 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +00002178 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
2179 return;
2180 }
2181 }
Chris Lattnere4f71d02005-05-14 13:56:55 +00002182 }
Chris Lattner476e67b2006-01-26 22:24:51 +00002183 } else if (isa<InlineAsm>(I.getOperand(0))) {
2184 visitInlineAsm(I);
2185 return;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002186 }
Misha Brukman835702a2005-04-21 22:36:52 +00002187
Chris Lattner18d2b342005-01-08 22:48:57 +00002188 SDOperand Callee;
2189 if (!RenameFn)
2190 Callee = getValue(I.getOperand(0));
2191 else
2192 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Chris Lattner7a60d912005-01-07 07:47:53 +00002193 std::vector<std::pair<SDOperand, const Type*> > Args;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002194 Args.reserve(I.getNumOperands());
Chris Lattner7a60d912005-01-07 07:47:53 +00002195 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2196 Value *Arg = I.getOperand(i);
2197 SDOperand ArgNode = getValue(Arg);
2198 Args.push_back(std::make_pair(ArgNode, Arg->getType()));
2199 }
Misha Brukman835702a2005-04-21 22:36:52 +00002200
Nate Begemanf6565252005-03-26 01:29:23 +00002201 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
2202 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Misha Brukman835702a2005-04-21 22:36:52 +00002203
Chris Lattner1f45cd72005-01-08 19:26:18 +00002204 std::pair<SDOperand,SDOperand> Result =
Chris Lattner111778e2005-05-12 19:56:57 +00002205 TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(),
Chris Lattner2e77db62005-05-13 18:50:42 +00002206 I.isTailCall(), Callee, Args, DAG);
Chris Lattner7a60d912005-01-07 07:47:53 +00002207 if (I.getType() != Type::VoidTy)
Chris Lattner1f45cd72005-01-08 19:26:18 +00002208 setValue(&I, Result.first);
2209 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00002210}
2211
Chris Lattner6f87d182006-02-22 22:37:12 +00002212SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002213 SDOperand &Chain, SDOperand &Flag)const{
Chris Lattner6f87d182006-02-22 22:37:12 +00002214 SDOperand Val = DAG.getCopyFromReg(Chain, Regs[0], RegVT, Flag);
2215 Chain = Val.getValue(1);
2216 Flag = Val.getValue(2);
2217
2218 // If the result was expanded, copy from the top part.
2219 if (Regs.size() > 1) {
2220 assert(Regs.size() == 2 &&
2221 "Cannot expand to more than 2 elts yet!");
2222 SDOperand Hi = DAG.getCopyFromReg(Chain, Regs[1], RegVT, Flag);
Evan Chengf80dfa82006-10-04 22:23:53 +00002223 Chain = Hi.getValue(1);
2224 Flag = Hi.getValue(2);
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002225 if (DAG.getTargetLoweringInfo().isLittleEndian())
2226 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi);
2227 else
2228 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Hi, Val);
Chris Lattner6f87d182006-02-22 22:37:12 +00002229 }
Chris Lattner1558fc62006-02-01 18:59:47 +00002230
Chris Lattner705948d2006-06-08 18:22:48 +00002231 // Otherwise, if the return value was promoted or extended, truncate it to the
Chris Lattner6f87d182006-02-22 22:37:12 +00002232 // appropriate type.
2233 if (RegVT == ValueVT)
2234 return Val;
2235
Chris Lattner705948d2006-06-08 18:22:48 +00002236 if (MVT::isInteger(RegVT)) {
2237 if (ValueVT < RegVT)
2238 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
2239 else
2240 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
2241 } else {
Chris Lattner6f87d182006-02-22 22:37:12 +00002242 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
Chris Lattner705948d2006-06-08 18:22:48 +00002243 }
Chris Lattner6f87d182006-02-22 22:37:12 +00002244}
2245
Chris Lattner571d9642006-02-23 19:21:04 +00002246/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
2247/// specified value into the registers specified by this object. This uses
2248/// Chain/Flag as the input and updates them for the output Chain/Flag.
2249void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Evan Chengef9e07d2006-06-15 08:11:54 +00002250 SDOperand &Chain, SDOperand &Flag,
2251 MVT::ValueType PtrVT) const {
Chris Lattner571d9642006-02-23 19:21:04 +00002252 if (Regs.size() == 1) {
2253 // If there is a single register and the types differ, this must be
2254 // a promotion.
2255 if (RegVT != ValueVT) {
Chris Lattnerc03a9252006-06-08 18:27:11 +00002256 if (MVT::isInteger(RegVT)) {
2257 if (RegVT < ValueVT)
2258 Val = DAG.getNode(ISD::TRUNCATE, RegVT, Val);
2259 else
2260 Val = DAG.getNode(ISD::ANY_EXTEND, RegVT, Val);
2261 } else
Chris Lattner571d9642006-02-23 19:21:04 +00002262 Val = DAG.getNode(ISD::FP_EXTEND, RegVT, Val);
2263 }
2264 Chain = DAG.getCopyToReg(Chain, Regs[0], Val, Flag);
2265 Flag = Chain.getValue(1);
2266 } else {
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002267 std::vector<unsigned> R(Regs);
2268 if (!DAG.getTargetLoweringInfo().isLittleEndian())
2269 std::reverse(R.begin(), R.end());
2270
2271 for (unsigned i = 0, e = R.size(); i != e; ++i) {
Chris Lattner571d9642006-02-23 19:21:04 +00002272 SDOperand Part = DAG.getNode(ISD::EXTRACT_ELEMENT, RegVT, Val,
Evan Chengef9e07d2006-06-15 08:11:54 +00002273 DAG.getConstant(i, PtrVT));
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002274 Chain = DAG.getCopyToReg(Chain, R[i], Part, Flag);
Chris Lattner571d9642006-02-23 19:21:04 +00002275 Flag = Chain.getValue(1);
2276 }
2277 }
2278}
Chris Lattner6f87d182006-02-22 22:37:12 +00002279
Chris Lattner571d9642006-02-23 19:21:04 +00002280/// AddInlineAsmOperands - Add this value to the specified inlineasm node
2281/// operand list. This adds the code marker and includes the number of
2282/// values added into it.
2283void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002284 std::vector<SDOperand> &Ops) const {
Chris Lattner571d9642006-02-23 19:21:04 +00002285 Ops.push_back(DAG.getConstant(Code | (Regs.size() << 3), MVT::i32));
2286 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
2287 Ops.push_back(DAG.getRegister(Regs[i], RegVT));
2288}
Chris Lattner6f87d182006-02-22 22:37:12 +00002289
2290/// isAllocatableRegister - If the specified register is safe to allocate,
2291/// i.e. it isn't a stack pointer or some other special register, return the
2292/// register class for the register. Otherwise, return null.
2293static const TargetRegisterClass *
Chris Lattnerb1124f32006-02-22 23:09:03 +00002294isAllocatableRegister(unsigned Reg, MachineFunction &MF,
2295 const TargetLowering &TLI, const MRegisterInfo *MRI) {
Chris Lattnerbec582f2006-04-02 00:24:45 +00002296 MVT::ValueType FoundVT = MVT::Other;
2297 const TargetRegisterClass *FoundRC = 0;
Chris Lattnerb1124f32006-02-22 23:09:03 +00002298 for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
2299 E = MRI->regclass_end(); RCI != E; ++RCI) {
Chris Lattnerbec582f2006-04-02 00:24:45 +00002300 MVT::ValueType ThisVT = MVT::Other;
2301
Chris Lattnerb1124f32006-02-22 23:09:03 +00002302 const TargetRegisterClass *RC = *RCI;
2303 // If none of the the value types for this register class are valid, we
2304 // can't use it. For example, 64-bit reg classes on 32-bit targets.
Chris Lattnerb1124f32006-02-22 23:09:03 +00002305 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
2306 I != E; ++I) {
2307 if (TLI.isTypeLegal(*I)) {
Chris Lattnerbec582f2006-04-02 00:24:45 +00002308 // If we have already found this register in a different register class,
2309 // choose the one with the largest VT specified. For example, on
2310 // PowerPC, we favor f64 register classes over f32.
2311 if (FoundVT == MVT::Other ||
2312 MVT::getSizeInBits(FoundVT) < MVT::getSizeInBits(*I)) {
2313 ThisVT = *I;
2314 break;
2315 }
Chris Lattnerb1124f32006-02-22 23:09:03 +00002316 }
2317 }
2318
Chris Lattnerbec582f2006-04-02 00:24:45 +00002319 if (ThisVT == MVT::Other) continue;
Chris Lattnerb1124f32006-02-22 23:09:03 +00002320
Chris Lattner6f87d182006-02-22 22:37:12 +00002321 // NOTE: This isn't ideal. In particular, this might allocate the
2322 // frame pointer in functions that need it (due to them not being taken
2323 // out of allocation, because a variable sized allocation hasn't been seen
2324 // yet). This is a slight code pessimization, but should still work.
Chris Lattnerb1124f32006-02-22 23:09:03 +00002325 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
2326 E = RC->allocation_order_end(MF); I != E; ++I)
Chris Lattnerbec582f2006-04-02 00:24:45 +00002327 if (*I == Reg) {
2328 // We found a matching register class. Keep looking at others in case
2329 // we find one with larger registers that this physreg is also in.
2330 FoundRC = RC;
2331 FoundVT = ThisVT;
2332 break;
2333 }
Chris Lattner1558fc62006-02-01 18:59:47 +00002334 }
Chris Lattnerbec582f2006-04-02 00:24:45 +00002335 return FoundRC;
Chris Lattner6f87d182006-02-22 22:37:12 +00002336}
2337
2338RegsForValue SelectionDAGLowering::
2339GetRegistersForValue(const std::string &ConstrCode,
2340 MVT::ValueType VT, bool isOutReg, bool isInReg,
2341 std::set<unsigned> &OutputRegs,
2342 std::set<unsigned> &InputRegs) {
2343 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
2344 TLI.getRegForInlineAsmConstraint(ConstrCode, VT);
2345 std::vector<unsigned> Regs;
2346
2347 unsigned NumRegs = VT != MVT::Other ? TLI.getNumElements(VT) : 1;
2348 MVT::ValueType RegVT;
2349 MVT::ValueType ValueVT = VT;
2350
Chris Lattner55402d42006-11-02 01:41:49 +00002351 // If this is a constraint for a specific physical register, like {r17},
2352 // assign it now.
Chris Lattner6f87d182006-02-22 22:37:12 +00002353 if (PhysReg.first) {
2354 if (VT == MVT::Other)
2355 ValueVT = *PhysReg.second->vt_begin();
Chris Lattner705948d2006-06-08 18:22:48 +00002356
2357 // Get the actual register value type. This is important, because the user
2358 // may have asked for (e.g.) the AX register in i32 type. We need to
2359 // remember that AX is actually i16 to get the right extension.
2360 RegVT = *PhysReg.second->vt_begin();
Chris Lattner6f87d182006-02-22 22:37:12 +00002361
2362 // This is a explicit reference to a physical register.
2363 Regs.push_back(PhysReg.first);
2364
2365 // If this is an expanded reference, add the rest of the regs to Regs.
2366 if (NumRegs != 1) {
Chris Lattner6f87d182006-02-22 22:37:12 +00002367 TargetRegisterClass::iterator I = PhysReg.second->begin();
2368 TargetRegisterClass::iterator E = PhysReg.second->end();
2369 for (; *I != PhysReg.first; ++I)
2370 assert(I != E && "Didn't find reg!");
2371
2372 // Already added the first reg.
2373 --NumRegs; ++I;
2374 for (; NumRegs; --NumRegs, ++I) {
2375 assert(I != E && "Ran out of registers to allocate!");
2376 Regs.push_back(*I);
2377 }
2378 }
2379 return RegsForValue(Regs, RegVT, ValueVT);
2380 }
2381
Chris Lattner55402d42006-11-02 01:41:49 +00002382 // Otherwise, if this was a reference to an LLVM register class, create vregs
2383 // for this reference.
2384 std::vector<unsigned> RegClassRegs;
2385 if (PhysReg.second) {
2386 // If this is an early clobber or tied register, our regalloc doesn't know
2387 // how to maintain the constraint. If it isn't, go ahead and create vreg
2388 // and let the regalloc do the right thing.
2389 if (!isOutReg || !isInReg) {
2390 if (VT == MVT::Other)
2391 ValueVT = *PhysReg.second->vt_begin();
2392 RegVT = *PhysReg.second->vt_begin();
2393
2394 // Create the appropriate number of virtual registers.
2395 SSARegMap *RegMap = DAG.getMachineFunction().getSSARegMap();
2396 for (; NumRegs; --NumRegs)
2397 Regs.push_back(RegMap->createVirtualRegister(PhysReg.second));
2398
2399 return RegsForValue(Regs, RegVT, ValueVT);
2400 }
2401
2402 // Otherwise, we can't allocate it. Let the code below figure out how to
2403 // maintain these constraints.
2404 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
2405
2406 } else {
2407 // This is a reference to a register class that doesn't directly correspond
2408 // to an LLVM register class. Allocate NumRegs consecutive, available,
2409 // registers from the class.
2410 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(ConstrCode, VT);
2411 }
Chris Lattner6f87d182006-02-22 22:37:12 +00002412
2413 const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
2414 MachineFunction &MF = *CurMBB->getParent();
2415 unsigned NumAllocated = 0;
2416 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
2417 unsigned Reg = RegClassRegs[i];
2418 // See if this register is available.
2419 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
2420 (isInReg && InputRegs.count(Reg))) { // Already used.
2421 // Make sure we find consecutive registers.
2422 NumAllocated = 0;
2423 continue;
2424 }
2425
2426 // Check to see if this register is allocatable (i.e. don't give out the
2427 // stack pointer).
Chris Lattnerb1124f32006-02-22 23:09:03 +00002428 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, MRI);
Chris Lattner6f87d182006-02-22 22:37:12 +00002429 if (!RC) {
2430 // Make sure we find consecutive registers.
2431 NumAllocated = 0;
2432 continue;
2433 }
2434
2435 // Okay, this register is good, we can use it.
2436 ++NumAllocated;
2437
2438 // If we allocated enough consecutive
2439 if (NumAllocated == NumRegs) {
2440 unsigned RegStart = (i-NumAllocated)+1;
2441 unsigned RegEnd = i+1;
2442 // Mark all of the allocated registers used.
2443 for (unsigned i = RegStart; i != RegEnd; ++i) {
2444 unsigned Reg = RegClassRegs[i];
2445 Regs.push_back(Reg);
2446 if (isOutReg) OutputRegs.insert(Reg); // Mark reg used.
2447 if (isInReg) InputRegs.insert(Reg); // Mark reg used.
2448 }
2449
2450 return RegsForValue(Regs, *RC->vt_begin(), VT);
2451 }
2452 }
2453
2454 // Otherwise, we couldn't allocate enough registers for this.
2455 return RegsForValue();
Chris Lattner1558fc62006-02-01 18:59:47 +00002456}
2457
Chris Lattner6f87d182006-02-22 22:37:12 +00002458
Chris Lattner476e67b2006-01-26 22:24:51 +00002459/// visitInlineAsm - Handle a call to an InlineAsm object.
2460///
2461void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
2462 InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
2463
2464 SDOperand AsmStr = DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
2465 MVT::Other);
2466
Chris Lattner3a5ed552006-02-01 01:28:23 +00002467 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
Chris Lattner7ad77df2006-02-22 00:56:39 +00002468 std::vector<MVT::ValueType> ConstraintVTs;
Chris Lattner476e67b2006-01-26 22:24:51 +00002469
2470 /// AsmNodeOperands - A list of pairs. The first element is a register, the
2471 /// second is a bitfield where bit #0 is set if it is a use and bit #1 is set
2472 /// if it is a def of that register.
2473 std::vector<SDOperand> AsmNodeOperands;
2474 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
2475 AsmNodeOperands.push_back(AsmStr);
2476
2477 SDOperand Chain = getRoot();
2478 SDOperand Flag;
2479
Chris Lattner1558fc62006-02-01 18:59:47 +00002480 // We fully assign registers here at isel time. This is not optimal, but
2481 // should work. For register classes that correspond to LLVM classes, we
2482 // could let the LLVM RA do its thing, but we currently don't. Do a prepass
2483 // over the constraints, collecting fixed registers that we know we can't use.
2484 std::set<unsigned> OutputRegs, InputRegs;
Chris Lattner7ad77df2006-02-22 00:56:39 +00002485 unsigned OpNum = 1;
Chris Lattner1558fc62006-02-01 18:59:47 +00002486 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
2487 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
2488 std::string &ConstraintCode = Constraints[i].Codes[0];
Chris Lattner7f5880b2006-02-02 00:25:23 +00002489
Chris Lattner7ad77df2006-02-22 00:56:39 +00002490 MVT::ValueType OpVT;
2491
2492 // Compute the value type for each operand and add it to ConstraintVTs.
2493 switch (Constraints[i].Type) {
2494 case InlineAsm::isOutput:
2495 if (!Constraints[i].isIndirectOutput) {
2496 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
2497 OpVT = TLI.getValueType(I.getType());
2498 } else {
Chris Lattner9fed5b62006-02-27 23:45:39 +00002499 const Type *OpTy = I.getOperand(OpNum)->getType();
Chris Lattner7ad77df2006-02-22 00:56:39 +00002500 OpVT = TLI.getValueType(cast<PointerType>(OpTy)->getElementType());
2501 OpNum++; // Consumes a call operand.
2502 }
2503 break;
2504 case InlineAsm::isInput:
2505 OpVT = TLI.getValueType(I.getOperand(OpNum)->getType());
2506 OpNum++; // Consumes a call operand.
2507 break;
2508 case InlineAsm::isClobber:
2509 OpVT = MVT::Other;
2510 break;
2511 }
2512
2513 ConstraintVTs.push_back(OpVT);
2514
Chris Lattner6f87d182006-02-22 22:37:12 +00002515 if (TLI.getRegForInlineAsmConstraint(ConstraintCode, OpVT).first == 0)
2516 continue; // Not assigned a fixed reg.
Chris Lattner7ad77df2006-02-22 00:56:39 +00002517
Chris Lattner6f87d182006-02-22 22:37:12 +00002518 // Build a list of regs that this operand uses. This always has a single
2519 // element for promoted/expanded operands.
2520 RegsForValue Regs = GetRegistersForValue(ConstraintCode, OpVT,
2521 false, false,
2522 OutputRegs, InputRegs);
Chris Lattner1558fc62006-02-01 18:59:47 +00002523
2524 switch (Constraints[i].Type) {
2525 case InlineAsm::isOutput:
2526 // We can't assign any other output to this register.
Chris Lattner6f87d182006-02-22 22:37:12 +00002527 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00002528 // If this is an early-clobber output, it cannot be assigned to the same
2529 // value as the input reg.
Chris Lattner7f5880b2006-02-02 00:25:23 +00002530 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
Chris Lattner6f87d182006-02-22 22:37:12 +00002531 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00002532 break;
Chris Lattner7ad77df2006-02-22 00:56:39 +00002533 case InlineAsm::isInput:
2534 // We can't assign any other input to this register.
Chris Lattner6f87d182006-02-22 22:37:12 +00002535 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner7ad77df2006-02-22 00:56:39 +00002536 break;
Chris Lattner1558fc62006-02-01 18:59:47 +00002537 case InlineAsm::isClobber:
2538 // Clobbered regs cannot be used as inputs or outputs.
Chris Lattner6f87d182006-02-22 22:37:12 +00002539 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2540 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00002541 break;
Chris Lattner1558fc62006-02-01 18:59:47 +00002542 }
2543 }
Chris Lattner3a5ed552006-02-01 01:28:23 +00002544
Chris Lattner5c79f982006-02-21 23:12:12 +00002545 // Loop over all of the inputs, copying the operand values into the
2546 // appropriate registers and processing the output regs.
Chris Lattner6f87d182006-02-22 22:37:12 +00002547 RegsForValue RetValRegs;
2548 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
Chris Lattner7ad77df2006-02-22 00:56:39 +00002549 OpNum = 1;
Chris Lattner5c79f982006-02-21 23:12:12 +00002550
Chris Lattner2e56e892006-01-31 02:03:41 +00002551 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
Chris Lattner3a5ed552006-02-01 01:28:23 +00002552 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
2553 std::string &ConstraintCode = Constraints[i].Codes[0];
Chris Lattner7ad77df2006-02-22 00:56:39 +00002554
Chris Lattner3a5ed552006-02-01 01:28:23 +00002555 switch (Constraints[i].Type) {
2556 case InlineAsm::isOutput: {
Chris Lattner9fed5b62006-02-27 23:45:39 +00002557 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
2558 if (ConstraintCode.size() == 1) // not a physreg name.
2559 CTy = TLI.getConstraintType(ConstraintCode[0]);
2560
2561 if (CTy == TargetLowering::C_Memory) {
2562 // Memory output.
2563 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
2564
2565 // Check that the operand (the address to store to) isn't a float.
2566 if (!MVT::isInteger(InOperandVal.getValueType()))
2567 assert(0 && "MATCH FAIL!");
2568
2569 if (!Constraints[i].isIndirectOutput)
2570 assert(0 && "MATCH FAIL!");
2571
2572 OpNum++; // Consumes a call operand.
2573
2574 // Extend/truncate to the right pointer type if needed.
2575 MVT::ValueType PtrType = TLI.getPointerTy();
2576 if (InOperandVal.getValueType() < PtrType)
2577 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
2578 else if (InOperandVal.getValueType() > PtrType)
2579 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
2580
2581 // Add information to the INLINEASM node to know about this output.
2582 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
2583 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2584 AsmNodeOperands.push_back(InOperandVal);
2585 break;
2586 }
2587
2588 // Otherwise, this is a register output.
2589 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
2590
Chris Lattner6f87d182006-02-22 22:37:12 +00002591 // If this is an early-clobber output, or if there is an input
2592 // constraint that matches this, we need to reserve the input register
2593 // so no other inputs allocate to it.
2594 bool UsesInputRegister = false;
2595 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
2596 UsesInputRegister = true;
2597
2598 // Copy the output from the appropriate register. Find a register that
Chris Lattner7ad77df2006-02-22 00:56:39 +00002599 // we can use.
Chris Lattner6f87d182006-02-22 22:37:12 +00002600 RegsForValue Regs =
2601 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
2602 true, UsesInputRegister,
2603 OutputRegs, InputRegs);
Chris Lattner968f8032006-10-31 07:33:13 +00002604 if (Regs.Regs.empty()) {
Bill Wendling22e978a2006-12-07 20:04:42 +00002605 cerr << "Couldn't allocate output reg for contraint '"
2606 << ConstraintCode << "'!\n";
Chris Lattner968f8032006-10-31 07:33:13 +00002607 exit(1);
2608 }
Chris Lattner7ad77df2006-02-22 00:56:39 +00002609
Chris Lattner3a5ed552006-02-01 01:28:23 +00002610 if (!Constraints[i].isIndirectOutput) {
Chris Lattner6f87d182006-02-22 22:37:12 +00002611 assert(RetValRegs.Regs.empty() &&
Chris Lattner3a5ed552006-02-01 01:28:23 +00002612 "Cannot have multiple output constraints yet!");
Chris Lattner3a5ed552006-02-01 01:28:23 +00002613 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
Chris Lattner6f87d182006-02-22 22:37:12 +00002614 RetValRegs = Regs;
Chris Lattner3a5ed552006-02-01 01:28:23 +00002615 } else {
Chris Lattner9fed5b62006-02-27 23:45:39 +00002616 IndirectStoresToEmit.push_back(std::make_pair(Regs,
2617 I.getOperand(OpNum)));
Chris Lattner3a5ed552006-02-01 01:28:23 +00002618 OpNum++; // Consumes a call operand.
2619 }
Chris Lattner2e56e892006-01-31 02:03:41 +00002620
2621 // Add information to the INLINEASM node to know that this register is
2622 // set.
Chris Lattner571d9642006-02-23 19:21:04 +00002623 Regs.AddInlineAsmOperands(2 /*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00002624 break;
2625 }
2626 case InlineAsm::isInput: {
Chris Lattner9fed5b62006-02-27 23:45:39 +00002627 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
Chris Lattner1558fc62006-02-01 18:59:47 +00002628 OpNum++; // Consumes a call operand.
Chris Lattner65ad53f2006-02-04 02:16:44 +00002629
Chris Lattner7f5880b2006-02-02 00:25:23 +00002630 if (isdigit(ConstraintCode[0])) { // Matching constraint?
2631 // If this is required to match an output register we have already set,
2632 // just use its register.
2633 unsigned OperandNo = atoi(ConstraintCode.c_str());
Chris Lattner65ad53f2006-02-04 02:16:44 +00002634
Chris Lattner571d9642006-02-23 19:21:04 +00002635 // Scan until we find the definition we already emitted of this operand.
2636 // When we find it, create a RegsForValue operand.
2637 unsigned CurOp = 2; // The first operand.
2638 for (; OperandNo; --OperandNo) {
2639 // Advance to the next operand.
2640 unsigned NumOps =
2641 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattnerb0305322006-07-20 19:02:21 +00002642 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
2643 (NumOps & 7) == 4 /*MEM*/) &&
Chris Lattner571d9642006-02-23 19:21:04 +00002644 "Skipped past definitions?");
2645 CurOp += (NumOps>>3)+1;
2646 }
2647
2648 unsigned NumOps =
2649 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
2650 assert((NumOps & 7) == 2 /*REGDEF*/ &&
2651 "Skipped past definitions?");
2652
2653 // Add NumOps>>3 registers to MatchedRegs.
2654 RegsForValue MatchedRegs;
2655 MatchedRegs.ValueVT = InOperandVal.getValueType();
2656 MatchedRegs.RegVT = AsmNodeOperands[CurOp+1].getValueType();
2657 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
2658 unsigned Reg=cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
2659 MatchedRegs.Regs.push_back(Reg);
2660 }
2661
2662 // Use the produced MatchedRegs object to
Evan Chengef9e07d2006-06-15 08:11:54 +00002663 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag,
2664 TLI.getPointerTy());
Chris Lattner571d9642006-02-23 19:21:04 +00002665 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattner571d9642006-02-23 19:21:04 +00002666 break;
Chris Lattner7f5880b2006-02-02 00:25:23 +00002667 }
Chris Lattner7ef7a642006-02-24 01:11:24 +00002668
2669 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
2670 if (ConstraintCode.size() == 1) // not a physreg name.
2671 CTy = TLI.getConstraintType(ConstraintCode[0]);
2672
2673 if (CTy == TargetLowering::C_Other) {
Chris Lattner6f043b92006-10-31 19:41:18 +00002674 InOperandVal = TLI.isOperandValidForConstraint(InOperandVal,
2675 ConstraintCode[0], DAG);
2676 if (!InOperandVal.Val) {
Bill Wendling22e978a2006-12-07 20:04:42 +00002677 cerr << "Invalid operand for inline asm constraint '"
2678 << ConstraintCode << "'!\n";
Chris Lattner6f043b92006-10-31 19:41:18 +00002679 exit(1);
2680 }
Chris Lattner7ef7a642006-02-24 01:11:24 +00002681
2682 // Add information to the INLINEASM node to know about this input.
2683 unsigned ResOpType = 3 /*IMM*/ | (1 << 3);
2684 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2685 AsmNodeOperands.push_back(InOperandVal);
2686 break;
2687 } else if (CTy == TargetLowering::C_Memory) {
2688 // Memory input.
2689
2690 // Check that the operand isn't a float.
2691 if (!MVT::isInteger(InOperandVal.getValueType()))
2692 assert(0 && "MATCH FAIL!");
2693
2694 // Extend/truncate to the right pointer type if needed.
2695 MVT::ValueType PtrType = TLI.getPointerTy();
2696 if (InOperandVal.getValueType() < PtrType)
2697 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
2698 else if (InOperandVal.getValueType() > PtrType)
2699 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
2700
2701 // Add information to the INLINEASM node to know about this input.
2702 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
2703 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2704 AsmNodeOperands.push_back(InOperandVal);
2705 break;
2706 }
2707
2708 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
2709
2710 // Copy the input into the appropriate registers.
2711 RegsForValue InRegs =
2712 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
2713 false, true, OutputRegs, InputRegs);
2714 // FIXME: should be match fail.
2715 assert(!InRegs.Regs.empty() && "Couldn't allocate input reg!");
2716
Evan Chengef9e07d2006-06-15 08:11:54 +00002717 InRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag, TLI.getPointerTy());
Chris Lattner7ef7a642006-02-24 01:11:24 +00002718
2719 InRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00002720 break;
2721 }
Chris Lattner571d9642006-02-23 19:21:04 +00002722 case InlineAsm::isClobber: {
2723 RegsForValue ClobberedRegs =
2724 GetRegistersForValue(ConstraintCode, MVT::Other, false, false,
2725 OutputRegs, InputRegs);
2726 // Add the clobbered value to the operand list, so that the register
2727 // allocator is aware that the physreg got clobbered.
2728 if (!ClobberedRegs.Regs.empty())
2729 ClobberedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00002730 break;
2731 }
Chris Lattner571d9642006-02-23 19:21:04 +00002732 }
Chris Lattner2e56e892006-01-31 02:03:41 +00002733 }
Chris Lattner476e67b2006-01-26 22:24:51 +00002734
2735 // Finish up input operands.
2736 AsmNodeOperands[0] = Chain;
2737 if (Flag.Val) AsmNodeOperands.push_back(Flag);
2738
Chris Lattnerbd887772006-08-14 23:53:35 +00002739 Chain = DAG.getNode(ISD::INLINEASM,
2740 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002741 &AsmNodeOperands[0], AsmNodeOperands.size());
Chris Lattner476e67b2006-01-26 22:24:51 +00002742 Flag = Chain.getValue(1);
2743
Chris Lattner2e56e892006-01-31 02:03:41 +00002744 // If this asm returns a register value, copy the result from that register
2745 // and set it as the value of the call.
Chris Lattner6f87d182006-02-22 22:37:12 +00002746 if (!RetValRegs.Regs.empty())
2747 setValue(&I, RetValRegs.getCopyFromRegs(DAG, Chain, Flag));
Chris Lattner476e67b2006-01-26 22:24:51 +00002748
Chris Lattner2e56e892006-01-31 02:03:41 +00002749 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
2750
2751 // Process indirect outputs, first output all of the flagged copies out of
2752 // physregs.
2753 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
Chris Lattner6f87d182006-02-22 22:37:12 +00002754 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Chris Lattner2e56e892006-01-31 02:03:41 +00002755 Value *Ptr = IndirectStoresToEmit[i].second;
Chris Lattner6f87d182006-02-22 22:37:12 +00002756 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, Flag);
2757 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner2e56e892006-01-31 02:03:41 +00002758 }
2759
2760 // Emit the non-flagged stores from the physregs.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002761 SmallVector<SDOperand, 8> OutChains;
Chris Lattner2e56e892006-01-31 02:03:41 +00002762 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
Evan Chengdf9ac472006-10-05 23:01:46 +00002763 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
Chris Lattner2e56e892006-01-31 02:03:41 +00002764 getValue(StoresToEmit[i].second),
Evan Chengab51cf22006-10-13 21:14:26 +00002765 StoresToEmit[i].second, 0));
Chris Lattner2e56e892006-01-31 02:03:41 +00002766 if (!OutChains.empty())
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002767 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
2768 &OutChains[0], OutChains.size());
Chris Lattner476e67b2006-01-26 22:24:51 +00002769 DAG.setRoot(Chain);
2770}
2771
2772
Chris Lattner7a60d912005-01-07 07:47:53 +00002773void SelectionDAGLowering::visitMalloc(MallocInst &I) {
2774 SDOperand Src = getValue(I.getOperand(0));
2775
2776 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnereccb73d2005-01-22 23:04:37 +00002777
2778 if (IntPtr < Src.getValueType())
2779 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
2780 else if (IntPtr > Src.getValueType())
2781 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner7a60d912005-01-07 07:47:53 +00002782
2783 // Scale the source by the type size.
Owen Anderson20a631f2006-05-03 01:29:57 +00002784 uint64_t ElementSize = TD->getTypeSize(I.getType()->getElementType());
Chris Lattner7a60d912005-01-07 07:47:53 +00002785 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
2786 Src, getIntPtrConstant(ElementSize));
2787
2788 std::vector<std::pair<SDOperand, const Type*> > Args;
Owen Anderson20a631f2006-05-03 01:29:57 +00002789 Args.push_back(std::make_pair(Src, TLI.getTargetData()->getIntPtrType()));
Chris Lattner1f45cd72005-01-08 19:26:18 +00002790
2791 std::pair<SDOperand,SDOperand> Result =
Chris Lattner2e77db62005-05-13 18:50:42 +00002792 TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00002793 DAG.getExternalSymbol("malloc", IntPtr),
2794 Args, DAG);
2795 setValue(&I, Result.first); // Pointers always fit in registers
2796 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00002797}
2798
2799void SelectionDAGLowering::visitFree(FreeInst &I) {
2800 std::vector<std::pair<SDOperand, const Type*> > Args;
2801 Args.push_back(std::make_pair(getValue(I.getOperand(0)),
Owen Anderson20a631f2006-05-03 01:29:57 +00002802 TLI.getTargetData()->getIntPtrType()));
Chris Lattner7a60d912005-01-07 07:47:53 +00002803 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner1f45cd72005-01-08 19:26:18 +00002804 std::pair<SDOperand,SDOperand> Result =
Chris Lattner2e77db62005-05-13 18:50:42 +00002805 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00002806 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
2807 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00002808}
2809
Chris Lattner13d7c252005-08-26 20:54:47 +00002810// InsertAtEndOfBasicBlock - This method should be implemented by targets that
2811// mark instructions with the 'usesCustomDAGSchedInserter' flag. These
2812// instructions are special in various ways, which require special support to
2813// insert. The specified MachineInstr is created but not inserted into any
2814// basic blocks, and the scheduler passes ownership of it to this method.
2815MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
2816 MachineBasicBlock *MBB) {
Bill Wendling22e978a2006-12-07 20:04:42 +00002817 cerr << "If a target marks an instruction with "
2818 << "'usesCustomDAGSchedInserter', it must implement "
2819 << "TargetLowering::InsertAtEndOfBasicBlock!\n";
Chris Lattner13d7c252005-08-26 20:54:47 +00002820 abort();
2821 return 0;
2822}
2823
Chris Lattner58cfd792005-01-09 00:00:49 +00002824void SelectionDAGLowering::visitVAStart(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00002825 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
2826 getValue(I.getOperand(1)),
2827 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner58cfd792005-01-09 00:00:49 +00002828}
2829
2830void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00002831 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
2832 getValue(I.getOperand(0)),
2833 DAG.getSrcValue(I.getOperand(0)));
2834 setValue(&I, V);
2835 DAG.setRoot(V.getValue(1));
Chris Lattner7a60d912005-01-07 07:47:53 +00002836}
2837
2838void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00002839 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
2840 getValue(I.getOperand(1)),
2841 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner7a60d912005-01-07 07:47:53 +00002842}
2843
2844void SelectionDAGLowering::visitVACopy(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00002845 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
2846 getValue(I.getOperand(1)),
2847 getValue(I.getOperand(2)),
2848 DAG.getSrcValue(I.getOperand(1)),
2849 DAG.getSrcValue(I.getOperand(2))));
Chris Lattner7a60d912005-01-07 07:47:53 +00002850}
2851
Evan Cheng0c0b78c2006-12-12 07:27:38 +00002852/// ExpandScalarFormalArgs - Recursively expand the formal_argument node, either
2853/// bit_convert it or join a pair of them with a BUILD_PAIR when appropriate.
2854static SDOperand ExpandScalarFormalArgs(MVT::ValueType VT, SDNode *Arg,
2855 unsigned &i, SelectionDAG &DAG,
2856 TargetLowering &TLI) {
2857 if (TLI.getTypeAction(VT) != TargetLowering::Expand)
2858 return SDOperand(Arg, i++);
2859
2860 MVT::ValueType EVT = TLI.getTypeToTransformTo(VT);
2861 unsigned NumVals = MVT::getSizeInBits(VT) / MVT::getSizeInBits(EVT);
2862 if (NumVals == 1) {
2863 return DAG.getNode(ISD::BIT_CONVERT, VT,
2864 ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI));
2865 } else if (NumVals == 2) {
2866 SDOperand Lo = ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI);
2867 SDOperand Hi = ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI);
2868 if (!TLI.isLittleEndian())
2869 std::swap(Lo, Hi);
2870 return DAG.getNode(ISD::BUILD_PAIR, VT, Lo, Hi);
2871 } else {
2872 // Value scalarized into many values. Unimp for now.
2873 assert(0 && "Cannot expand i64 -> i16 yet!");
2874 }
2875 return SDOperand();
2876}
2877
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002878/// TargetLowering::LowerArguments - This is the default LowerArguments
2879/// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
Chris Lattneraaa23d92006-05-16 22:53:20 +00002880/// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
2881/// integrated into SDISel.
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002882std::vector<SDOperand>
2883TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
2884 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
2885 std::vector<SDOperand> Ops;
Chris Lattner3d826992006-05-16 06:45:34 +00002886 Ops.push_back(DAG.getRoot());
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002887 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
2888 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
2889
2890 // Add one result value for each formal argument.
2891 std::vector<MVT::ValueType> RetVals;
2892 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
2893 MVT::ValueType VT = getValueType(I->getType());
2894
2895 switch (getTypeAction(VT)) {
2896 default: assert(0 && "Unknown type action!");
2897 case Legal:
2898 RetVals.push_back(VT);
2899 break;
2900 case Promote:
2901 RetVals.push_back(getTypeToTransformTo(VT));
2902 break;
2903 case Expand:
2904 if (VT != MVT::Vector) {
2905 // If this is a large integer, it needs to be broken up into small
2906 // integers. Figure out what the destination type is and how many small
2907 // integers it turns into.
Evan Cheng22cf8992006-12-13 20:57:08 +00002908 MVT::ValueType NVT = getTypeToExpandTo(VT);
2909 unsigned NumVals = getNumElements(VT);
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002910 for (unsigned i = 0; i != NumVals; ++i)
2911 RetVals.push_back(NVT);
2912 } else {
2913 // Otherwise, this is a vector type. We only support legal vectors
2914 // right now.
2915 unsigned NumElems = cast<PackedType>(I->getType())->getNumElements();
2916 const Type *EltTy = cast<PackedType>(I->getType())->getElementType();
Evan Cheng3784f3c52006-04-27 08:29:42 +00002917
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002918 // Figure out if there is a Packed type corresponding to this Vector
2919 // type. If so, convert to the packed type.
2920 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
2921 if (TVT != MVT::Other && isTypeLegal(TVT)) {
2922 RetVals.push_back(TVT);
2923 } else {
2924 assert(0 && "Don't support illegal by-val vector arguments yet!");
2925 }
2926 }
2927 break;
2928 }
2929 }
Evan Cheng9618df12006-04-25 23:03:35 +00002930
Chris Lattner3d826992006-05-16 06:45:34 +00002931 RetVals.push_back(MVT::Other);
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002932
2933 // Create the node.
Chris Lattnerbd887772006-08-14 23:53:35 +00002934 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
2935 DAG.getNodeValueTypes(RetVals), RetVals.size(),
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002936 &Ops[0], Ops.size()).Val;
Chris Lattner3d826992006-05-16 06:45:34 +00002937
2938 DAG.setRoot(SDOperand(Result, Result->getNumValues()-1));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002939
2940 // Set up the return result vector.
2941 Ops.clear();
2942 unsigned i = 0;
2943 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
2944 MVT::ValueType VT = getValueType(I->getType());
2945
2946 switch (getTypeAction(VT)) {
2947 default: assert(0 && "Unknown type action!");
2948 case Legal:
2949 Ops.push_back(SDOperand(Result, i++));
2950 break;
2951 case Promote: {
2952 SDOperand Op(Result, i++);
2953 if (MVT::isInteger(VT)) {
2954 unsigned AssertOp = I->getType()->isSigned() ? ISD::AssertSext
2955 : ISD::AssertZext;
2956 Op = DAG.getNode(AssertOp, Op.getValueType(), Op, DAG.getValueType(VT));
2957 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
2958 } else {
2959 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
2960 Op = DAG.getNode(ISD::FP_ROUND, VT, Op);
2961 }
2962 Ops.push_back(Op);
2963 break;
2964 }
2965 case Expand:
2966 if (VT != MVT::Vector) {
Evan Cheng0c0b78c2006-12-12 07:27:38 +00002967 // If this is a large integer or a floating point node that needs to be
2968 // expanded, it needs to be reassembled from small integers. Figure out
2969 // what the source elt type is and how many small integers it is.
2970 Ops.push_back(ExpandScalarFormalArgs(VT, Result, i, DAG, *this));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002971 } else {
2972 // Otherwise, this is a vector type. We only support legal vectors
2973 // right now.
Evan Chengd43c5c62006-04-28 05:25:15 +00002974 const PackedType *PTy = cast<PackedType>(I->getType());
2975 unsigned NumElems = PTy->getNumElements();
2976 const Type *EltTy = PTy->getElementType();
Evan Cheng3784f3c52006-04-27 08:29:42 +00002977
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002978 // Figure out if there is a Packed type corresponding to this Vector
2979 // type. If so, convert to the packed type.
2980 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
Chris Lattner7949c2e2006-05-17 20:49:36 +00002981 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Evan Chengd43c5c62006-04-28 05:25:15 +00002982 SDOperand N = SDOperand(Result, i++);
2983 // Handle copies from generic vectors to registers.
Chris Lattner7949c2e2006-05-17 20:49:36 +00002984 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
2985 DAG.getConstant(NumElems, MVT::i32),
2986 DAG.getValueType(getValueType(EltTy)));
2987 Ops.push_back(N);
2988 } else {
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002989 assert(0 && "Don't support illegal by-val vector arguments yet!");
Chris Lattnerb77ba732006-05-16 23:39:44 +00002990 abort();
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002991 }
2992 }
2993 break;
2994 }
2995 }
2996 return Ops;
2997}
2998
Chris Lattneraaa23d92006-05-16 22:53:20 +00002999
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003000/// ExpandScalarCallArgs - Recursively expand call argument node by
3001/// bit_converting it or extract a pair of elements from the larger node.
3002static void ExpandScalarCallArgs(MVT::ValueType VT, SDOperand Arg,
3003 bool isSigned,
3004 SmallVector<SDOperand, 32> &Ops,
3005 SelectionDAG &DAG,
3006 TargetLowering &TLI) {
3007 if (TLI.getTypeAction(VT) != TargetLowering::Expand) {
3008 Ops.push_back(Arg);
3009 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
3010 return;
3011 }
3012
3013 MVT::ValueType EVT = TLI.getTypeToTransformTo(VT);
3014 unsigned NumVals = MVT::getSizeInBits(VT) / MVT::getSizeInBits(EVT);
3015 if (NumVals == 1) {
3016 Arg = DAG.getNode(ISD::BIT_CONVERT, EVT, Arg);
3017 ExpandScalarCallArgs(EVT, Arg, isSigned, Ops, DAG, TLI);
3018 } else if (NumVals == 2) {
3019 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, EVT, Arg,
3020 DAG.getConstant(0, TLI.getPointerTy()));
3021 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, EVT, Arg,
3022 DAG.getConstant(1, TLI.getPointerTy()));
3023 if (!TLI.isLittleEndian())
3024 std::swap(Lo, Hi);
3025 ExpandScalarCallArgs(EVT, Lo, isSigned, Ops, DAG, TLI);
3026 ExpandScalarCallArgs(EVT, Hi, isSigned, Ops, DAG, TLI);
3027 } else {
3028 // Value scalarized into many values. Unimp for now.
3029 assert(0 && "Cannot expand i64 -> i16 yet!");
3030 }
3031}
3032
Chris Lattneraaa23d92006-05-16 22:53:20 +00003033/// TargetLowering::LowerCallTo - This is the default LowerCallTo
3034/// implementation, which just inserts an ISD::CALL node, which is later custom
3035/// lowered by the target to something concrete. FIXME: When all targets are
3036/// migrated to using ISD::CALL, this hook should be integrated into SDISel.
3037std::pair<SDOperand, SDOperand>
3038TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy, bool isVarArg,
3039 unsigned CallingConv, bool isTailCall,
3040 SDOperand Callee,
3041 ArgListTy &Args, SelectionDAG &DAG) {
Chris Lattner65879ca2006-08-16 22:57:46 +00003042 SmallVector<SDOperand, 32> Ops;
Chris Lattneraaa23d92006-05-16 22:53:20 +00003043 Ops.push_back(Chain); // Op#0 - Chain
3044 Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
3045 Ops.push_back(DAG.getConstant(isVarArg, getPointerTy())); // Op#2 - VarArg
3046 Ops.push_back(DAG.getConstant(isTailCall, getPointerTy())); // Op#3 - Tail
3047 Ops.push_back(Callee);
3048
3049 // Handle all of the outgoing arguments.
3050 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
3051 MVT::ValueType VT = getValueType(Args[i].second);
3052 SDOperand Op = Args[i].first;
Evan Cheng45827712006-05-25 00:55:32 +00003053 bool isSigned = Args[i].second->isSigned();
Chris Lattneraaa23d92006-05-16 22:53:20 +00003054 switch (getTypeAction(VT)) {
3055 default: assert(0 && "Unknown type action!");
3056 case Legal:
3057 Ops.push_back(Op);
Evan Cheng21dee4e2006-05-26 23:13:20 +00003058 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattneraaa23d92006-05-16 22:53:20 +00003059 break;
3060 case Promote:
3061 if (MVT::isInteger(VT)) {
Evan Cheng45827712006-05-25 00:55:32 +00003062 unsigned ExtOp = isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
Chris Lattneraaa23d92006-05-16 22:53:20 +00003063 Op = DAG.getNode(ExtOp, getTypeToTransformTo(VT), Op);
3064 } else {
3065 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
3066 Op = DAG.getNode(ISD::FP_EXTEND, getTypeToTransformTo(VT), Op);
3067 }
3068 Ops.push_back(Op);
Evan Cheng21dee4e2006-05-26 23:13:20 +00003069 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattneraaa23d92006-05-16 22:53:20 +00003070 break;
3071 case Expand:
3072 if (VT != MVT::Vector) {
3073 // If this is a large integer, it needs to be broken down into small
3074 // integers. Figure out what the source elt type is and how many small
3075 // integers it is.
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003076 ExpandScalarCallArgs(VT, Op, isSigned, Ops, DAG, *this);
Chris Lattneraaa23d92006-05-16 22:53:20 +00003077 } else {
Chris Lattnerb77ba732006-05-16 23:39:44 +00003078 // Otherwise, this is a vector type. We only support legal vectors
3079 // right now.
3080 const PackedType *PTy = cast<PackedType>(Args[i].second);
3081 unsigned NumElems = PTy->getNumElements();
3082 const Type *EltTy = PTy->getElementType();
3083
3084 // Figure out if there is a Packed type corresponding to this Vector
3085 // type. If so, convert to the packed type.
3086 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
Chris Lattner938155c2006-05-17 20:43:21 +00003087 if (TVT != MVT::Other && isTypeLegal(TVT)) {
3088 // Insert a VBIT_CONVERT of the MVT::Vector type to the packed type.
3089 Op = DAG.getNode(ISD::VBIT_CONVERT, TVT, Op);
3090 Ops.push_back(Op);
Evan Cheng21dee4e2006-05-26 23:13:20 +00003091 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattner938155c2006-05-17 20:43:21 +00003092 } else {
Chris Lattnerb77ba732006-05-16 23:39:44 +00003093 assert(0 && "Don't support illegal by-val vector call args yet!");
3094 abort();
3095 }
Chris Lattneraaa23d92006-05-16 22:53:20 +00003096 }
3097 break;
3098 }
3099 }
3100
3101 // Figure out the result value types.
Chris Lattner65879ca2006-08-16 22:57:46 +00003102 SmallVector<MVT::ValueType, 4> RetTys;
Chris Lattneraaa23d92006-05-16 22:53:20 +00003103
3104 if (RetTy != Type::VoidTy) {
3105 MVT::ValueType VT = getValueType(RetTy);
3106 switch (getTypeAction(VT)) {
3107 default: assert(0 && "Unknown type action!");
3108 case Legal:
3109 RetTys.push_back(VT);
3110 break;
3111 case Promote:
3112 RetTys.push_back(getTypeToTransformTo(VT));
3113 break;
3114 case Expand:
3115 if (VT != MVT::Vector) {
3116 // If this is a large integer, it needs to be reassembled from small
3117 // integers. Figure out what the source elt type is and how many small
3118 // integers it is.
Evan Cheng22cf8992006-12-13 20:57:08 +00003119 MVT::ValueType NVT = getTypeToExpandTo(VT);
3120 unsigned NumVals = getNumElements(VT);
Chris Lattneraaa23d92006-05-16 22:53:20 +00003121 for (unsigned i = 0; i != NumVals; ++i)
3122 RetTys.push_back(NVT);
3123 } else {
Chris Lattnerb77ba732006-05-16 23:39:44 +00003124 // Otherwise, this is a vector type. We only support legal vectors
3125 // right now.
3126 const PackedType *PTy = cast<PackedType>(RetTy);
3127 unsigned NumElems = PTy->getNumElements();
3128 const Type *EltTy = PTy->getElementType();
3129
3130 // Figure out if there is a Packed type corresponding to this Vector
3131 // type. If so, convert to the packed type.
3132 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
3133 if (TVT != MVT::Other && isTypeLegal(TVT)) {
3134 RetTys.push_back(TVT);
3135 } else {
3136 assert(0 && "Don't support illegal by-val vector call results yet!");
3137 abort();
3138 }
Chris Lattneraaa23d92006-05-16 22:53:20 +00003139 }
3140 }
3141 }
3142
3143 RetTys.push_back(MVT::Other); // Always has a chain.
3144
3145 // Finally, create the CALL node.
Chris Lattner65879ca2006-08-16 22:57:46 +00003146 SDOperand Res = DAG.getNode(ISD::CALL,
3147 DAG.getVTList(&RetTys[0], RetTys.size()),
3148 &Ops[0], Ops.size());
Chris Lattneraaa23d92006-05-16 22:53:20 +00003149
3150 // This returns a pair of operands. The first element is the
3151 // return value for the function (if RetTy is not VoidTy). The second
3152 // element is the outgoing token chain.
3153 SDOperand ResVal;
3154 if (RetTys.size() != 1) {
3155 MVT::ValueType VT = getValueType(RetTy);
3156 if (RetTys.size() == 2) {
3157 ResVal = Res;
3158
3159 // If this value was promoted, truncate it down.
3160 if (ResVal.getValueType() != VT) {
Chris Lattnerb77ba732006-05-16 23:39:44 +00003161 if (VT == MVT::Vector) {
3162 // Insert a VBITCONVERT to convert from the packed result type to the
3163 // MVT::Vector type.
3164 unsigned NumElems = cast<PackedType>(RetTy)->getNumElements();
3165 const Type *EltTy = cast<PackedType>(RetTy)->getElementType();
3166
3167 // Figure out if there is a Packed type corresponding to this Vector
3168 // type. If so, convert to the packed type.
3169 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
3170 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Chris Lattnerb77ba732006-05-16 23:39:44 +00003171 // Insert a VBIT_CONVERT of the FORMAL_ARGUMENTS to a
3172 // "N x PTyElementVT" MVT::Vector type.
3173 ResVal = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, ResVal,
Chris Lattner7949c2e2006-05-17 20:49:36 +00003174 DAG.getConstant(NumElems, MVT::i32),
3175 DAG.getValueType(getValueType(EltTy)));
Chris Lattnerb77ba732006-05-16 23:39:44 +00003176 } else {
3177 abort();
3178 }
3179 } else if (MVT::isInteger(VT)) {
Chris Lattneraaa23d92006-05-16 22:53:20 +00003180 unsigned AssertOp = RetTy->isSigned() ?
3181 ISD::AssertSext : ISD::AssertZext;
3182 ResVal = DAG.getNode(AssertOp, ResVal.getValueType(), ResVal,
3183 DAG.getValueType(VT));
3184 ResVal = DAG.getNode(ISD::TRUNCATE, VT, ResVal);
3185 } else {
3186 assert(MVT::isFloatingPoint(VT));
Evan Cheng4eee7242006-12-09 02:42:38 +00003187 if (getTypeAction(VT) == Expand)
3188 ResVal = DAG.getNode(ISD::BIT_CONVERT, VT, ResVal);
3189 else
3190 ResVal = DAG.getNode(ISD::FP_ROUND, VT, ResVal);
Chris Lattneraaa23d92006-05-16 22:53:20 +00003191 }
3192 }
3193 } else if (RetTys.size() == 3) {
3194 ResVal = DAG.getNode(ISD::BUILD_PAIR, VT,
3195 Res.getValue(0), Res.getValue(1));
3196
3197 } else {
3198 assert(0 && "Case not handled yet!");
3199 }
3200 }
3201
3202 return std::make_pair(ResVal, Res.getValue(Res.Val->getNumValues()-1));
3203}
3204
3205
3206
Chris Lattner58cfd792005-01-09 00:00:49 +00003207// It is always conservatively correct for llvm.returnaddress and
3208// llvm.frameaddress to return 0.
Chris Lattneraaa23d92006-05-16 22:53:20 +00003209//
3210// FIXME: Change this to insert a FRAMEADDR/RETURNADDR node, and have that be
3211// expanded to 0 if the target wants.
Chris Lattner58cfd792005-01-09 00:00:49 +00003212std::pair<SDOperand, SDOperand>
3213TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
3214 unsigned Depth, SelectionDAG &DAG) {
3215 return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
Chris Lattner7a60d912005-01-07 07:47:53 +00003216}
3217
Chris Lattner29dcc712005-05-14 05:50:48 +00003218SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner897cd7d2005-01-16 07:28:41 +00003219 assert(0 && "LowerOperation not implemented for this target!");
3220 abort();
Misha Brukman73e929f2005-02-17 21:39:27 +00003221 return SDOperand();
Chris Lattner897cd7d2005-01-16 07:28:41 +00003222}
3223
Nate Begeman595ec732006-01-28 03:14:31 +00003224SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
3225 SelectionDAG &DAG) {
3226 assert(0 && "CustomPromoteOperation not implemented for this target!");
3227 abort();
3228 return SDOperand();
3229}
3230
Chris Lattner58cfd792005-01-09 00:00:49 +00003231void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00003232 unsigned Depth = (unsigned)cast<ConstantInt>(I.getOperand(1))->getZExtValue();
Chris Lattner58cfd792005-01-09 00:00:49 +00003233 std::pair<SDOperand,SDOperand> Result =
Chris Lattner4108bb02005-01-17 19:43:36 +00003234 TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
Chris Lattner58cfd792005-01-09 00:00:49 +00003235 setValue(&I, Result.first);
3236 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00003237}
3238
Evan Cheng6781b6e2006-02-15 21:59:04 +00003239/// getMemsetValue - Vectorized representation of the memset value
Evan Cheng81fcea82006-02-14 08:22:34 +00003240/// operand.
3241static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
Evan Cheng93e48652006-02-15 22:12:35 +00003242 SelectionDAG &DAG) {
Evan Cheng81fcea82006-02-14 08:22:34 +00003243 MVT::ValueType CurVT = VT;
3244 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
3245 uint64_t Val = C->getValue() & 255;
3246 unsigned Shift = 8;
3247 while (CurVT != MVT::i8) {
3248 Val = (Val << Shift) | Val;
3249 Shift <<= 1;
3250 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00003251 }
3252 return DAG.getConstant(Val, VT);
3253 } else {
3254 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
3255 unsigned Shift = 8;
3256 while (CurVT != MVT::i8) {
3257 Value =
3258 DAG.getNode(ISD::OR, VT,
3259 DAG.getNode(ISD::SHL, VT, Value,
3260 DAG.getConstant(Shift, MVT::i8)), Value);
3261 Shift <<= 1;
3262 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00003263 }
3264
3265 return Value;
3266 }
3267}
3268
Evan Cheng6781b6e2006-02-15 21:59:04 +00003269/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
3270/// used when a memcpy is turned into a memset when the source is a constant
3271/// string ptr.
3272static SDOperand getMemsetStringVal(MVT::ValueType VT,
3273 SelectionDAG &DAG, TargetLowering &TLI,
3274 std::string &Str, unsigned Offset) {
Evan Cheng6781b6e2006-02-15 21:59:04 +00003275 uint64_t Val = 0;
3276 unsigned MSB = getSizeInBits(VT) / 8;
3277 if (TLI.isLittleEndian())
3278 Offset = Offset + MSB - 1;
3279 for (unsigned i = 0; i != MSB; ++i) {
Evan Cheng6e12a052006-11-29 01:38:07 +00003280 Val = (Val << 8) | (unsigned char)Str[Offset];
Evan Cheng6781b6e2006-02-15 21:59:04 +00003281 Offset += TLI.isLittleEndian() ? -1 : 1;
3282 }
3283 return DAG.getConstant(Val, VT);
3284}
3285
Evan Cheng81fcea82006-02-14 08:22:34 +00003286/// getMemBasePlusOffset - Returns base and offset node for the
3287static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
3288 SelectionDAG &DAG, TargetLowering &TLI) {
3289 MVT::ValueType VT = Base.getValueType();
3290 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
3291}
3292
Evan Chengdb2a7a72006-02-14 20:12:38 +00003293/// MeetsMaxMemopRequirement - Determines if the number of memory ops required
Evan Chengd5026102006-02-14 09:11:59 +00003294/// to replace the memset / memcpy is below the threshold. It also returns the
3295/// types of the sequence of memory ops to perform memset / memcpy.
Evan Chengdb2a7a72006-02-14 20:12:38 +00003296static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
3297 unsigned Limit, uint64_t Size,
3298 unsigned Align, TargetLowering &TLI) {
Evan Cheng81fcea82006-02-14 08:22:34 +00003299 MVT::ValueType VT;
3300
3301 if (TLI.allowsUnalignedMemoryAccesses()) {
3302 VT = MVT::i64;
3303 } else {
3304 switch (Align & 7) {
3305 case 0:
3306 VT = MVT::i64;
3307 break;
3308 case 4:
3309 VT = MVT::i32;
3310 break;
3311 case 2:
3312 VT = MVT::i16;
3313 break;
3314 default:
3315 VT = MVT::i8;
3316 break;
3317 }
3318 }
3319
Evan Chengd5026102006-02-14 09:11:59 +00003320 MVT::ValueType LVT = MVT::i64;
3321 while (!TLI.isTypeLegal(LVT))
3322 LVT = (MVT::ValueType)((unsigned)LVT - 1);
3323 assert(MVT::isInteger(LVT));
Evan Cheng81fcea82006-02-14 08:22:34 +00003324
Evan Chengd5026102006-02-14 09:11:59 +00003325 if (VT > LVT)
3326 VT = LVT;
3327
Evan Cheng04514992006-02-14 23:05:54 +00003328 unsigned NumMemOps = 0;
Evan Cheng81fcea82006-02-14 08:22:34 +00003329 while (Size != 0) {
3330 unsigned VTSize = getSizeInBits(VT) / 8;
3331 while (VTSize > Size) {
3332 VT = (MVT::ValueType)((unsigned)VT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00003333 VTSize >>= 1;
3334 }
Evan Chengd5026102006-02-14 09:11:59 +00003335 assert(MVT::isInteger(VT));
3336
3337 if (++NumMemOps > Limit)
3338 return false;
Evan Cheng81fcea82006-02-14 08:22:34 +00003339 MemOps.push_back(VT);
3340 Size -= VTSize;
3341 }
Evan Chengd5026102006-02-14 09:11:59 +00003342
3343 return true;
Evan Cheng81fcea82006-02-14 08:22:34 +00003344}
3345
Chris Lattner875def92005-01-11 05:56:49 +00003346void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
Evan Cheng81fcea82006-02-14 08:22:34 +00003347 SDOperand Op1 = getValue(I.getOperand(1));
3348 SDOperand Op2 = getValue(I.getOperand(2));
3349 SDOperand Op3 = getValue(I.getOperand(3));
3350 SDOperand Op4 = getValue(I.getOperand(4));
3351 unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
3352 if (Align == 0) Align = 1;
3353
3354 if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
3355 std::vector<MVT::ValueType> MemOps;
Evan Cheng81fcea82006-02-14 08:22:34 +00003356
3357 // Expand memset / memcpy to a series of load / store ops
3358 // if the size operand falls below a certain threshold.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003359 SmallVector<SDOperand, 8> OutChains;
Evan Cheng81fcea82006-02-14 08:22:34 +00003360 switch (Op) {
Evan Cheng038521e2006-02-14 19:45:56 +00003361 default: break; // Do nothing for now.
Evan Cheng81fcea82006-02-14 08:22:34 +00003362 case ISD::MEMSET: {
Evan Chengdb2a7a72006-02-14 20:12:38 +00003363 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
3364 Size->getValue(), Align, TLI)) {
Evan Chengd5026102006-02-14 09:11:59 +00003365 unsigned NumMemOps = MemOps.size();
Evan Cheng81fcea82006-02-14 08:22:34 +00003366 unsigned Offset = 0;
3367 for (unsigned i = 0; i < NumMemOps; i++) {
3368 MVT::ValueType VT = MemOps[i];
3369 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng93e48652006-02-15 22:12:35 +00003370 SDOperand Value = getMemsetValue(Op2, VT, DAG);
Evan Chengdf9ac472006-10-05 23:01:46 +00003371 SDOperand Store = DAG.getStore(getRoot(), Value,
Chris Lattner6f87d182006-02-22 22:37:12 +00003372 getMemBasePlusOffset(Op1, Offset, DAG, TLI),
Evan Chengab51cf22006-10-13 21:14:26 +00003373 I.getOperand(1), Offset);
Evan Chenge2038bd2006-02-15 01:54:51 +00003374 OutChains.push_back(Store);
Evan Cheng81fcea82006-02-14 08:22:34 +00003375 Offset += VTSize;
3376 }
Evan Cheng81fcea82006-02-14 08:22:34 +00003377 }
Evan Chenge2038bd2006-02-15 01:54:51 +00003378 break;
Evan Cheng81fcea82006-02-14 08:22:34 +00003379 }
Evan Chenge2038bd2006-02-15 01:54:51 +00003380 case ISD::MEMCPY: {
3381 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
3382 Size->getValue(), Align, TLI)) {
3383 unsigned NumMemOps = MemOps.size();
Evan Chengc3dcf5a2006-02-16 23:11:42 +00003384 unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
Evan Cheng6781b6e2006-02-15 21:59:04 +00003385 GlobalAddressSDNode *G = NULL;
3386 std::string Str;
Evan Chengc3dcf5a2006-02-16 23:11:42 +00003387 bool CopyFromStr = false;
Evan Cheng6781b6e2006-02-15 21:59:04 +00003388
3389 if (Op2.getOpcode() == ISD::GlobalAddress)
3390 G = cast<GlobalAddressSDNode>(Op2);
3391 else if (Op2.getOpcode() == ISD::ADD &&
3392 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
3393 Op2.getOperand(1).getOpcode() == ISD::Constant) {
3394 G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
Evan Chengc3dcf5a2006-02-16 23:11:42 +00003395 SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
Evan Cheng6781b6e2006-02-15 21:59:04 +00003396 }
3397 if (G) {
3398 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
Evan Chengfeba5072006-11-29 01:58:12 +00003399 if (GV && GV->isConstant()) {
Evan Cheng38280c02006-03-10 23:52:03 +00003400 Str = GV->getStringValue(false);
Evan Chengc3dcf5a2006-02-16 23:11:42 +00003401 if (!Str.empty()) {
3402 CopyFromStr = true;
3403 SrcOff += SrcDelta;
3404 }
3405 }
Evan Cheng6781b6e2006-02-15 21:59:04 +00003406 }
3407
Evan Chenge2038bd2006-02-15 01:54:51 +00003408 for (unsigned i = 0; i < NumMemOps; i++) {
3409 MVT::ValueType VT = MemOps[i];
3410 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng6781b6e2006-02-15 21:59:04 +00003411 SDOperand Value, Chain, Store;
3412
Evan Chengc3dcf5a2006-02-16 23:11:42 +00003413 if (CopyFromStr) {
Evan Cheng6781b6e2006-02-15 21:59:04 +00003414 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
3415 Chain = getRoot();
3416 Store =
Evan Chengdf9ac472006-10-05 23:01:46 +00003417 DAG.getStore(Chain, Value,
3418 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
Evan Chengab51cf22006-10-13 21:14:26 +00003419 I.getOperand(1), DstOff);
Evan Cheng6781b6e2006-02-15 21:59:04 +00003420 } else {
3421 Value = DAG.getLoad(VT, getRoot(),
3422 getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
Evan Chenge71fe34d2006-10-09 20:57:25 +00003423 I.getOperand(2), SrcOff);
Evan Cheng6781b6e2006-02-15 21:59:04 +00003424 Chain = Value.getValue(1);
3425 Store =
Evan Chengdf9ac472006-10-05 23:01:46 +00003426 DAG.getStore(Chain, Value,
3427 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
Evan Chengab51cf22006-10-13 21:14:26 +00003428 I.getOperand(1), DstOff);
Evan Cheng6781b6e2006-02-15 21:59:04 +00003429 }
Evan Chenge2038bd2006-02-15 01:54:51 +00003430 OutChains.push_back(Store);
Evan Cheng6781b6e2006-02-15 21:59:04 +00003431 SrcOff += VTSize;
3432 DstOff += VTSize;
Evan Chenge2038bd2006-02-15 01:54:51 +00003433 }
3434 }
3435 break;
3436 }
3437 }
3438
3439 if (!OutChains.empty()) {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003440 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
3441 &OutChains[0], OutChains.size()));
Evan Chenge2038bd2006-02-15 01:54:51 +00003442 return;
Evan Cheng81fcea82006-02-14 08:22:34 +00003443 }
3444 }
3445
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003446 DAG.setRoot(DAG.getNode(Op, MVT::Other, getRoot(), Op1, Op2, Op3, Op4));
Chris Lattner7a60d912005-01-07 07:47:53 +00003447}
3448
Chris Lattner875def92005-01-11 05:56:49 +00003449//===----------------------------------------------------------------------===//
3450// SelectionDAGISel code
3451//===----------------------------------------------------------------------===//
Chris Lattner7a60d912005-01-07 07:47:53 +00003452
3453unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
3454 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
3455}
3456
Chris Lattnerc9950c12005-08-17 06:37:43 +00003457void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner1a908c82005-08-18 17:35:14 +00003458 // FIXME: we only modify the CFG to split critical edges. This
3459 // updates dom and loop info.
Jim Laskeydcb2b832006-10-16 20:52:31 +00003460 AU.addRequired<AliasAnalysis>();
Chris Lattnerc9950c12005-08-17 06:37:43 +00003461}
Chris Lattner7a60d912005-01-07 07:47:53 +00003462
Chris Lattner35397782005-12-05 07:10:48 +00003463
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003464/// OptimizeNoopCopyExpression - We have determined that the specified cast
3465/// instruction is a noop copy (e.g. it's casting from one pointer type to
3466/// another, int->uint, or int->sbyte on PPC.
3467///
3468/// Return true if any changes are made.
3469static bool OptimizeNoopCopyExpression(CastInst *CI) {
3470 BasicBlock *DefBB = CI->getParent();
3471
3472 /// InsertedCasts - Only insert a cast in each block once.
3473 std::map<BasicBlock*, CastInst*> InsertedCasts;
3474
3475 bool MadeChange = false;
3476 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
3477 UI != E; ) {
3478 Use &TheUse = UI.getUse();
3479 Instruction *User = cast<Instruction>(*UI);
3480
3481 // Figure out which BB this cast is used in. For PHI's this is the
3482 // appropriate predecessor block.
3483 BasicBlock *UserBB = User->getParent();
3484 if (PHINode *PN = dyn_cast<PHINode>(User)) {
3485 unsigned OpVal = UI.getOperandNo()/2;
3486 UserBB = PN->getIncomingBlock(OpVal);
3487 }
3488
3489 // Preincrement use iterator so we don't invalidate it.
3490 ++UI;
3491
3492 // If this user is in the same block as the cast, don't change the cast.
3493 if (UserBB == DefBB) continue;
3494
3495 // If we have already inserted a cast into this block, use it.
3496 CastInst *&InsertedCast = InsertedCasts[UserBB];
3497
3498 if (!InsertedCast) {
3499 BasicBlock::iterator InsertPt = UserBB->begin();
3500 while (isa<PHINode>(InsertPt)) ++InsertPt;
3501
3502 InsertedCast =
Reid Spencerbfe26ff2006-12-13 00:50:17 +00003503 CastInst::create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
3504 InsertPt);
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003505 MadeChange = true;
3506 }
3507
3508 // Replace a use of the cast with a use of the new casat.
3509 TheUse = InsertedCast;
3510 }
3511
3512 // If we removed all uses, nuke the cast.
3513 if (CI->use_empty())
3514 CI->eraseFromParent();
3515
3516 return MadeChange;
3517}
3518
Chris Lattner35397782005-12-05 07:10:48 +00003519/// InsertGEPComputeCode - Insert code into BB to compute Ptr+PtrOffset,
3520/// casting to the type of GEPI.
Chris Lattner21cd9902006-05-06 09:10:37 +00003521static Instruction *InsertGEPComputeCode(Instruction *&V, BasicBlock *BB,
3522 Instruction *GEPI, Value *Ptr,
3523 Value *PtrOffset) {
Chris Lattner35397782005-12-05 07:10:48 +00003524 if (V) return V; // Already computed.
3525
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003526 // Figure out the insertion point
Chris Lattner35397782005-12-05 07:10:48 +00003527 BasicBlock::iterator InsertPt;
3528 if (BB == GEPI->getParent()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003529 // If GEP is already inserted into BB, insert right after the GEP.
Chris Lattner35397782005-12-05 07:10:48 +00003530 InsertPt = GEPI;
3531 ++InsertPt;
3532 } else {
3533 // Otherwise, insert at the top of BB, after any PHI nodes
3534 InsertPt = BB->begin();
3535 while (isa<PHINode>(InsertPt)) ++InsertPt;
3536 }
3537
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00003538 // If Ptr is itself a cast, but in some other BB, emit a copy of the cast into
3539 // BB so that there is only one value live across basic blocks (the cast
3540 // operand).
3541 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
3542 if (CI->getParent() != BB && isa<PointerType>(CI->getOperand(0)->getType()))
Reid Spencerbfe26ff2006-12-13 00:50:17 +00003543 Ptr = CastInst::create(CI->getOpcode(), CI->getOperand(0), CI->getType(),
3544 "", InsertPt);
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00003545
Chris Lattner35397782005-12-05 07:10:48 +00003546 // Add the offset, cast it to the right type.
3547 Ptr = BinaryOperator::createAdd(Ptr, PtrOffset, "", InsertPt);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003548 // Ptr is an integer type, GEPI is pointer type ==> IntToPtr
3549 return V = CastInst::create(Instruction::IntToPtr, Ptr, GEPI->getType(),
3550 "", InsertPt);
Chris Lattner35397782005-12-05 07:10:48 +00003551}
3552
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003553/// ReplaceUsesOfGEPInst - Replace all uses of RepPtr with inserted code to
3554/// compute its value. The RepPtr value can be computed with Ptr+PtrOffset. One
3555/// trivial way of doing this would be to evaluate Ptr+PtrOffset in RepPtr's
3556/// block, then ReplaceAllUsesWith'ing everything. However, we would prefer to
3557/// sink PtrOffset into user blocks where doing so will likely allow us to fold
3558/// the constant add into a load or store instruction. Additionally, if a user
3559/// is a pointer-pointer cast, we look through it to find its users.
3560static void ReplaceUsesOfGEPInst(Instruction *RepPtr, Value *Ptr,
3561 Constant *PtrOffset, BasicBlock *DefBB,
3562 GetElementPtrInst *GEPI,
Chris Lattner21cd9902006-05-06 09:10:37 +00003563 std::map<BasicBlock*,Instruction*> &InsertedExprs) {
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003564 while (!RepPtr->use_empty()) {
3565 Instruction *User = cast<Instruction>(RepPtr->use_back());
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003566
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003567 // If the user is a Pointer-Pointer cast, recurse. Only BitCast can be
3568 // used for a Pointer-Pointer cast.
3569 if (isa<BitCastInst>(User)) {
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003570 ReplaceUsesOfGEPInst(User, Ptr, PtrOffset, DefBB, GEPI, InsertedExprs);
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003571
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003572 // Drop the use of RepPtr. The cast is dead. Don't delete it now, else we
3573 // could invalidate an iterator.
3574 User->setOperand(0, UndefValue::get(RepPtr->getType()));
3575 continue;
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003576 }
3577
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003578 // If this is a load of the pointer, or a store through the pointer, emit
3579 // the increment into the load/store block.
Chris Lattner21cd9902006-05-06 09:10:37 +00003580 Instruction *NewVal;
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003581 if (isa<LoadInst>(User) ||
3582 (isa<StoreInst>(User) && User->getOperand(0) != RepPtr)) {
3583 NewVal = InsertGEPComputeCode(InsertedExprs[User->getParent()],
3584 User->getParent(), GEPI,
3585 Ptr, PtrOffset);
3586 } else {
3587 // If this use is not foldable into the addressing mode, use a version
3588 // emitted in the GEP block.
3589 NewVal = InsertGEPComputeCode(InsertedExprs[DefBB], DefBB, GEPI,
3590 Ptr, PtrOffset);
3591 }
3592
Chris Lattner21cd9902006-05-06 09:10:37 +00003593 if (GEPI->getType() != RepPtr->getType()) {
3594 BasicBlock::iterator IP = NewVal;
3595 ++IP;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003596 // NewVal must be a GEP which must be pointer type, so BitCast
3597 NewVal = new BitCastInst(NewVal, RepPtr->getType(), "", IP);
Chris Lattner21cd9902006-05-06 09:10:37 +00003598 }
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003599 User->replaceUsesOfWith(RepPtr, NewVal);
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003600 }
3601}
Chris Lattner35397782005-12-05 07:10:48 +00003602
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003603
Chris Lattner35397782005-12-05 07:10:48 +00003604/// OptimizeGEPExpression - Since we are doing basic-block-at-a-time instruction
3605/// selection, we want to be a bit careful about some things. In particular, if
3606/// we have a GEP instruction that is used in a different block than it is
3607/// defined, the addressing expression of the GEP cannot be folded into loads or
3608/// stores that use it. In this case, decompose the GEP and move constant
3609/// indices into blocks that use it.
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003610static bool OptimizeGEPExpression(GetElementPtrInst *GEPI,
Owen Anderson20a631f2006-05-03 01:29:57 +00003611 const TargetData *TD) {
Chris Lattner35397782005-12-05 07:10:48 +00003612 // If this GEP is only used inside the block it is defined in, there is no
3613 // need to rewrite it.
3614 bool isUsedOutsideDefBB = false;
3615 BasicBlock *DefBB = GEPI->getParent();
3616 for (Value::use_iterator UI = GEPI->use_begin(), E = GEPI->use_end();
3617 UI != E; ++UI) {
3618 if (cast<Instruction>(*UI)->getParent() != DefBB) {
3619 isUsedOutsideDefBB = true;
3620 break;
3621 }
3622 }
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003623 if (!isUsedOutsideDefBB) return false;
Chris Lattner35397782005-12-05 07:10:48 +00003624
3625 // If this GEP has no non-zero constant indices, there is nothing we can do,
3626 // ignore it.
3627 bool hasConstantIndex = false;
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003628 bool hasVariableIndex = false;
Chris Lattner35397782005-12-05 07:10:48 +00003629 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
3630 E = GEPI->op_end(); OI != E; ++OI) {
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003631 if (ConstantInt *CI = dyn_cast<ConstantInt>(*OI)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00003632 if (CI->getZExtValue()) {
Chris Lattner35397782005-12-05 07:10:48 +00003633 hasConstantIndex = true;
3634 break;
3635 }
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003636 } else {
3637 hasVariableIndex = true;
3638 }
Chris Lattner35397782005-12-05 07:10:48 +00003639 }
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003640
3641 // If this is a "GEP X, 0, 0, 0", turn this into a cast.
3642 if (!hasConstantIndex && !hasVariableIndex) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003643 /// The GEP operand must be a pointer, so must its result -> BitCast
3644 Value *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003645 GEPI->getName(), GEPI);
3646 GEPI->replaceAllUsesWith(NC);
3647 GEPI->eraseFromParent();
3648 return true;
3649 }
3650
Chris Lattnerf1a54c02005-12-11 09:05:13 +00003651 // If this is a GEP &Alloca, 0, 0, forward subst the frame index into uses.
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003652 if (!hasConstantIndex && !isa<AllocaInst>(GEPI->getOperand(0)))
3653 return false;
Chris Lattner35397782005-12-05 07:10:48 +00003654
3655 // Otherwise, decompose the GEP instruction into multiplies and adds. Sum the
3656 // constant offset (which we now know is non-zero) and deal with it later.
3657 uint64_t ConstantOffset = 0;
Owen Anderson20a631f2006-05-03 01:29:57 +00003658 const Type *UIntPtrTy = TD->getIntPtrType();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003659 Value *Ptr = new PtrToIntInst(GEPI->getOperand(0), UIntPtrTy, "", GEPI);
Chris Lattner35397782005-12-05 07:10:48 +00003660 const Type *Ty = GEPI->getOperand(0)->getType();
3661
3662 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
3663 E = GEPI->op_end(); OI != E; ++OI) {
3664 Value *Idx = *OI;
3665 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00003666 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
Chris Lattner35397782005-12-05 07:10:48 +00003667 if (Field)
Owen Anderson20a631f2006-05-03 01:29:57 +00003668 ConstantOffset += TD->getStructLayout(StTy)->MemberOffsets[Field];
Chris Lattner35397782005-12-05 07:10:48 +00003669 Ty = StTy->getElementType(Field);
3670 } else {
3671 Ty = cast<SequentialType>(Ty)->getElementType();
3672
3673 // Handle constant subscripts.
3674 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00003675 if (CI->getZExtValue() == 0) continue;
3676 if (CI->getType()->isSigned())
3677 ConstantOffset += (int64_t)TD->getTypeSize(Ty)*CI->getSExtValue();
Chris Lattner35397782005-12-05 07:10:48 +00003678 else
Reid Spencere0fc4df2006-10-20 07:07:24 +00003679 ConstantOffset += TD->getTypeSize(Ty)*CI->getZExtValue();
Chris Lattner35397782005-12-05 07:10:48 +00003680 continue;
3681 }
3682
3683 // Ptr = Ptr + Idx * ElementSize;
3684
3685 // Cast Idx to UIntPtrTy if needed.
Reid Spencerbfe26ff2006-12-13 00:50:17 +00003686 Idx = CastInst::createIntegerCast(Idx, UIntPtrTy, true/*SExt*/, "", GEPI);
Chris Lattner35397782005-12-05 07:10:48 +00003687
Owen Anderson20a631f2006-05-03 01:29:57 +00003688 uint64_t ElementSize = TD->getTypeSize(Ty);
Chris Lattner35397782005-12-05 07:10:48 +00003689 // Mask off bits that should not be set.
3690 ElementSize &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
Reid Spencere0fc4df2006-10-20 07:07:24 +00003691 Constant *SizeCst = ConstantInt::get(UIntPtrTy, ElementSize);
Chris Lattner35397782005-12-05 07:10:48 +00003692
3693 // Multiply by the element size and add to the base.
3694 Idx = BinaryOperator::createMul(Idx, SizeCst, "", GEPI);
3695 Ptr = BinaryOperator::createAdd(Ptr, Idx, "", GEPI);
3696 }
3697 }
3698
3699 // Make sure that the offset fits in uintptr_t.
3700 ConstantOffset &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
Reid Spencere0fc4df2006-10-20 07:07:24 +00003701 Constant *PtrOffset = ConstantInt::get(UIntPtrTy, ConstantOffset);
Chris Lattner35397782005-12-05 07:10:48 +00003702
3703 // Okay, we have now emitted all of the variable index parts to the BB that
3704 // the GEP is defined in. Loop over all of the using instructions, inserting
3705 // an "add Ptr, ConstantOffset" into each block that uses it and update the
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00003706 // instruction to use the newly computed value, making GEPI dead. When the
3707 // user is a load or store instruction address, we emit the add into the user
3708 // block, otherwise we use a canonical version right next to the gep (these
3709 // won't be foldable as addresses, so we might as well share the computation).
3710
Chris Lattner21cd9902006-05-06 09:10:37 +00003711 std::map<BasicBlock*,Instruction*> InsertedExprs;
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003712 ReplaceUsesOfGEPInst(GEPI, Ptr, PtrOffset, DefBB, GEPI, InsertedExprs);
Chris Lattner35397782005-12-05 07:10:48 +00003713
3714 // Finally, the GEP is dead, remove it.
3715 GEPI->eraseFromParent();
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003716
3717 return true;
Chris Lattner35397782005-12-05 07:10:48 +00003718}
3719
Chris Lattnerbba52192006-10-28 19:22:10 +00003720
3721/// SplitEdgeNicely - Split the critical edge from TI to it's specified
3722/// successor if it will improve codegen. We only do this if the successor has
3723/// phi nodes (otherwise critical edges are ok). If there is already another
3724/// predecessor of the succ that is empty (and thus has no phi nodes), use it
3725/// instead of introducing a new block.
3726static void SplitEdgeNicely(TerminatorInst *TI, unsigned SuccNum, Pass *P) {
3727 BasicBlock *TIBB = TI->getParent();
3728 BasicBlock *Dest = TI->getSuccessor(SuccNum);
3729 assert(isa<PHINode>(Dest->begin()) &&
3730 "This should only be called if Dest has a PHI!");
3731
3732 /// TIPHIValues - This array is lazily computed to determine the values of
3733 /// PHIs in Dest that TI would provide.
3734 std::vector<Value*> TIPHIValues;
3735
3736 // Check to see if Dest has any blocks that can be used as a split edge for
3737 // this terminator.
3738 for (pred_iterator PI = pred_begin(Dest), E = pred_end(Dest); PI != E; ++PI) {
3739 BasicBlock *Pred = *PI;
3740 // To be usable, the pred has to end with an uncond branch to the dest.
3741 BranchInst *PredBr = dyn_cast<BranchInst>(Pred->getTerminator());
3742 if (!PredBr || !PredBr->isUnconditional() ||
3743 // Must be empty other than the branch.
3744 &Pred->front() != PredBr)
3745 continue;
3746
3747 // Finally, since we know that Dest has phi nodes in it, we have to make
3748 // sure that jumping to Pred will have the same affect as going to Dest in
3749 // terms of PHI values.
3750 PHINode *PN;
3751 unsigned PHINo = 0;
3752 bool FoundMatch = true;
3753 for (BasicBlock::iterator I = Dest->begin();
3754 (PN = dyn_cast<PHINode>(I)); ++I, ++PHINo) {
3755 if (PHINo == TIPHIValues.size())
3756 TIPHIValues.push_back(PN->getIncomingValueForBlock(TIBB));
3757
3758 // If the PHI entry doesn't work, we can't use this pred.
3759 if (TIPHIValues[PHINo] != PN->getIncomingValueForBlock(Pred)) {
3760 FoundMatch = false;
3761 break;
3762 }
3763 }
3764
3765 // If we found a workable predecessor, change TI to branch to Succ.
3766 if (FoundMatch) {
3767 Dest->removePredecessor(TIBB);
3768 TI->setSuccessor(SuccNum, Pred);
3769 return;
3770 }
3771 }
3772
3773 SplitCriticalEdge(TI, SuccNum, P, true);
3774}
3775
3776
Chris Lattner7a60d912005-01-07 07:47:53 +00003777bool SelectionDAGISel::runOnFunction(Function &Fn) {
3778 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
3779 RegMap = MF.getSSARegMap();
Bill Wendling22e978a2006-12-07 20:04:42 +00003780 DOUT << "\n\n\n=== " << Fn.getName() << "\n";
Chris Lattner7a60d912005-01-07 07:47:53 +00003781
Chris Lattner3e6b1c62006-10-28 17:04:37 +00003782 // First, split all critical edges.
Chris Lattner35397782005-12-05 07:10:48 +00003783 //
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003784 // In this pass we also look for GEP and cast instructions that are used
3785 // across basic blocks and rewrite them to improve basic-block-at-a-time
3786 // selection.
3787 //
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003788 bool MadeChange = true;
3789 while (MadeChange) {
3790 MadeChange = false;
Chris Lattner1a908c82005-08-18 17:35:14 +00003791 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
Chris Lattnerbba52192006-10-28 19:22:10 +00003792 // Split all critical edges where the dest block has a PHI.
Chris Lattner3e6b1c62006-10-28 17:04:37 +00003793 TerminatorInst *BBTI = BB->getTerminator();
3794 if (BBTI->getNumSuccessors() > 1) {
3795 for (unsigned i = 0, e = BBTI->getNumSuccessors(); i != e; ++i)
Chris Lattnerbba52192006-10-28 19:22:10 +00003796 if (isa<PHINode>(BBTI->getSuccessor(i)->begin()) &&
3797 isCriticalEdge(BBTI, i, true))
3798 SplitEdgeNicely(BBTI, i, this);
Chris Lattner3e6b1c62006-10-28 17:04:37 +00003799 }
3800
Chris Lattner35397782005-12-05 07:10:48 +00003801
Chris Lattnera9caf952006-09-28 06:17:10 +00003802 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003803 Instruction *I = BBI++;
Chris Lattner90f42382006-11-29 01:12:32 +00003804
3805 if (CallInst *CI = dyn_cast<CallInst>(I)) {
3806 // If we found an inline asm expession, and if the target knows how to
3807 // lower it to normal LLVM code, do so now.
3808 if (isa<InlineAsm>(CI->getCalledValue()))
3809 if (const TargetAsmInfo *TAI =
3810 TLI.getTargetMachine().getTargetAsmInfo()) {
3811 if (TAI->ExpandInlineAsm(CI))
3812 BBI = BB->begin();
3813 }
3814 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003815 MadeChange |= OptimizeGEPExpression(GEPI, TLI.getTargetData());
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003816 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattner84cc1f72006-09-13 06:02:42 +00003817 // If the source of the cast is a constant, then this should have
3818 // already been constant folded. The only reason NOT to constant fold
3819 // it is if something (e.g. LSR) was careful to place the constant
3820 // evaluation in a block other than then one that uses it (e.g. to hoist
3821 // the address of globals out of a loop). If this is the case, we don't
3822 // want to forward-subst the cast.
3823 if (isa<Constant>(CI->getOperand(0)))
3824 continue;
3825
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003826 // If this is a noop copy, sink it into user blocks to reduce the number
3827 // of virtual registers that must be created and coallesced.
3828 MVT::ValueType SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
3829 MVT::ValueType DstVT = TLI.getValueType(CI->getType());
3830
3831 // This is an fp<->int conversion?
3832 if (MVT::isInteger(SrcVT) != MVT::isInteger(DstVT))
3833 continue;
3834
3835 // If this is an extension, it will be a zero or sign extension, which
3836 // isn't a noop.
3837 if (SrcVT < DstVT) continue;
3838
3839 // If these values will be promoted, find out what they will be promoted
3840 // to. This helps us consider truncates on PPC as noop copies when they
3841 // are.
3842 if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote)
3843 SrcVT = TLI.getTypeToTransformTo(SrcVT);
3844 if (TLI.getTypeAction(DstVT) == TargetLowering::Promote)
3845 DstVT = TLI.getTypeToTransformTo(DstVT);
3846
3847 // If, after promotion, these are the same types, this is a noop copy.
3848 if (SrcVT == DstVT)
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003849 MadeChange |= OptimizeNoopCopyExpression(CI);
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003850 }
3851 }
Chris Lattner1a908c82005-08-18 17:35:14 +00003852 }
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003853 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00003854
Chris Lattner7a60d912005-01-07 07:47:53 +00003855 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
3856
3857 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
3858 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukman835702a2005-04-21 22:36:52 +00003859
Chris Lattner7a60d912005-01-07 07:47:53 +00003860 return true;
3861}
3862
Chris Lattnered0110b2006-10-27 21:36:01 +00003863SDOperand SelectionDAGLowering::CopyValueToVirtualRegister(Value *V,
3864 unsigned Reg) {
3865 SDOperand Op = getValue(V);
Chris Lattnere727af02005-01-13 20:50:02 +00003866 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattner33182322005-08-16 21:55:35 +00003867 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattnere727af02005-01-13 20:50:02 +00003868 "Copy from a reg to the same reg!");
Chris Lattner33182322005-08-16 21:55:35 +00003869
3870 // If this type is not legal, we must make sure to not create an invalid
3871 // register use.
3872 MVT::ValueType SrcVT = Op.getValueType();
3873 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
Chris Lattner33182322005-08-16 21:55:35 +00003874 if (SrcVT == DestVT) {
Chris Lattnered0110b2006-10-27 21:36:01 +00003875 return DAG.getCopyToReg(getRoot(), Reg, Op);
Chris Lattner672a42d2006-03-21 19:20:37 +00003876 } else if (SrcVT == MVT::Vector) {
Chris Lattner5fe1f542006-03-31 02:06:56 +00003877 // Handle copies from generic vectors to registers.
3878 MVT::ValueType PTyElementVT, PTyLegalElementVT;
3879 unsigned NE = TLI.getPackedTypeBreakdown(cast<PackedType>(V->getType()),
3880 PTyElementVT, PTyLegalElementVT);
Chris Lattner672a42d2006-03-21 19:20:37 +00003881
Chris Lattner5fe1f542006-03-31 02:06:56 +00003882 // Insert a VBIT_CONVERT of the input vector to a "N x PTyElementVT"
3883 // MVT::Vector type.
3884 Op = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Op,
3885 DAG.getConstant(NE, MVT::i32),
3886 DAG.getValueType(PTyElementVT));
Chris Lattner672a42d2006-03-21 19:20:37 +00003887
Chris Lattner5fe1f542006-03-31 02:06:56 +00003888 // Loop over all of the elements of the resultant vector,
3889 // VEXTRACT_VECTOR_ELT'ing them, converting them to PTyLegalElementVT, then
3890 // copying them into output registers.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003891 SmallVector<SDOperand, 8> OutChains;
Chris Lattnered0110b2006-10-27 21:36:01 +00003892 SDOperand Root = getRoot();
Chris Lattner5fe1f542006-03-31 02:06:56 +00003893 for (unsigned i = 0; i != NE; ++i) {
3894 SDOperand Elt = DAG.getNode(ISD::VEXTRACT_VECTOR_ELT, PTyElementVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00003895 Op, DAG.getConstant(i, TLI.getPointerTy()));
Chris Lattner5fe1f542006-03-31 02:06:56 +00003896 if (PTyElementVT == PTyLegalElementVT) {
3897 // Elements are legal.
3898 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
3899 } else if (PTyLegalElementVT > PTyElementVT) {
3900 // Elements are promoted.
3901 if (MVT::isFloatingPoint(PTyLegalElementVT))
3902 Elt = DAG.getNode(ISD::FP_EXTEND, PTyLegalElementVT, Elt);
3903 else
3904 Elt = DAG.getNode(ISD::ANY_EXTEND, PTyLegalElementVT, Elt);
3905 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
3906 } else {
3907 // Elements are expanded.
3908 // The src value is expanded into multiple registers.
3909 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00003910 Elt, DAG.getConstant(0, TLI.getPointerTy()));
Chris Lattner5fe1f542006-03-31 02:06:56 +00003911 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00003912 Elt, DAG.getConstant(1, TLI.getPointerTy()));
Chris Lattner5fe1f542006-03-31 02:06:56 +00003913 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Lo));
3914 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Hi));
3915 }
Chris Lattner672a42d2006-03-21 19:20:37 +00003916 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003917 return DAG.getNode(ISD::TokenFactor, MVT::Other,
3918 &OutChains[0], OutChains.size());
Evan Cheng22cf8992006-12-13 20:57:08 +00003919 } else if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote) {
Chris Lattner33182322005-08-16 21:55:35 +00003920 // The src value is promoted to the register.
Chris Lattnerba28c272005-08-17 06:06:25 +00003921 if (MVT::isFloatingPoint(SrcVT))
3922 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
3923 else
Chris Lattnera66403d2005-09-02 00:19:37 +00003924 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
Chris Lattnered0110b2006-10-27 21:36:01 +00003925 return DAG.getCopyToReg(getRoot(), Reg, Op);
Chris Lattner33182322005-08-16 21:55:35 +00003926 } else {
Evan Cheng22cf8992006-12-13 20:57:08 +00003927 DestVT = TLI.getTypeToExpandTo(SrcVT);
3928 unsigned NumVals = TLI.getNumElements(SrcVT);
3929 if (NumVals == 1)
3930 return DAG.getCopyToReg(getRoot(), Reg,
3931 DAG.getNode(ISD::BIT_CONVERT, DestVT, Op));
3932 assert(NumVals == 2 && "1 to 4 (and more) expansion not implemented!");
Chris Lattner33182322005-08-16 21:55:35 +00003933 // The src value is expanded into multiple registers.
3934 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00003935 Op, DAG.getConstant(0, TLI.getPointerTy()));
Chris Lattner33182322005-08-16 21:55:35 +00003936 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00003937 Op, DAG.getConstant(1, TLI.getPointerTy()));
Chris Lattnered0110b2006-10-27 21:36:01 +00003938 Op = DAG.getCopyToReg(getRoot(), Reg, Lo);
Chris Lattner33182322005-08-16 21:55:35 +00003939 return DAG.getCopyToReg(Op, Reg+1, Hi);
3940 }
Chris Lattner7a60d912005-01-07 07:47:53 +00003941}
3942
Chris Lattner16f64df2005-01-17 17:15:02 +00003943void SelectionDAGISel::
3944LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
3945 std::vector<SDOperand> &UnorderedChains) {
3946 // If this is the entry block, emit arguments.
3947 Function &F = *BB->getParent();
Chris Lattnere3c2cf42005-01-17 17:55:19 +00003948 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattner6871b232005-10-30 19:42:35 +00003949 SDOperand OldRoot = SDL.DAG.getRoot();
3950 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner16f64df2005-01-17 17:15:02 +00003951
Chris Lattner6871b232005-10-30 19:42:35 +00003952 unsigned a = 0;
3953 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
3954 AI != E; ++AI, ++a)
3955 if (!AI->use_empty()) {
3956 SDL.setValue(AI, Args[a]);
Evan Cheng3784f3c52006-04-27 08:29:42 +00003957
Chris Lattner6871b232005-10-30 19:42:35 +00003958 // If this argument is live outside of the entry block, insert a copy from
3959 // whereever we got it to the vreg that other BB's will reference it as.
3960 if (FuncInfo.ValueMap.count(AI)) {
3961 SDOperand Copy =
Chris Lattnered0110b2006-10-27 21:36:01 +00003962 SDL.CopyValueToVirtualRegister(AI, FuncInfo.ValueMap[AI]);
Chris Lattner6871b232005-10-30 19:42:35 +00003963 UnorderedChains.push_back(Copy);
3964 }
Chris Lattnere3c2cf42005-01-17 17:55:19 +00003965 }
Chris Lattner6871b232005-10-30 19:42:35 +00003966
Chris Lattner6871b232005-10-30 19:42:35 +00003967 // Finally, if the target has anything special to do, allow it to do so.
Chris Lattner957cb672006-05-16 06:10:58 +00003968 // FIXME: this should insert code into the DAG!
Chris Lattner6871b232005-10-30 19:42:35 +00003969 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner16f64df2005-01-17 17:15:02 +00003970}
3971
Chris Lattner7a60d912005-01-07 07:47:53 +00003972void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
3973 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
Nate Begemaned728c12006-03-27 01:32:24 +00003974 FunctionLoweringInfo &FuncInfo) {
Chris Lattner7a60d912005-01-07 07:47:53 +00003975 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattner718b5c22005-01-13 17:59:43 +00003976
3977 std::vector<SDOperand> UnorderedChains;
Misha Brukman835702a2005-04-21 22:36:52 +00003978
Chris Lattner6871b232005-10-30 19:42:35 +00003979 // Lower any arguments needed in this block if this is the entry block.
3980 if (LLVMBB == &LLVMBB->getParent()->front())
3981 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner7a60d912005-01-07 07:47:53 +00003982
3983 BB = FuncInfo.MBBMap[LLVMBB];
3984 SDL.setCurrentBasicBlock(BB);
3985
3986 // Lower all of the non-terminator instructions.
3987 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
3988 I != E; ++I)
3989 SDL.visit(*I);
Nate Begemaned728c12006-03-27 01:32:24 +00003990
Chris Lattner7a60d912005-01-07 07:47:53 +00003991 // Ensure that all instructions which are used outside of their defining
3992 // blocks are available as virtual registers.
3993 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Chris Lattner613f79f2005-01-11 22:03:46 +00003994 if (!I->use_empty() && !isa<PHINode>(I)) {
Chris Lattnera2c5d912005-01-09 01:16:24 +00003995 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner7a60d912005-01-07 07:47:53 +00003996 if (VMI != FuncInfo.ValueMap.end())
Chris Lattner718b5c22005-01-13 17:59:43 +00003997 UnorderedChains.push_back(
Chris Lattnered0110b2006-10-27 21:36:01 +00003998 SDL.CopyValueToVirtualRegister(I, VMI->second));
Chris Lattner7a60d912005-01-07 07:47:53 +00003999 }
4000
4001 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
4002 // ensure constants are generated when needed. Remember the virtual registers
4003 // that need to be added to the Machine PHI nodes as input. We cannot just
4004 // directly add them, because expansion might result in multiple MBB's for one
4005 // BB. As such, the start of the BB might correspond to a different MBB than
4006 // the end.
Misha Brukman835702a2005-04-21 22:36:52 +00004007 //
Chris Lattner84a03502006-10-27 23:50:33 +00004008 TerminatorInst *TI = LLVMBB->getTerminator();
Chris Lattner7a60d912005-01-07 07:47:53 +00004009
4010 // Emit constants only once even if used by multiple PHI nodes.
4011 std::map<Constant*, unsigned> ConstantsOut;
Chris Lattner707339a52006-09-07 01:59:34 +00004012
Chris Lattner84a03502006-10-27 23:50:33 +00004013 // Vector bool would be better, but vector<bool> is really slow.
4014 std::vector<unsigned char> SuccsHandled;
4015 if (TI->getNumSuccessors())
4016 SuccsHandled.resize(BB->getParent()->getNumBlockIDs());
4017
Chris Lattner7a60d912005-01-07 07:47:53 +00004018 // Check successor nodes PHI nodes that expect a constant to be available from
4019 // this block.
Chris Lattner7a60d912005-01-07 07:47:53 +00004020 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
4021 BasicBlock *SuccBB = TI->getSuccessor(succ);
Chris Lattner707339a52006-09-07 01:59:34 +00004022 if (!isa<PHINode>(SuccBB->begin())) continue;
Chris Lattner84a03502006-10-27 23:50:33 +00004023 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
Chris Lattner707339a52006-09-07 01:59:34 +00004024
Chris Lattner84a03502006-10-27 23:50:33 +00004025 // If this terminator has multiple identical successors (common for
4026 // switches), only handle each succ once.
4027 unsigned SuccMBBNo = SuccMBB->getNumber();
4028 if (SuccsHandled[SuccMBBNo]) continue;
4029 SuccsHandled[SuccMBBNo] = true;
4030
4031 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
Chris Lattner7a60d912005-01-07 07:47:53 +00004032 PHINode *PN;
4033
4034 // At this point we know that there is a 1-1 correspondence between LLVM PHI
4035 // nodes and Machine PHI nodes, but the incoming operands have not been
4036 // emitted yet.
4037 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner84a03502006-10-27 23:50:33 +00004038 (PN = dyn_cast<PHINode>(I)); ++I) {
4039 // Ignore dead phi's.
4040 if (PN->use_empty()) continue;
4041
4042 unsigned Reg;
4043 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
Chris Lattner90f42382006-11-29 01:12:32 +00004044
Chris Lattner84a03502006-10-27 23:50:33 +00004045 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
4046 unsigned &RegOut = ConstantsOut[C];
4047 if (RegOut == 0) {
4048 RegOut = FuncInfo.CreateRegForValue(C);
4049 UnorderedChains.push_back(
4050 SDL.CopyValueToVirtualRegister(C, RegOut));
Chris Lattner7a60d912005-01-07 07:47:53 +00004051 }
Chris Lattner84a03502006-10-27 23:50:33 +00004052 Reg = RegOut;
4053 } else {
4054 Reg = FuncInfo.ValueMap[PHIOp];
4055 if (Reg == 0) {
4056 assert(isa<AllocaInst>(PHIOp) &&
4057 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
4058 "Didn't codegen value into a register!??");
4059 Reg = FuncInfo.CreateRegForValue(PHIOp);
4060 UnorderedChains.push_back(
4061 SDL.CopyValueToVirtualRegister(PHIOp, Reg));
Chris Lattnerba380352006-03-31 02:12:18 +00004062 }
Chris Lattner7a60d912005-01-07 07:47:53 +00004063 }
Chris Lattner84a03502006-10-27 23:50:33 +00004064
4065 // Remember that this register needs to added to the machine PHI node as
4066 // the input for this MBB.
4067 MVT::ValueType VT = TLI.getValueType(PN->getType());
4068 unsigned NumElements;
4069 if (VT != MVT::Vector)
4070 NumElements = TLI.getNumElements(VT);
4071 else {
4072 MVT::ValueType VT1,VT2;
4073 NumElements =
4074 TLI.getPackedTypeBreakdown(cast<PackedType>(PN->getType()),
4075 VT1, VT2);
4076 }
4077 for (unsigned i = 0, e = NumElements; i != e; ++i)
4078 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
4079 }
Chris Lattner7a60d912005-01-07 07:47:53 +00004080 }
4081 ConstantsOut.clear();
4082
Chris Lattner718b5c22005-01-13 17:59:43 +00004083 // Turn all of the unordered chains into one factored node.
Chris Lattner24516842005-01-13 19:53:14 +00004084 if (!UnorderedChains.empty()) {
Chris Lattnerb7cad902005-11-09 05:03:03 +00004085 SDOperand Root = SDL.getRoot();
4086 if (Root.getOpcode() != ISD::EntryToken) {
4087 unsigned i = 0, e = UnorderedChains.size();
4088 for (; i != e; ++i) {
4089 assert(UnorderedChains[i].Val->getNumOperands() > 1);
4090 if (UnorderedChains[i].Val->getOperand(0) == Root)
4091 break; // Don't add the root if we already indirectly depend on it.
4092 }
4093
4094 if (i == e)
4095 UnorderedChains.push_back(Root);
4096 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +00004097 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
4098 &UnorderedChains[0], UnorderedChains.size()));
Chris Lattner718b5c22005-01-13 17:59:43 +00004099 }
4100
Chris Lattner7a60d912005-01-07 07:47:53 +00004101 // Lower the terminator after the copies are emitted.
4102 SDL.visit(*LLVMBB->getTerminator());
Chris Lattner4108bb02005-01-17 19:43:36 +00004103
Nate Begemaned728c12006-03-27 01:32:24 +00004104 // Copy over any CaseBlock records that may now exist due to SwitchInst
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004105 // lowering, as well as any jump table information.
Nate Begemaned728c12006-03-27 01:32:24 +00004106 SwitchCases.clear();
4107 SwitchCases = SDL.SwitchCases;
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004108 JT = SDL.JT;
Nate Begemaned728c12006-03-27 01:32:24 +00004109
Chris Lattner4108bb02005-01-17 19:43:36 +00004110 // Make sure the root of the DAG is up-to-date.
4111 DAG.setRoot(SDL.getRoot());
Chris Lattner7a60d912005-01-07 07:47:53 +00004112}
4113
Nate Begemaned728c12006-03-27 01:32:24 +00004114void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
Jim Laskeydcb2b832006-10-16 20:52:31 +00004115 // Get alias analysis for load/store combining.
4116 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
4117
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00004118 // Run the DAG combiner in pre-legalize mode.
Jim Laskeydcb2b832006-10-16 20:52:31 +00004119 DAG.Combine(false, AA);
Nate Begeman007c6502005-09-07 00:15:36 +00004120
Bill Wendling22e978a2006-12-07 20:04:42 +00004121 DOUT << "Lowered selection DAG:\n";
Chris Lattner7a60d912005-01-07 07:47:53 +00004122 DEBUG(DAG.dump());
Nate Begemaned728c12006-03-27 01:32:24 +00004123
Chris Lattner7a60d912005-01-07 07:47:53 +00004124 // Second step, hack on the DAG until it only uses operations and types that
4125 // the target supports.
Chris Lattnerffcb0ae2005-01-23 04:36:26 +00004126 DAG.Legalize();
Nate Begemaned728c12006-03-27 01:32:24 +00004127
Bill Wendling22e978a2006-12-07 20:04:42 +00004128 DOUT << "Legalized selection DAG:\n";
Chris Lattner7a60d912005-01-07 07:47:53 +00004129 DEBUG(DAG.dump());
Nate Begemaned728c12006-03-27 01:32:24 +00004130
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00004131 // Run the DAG combiner in post-legalize mode.
Jim Laskeydcb2b832006-10-16 20:52:31 +00004132 DAG.Combine(true, AA);
Nate Begeman007c6502005-09-07 00:15:36 +00004133
Evan Cheng739a6a42006-01-21 02:32:06 +00004134 if (ViewISelDAGs) DAG.viewGraph();
Evan Cheng51ab4492006-04-28 02:09:19 +00004135
Chris Lattner5ca31d92005-03-30 01:10:47 +00004136 // Third, instruction select all of the operations to machine code, adding the
4137 // code to the MachineBasicBlock.
Chris Lattner7a60d912005-01-07 07:47:53 +00004138 InstructionSelectBasicBlock(DAG);
Nate Begemaned728c12006-03-27 01:32:24 +00004139
Bill Wendling22e978a2006-12-07 20:04:42 +00004140 DOUT << "Selected machine code:\n";
Chris Lattner7a60d912005-01-07 07:47:53 +00004141 DEBUG(BB->dump());
Nate Begemaned728c12006-03-27 01:32:24 +00004142}
Chris Lattner7a60d912005-01-07 07:47:53 +00004143
Nate Begemaned728c12006-03-27 01:32:24 +00004144void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
4145 FunctionLoweringInfo &FuncInfo) {
4146 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
4147 {
4148 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
4149 CurDAG = &DAG;
4150
4151 // First step, lower LLVM code to some DAG. This DAG may use operations and
4152 // types that are not supported by the target.
4153 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
4154
4155 // Second step, emit the lowered DAG as machine code.
4156 CodeGenAndEmitDAG(DAG);
4157 }
4158
Chris Lattner5ca31d92005-03-30 01:10:47 +00004159 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner7a60d912005-01-07 07:47:53 +00004160 // PHI nodes in successors.
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004161 if (SwitchCases.empty() && JT.Reg == 0) {
Nate Begemaned728c12006-03-27 01:32:24 +00004162 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4163 MachineInstr *PHI = PHINodesToUpdate[i].first;
4164 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4165 "This is not a machine PHI node that we are updating!");
Chris Lattneraf23f9b2006-09-05 02:31:13 +00004166 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
Nate Begemaned728c12006-03-27 01:32:24 +00004167 PHI->addMachineBasicBlockOperand(BB);
4168 }
4169 return;
Chris Lattner7a60d912005-01-07 07:47:53 +00004170 }
Nate Begemaned728c12006-03-27 01:32:24 +00004171
Nate Begeman866b4b42006-04-23 06:26:20 +00004172 // If the JumpTable record is filled in, then we need to emit a jump table.
4173 // Updating the PHI nodes is tricky in this case, since we need to determine
4174 // whether the PHI is a successor of the range check MBB or the jump table MBB
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004175 if (JT.Reg) {
4176 assert(SwitchCases.empty() && "Cannot have jump table and lowered switch");
4177 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
4178 CurDAG = &SDAG;
4179 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
Nate Begeman866b4b42006-04-23 06:26:20 +00004180 MachineBasicBlock *RangeBB = BB;
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004181 // Set the current basic block to the mbb we wish to insert the code into
4182 BB = JT.MBB;
4183 SDL.setCurrentBasicBlock(BB);
4184 // Emit the code
4185 SDL.visitJumpTable(JT);
4186 SDAG.setRoot(SDL.getRoot());
4187 CodeGenAndEmitDAG(SDAG);
4188 // Update PHI Nodes
4189 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
4190 MachineInstr *PHI = PHINodesToUpdate[pi].first;
4191 MachineBasicBlock *PHIBB = PHI->getParent();
4192 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4193 "This is not a machine PHI node that we are updating!");
Nate Begemandf488392006-05-03 03:48:02 +00004194 if (PHIBB == JT.Default) {
Chris Lattneraf23f9b2006-09-05 02:31:13 +00004195 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Nate Begemandf488392006-05-03 03:48:02 +00004196 PHI->addMachineBasicBlockOperand(RangeBB);
4197 }
4198 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
Chris Lattneraf23f9b2006-09-05 02:31:13 +00004199 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Nate Begemandf488392006-05-03 03:48:02 +00004200 PHI->addMachineBasicBlockOperand(BB);
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004201 }
4202 }
4203 return;
4204 }
4205
Chris Lattner76a7bc82006-10-22 23:00:53 +00004206 // If the switch block involved a branch to one of the actual successors, we
4207 // need to update PHI nodes in that block.
4208 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4209 MachineInstr *PHI = PHINodesToUpdate[i].first;
4210 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4211 "This is not a machine PHI node that we are updating!");
4212 if (BB->isSuccessor(PHI->getParent())) {
4213 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
4214 PHI->addMachineBasicBlockOperand(BB);
4215 }
4216 }
4217
Nate Begemaned728c12006-03-27 01:32:24 +00004218 // If we generated any switch lowering information, build and codegen any
4219 // additional DAGs necessary.
Chris Lattner707339a52006-09-07 01:59:34 +00004220 for (unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
Nate Begemaned728c12006-03-27 01:32:24 +00004221 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
4222 CurDAG = &SDAG;
4223 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
Chris Lattner707339a52006-09-07 01:59:34 +00004224
Nate Begemaned728c12006-03-27 01:32:24 +00004225 // Set the current basic block to the mbb we wish to insert the code into
4226 BB = SwitchCases[i].ThisBB;
4227 SDL.setCurrentBasicBlock(BB);
Chris Lattner707339a52006-09-07 01:59:34 +00004228
Nate Begemaned728c12006-03-27 01:32:24 +00004229 // Emit the code
4230 SDL.visitSwitchCase(SwitchCases[i]);
4231 SDAG.setRoot(SDL.getRoot());
4232 CodeGenAndEmitDAG(SDAG);
Chris Lattner707339a52006-09-07 01:59:34 +00004233
4234 // Handle any PHI nodes in successors of this chunk, as if we were coming
4235 // from the original BB before switch expansion. Note that PHI nodes can
4236 // occur multiple times in PHINodesToUpdate. We have to be very careful to
4237 // handle them the right number of times.
Chris Lattner963ddad2006-10-24 17:57:59 +00004238 while ((BB = SwitchCases[i].TrueBB)) { // Handle LHS and RHS.
Chris Lattner707339a52006-09-07 01:59:34 +00004239 for (MachineBasicBlock::iterator Phi = BB->begin();
4240 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
4241 // This value for this PHI node is recorded in PHINodesToUpdate, get it.
4242 for (unsigned pn = 0; ; ++pn) {
4243 assert(pn != PHINodesToUpdate.size() && "Didn't find PHI entry!");
4244 if (PHINodesToUpdate[pn].first == Phi) {
4245 Phi->addRegOperand(PHINodesToUpdate[pn].second, false);
4246 Phi->addMachineBasicBlockOperand(SwitchCases[i].ThisBB);
4247 break;
4248 }
4249 }
Nate Begemaned728c12006-03-27 01:32:24 +00004250 }
Chris Lattner707339a52006-09-07 01:59:34 +00004251
4252 // Don't process RHS if same block as LHS.
Chris Lattner963ddad2006-10-24 17:57:59 +00004253 if (BB == SwitchCases[i].FalseBB)
4254 SwitchCases[i].FalseBB = 0;
Chris Lattner707339a52006-09-07 01:59:34 +00004255
4256 // If we haven't handled the RHS, do so now. Otherwise, we're done.
Chris Lattner61bcf912006-10-24 18:07:37 +00004257 SwitchCases[i].TrueBB = SwitchCases[i].FalseBB;
Chris Lattner963ddad2006-10-24 17:57:59 +00004258 SwitchCases[i].FalseBB = 0;
Nate Begemaned728c12006-03-27 01:32:24 +00004259 }
Chris Lattner963ddad2006-10-24 17:57:59 +00004260 assert(SwitchCases[i].TrueBB == 0 && SwitchCases[i].FalseBB == 0);
Chris Lattner5ca31d92005-03-30 01:10:47 +00004261 }
Chris Lattner7a60d912005-01-07 07:47:53 +00004262}
Evan Cheng739a6a42006-01-21 02:32:06 +00004263
Jim Laskey95eda5b2006-08-01 14:21:23 +00004264
Evan Cheng739a6a42006-01-21 02:32:06 +00004265//===----------------------------------------------------------------------===//
4266/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
4267/// target node in the graph.
4268void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
4269 if (ViewSchedDAGs) DAG.viewGraph();
Evan Chengc1e1d972006-01-23 07:01:07 +00004270
Jim Laskey29e635d2006-08-02 12:30:23 +00004271 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
Jim Laskey95eda5b2006-08-01 14:21:23 +00004272
4273 if (!Ctor) {
Jim Laskey29e635d2006-08-02 12:30:23 +00004274 Ctor = ISHeuristic;
Jim Laskey17c67ef2006-08-01 19:14:14 +00004275 RegisterScheduler::setDefault(Ctor);
Evan Chengc1e1d972006-01-23 07:01:07 +00004276 }
Jim Laskey95eda5b2006-08-01 14:21:23 +00004277
Jim Laskey03593f72006-08-01 18:29:48 +00004278 ScheduleDAG *SL = Ctor(this, &DAG, BB);
Chris Lattnere23928c2006-01-21 19:12:11 +00004279 BB = SL->Run();
Evan Chengf9adce92006-02-04 06:49:00 +00004280 delete SL;
Evan Cheng739a6a42006-01-21 02:32:06 +00004281}
Chris Lattnerdcf785b2006-02-24 02:13:54 +00004282
Chris Lattner47639db2006-03-06 00:22:00 +00004283
Jim Laskey03593f72006-08-01 18:29:48 +00004284HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
4285 return new HazardRecognizer();
4286}
4287
Chris Lattner6df34962006-10-11 03:58:02 +00004288//===----------------------------------------------------------------------===//
4289// Helper functions used by the generated instruction selector.
4290//===----------------------------------------------------------------------===//
4291// Calls to these methods are generated by tblgen.
4292
4293/// CheckAndMask - The isel is trying to match something like (and X, 255). If
4294/// the dag combiner simplified the 255, we still want to match. RHS is the
4295/// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
4296/// specified in the .td file (e.g. 255).
4297bool SelectionDAGISel::CheckAndMask(SDOperand LHS, ConstantSDNode *RHS,
4298 int64_t DesiredMaskS) {
4299 uint64_t ActualMask = RHS->getValue();
4300 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4301
4302 // If the actual mask exactly matches, success!
4303 if (ActualMask == DesiredMask)
4304 return true;
4305
4306 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4307 if (ActualMask & ~DesiredMask)
4308 return false;
4309
4310 // Otherwise, the DAG Combiner may have proven that the value coming in is
4311 // either already zero or is not demanded. Check for known zero input bits.
4312 uint64_t NeededMask = DesiredMask & ~ActualMask;
4313 if (getTargetLowering().MaskedValueIsZero(LHS, NeededMask))
4314 return true;
4315
4316 // TODO: check to see if missing bits are just not demanded.
4317
4318 // Otherwise, this pattern doesn't match.
4319 return false;
4320}
4321
4322/// CheckOrMask - The isel is trying to match something like (or X, 255). If
4323/// the dag combiner simplified the 255, we still want to match. RHS is the
4324/// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
4325/// specified in the .td file (e.g. 255).
4326bool SelectionDAGISel::CheckOrMask(SDOperand LHS, ConstantSDNode *RHS,
4327 int64_t DesiredMaskS) {
4328 uint64_t ActualMask = RHS->getValue();
4329 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4330
4331 // If the actual mask exactly matches, success!
4332 if (ActualMask == DesiredMask)
4333 return true;
4334
4335 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4336 if (ActualMask & ~DesiredMask)
4337 return false;
4338
4339 // Otherwise, the DAG Combiner may have proven that the value coming in is
4340 // either already zero or is not demanded. Check for known zero input bits.
4341 uint64_t NeededMask = DesiredMask & ~ActualMask;
4342
4343 uint64_t KnownZero, KnownOne;
4344 getTargetLowering().ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
4345
4346 // If all the missing bits in the or are already known to be set, match!
4347 if ((NeededMask & KnownOne) == NeededMask)
4348 return true;
4349
4350 // TODO: check to see if missing bits are just not demanded.
4351
4352 // Otherwise, this pattern doesn't match.
4353 return false;
4354}
4355
Jim Laskey03593f72006-08-01 18:29:48 +00004356
Chris Lattnerdcf785b2006-02-24 02:13:54 +00004357/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
4358/// by tblgen. Others should not call it.
4359void SelectionDAGISel::
4360SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
4361 std::vector<SDOperand> InOps;
4362 std::swap(InOps, Ops);
4363
4364 Ops.push_back(InOps[0]); // input chain.
4365 Ops.push_back(InOps[1]); // input asm string.
4366
Chris Lattnerdcf785b2006-02-24 02:13:54 +00004367 unsigned i = 2, e = InOps.size();
4368 if (InOps[e-1].getValueType() == MVT::Flag)
4369 --e; // Don't process a flag operand if it is here.
4370
4371 while (i != e) {
4372 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
4373 if ((Flags & 7) != 4 /*MEM*/) {
4374 // Just skip over this operand, copying the operands verbatim.
4375 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
4376 i += (Flags >> 3) + 1;
4377 } else {
4378 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
4379 // Otherwise, this is a memory operand. Ask the target to select it.
4380 std::vector<SDOperand> SelOps;
4381 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
Bill Wendling22e978a2006-12-07 20:04:42 +00004382 cerr << "Could not match memory address. Inline asm failure!\n";
Chris Lattnerdcf785b2006-02-24 02:13:54 +00004383 exit(1);
4384 }
4385
4386 // Add this to the output node.
Chris Lattner9bd5ed62006-12-16 21:14:48 +00004387 Ops.push_back(DAG.getTargetConstant(4/*MEM*/ | (SelOps.size() << 3),
4388 MVT::i32));
Chris Lattnerdcf785b2006-02-24 02:13:54 +00004389 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
4390 i += 2;
4391 }
4392 }
4393
4394 // Add the flag input back if present.
4395 if (e != InOps.size())
4396 Ops.push_back(InOps.back());
4397}