blob: fc8e560aaf4f33c0ebc8913e741b4871361ffdf9 [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"
15#include "llvm/CodeGen/SelectionDAGISel.h"
Evan Cheng739a6a42006-01-21 02:32:06 +000016#include "llvm/CodeGen/ScheduleDAG.h"
Chris Lattner2e77db62005-05-13 18:50:42 +000017#include "llvm/CallingConv.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000018#include "llvm/Constants.h"
19#include "llvm/DerivedTypes.h"
20#include "llvm/Function.h"
Chris Lattner435b4022005-11-29 06:21:05 +000021#include "llvm/GlobalVariable.h"
Chris Lattner476e67b2006-01-26 22:24:51 +000022#include "llvm/InlineAsm.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000023#include "llvm/Instructions.h"
24#include "llvm/Intrinsics.h"
Chris Lattnerf2b62f32005-11-16 07:22:30 +000025#include "llvm/CodeGen/IntrinsicLowering.h"
Jim Laskey219d5592006-01-04 22:28:25 +000026#include "llvm/CodeGen/MachineDebugInfo.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000027#include "llvm/CodeGen/MachineFunction.h"
28#include "llvm/CodeGen/MachineFrameInfo.h"
29#include "llvm/CodeGen/MachineInstrBuilder.h"
30#include "llvm/CodeGen/SelectionDAG.h"
31#include "llvm/CodeGen/SSARegMap.h"
Chris Lattnerd4382f02005-09-13 19:30:54 +000032#include "llvm/Target/MRegisterInfo.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000033#include "llvm/Target/TargetData.h"
34#include "llvm/Target/TargetFrameInfo.h"
35#include "llvm/Target/TargetInstrInfo.h"
36#include "llvm/Target/TargetLowering.h"
37#include "llvm/Target/TargetMachine.h"
Chris Lattnerc9950c12005-08-17 06:37:43 +000038#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattnere05a4612005-01-12 03:41:21 +000039#include "llvm/Support/CommandLine.h"
Chris Lattner43535a12005-11-09 04:45:33 +000040#include "llvm/Support/MathExtras.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000041#include "llvm/Support/Debug.h"
42#include <map>
Chris Lattner1558fc62006-02-01 18:59:47 +000043#include <set>
Chris Lattner7a60d912005-01-07 07:47:53 +000044#include <iostream>
Jeff Cohen83c22e02006-02-24 02:52:40 +000045#include <algorithm>
Chris Lattner7a60d912005-01-07 07:47:53 +000046using namespace llvm;
47
Chris Lattner975f5c92005-09-01 18:44:10 +000048#ifndef NDEBUG
Chris Lattnere05a4612005-01-12 03:41:21 +000049static cl::opt<bool>
Evan Cheng739a6a42006-01-21 02:32:06 +000050ViewISelDAGs("view-isel-dags", cl::Hidden,
51 cl::desc("Pop up a window to show isel dags as they are selected"));
52static cl::opt<bool>
53ViewSchedDAGs("view-sched-dags", cl::Hidden,
54 cl::desc("Pop up a window to show sched dags as they are processed"));
Chris Lattnere05a4612005-01-12 03:41:21 +000055#else
Evan Cheng739a6a42006-01-21 02:32:06 +000056static const bool ViewISelDAGs = 0;
57static const bool ViewSchedDAGs = 0;
Chris Lattnere05a4612005-01-12 03:41:21 +000058#endif
59
Chris Lattner5255d042006-03-10 07:49:12 +000060// Scheduling heuristics
61enum SchedHeuristics {
62 defaultScheduling, // Let the target specify its preference.
63 noScheduling, // No scheduling, emit breadth first sequence.
64 simpleScheduling, // Two pass, min. critical path, max. utilization.
65 simpleNoItinScheduling, // Same as above exact using generic latency.
66 listSchedulingBURR, // Bottom up reg reduction list scheduling.
67 listSchedulingTD // Top-down list scheduler.
68};
69
Evan Chengc1e1d972006-01-23 07:01:07 +000070namespace {
71 cl::opt<SchedHeuristics>
72 ISHeuristic(
73 "sched",
74 cl::desc("Choose scheduling style"),
Evan Chenga6eff8a2006-01-25 09:12:57 +000075 cl::init(defaultScheduling),
Evan Chengc1e1d972006-01-23 07:01:07 +000076 cl::values(
Evan Chenga6eff8a2006-01-25 09:12:57 +000077 clEnumValN(defaultScheduling, "default",
78 "Target preferred scheduling style"),
Evan Chengc1e1d972006-01-23 07:01:07 +000079 clEnumValN(noScheduling, "none",
Jim Laskeyb8566fa2006-01-23 13:34:04 +000080 "No scheduling: breadth first sequencing"),
Evan Chengc1e1d972006-01-23 07:01:07 +000081 clEnumValN(simpleScheduling, "simple",
82 "Simple two pass scheduling: minimize critical path "
83 "and maximize processor utilization"),
84 clEnumValN(simpleNoItinScheduling, "simple-noitin",
85 "Simple two pass scheduling: Same as simple "
86 "except using generic latency"),
Evan Chenga6eff8a2006-01-25 09:12:57 +000087 clEnumValN(listSchedulingBURR, "list-burr",
Evan Cheng31272342006-01-23 08:26:10 +000088 "Bottom up register reduction list scheduling"),
Chris Lattner47639db2006-03-06 00:22:00 +000089 clEnumValN(listSchedulingTD, "list-td",
90 "Top-down list scheduler"),
Evan Chengc1e1d972006-01-23 07:01:07 +000091 clEnumValEnd));
92} // namespace
93
Chris Lattner6f87d182006-02-22 22:37:12 +000094namespace {
95 /// RegsForValue - This struct represents the physical registers that a
96 /// particular value is assigned and the type information about the value.
97 /// This is needed because values can be promoted into larger registers and
98 /// expanded into multiple smaller registers than the value.
99 struct RegsForValue {
100 /// Regs - This list hold the register (for legal and promoted values)
101 /// or register set (for expanded values) that the value should be assigned
102 /// to.
103 std::vector<unsigned> Regs;
104
105 /// RegVT - The value type of each register.
106 ///
107 MVT::ValueType RegVT;
108
109 /// ValueVT - The value type of the LLVM value, which may be promoted from
110 /// RegVT or made from merging the two expanded parts.
111 MVT::ValueType ValueVT;
112
113 RegsForValue() : RegVT(MVT::Other), ValueVT(MVT::Other) {}
114
115 RegsForValue(unsigned Reg, MVT::ValueType regvt, MVT::ValueType valuevt)
116 : RegVT(regvt), ValueVT(valuevt) {
117 Regs.push_back(Reg);
118 }
119 RegsForValue(const std::vector<unsigned> &regs,
120 MVT::ValueType regvt, MVT::ValueType valuevt)
121 : Regs(regs), RegVT(regvt), ValueVT(valuevt) {
122 }
123
124 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
125 /// this value and returns the result as a ValueVT value. This uses
126 /// Chain/Flag as the input and updates them for the output Chain/Flag.
127 SDOperand getCopyFromRegs(SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +0000128 SDOperand &Chain, SDOperand &Flag) const;
Chris Lattner571d9642006-02-23 19:21:04 +0000129
130 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
131 /// specified value into the registers specified by this object. This uses
132 /// Chain/Flag as the input and updates them for the output Chain/Flag.
133 void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +0000134 SDOperand &Chain, SDOperand &Flag) const;
Chris Lattner571d9642006-02-23 19:21:04 +0000135
136 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
137 /// operand list. This adds the code marker and includes the number of
138 /// values added into it.
139 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +0000140 std::vector<SDOperand> &Ops) const;
Chris Lattner6f87d182006-02-22 22:37:12 +0000141 };
142}
Evan Chengc1e1d972006-01-23 07:01:07 +0000143
Chris Lattner7a60d912005-01-07 07:47:53 +0000144namespace llvm {
145 //===--------------------------------------------------------------------===//
146 /// FunctionLoweringInfo - This contains information that is global to a
147 /// function that is used when lowering a region of the function.
Chris Lattnerd0061952005-01-08 19:52:31 +0000148 class FunctionLoweringInfo {
149 public:
Chris Lattner7a60d912005-01-07 07:47:53 +0000150 TargetLowering &TLI;
151 Function &Fn;
152 MachineFunction &MF;
153 SSARegMap *RegMap;
154
155 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
156
157 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
158 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
159
160 /// ValueMap - Since we emit code for the function a basic block at a time,
161 /// we must remember which virtual registers hold the values for
162 /// cross-basic-block values.
163 std::map<const Value*, unsigned> ValueMap;
164
165 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
166 /// the entry block. This allows the allocas to be efficiently referenced
167 /// anywhere in the function.
168 std::map<const AllocaInst*, int> StaticAllocaMap;
169
170 unsigned MakeReg(MVT::ValueType VT) {
171 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
172 }
Misha Brukman835702a2005-04-21 22:36:52 +0000173
Chris Lattner7a60d912005-01-07 07:47:53 +0000174 unsigned CreateRegForValue(const Value *V) {
175 MVT::ValueType VT = TLI.getValueType(V->getType());
176 // The common case is that we will only create one register for this
177 // value. If we have that case, create and return the virtual register.
178 unsigned NV = TLI.getNumElements(VT);
Chris Lattnera8d34fb2005-01-16 00:37:38 +0000179 if (NV == 1) {
180 // If we are promoting this value, pick the next largest supported type.
Chris Lattnerd58384f2005-01-16 01:11:19 +0000181 return MakeReg(TLI.getTypeToTransformTo(VT));
Chris Lattnera8d34fb2005-01-16 00:37:38 +0000182 }
Misha Brukman835702a2005-04-21 22:36:52 +0000183
Chris Lattner7a60d912005-01-07 07:47:53 +0000184 // If this value is represented with multiple target registers, make sure
Chris Lattner6f87d182006-02-22 22:37:12 +0000185 // to create enough consecutive registers of the right (smaller) type.
Chris Lattner7a60d912005-01-07 07:47:53 +0000186 unsigned NT = VT-1; // Find the type to use.
187 while (TLI.getNumElements((MVT::ValueType)NT) != 1)
188 --NT;
Misha Brukman835702a2005-04-21 22:36:52 +0000189
Chris Lattner7a60d912005-01-07 07:47:53 +0000190 unsigned R = MakeReg((MVT::ValueType)NT);
191 for (unsigned i = 1; i != NV; ++i)
192 MakeReg((MVT::ValueType)NT);
193 return R;
194 }
Misha Brukman835702a2005-04-21 22:36:52 +0000195
Chris Lattner7a60d912005-01-07 07:47:53 +0000196 unsigned InitializeRegForValue(const Value *V) {
197 unsigned &R = ValueMap[V];
198 assert(R == 0 && "Already initialized this value register!");
199 return R = CreateRegForValue(V);
200 }
201 };
202}
203
204/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
205/// PHI nodes or outside of the basic block that defines it.
206static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
207 if (isa<PHINode>(I)) return true;
208 BasicBlock *BB = I->getParent();
209 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
210 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI))
211 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
216/// entry block, return true.
217static bool isOnlyUsedInEntryBlock(Argument *A) {
218 BasicBlock *Entry = A->getParent()->begin();
219 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
220 if (cast<Instruction>(*UI)->getParent() != Entry)
221 return false; // Use not in entry block.
222 return true;
223}
224
Chris Lattner7a60d912005-01-07 07:47:53 +0000225FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
Misha Brukman835702a2005-04-21 22:36:52 +0000226 Function &fn, MachineFunction &mf)
Chris Lattner7a60d912005-01-07 07:47:53 +0000227 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
228
Chris Lattner6871b232005-10-30 19:42:35 +0000229 // Create a vreg for each argument register that is not dead and is used
230 // outside of the entry block for the function.
231 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
232 AI != E; ++AI)
233 if (!isOnlyUsedInEntryBlock(AI))
234 InitializeRegForValue(AI);
235
Chris Lattner7a60d912005-01-07 07:47:53 +0000236 // Initialize the mapping of values to registers. This is only set up for
237 // instruction values that are used outside of the block that defines
238 // them.
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000239 Function::iterator BB = Fn.begin(), EB = Fn.end();
Chris Lattner7a60d912005-01-07 07:47:53 +0000240 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
241 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
242 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(AI->getArraySize())) {
243 const Type *Ty = AI->getAllocatedType();
244 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
Nate Begeman3ee3e692005-11-06 09:00:38 +0000245 unsigned Align =
246 std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
247 AI->getAlignment());
Chris Lattnercbefe722005-05-13 23:14:17 +0000248
249 // If the alignment of the value is smaller than the size of the value,
250 // and if the size of the value is particularly small (<= 8 bytes),
251 // round up to the size of the value for potentially better performance.
252 //
253 // FIXME: This could be made better with a preferred alignment hook in
254 // TargetData. It serves primarily to 8-byte align doubles for X86.
255 if (Align < TySize && TySize <= 8) Align = TySize;
Chris Lattner8396a302005-10-18 22:11:42 +0000256 TySize *= CUI->getValue(); // Get total allocated size.
Chris Lattner0a71a9a2005-10-18 22:14:06 +0000257 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
Chris Lattner7a60d912005-01-07 07:47:53 +0000258 StaticAllocaMap[AI] =
Chris Lattnerd0061952005-01-08 19:52:31 +0000259 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
Chris Lattner7a60d912005-01-07 07:47:53 +0000260 }
261
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000262 for (; BB != EB; ++BB)
263 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner7a60d912005-01-07 07:47:53 +0000264 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
265 if (!isa<AllocaInst>(I) ||
266 !StaticAllocaMap.count(cast<AllocaInst>(I)))
267 InitializeRegForValue(I);
268
269 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
270 // also creates the initial PHI MachineInstrs, though none of the input
271 // operands are populated.
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000272 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000273 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
274 MBBMap[BB] = MBB;
275 MF.getBasicBlockList().push_back(MBB);
276
277 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
278 // appropriate.
279 PHINode *PN;
280 for (BasicBlock::iterator I = BB->begin();
Chris Lattner8ea875f2005-01-07 21:34:19 +0000281 (PN = dyn_cast<PHINode>(I)); ++I)
282 if (!PN->use_empty()) {
283 unsigned NumElements =
284 TLI.getNumElements(TLI.getValueType(PN->getType()));
285 unsigned PHIReg = ValueMap[PN];
286 assert(PHIReg &&"PHI node does not have an assigned virtual register!");
287 for (unsigned i = 0; i != NumElements; ++i)
288 BuildMI(MBB, TargetInstrInfo::PHI, PN->getNumOperands(), PHIReg+i);
289 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000290 }
291}
292
293
294
295//===----------------------------------------------------------------------===//
296/// SelectionDAGLowering - This is the common target-independent lowering
297/// implementation that is parameterized by a TargetLowering object.
298/// Also, targets can overload any lowering method.
299///
300namespace llvm {
301class SelectionDAGLowering {
302 MachineBasicBlock *CurMBB;
303
304 std::map<const Value*, SDOperand> NodeMap;
305
Chris Lattner4d9651c2005-01-17 22:19:26 +0000306 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
307 /// them up and then emit token factor nodes when possible. This allows us to
308 /// get simple disambiguation between loads without worrying about alias
309 /// analysis.
310 std::vector<SDOperand> PendingLoads;
311
Chris Lattner7a60d912005-01-07 07:47:53 +0000312public:
313 // TLI - This is information that describes the available target features we
314 // need for lowering. This indicates when operations are unavailable,
315 // implemented with a libcall, etc.
316 TargetLowering &TLI;
317 SelectionDAG &DAG;
318 const TargetData &TD;
319
320 /// FuncInfo - Information about the function as a whole.
321 ///
322 FunctionLoweringInfo &FuncInfo;
323
324 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Misha Brukman835702a2005-04-21 22:36:52 +0000325 FunctionLoweringInfo &funcinfo)
Chris Lattner7a60d912005-01-07 07:47:53 +0000326 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
327 FuncInfo(funcinfo) {
328 }
329
Chris Lattner4108bb02005-01-17 19:43:36 +0000330 /// getRoot - Return the current virtual root of the Selection DAG.
331 ///
332 SDOperand getRoot() {
Chris Lattner4d9651c2005-01-17 22:19:26 +0000333 if (PendingLoads.empty())
334 return DAG.getRoot();
Misha Brukman835702a2005-04-21 22:36:52 +0000335
Chris Lattner4d9651c2005-01-17 22:19:26 +0000336 if (PendingLoads.size() == 1) {
337 SDOperand Root = PendingLoads[0];
338 DAG.setRoot(Root);
339 PendingLoads.clear();
340 return Root;
341 }
342
343 // Otherwise, we have to make a token factor node.
344 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other, PendingLoads);
345 PendingLoads.clear();
346 DAG.setRoot(Root);
347 return Root;
Chris Lattner4108bb02005-01-17 19:43:36 +0000348 }
349
Chris Lattner7a60d912005-01-07 07:47:53 +0000350 void visit(Instruction &I) { visit(I.getOpcode(), I); }
351
352 void visit(unsigned Opcode, User &I) {
353 switch (Opcode) {
354 default: assert(0 && "Unknown instruction type encountered!");
355 abort();
356 // Build the switch statement using the Instruction.def file.
357#define HANDLE_INST(NUM, OPCODE, CLASS) \
358 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
359#include "llvm/Instruction.def"
360 }
361 }
362
363 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
364
365
366 SDOperand getIntPtrConstant(uint64_t Val) {
367 return DAG.getConstant(Val, TLI.getPointerTy());
368 }
369
370 SDOperand getValue(const Value *V) {
371 SDOperand &N = NodeMap[V];
372 if (N.Val) return N;
373
Nate Begeman41b1cdc2005-12-06 06:18:55 +0000374 const Type *VTy = V->getType();
375 MVT::ValueType VT = TLI.getValueType(VTy);
Chris Lattner7a60d912005-01-07 07:47:53 +0000376 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V)))
377 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
378 visit(CE->getOpcode(), *CE);
379 assert(N.Val && "visit didn't populate the ValueMap!");
380 return N;
381 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
382 return N = DAG.getGlobalAddress(GV, VT);
383 } else if (isa<ConstantPointerNull>(C)) {
384 return N = DAG.getConstant(0, TLI.getPointerTy());
385 } else if (isa<UndefValue>(C)) {
Nate Begemanaf1c0f72005-04-12 23:12:17 +0000386 return N = DAG.getNode(ISD::UNDEF, VT);
Chris Lattner7a60d912005-01-07 07:47:53 +0000387 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
388 return N = DAG.getConstantFP(CFP->getValue(), VT);
Nate Begeman41b1cdc2005-12-06 06:18:55 +0000389 } else if (const PackedType *PTy = dyn_cast<PackedType>(VTy)) {
390 unsigned NumElements = PTy->getNumElements();
391 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
392 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
393
394 // Now that we know the number and type of the elements, push a
395 // Constant or ConstantFP node onto the ops list for each element of
396 // the packed constant.
397 std::vector<SDOperand> Ops;
Chris Lattner803a5752005-12-21 02:43:26 +0000398 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(C)) {
399 if (MVT::isFloatingPoint(PVT)) {
400 for (unsigned i = 0; i != NumElements; ++i) {
401 const ConstantFP *El = cast<ConstantFP>(CP->getOperand(i));
402 Ops.push_back(DAG.getConstantFP(El->getValue(), PVT));
403 }
404 } else {
405 for (unsigned i = 0; i != NumElements; ++i) {
406 const ConstantIntegral *El =
407 cast<ConstantIntegral>(CP->getOperand(i));
408 Ops.push_back(DAG.getConstant(El->getRawValue(), PVT));
409 }
410 }
411 } else {
412 assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
413 SDOperand Op;
Nate Begeman41b1cdc2005-12-06 06:18:55 +0000414 if (MVT::isFloatingPoint(PVT))
Chris Lattner803a5752005-12-21 02:43:26 +0000415 Op = DAG.getConstantFP(0, PVT);
Nate Begeman41b1cdc2005-12-06 06:18:55 +0000416 else
Chris Lattner803a5752005-12-21 02:43:26 +0000417 Op = DAG.getConstant(0, PVT);
418 Ops.assign(NumElements, Op);
Nate Begeman41b1cdc2005-12-06 06:18:55 +0000419 }
Chris Lattner803a5752005-12-21 02:43:26 +0000420
Nate Begeman41b1cdc2005-12-06 06:18:55 +0000421 // Handle the case where we have a 1-element vector, in which
422 // case we want to immediately turn it into a scalar constant.
Nate Begemanae89d862005-12-07 19:48:11 +0000423 if (Ops.size() == 1) {
Nate Begeman41b1cdc2005-12-06 06:18:55 +0000424 return N = Ops[0];
Nate Begemanae89d862005-12-07 19:48:11 +0000425 } else if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
426 return N = DAG.getNode(ISD::ConstantVec, TVT, Ops);
427 } else {
428 // If the packed type isn't legal, then create a ConstantVec node with
429 // generic Vector type instead.
Evan Chengb97aab42006-03-01 01:09:54 +0000430 SDOperand Num = DAG.getConstant(NumElements, MVT::i32);
431 SDOperand Typ = DAG.getValueType(PVT);
432 Ops.insert(Ops.begin(), Typ);
433 Ops.insert(Ops.begin(), Num);
434 return N = DAG.getNode(ISD::VConstant, MVT::Vector, Ops);
Nate Begemanae89d862005-12-07 19:48:11 +0000435 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000436 } else {
437 // Canonicalize all constant ints to be unsigned.
438 return N = DAG.getConstant(cast<ConstantIntegral>(C)->getRawValue(),VT);
439 }
440
441 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
442 std::map<const AllocaInst*, int>::iterator SI =
443 FuncInfo.StaticAllocaMap.find(AI);
444 if (SI != FuncInfo.StaticAllocaMap.end())
445 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
446 }
447
448 std::map<const Value*, unsigned>::const_iterator VMI =
449 FuncInfo.ValueMap.find(V);
450 assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
Chris Lattner209f5852005-01-16 02:23:07 +0000451
Chris Lattner33182322005-08-16 21:55:35 +0000452 unsigned InReg = VMI->second;
453
454 // If this type is not legal, make it so now.
455 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
456
457 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
458 if (DestVT < VT) {
459 // Source must be expanded. This input value is actually coming from the
460 // register pair VMI->second and VMI->second+1.
461 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
462 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
463 } else {
464 if (DestVT > VT) { // Promotion case
465 if (MVT::isFloatingPoint(VT))
466 N = DAG.getNode(ISD::FP_ROUND, VT, N);
467 else
468 N = DAG.getNode(ISD::TRUNCATE, VT, N);
469 }
470 }
471
472 return N;
Chris Lattner7a60d912005-01-07 07:47:53 +0000473 }
474
475 const SDOperand &setValue(const Value *V, SDOperand NewN) {
476 SDOperand &N = NodeMap[V];
477 assert(N.Val == 0 && "Already set a value for this node!");
478 return N = NewN;
479 }
Chris Lattner1558fc62006-02-01 18:59:47 +0000480
Chris Lattner6f87d182006-02-22 22:37:12 +0000481 RegsForValue GetRegistersForValue(const std::string &ConstrCode,
482 MVT::ValueType VT,
483 bool OutReg, bool InReg,
484 std::set<unsigned> &OutputRegs,
485 std::set<unsigned> &InputRegs);
486
Chris Lattner7a60d912005-01-07 07:47:53 +0000487 // Terminator instructions.
488 void visitRet(ReturnInst &I);
489 void visitBr(BranchInst &I);
490 void visitUnreachable(UnreachableInst &I) { /* noop */ }
491
492 // These all get lowered before this pass.
Robert Bocchino2c966e72006-01-10 19:04:57 +0000493 void visitExtractElement(ExtractElementInst &I) { assert(0 && "TODO"); }
Robert Bocchino03e95af2006-01-17 20:06:42 +0000494 void visitInsertElement(InsertElementInst &I) { assert(0 && "TODO"); }
Chris Lattner7a60d912005-01-07 07:47:53 +0000495 void visitSwitch(SwitchInst &I) { assert(0 && "TODO"); }
496 void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
497 void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
498
499 //
Nate Begemanb2e089c2005-11-19 00:36:38 +0000500 void visitBinary(User &I, unsigned IntOp, unsigned FPOp, unsigned VecOp);
Nate Begeman127321b2005-11-18 07:42:56 +0000501 void visitShift(User &I, unsigned Opcode);
Nate Begemanb2e089c2005-11-19 00:36:38 +0000502 void visitAdd(User &I) {
503 visitBinary(I, ISD::ADD, ISD::FADD, ISD::VADD);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000504 }
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000505 void visitSub(User &I);
Nate Begemanb2e089c2005-11-19 00:36:38 +0000506 void visitMul(User &I) {
507 visitBinary(I, ISD::MUL, ISD::FMUL, ISD::VMUL);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000508 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000509 void visitDiv(User &I) {
Chris Lattner6f3b5772005-09-28 22:28:18 +0000510 const Type *Ty = I.getType();
Evan Cheng3bf916d2006-03-03 07:01:07 +0000511 visitBinary(I,
512 Ty->isSigned() ? ISD::SDIV : ISD::UDIV, ISD::FDIV,
513 Ty->isSigned() ? ISD::VSDIV : ISD::VUDIV);
Chris Lattner7a60d912005-01-07 07:47:53 +0000514 }
515 void visitRem(User &I) {
Chris Lattner6f3b5772005-09-28 22:28:18 +0000516 const Type *Ty = I.getType();
Nate Begemanb2e089c2005-11-19 00:36:38 +0000517 visitBinary(I, Ty->isSigned() ? ISD::SREM : ISD::UREM, ISD::FREM, 0);
Chris Lattner7a60d912005-01-07 07:47:53 +0000518 }
Evan Cheng3bf916d2006-03-03 07:01:07 +0000519 void visitAnd(User &I) { visitBinary(I, ISD::AND, 0, ISD::VAND); }
520 void visitOr (User &I) { visitBinary(I, ISD::OR, 0, ISD::VOR); }
521 void visitXor(User &I) { visitBinary(I, ISD::XOR, 0, ISD::VXOR); }
Nate Begeman127321b2005-11-18 07:42:56 +0000522 void visitShl(User &I) { visitShift(I, ISD::SHL); }
523 void visitShr(User &I) {
524 visitShift(I, I.getType()->isUnsigned() ? ISD::SRL : ISD::SRA);
Chris Lattner7a60d912005-01-07 07:47:53 +0000525 }
526
527 void visitSetCC(User &I, ISD::CondCode SignedOpc, ISD::CondCode UnsignedOpc);
528 void visitSetEQ(User &I) { visitSetCC(I, ISD::SETEQ, ISD::SETEQ); }
529 void visitSetNE(User &I) { visitSetCC(I, ISD::SETNE, ISD::SETNE); }
530 void visitSetLE(User &I) { visitSetCC(I, ISD::SETLE, ISD::SETULE); }
531 void visitSetGE(User &I) { visitSetCC(I, ISD::SETGE, ISD::SETUGE); }
532 void visitSetLT(User &I) { visitSetCC(I, ISD::SETLT, ISD::SETULT); }
533 void visitSetGT(User &I) { visitSetCC(I, ISD::SETGT, ISD::SETUGT); }
534
535 void visitGetElementPtr(User &I);
536 void visitCast(User &I);
537 void visitSelect(User &I);
538 //
539
540 void visitMalloc(MallocInst &I);
541 void visitFree(FreeInst &I);
542 void visitAlloca(AllocaInst &I);
543 void visitLoad(LoadInst &I);
544 void visitStore(StoreInst &I);
545 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
546 void visitCall(CallInst &I);
Chris Lattner476e67b2006-01-26 22:24:51 +0000547 void visitInlineAsm(CallInst &I);
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000548 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattner7a60d912005-01-07 07:47:53 +0000549
Chris Lattner7a60d912005-01-07 07:47:53 +0000550 void visitVAStart(CallInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000551 void visitVAArg(VAArgInst &I);
552 void visitVAEnd(CallInst &I);
553 void visitVACopy(CallInst &I);
Chris Lattner58cfd792005-01-09 00:00:49 +0000554 void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
Chris Lattner7a60d912005-01-07 07:47:53 +0000555
Chris Lattner875def92005-01-11 05:56:49 +0000556 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner7a60d912005-01-07 07:47:53 +0000557
558 void visitUserOp1(Instruction &I) {
559 assert(0 && "UserOp1 should not exist at instruction selection time!");
560 abort();
561 }
562 void visitUserOp2(Instruction &I) {
563 assert(0 && "UserOp2 should not exist at instruction selection time!");
564 abort();
565 }
566};
567} // end namespace llvm
568
569void SelectionDAGLowering::visitRet(ReturnInst &I) {
570 if (I.getNumOperands() == 0) {
Chris Lattner4108bb02005-01-17 19:43:36 +0000571 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
Chris Lattner7a60d912005-01-07 07:47:53 +0000572 return;
573 }
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000574 std::vector<SDOperand> NewValues;
575 NewValues.push_back(getRoot());
576 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
577 SDOperand RetOp = getValue(I.getOperand(i));
578
579 // If this is an integer return value, we need to promote it ourselves to
580 // the full width of a register, since LegalizeOp will use ANY_EXTEND rather
581 // than sign/zero.
582 if (MVT::isInteger(RetOp.getValueType()) &&
583 RetOp.getValueType() < MVT::i64) {
584 MVT::ValueType TmpVT;
585 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
586 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
587 else
588 TmpVT = MVT::i32;
Chris Lattner7a60d912005-01-07 07:47:53 +0000589
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000590 if (I.getOperand(i)->getType()->isSigned())
591 RetOp = DAG.getNode(ISD::SIGN_EXTEND, TmpVT, RetOp);
592 else
593 RetOp = DAG.getNode(ISD::ZERO_EXTEND, TmpVT, RetOp);
594 }
595 NewValues.push_back(RetOp);
Chris Lattner7a60d912005-01-07 07:47:53 +0000596 }
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000597 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, NewValues));
Chris Lattner7a60d912005-01-07 07:47:53 +0000598}
599
600void SelectionDAGLowering::visitBr(BranchInst &I) {
601 // Update machine-CFG edges.
602 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner7a60d912005-01-07 07:47:53 +0000603
604 // Figure out which block is immediately after the current one.
605 MachineBasicBlock *NextBlock = 0;
606 MachineFunction::iterator BBI = CurMBB;
607 if (++BBI != CurMBB->getParent()->end())
608 NextBlock = BBI;
609
610 if (I.isUnconditional()) {
611 // If this is not a fall-through branch, emit the branch.
612 if (Succ0MBB != NextBlock)
Chris Lattner4108bb02005-01-17 19:43:36 +0000613 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000614 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000615 } else {
616 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattner7a60d912005-01-07 07:47:53 +0000617
618 SDOperand Cond = getValue(I.getCondition());
Chris Lattner7a60d912005-01-07 07:47:53 +0000619 if (Succ1MBB == NextBlock) {
620 // If the condition is false, fall through. This means we should branch
621 // if the condition is true to Succ #0.
Chris Lattner4108bb02005-01-17 19:43:36 +0000622 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000623 Cond, DAG.getBasicBlock(Succ0MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000624 } else if (Succ0MBB == NextBlock) {
625 // If the condition is true, fall through. This means we should branch if
626 // the condition is false to Succ #1. Invert the condition first.
627 SDOperand True = DAG.getConstant(1, Cond.getValueType());
628 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
Chris Lattner4108bb02005-01-17 19:43:36 +0000629 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000630 Cond, DAG.getBasicBlock(Succ1MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000631 } else {
Chris Lattner8a98c7f2005-04-09 03:30:29 +0000632 std::vector<SDOperand> Ops;
633 Ops.push_back(getRoot());
Evan Cheng42c01c82006-02-16 08:27:56 +0000634 // If the false case is the current basic block, then this is a self
635 // loop. We do not want to emit "Loop: ... brcond Out; br Loop", as it
636 // adds an extra instruction in the loop. Instead, invert the
637 // condition and emit "Loop: ... br!cond Loop; br Out.
638 if (CurMBB == Succ1MBB) {
639 std::swap(Succ0MBB, Succ1MBB);
640 SDOperand True = DAG.getConstant(1, Cond.getValueType());
641 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
642 }
Chris Lattner8a98c7f2005-04-09 03:30:29 +0000643 Ops.push_back(Cond);
644 Ops.push_back(DAG.getBasicBlock(Succ0MBB));
645 Ops.push_back(DAG.getBasicBlock(Succ1MBB));
646 DAG.setRoot(DAG.getNode(ISD::BRCONDTWOWAY, MVT::Other, Ops));
Chris Lattner7a60d912005-01-07 07:47:53 +0000647 }
648 }
649}
650
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000651void SelectionDAGLowering::visitSub(User &I) {
652 // -0.0 - X --> fneg
Chris Lattner6f3b5772005-09-28 22:28:18 +0000653 if (I.getType()->isFloatingPoint()) {
654 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
655 if (CFP->isExactlyValue(-0.0)) {
656 SDOperand Op2 = getValue(I.getOperand(1));
657 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
658 return;
659 }
Chris Lattner6f3b5772005-09-28 22:28:18 +0000660 }
Nate Begemanb2e089c2005-11-19 00:36:38 +0000661 visitBinary(I, ISD::SUB, ISD::FSUB, ISD::VSUB);
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000662}
663
Nate Begemanb2e089c2005-11-19 00:36:38 +0000664void SelectionDAGLowering::visitBinary(User &I, unsigned IntOp, unsigned FPOp,
665 unsigned VecOp) {
666 const Type *Ty = I.getType();
Chris Lattner7a60d912005-01-07 07:47:53 +0000667 SDOperand Op1 = getValue(I.getOperand(0));
668 SDOperand Op2 = getValue(I.getOperand(1));
Chris Lattner96c26752005-01-19 22:31:21 +0000669
Chris Lattner19baba62005-11-19 18:40:42 +0000670 if (Ty->isIntegral()) {
Nate Begemanb2e089c2005-11-19 00:36:38 +0000671 setValue(&I, DAG.getNode(IntOp, Op1.getValueType(), Op1, Op2));
672 } else if (Ty->isFloatingPoint()) {
673 setValue(&I, DAG.getNode(FPOp, Op1.getValueType(), Op1, Op2));
674 } else {
675 const PackedType *PTy = cast<PackedType>(Ty);
Nate Begeman07890bb2005-11-22 01:29:36 +0000676 unsigned NumElements = PTy->getNumElements();
677 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Nate Begeman1064d6e2005-11-30 08:22:07 +0000678 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
Nate Begeman07890bb2005-11-22 01:29:36 +0000679
680 // Immediately scalarize packed types containing only one element, so that
Nate Begeman1064d6e2005-11-30 08:22:07 +0000681 // the Legalize pass does not have to deal with them. Similarly, if the
682 // abstract vector is going to turn into one that the target natively
683 // supports, generate that type now so that Legalize doesn't have to deal
684 // with that either. These steps ensure that Legalize only has to handle
685 // vector types in its Expand case.
686 unsigned Opc = MVT::isFloatingPoint(PVT) ? FPOp : IntOp;
Nate Begeman07890bb2005-11-22 01:29:36 +0000687 if (NumElements == 1) {
Nate Begeman07890bb2005-11-22 01:29:36 +0000688 setValue(&I, DAG.getNode(Opc, PVT, Op1, Op2));
Evan Chengb97aab42006-03-01 01:09:54 +0000689 } else if (TVT != MVT::Other &&
690 TLI.isTypeLegal(TVT) && TLI.isOperationLegal(Opc, TVT)) {
Nate Begeman1064d6e2005-11-30 08:22:07 +0000691 setValue(&I, DAG.getNode(Opc, TVT, Op1, Op2));
Nate Begeman07890bb2005-11-22 01:29:36 +0000692 } else {
693 SDOperand Num = DAG.getConstant(NumElements, MVT::i32);
694 SDOperand Typ = DAG.getValueType(PVT);
Evan Chengb97aab42006-03-01 01:09:54 +0000695 setValue(&I, DAG.getNode(VecOp, MVT::Vector, Num, Typ, Op1, Op2));
Nate Begeman07890bb2005-11-22 01:29:36 +0000696 }
Nate Begemanb2e089c2005-11-19 00:36:38 +0000697 }
Nate Begeman127321b2005-11-18 07:42:56 +0000698}
Chris Lattner96c26752005-01-19 22:31:21 +0000699
Nate Begeman127321b2005-11-18 07:42:56 +0000700void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
701 SDOperand Op1 = getValue(I.getOperand(0));
702 SDOperand Op2 = getValue(I.getOperand(1));
703
704 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
705
Chris Lattner7a60d912005-01-07 07:47:53 +0000706 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
707}
708
709void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
710 ISD::CondCode UnsignedOpcode) {
711 SDOperand Op1 = getValue(I.getOperand(0));
712 SDOperand Op2 = getValue(I.getOperand(1));
713 ISD::CondCode Opcode = SignedOpcode;
714 if (I.getOperand(0)->getType()->isUnsigned())
715 Opcode = UnsignedOpcode;
Chris Lattnerd47675e2005-08-09 20:20:18 +0000716 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
Chris Lattner7a60d912005-01-07 07:47:53 +0000717}
718
719void SelectionDAGLowering::visitSelect(User &I) {
720 SDOperand Cond = getValue(I.getOperand(0));
721 SDOperand TrueVal = getValue(I.getOperand(1));
722 SDOperand FalseVal = getValue(I.getOperand(2));
723 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
724 TrueVal, FalseVal));
725}
726
727void SelectionDAGLowering::visitCast(User &I) {
728 SDOperand N = getValue(I.getOperand(0));
729 MVT::ValueType SrcTy = TLI.getValueType(I.getOperand(0)->getType());
730 MVT::ValueType DestTy = TLI.getValueType(I.getType());
731
732 if (N.getValueType() == DestTy) {
733 setValue(&I, N); // noop cast.
Chris Lattner2d8b55c2005-05-09 22:17:13 +0000734 } else if (DestTy == MVT::i1) {
735 // Cast to bool is a comparison against zero, not truncation to zero.
736 SDOperand Zero = isInteger(SrcTy) ? DAG.getConstant(0, N.getValueType()) :
737 DAG.getConstantFP(0.0, N.getValueType());
Chris Lattnerd47675e2005-08-09 20:20:18 +0000738 setValue(&I, DAG.getSetCC(MVT::i1, N, Zero, ISD::SETNE));
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000739 } else if (isInteger(SrcTy)) {
740 if (isInteger(DestTy)) { // Int -> Int cast
741 if (DestTy < SrcTy) // Truncating cast?
742 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestTy, N));
743 else if (I.getOperand(0)->getType()->isSigned())
744 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestTy, N));
745 else
746 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestTy, N));
747 } else { // Int -> FP cast
748 if (I.getOperand(0)->getType()->isSigned())
749 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestTy, N));
750 else
751 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestTy, N));
752 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000753 } else {
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000754 assert(isFloatingPoint(SrcTy) && "Unknown value type!");
755 if (isFloatingPoint(DestTy)) { // FP -> FP cast
756 if (DestTy < SrcTy) // Rounding cast?
757 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestTy, N));
758 else
759 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestTy, N));
760 } else { // FP -> Int cast.
761 if (I.getType()->isSigned())
762 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestTy, N));
763 else
764 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestTy, N));
765 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000766 }
767}
768
769void SelectionDAGLowering::visitGetElementPtr(User &I) {
770 SDOperand N = getValue(I.getOperand(0));
771 const Type *Ty = I.getOperand(0)->getType();
772 const Type *UIntPtrTy = TD.getIntPtrType();
773
774 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
775 OI != E; ++OI) {
776 Value *Idx = *OI;
Chris Lattner35397782005-12-05 07:10:48 +0000777 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000778 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
779 if (Field) {
780 // N = N + Offset
781 uint64_t Offset = TD.getStructLayout(StTy)->MemberOffsets[Field];
782 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Misha Brukman77451162005-04-22 04:01:18 +0000783 getIntPtrConstant(Offset));
Chris Lattner7a60d912005-01-07 07:47:53 +0000784 }
785 Ty = StTy->getElementType(Field);
786 } else {
787 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner19a83992005-01-07 21:56:57 +0000788
Chris Lattner43535a12005-11-09 04:45:33 +0000789 // If this is a constant subscript, handle it quickly.
790 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
791 if (CI->getRawValue() == 0) continue;
Chris Lattner19a83992005-01-07 21:56:57 +0000792
Chris Lattner43535a12005-11-09 04:45:33 +0000793 uint64_t Offs;
794 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
795 Offs = (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
796 else
797 Offs = TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
798 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
799 continue;
Chris Lattner7a60d912005-01-07 07:47:53 +0000800 }
Chris Lattner43535a12005-11-09 04:45:33 +0000801
802 // N = N + Idx * ElementSize;
803 uint64_t ElementSize = TD.getTypeSize(Ty);
804 SDOperand IdxN = getValue(Idx);
805
806 // If the index is smaller or larger than intptr_t, truncate or extend
807 // it.
808 if (IdxN.getValueType() < N.getValueType()) {
809 if (Idx->getType()->isSigned())
810 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
811 else
812 IdxN = DAG.getNode(ISD::ZERO_EXTEND, N.getValueType(), IdxN);
813 } else if (IdxN.getValueType() > N.getValueType())
814 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
815
816 // If this is a multiply by a power of two, turn it into a shl
817 // immediately. This is a very common case.
818 if (isPowerOf2_64(ElementSize)) {
819 unsigned Amt = Log2_64(ElementSize);
820 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner41fd6d52005-11-09 16:50:40 +0000821 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner43535a12005-11-09 04:45:33 +0000822 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
823 continue;
824 }
825
826 SDOperand Scale = getIntPtrConstant(ElementSize);
827 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
828 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner7a60d912005-01-07 07:47:53 +0000829 }
830 }
831 setValue(&I, N);
832}
833
834void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
835 // If this is a fixed sized alloca in the entry block of the function,
836 // allocate it statically on the stack.
837 if (FuncInfo.StaticAllocaMap.count(&I))
838 return; // getValue will auto-populate this.
839
840 const Type *Ty = I.getAllocatedType();
841 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
Nate Begeman3ee3e692005-11-06 09:00:38 +0000842 unsigned Align = std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
843 I.getAlignment());
Chris Lattner7a60d912005-01-07 07:47:53 +0000844
845 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattnereccb73d2005-01-22 23:04:37 +0000846 MVT::ValueType IntPtr = TLI.getPointerTy();
847 if (IntPtr < AllocSize.getValueType())
848 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
849 else if (IntPtr > AllocSize.getValueType())
850 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner7a60d912005-01-07 07:47:53 +0000851
Chris Lattnereccb73d2005-01-22 23:04:37 +0000852 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner7a60d912005-01-07 07:47:53 +0000853 getIntPtrConstant(TySize));
854
855 // Handle alignment. If the requested alignment is less than or equal to the
856 // stack alignment, ignore it and round the size of the allocation up to the
857 // stack alignment size. If the size is greater than the stack alignment, we
858 // note this in the DYNAMIC_STACKALLOC node.
859 unsigned StackAlign =
860 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
861 if (Align <= StackAlign) {
862 Align = 0;
863 // Add SA-1 to the size.
864 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
865 getIntPtrConstant(StackAlign-1));
866 // Mask out the low bits for alignment purposes.
867 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
868 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
869 }
870
Chris Lattner96c262e2005-05-14 07:29:57 +0000871 std::vector<MVT::ValueType> VTs;
872 VTs.push_back(AllocSize.getValueType());
873 VTs.push_back(MVT::Other);
874 std::vector<SDOperand> Ops;
875 Ops.push_back(getRoot());
876 Ops.push_back(AllocSize);
877 Ops.push_back(getIntPtrConstant(Align));
878 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, Ops);
Chris Lattner7a60d912005-01-07 07:47:53 +0000879 DAG.setRoot(setValue(&I, DSA).getValue(1));
880
881 // Inform the Frame Information that we have just allocated a variable-sized
882 // object.
883 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
884}
885
Chris Lattner7a60d912005-01-07 07:47:53 +0000886void SelectionDAGLowering::visitLoad(LoadInst &I) {
887 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukman835702a2005-04-21 22:36:52 +0000888
Chris Lattner4d9651c2005-01-17 22:19:26 +0000889 SDOperand Root;
890 if (I.isVolatile())
891 Root = getRoot();
892 else {
893 // Do not serialize non-volatile loads against each other.
894 Root = DAG.getRoot();
895 }
Nate Begemanb2e089c2005-11-19 00:36:38 +0000896
897 const Type *Ty = I.getType();
898 SDOperand L;
899
Nate Begeman41b1cdc2005-12-06 06:18:55 +0000900 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
Nate Begeman07890bb2005-11-22 01:29:36 +0000901 unsigned NumElements = PTy->getNumElements();
902 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Nate Begeman1064d6e2005-11-30 08:22:07 +0000903 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
Nate Begeman07890bb2005-11-22 01:29:36 +0000904
905 // Immediately scalarize packed types containing only one element, so that
906 // the Legalize pass does not have to deal with them.
907 if (NumElements == 1) {
908 L = DAG.getLoad(PVT, Root, Ptr, DAG.getSrcValue(I.getOperand(0)));
Evan Chengb97aab42006-03-01 01:09:54 +0000909 } else if (TVT != MVT::Other &&
910 TLI.isTypeLegal(TVT) && TLI.isOperationLegal(ISD::LOAD, TVT)) {
Nate Begeman1064d6e2005-11-30 08:22:07 +0000911 L = DAG.getLoad(TVT, Root, Ptr, DAG.getSrcValue(I.getOperand(0)));
Nate Begeman07890bb2005-11-22 01:29:36 +0000912 } else {
913 L = DAG.getVecLoad(NumElements, PVT, Root, Ptr,
914 DAG.getSrcValue(I.getOperand(0)));
915 }
Nate Begemanb2e089c2005-11-19 00:36:38 +0000916 } else {
917 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr,
918 DAG.getSrcValue(I.getOperand(0)));
919 }
Chris Lattner4d9651c2005-01-17 22:19:26 +0000920 setValue(&I, L);
921
922 if (I.isVolatile())
923 DAG.setRoot(L.getValue(1));
924 else
925 PendingLoads.push_back(L.getValue(1));
Chris Lattner7a60d912005-01-07 07:47:53 +0000926}
927
928
929void SelectionDAGLowering::visitStore(StoreInst &I) {
930 Value *SrcV = I.getOperand(0);
931 SDOperand Src = getValue(SrcV);
932 SDOperand Ptr = getValue(I.getOperand(1));
Chris Lattnerf5675a02005-05-09 04:08:33 +0000933 DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, getRoot(), Src, Ptr,
Andrew Lenharth2edc1882005-06-29 18:54:02 +0000934 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner7a60d912005-01-07 07:47:53 +0000935}
936
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000937/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
938/// we want to emit this as a call to a named external function, return the name
939/// otherwise lower it and return null.
940const char *
941SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
942 switch (Intrinsic) {
943 case Intrinsic::vastart: visitVAStart(I); return 0;
944 case Intrinsic::vaend: visitVAEnd(I); return 0;
945 case Intrinsic::vacopy: visitVACopy(I); return 0;
946 case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return 0;
947 case Intrinsic::frameaddress: visitFrameReturnAddress(I, true); return 0;
948 case Intrinsic::setjmp:
949 return "_setjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
950 break;
951 case Intrinsic::longjmp:
952 return "_longjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
953 break;
Chris Lattner093c1592006-03-03 00:00:25 +0000954 case Intrinsic::memcpy_i32:
955 case Intrinsic::memcpy_i64:
956 visitMemIntrinsic(I, ISD::MEMCPY);
957 return 0;
958 case Intrinsic::memset_i32:
959 case Intrinsic::memset_i64:
960 visitMemIntrinsic(I, ISD::MEMSET);
961 return 0;
962 case Intrinsic::memmove_i32:
963 case Intrinsic::memmove_i64:
964 visitMemIntrinsic(I, ISD::MEMMOVE);
965 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000966
Chris Lattner5d4e61d2005-12-13 17:40:33 +0000967 case Intrinsic::dbg_stoppoint: {
Chris Lattnerf2b62f32005-11-16 07:22:30 +0000968 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
969 return "llvm_debugger_stop";
Chris Lattner435b4022005-11-29 06:21:05 +0000970
Jim Laskey5995d012006-02-11 01:01:30 +0000971 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
972 if (DebugInfo && DebugInfo->Verify(I.getOperand(4))) {
973 std::vector<SDOperand> Ops;
Chris Lattner435b4022005-11-29 06:21:05 +0000974
Jim Laskey5995d012006-02-11 01:01:30 +0000975 // Input Chain
976 Ops.push_back(getRoot());
977
978 // line number
979 Ops.push_back(getValue(I.getOperand(2)));
980
981 // column
982 Ops.push_back(getValue(I.getOperand(3)));
Chris Lattner435b4022005-11-29 06:21:05 +0000983
Jim Laskey390c63e2006-02-13 12:50:39 +0000984 DebugInfoDesc *DD = DebugInfo->getDescFor(I.getOperand(4));
Jim Laskey5995d012006-02-11 01:01:30 +0000985 assert(DD && "Not a debug information descriptor");
986 CompileUnitDesc *CompileUnit = dyn_cast<CompileUnitDesc>(DD);
987 assert(CompileUnit && "Not a compile unit");
988 Ops.push_back(DAG.getString(CompileUnit->getFileName()));
989 Ops.push_back(DAG.getString(CompileUnit->getDirectory()));
990
991 if (Ops.size() == 5) // Found filename/workingdir.
992 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops));
Chris Lattner5d4e61d2005-12-13 17:40:33 +0000993 }
994
Chris Lattner8782b782005-12-03 18:50:48 +0000995 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
Chris Lattnerf2b62f32005-11-16 07:22:30 +0000996 return 0;
Chris Lattner435b4022005-11-29 06:21:05 +0000997 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000998 case Intrinsic::dbg_region_start:
Chris Lattnerf2b62f32005-11-16 07:22:30 +0000999 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
1000 return "llvm_dbg_region_start";
1001 if (I.getType() != Type::VoidTy)
1002 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
1003 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001004 case Intrinsic::dbg_region_end:
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001005 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
1006 return "llvm_dbg_region_end";
1007 if (I.getType() != Type::VoidTy)
1008 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
1009 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001010 case Intrinsic::dbg_func_start:
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001011 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
1012 return "llvm_dbg_subprogram";
1013 if (I.getType() != Type::VoidTy)
1014 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
1015 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001016
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001017 case Intrinsic::isunordered_f32:
1018 case Intrinsic::isunordered_f64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001019 setValue(&I, DAG.getSetCC(MVT::i1,getValue(I.getOperand(1)),
1020 getValue(I.getOperand(2)), ISD::SETUO));
1021 return 0;
1022
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001023 case Intrinsic::sqrt_f32:
1024 case Intrinsic::sqrt_f64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001025 setValue(&I, DAG.getNode(ISD::FSQRT,
1026 getValue(I.getOperand(1)).getValueType(),
1027 getValue(I.getOperand(1))));
1028 return 0;
1029 case Intrinsic::pcmarker: {
1030 SDOperand Tmp = getValue(I.getOperand(1));
1031 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
1032 return 0;
1033 }
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00001034 case Intrinsic::readcyclecounter: {
1035 std::vector<MVT::ValueType> VTs;
1036 VTs.push_back(MVT::i64);
1037 VTs.push_back(MVT::Other);
1038 std::vector<SDOperand> Ops;
1039 Ops.push_back(getRoot());
1040 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER, VTs, Ops);
1041 setValue(&I, Tmp);
1042 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth01aa5632005-11-11 16:47:30 +00001043 return 0;
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00001044 }
Nate Begeman2fba8a32006-01-14 03:14:10 +00001045 case Intrinsic::bswap_i16:
Nate Begeman2fba8a32006-01-14 03:14:10 +00001046 case Intrinsic::bswap_i32:
Nate Begeman2fba8a32006-01-14 03:14:10 +00001047 case Intrinsic::bswap_i64:
1048 setValue(&I, DAG.getNode(ISD::BSWAP,
1049 getValue(I.getOperand(1)).getValueType(),
1050 getValue(I.getOperand(1))));
1051 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001052 case Intrinsic::cttz_i8:
1053 case Intrinsic::cttz_i16:
1054 case Intrinsic::cttz_i32:
1055 case Intrinsic::cttz_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001056 setValue(&I, DAG.getNode(ISD::CTTZ,
1057 getValue(I.getOperand(1)).getValueType(),
1058 getValue(I.getOperand(1))));
1059 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001060 case Intrinsic::ctlz_i8:
1061 case Intrinsic::ctlz_i16:
1062 case Intrinsic::ctlz_i32:
1063 case Intrinsic::ctlz_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001064 setValue(&I, DAG.getNode(ISD::CTLZ,
1065 getValue(I.getOperand(1)).getValueType(),
1066 getValue(I.getOperand(1))));
1067 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001068 case Intrinsic::ctpop_i8:
1069 case Intrinsic::ctpop_i16:
1070 case Intrinsic::ctpop_i32:
1071 case Intrinsic::ctpop_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001072 setValue(&I, DAG.getNode(ISD::CTPOP,
1073 getValue(I.getOperand(1)).getValueType(),
1074 getValue(I.getOperand(1))));
1075 return 0;
Chris Lattnerb3266452006-01-13 02:50:02 +00001076 case Intrinsic::stacksave: {
1077 std::vector<MVT::ValueType> VTs;
1078 VTs.push_back(TLI.getPointerTy());
1079 VTs.push_back(MVT::Other);
1080 std::vector<SDOperand> Ops;
1081 Ops.push_back(getRoot());
1082 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE, VTs, Ops);
1083 setValue(&I, Tmp);
1084 DAG.setRoot(Tmp.getValue(1));
1085 return 0;
1086 }
Chris Lattnerdeda32a2006-01-23 05:22:07 +00001087 case Intrinsic::stackrestore: {
1088 SDOperand Tmp = getValue(I.getOperand(1));
1089 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
Chris Lattnerb3266452006-01-13 02:50:02 +00001090 return 0;
Chris Lattnerdeda32a2006-01-23 05:22:07 +00001091 }
Chris Lattner9e8b6332005-12-12 22:51:16 +00001092 case Intrinsic::prefetch:
1093 // FIXME: Currently discarding prefetches.
1094 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001095 default:
1096 std::cerr << I;
1097 assert(0 && "This intrinsic is not implemented yet!");
1098 return 0;
1099 }
1100}
1101
1102
Chris Lattner7a60d912005-01-07 07:47:53 +00001103void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner18d2b342005-01-08 22:48:57 +00001104 const char *RenameFn = 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001105 if (Function *F = I.getCalledFunction()) {
Chris Lattner0c140002005-04-02 05:26:53 +00001106 if (F->isExternal())
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001107 if (unsigned IID = F->getIntrinsicID()) {
1108 RenameFn = visitIntrinsicCall(I, IID);
1109 if (!RenameFn)
1110 return;
1111 } else { // Not an LLVM intrinsic.
1112 const std::string &Name = F->getName();
Chris Lattner5c1ba2a2006-03-05 05:09:38 +00001113 if (Name[0] == 'c' && (Name == "copysign" || Name == "copysignf")) {
1114 if (I.getNumOperands() == 3 && // Basic sanity checks.
1115 I.getOperand(1)->getType()->isFloatingPoint() &&
1116 I.getType() == I.getOperand(1)->getType() &&
1117 I.getType() == I.getOperand(2)->getType()) {
1118 SDOperand LHS = getValue(I.getOperand(1));
1119 SDOperand RHS = getValue(I.getOperand(2));
1120 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
1121 LHS, RHS));
1122 return;
1123 }
1124 } else if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
Chris Lattner0c140002005-04-02 05:26:53 +00001125 if (I.getNumOperands() == 2 && // Basic sanity checks.
1126 I.getOperand(1)->getType()->isFloatingPoint() &&
1127 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001128 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner0c140002005-04-02 05:26:53 +00001129 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
1130 return;
1131 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001132 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
Chris Lattner80026402005-04-30 04:43:14 +00001133 if (I.getNumOperands() == 2 && // Basic sanity checks.
1134 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner1784a9d22006-02-14 05:39:35 +00001135 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001136 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +00001137 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
1138 return;
1139 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001140 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
Chris Lattner80026402005-04-30 04:43:14 +00001141 if (I.getNumOperands() == 2 && // Basic sanity checks.
1142 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner1784a9d22006-02-14 05:39:35 +00001143 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001144 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +00001145 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
1146 return;
1147 }
1148 }
Chris Lattnere4f71d02005-05-14 13:56:55 +00001149 }
Chris Lattner476e67b2006-01-26 22:24:51 +00001150 } else if (isa<InlineAsm>(I.getOperand(0))) {
1151 visitInlineAsm(I);
1152 return;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001153 }
Misha Brukman835702a2005-04-21 22:36:52 +00001154
Chris Lattner18d2b342005-01-08 22:48:57 +00001155 SDOperand Callee;
1156 if (!RenameFn)
1157 Callee = getValue(I.getOperand(0));
1158 else
1159 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Chris Lattner7a60d912005-01-07 07:47:53 +00001160 std::vector<std::pair<SDOperand, const Type*> > Args;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001161 Args.reserve(I.getNumOperands());
Chris Lattner7a60d912005-01-07 07:47:53 +00001162 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1163 Value *Arg = I.getOperand(i);
1164 SDOperand ArgNode = getValue(Arg);
1165 Args.push_back(std::make_pair(ArgNode, Arg->getType()));
1166 }
Misha Brukman835702a2005-04-21 22:36:52 +00001167
Nate Begemanf6565252005-03-26 01:29:23 +00001168 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
1169 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Misha Brukman835702a2005-04-21 22:36:52 +00001170
Chris Lattner1f45cd72005-01-08 19:26:18 +00001171 std::pair<SDOperand,SDOperand> Result =
Chris Lattner111778e2005-05-12 19:56:57 +00001172 TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(),
Chris Lattner2e77db62005-05-13 18:50:42 +00001173 I.isTailCall(), Callee, Args, DAG);
Chris Lattner7a60d912005-01-07 07:47:53 +00001174 if (I.getType() != Type::VoidTy)
Chris Lattner1f45cd72005-01-08 19:26:18 +00001175 setValue(&I, Result.first);
1176 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001177}
1178
Chris Lattner6f87d182006-02-22 22:37:12 +00001179SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001180 SDOperand &Chain, SDOperand &Flag)const{
Chris Lattner6f87d182006-02-22 22:37:12 +00001181 SDOperand Val = DAG.getCopyFromReg(Chain, Regs[0], RegVT, Flag);
1182 Chain = Val.getValue(1);
1183 Flag = Val.getValue(2);
1184
1185 // If the result was expanded, copy from the top part.
1186 if (Regs.size() > 1) {
1187 assert(Regs.size() == 2 &&
1188 "Cannot expand to more than 2 elts yet!");
1189 SDOperand Hi = DAG.getCopyFromReg(Chain, Regs[1], RegVT, Flag);
1190 Chain = Val.getValue(1);
1191 Flag = Val.getValue(2);
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001192 if (DAG.getTargetLoweringInfo().isLittleEndian())
1193 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi);
1194 else
1195 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Hi, Val);
Chris Lattner6f87d182006-02-22 22:37:12 +00001196 }
Chris Lattner1558fc62006-02-01 18:59:47 +00001197
Chris Lattner6f87d182006-02-22 22:37:12 +00001198 // Otherwise, if the return value was promoted, truncate it to the
1199 // appropriate type.
1200 if (RegVT == ValueVT)
1201 return Val;
1202
1203 if (MVT::isInteger(RegVT))
1204 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
1205 else
1206 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
1207}
1208
Chris Lattner571d9642006-02-23 19:21:04 +00001209/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
1210/// specified value into the registers specified by this object. This uses
1211/// Chain/Flag as the input and updates them for the output Chain/Flag.
1212void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001213 SDOperand &Chain, SDOperand &Flag) const {
Chris Lattner571d9642006-02-23 19:21:04 +00001214 if (Regs.size() == 1) {
1215 // If there is a single register and the types differ, this must be
1216 // a promotion.
1217 if (RegVT != ValueVT) {
1218 if (MVT::isInteger(RegVT))
1219 Val = DAG.getNode(ISD::ANY_EXTEND, RegVT, Val);
1220 else
1221 Val = DAG.getNode(ISD::FP_EXTEND, RegVT, Val);
1222 }
1223 Chain = DAG.getCopyToReg(Chain, Regs[0], Val, Flag);
1224 Flag = Chain.getValue(1);
1225 } else {
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001226 std::vector<unsigned> R(Regs);
1227 if (!DAG.getTargetLoweringInfo().isLittleEndian())
1228 std::reverse(R.begin(), R.end());
1229
1230 for (unsigned i = 0, e = R.size(); i != e; ++i) {
Chris Lattner571d9642006-02-23 19:21:04 +00001231 SDOperand Part = DAG.getNode(ISD::EXTRACT_ELEMENT, RegVT, Val,
1232 DAG.getConstant(i, MVT::i32));
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001233 Chain = DAG.getCopyToReg(Chain, R[i], Part, Flag);
Chris Lattner571d9642006-02-23 19:21:04 +00001234 Flag = Chain.getValue(1);
1235 }
1236 }
1237}
Chris Lattner6f87d182006-02-22 22:37:12 +00001238
Chris Lattner571d9642006-02-23 19:21:04 +00001239/// AddInlineAsmOperands - Add this value to the specified inlineasm node
1240/// operand list. This adds the code marker and includes the number of
1241/// values added into it.
1242void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001243 std::vector<SDOperand> &Ops) const {
Chris Lattner571d9642006-02-23 19:21:04 +00001244 Ops.push_back(DAG.getConstant(Code | (Regs.size() << 3), MVT::i32));
1245 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
1246 Ops.push_back(DAG.getRegister(Regs[i], RegVT));
1247}
Chris Lattner6f87d182006-02-22 22:37:12 +00001248
1249/// isAllocatableRegister - If the specified register is safe to allocate,
1250/// i.e. it isn't a stack pointer or some other special register, return the
1251/// register class for the register. Otherwise, return null.
1252static const TargetRegisterClass *
Chris Lattnerb1124f32006-02-22 23:09:03 +00001253isAllocatableRegister(unsigned Reg, MachineFunction &MF,
1254 const TargetLowering &TLI, const MRegisterInfo *MRI) {
1255 for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
1256 E = MRI->regclass_end(); RCI != E; ++RCI) {
1257 const TargetRegisterClass *RC = *RCI;
1258 // If none of the the value types for this register class are valid, we
1259 // can't use it. For example, 64-bit reg classes on 32-bit targets.
1260 bool isLegal = false;
1261 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
1262 I != E; ++I) {
1263 if (TLI.isTypeLegal(*I)) {
1264 isLegal = true;
1265 break;
1266 }
1267 }
1268
1269 if (!isLegal) continue;
1270
Chris Lattner6f87d182006-02-22 22:37:12 +00001271 // NOTE: This isn't ideal. In particular, this might allocate the
1272 // frame pointer in functions that need it (due to them not being taken
1273 // out of allocation, because a variable sized allocation hasn't been seen
1274 // yet). This is a slight code pessimization, but should still work.
Chris Lattnerb1124f32006-02-22 23:09:03 +00001275 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
1276 E = RC->allocation_order_end(MF); I != E; ++I)
Chris Lattner6f87d182006-02-22 22:37:12 +00001277 if (*I == Reg)
Chris Lattnerb1124f32006-02-22 23:09:03 +00001278 return RC;
Chris Lattner1558fc62006-02-01 18:59:47 +00001279 }
1280 return 0;
Chris Lattner6f87d182006-02-22 22:37:12 +00001281}
1282
1283RegsForValue SelectionDAGLowering::
1284GetRegistersForValue(const std::string &ConstrCode,
1285 MVT::ValueType VT, bool isOutReg, bool isInReg,
1286 std::set<unsigned> &OutputRegs,
1287 std::set<unsigned> &InputRegs) {
1288 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
1289 TLI.getRegForInlineAsmConstraint(ConstrCode, VT);
1290 std::vector<unsigned> Regs;
1291
1292 unsigned NumRegs = VT != MVT::Other ? TLI.getNumElements(VT) : 1;
1293 MVT::ValueType RegVT;
1294 MVT::ValueType ValueVT = VT;
1295
1296 if (PhysReg.first) {
1297 if (VT == MVT::Other)
1298 ValueVT = *PhysReg.second->vt_begin();
1299 RegVT = VT;
1300
1301 // This is a explicit reference to a physical register.
1302 Regs.push_back(PhysReg.first);
1303
1304 // If this is an expanded reference, add the rest of the regs to Regs.
1305 if (NumRegs != 1) {
1306 RegVT = *PhysReg.second->vt_begin();
1307 TargetRegisterClass::iterator I = PhysReg.second->begin();
1308 TargetRegisterClass::iterator E = PhysReg.second->end();
1309 for (; *I != PhysReg.first; ++I)
1310 assert(I != E && "Didn't find reg!");
1311
1312 // Already added the first reg.
1313 --NumRegs; ++I;
1314 for (; NumRegs; --NumRegs, ++I) {
1315 assert(I != E && "Ran out of registers to allocate!");
1316 Regs.push_back(*I);
1317 }
1318 }
1319 return RegsForValue(Regs, RegVT, ValueVT);
1320 }
1321
1322 // This is a reference to a register class. Allocate NumRegs consecutive,
1323 // available, registers from the class.
1324 std::vector<unsigned> RegClassRegs =
1325 TLI.getRegClassForInlineAsmConstraint(ConstrCode, VT);
1326
1327 const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
1328 MachineFunction &MF = *CurMBB->getParent();
1329 unsigned NumAllocated = 0;
1330 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
1331 unsigned Reg = RegClassRegs[i];
1332 // See if this register is available.
1333 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
1334 (isInReg && InputRegs.count(Reg))) { // Already used.
1335 // Make sure we find consecutive registers.
1336 NumAllocated = 0;
1337 continue;
1338 }
1339
1340 // Check to see if this register is allocatable (i.e. don't give out the
1341 // stack pointer).
Chris Lattnerb1124f32006-02-22 23:09:03 +00001342 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, MRI);
Chris Lattner6f87d182006-02-22 22:37:12 +00001343 if (!RC) {
1344 // Make sure we find consecutive registers.
1345 NumAllocated = 0;
1346 continue;
1347 }
1348
1349 // Okay, this register is good, we can use it.
1350 ++NumAllocated;
1351
1352 // If we allocated enough consecutive
1353 if (NumAllocated == NumRegs) {
1354 unsigned RegStart = (i-NumAllocated)+1;
1355 unsigned RegEnd = i+1;
1356 // Mark all of the allocated registers used.
1357 for (unsigned i = RegStart; i != RegEnd; ++i) {
1358 unsigned Reg = RegClassRegs[i];
1359 Regs.push_back(Reg);
1360 if (isOutReg) OutputRegs.insert(Reg); // Mark reg used.
1361 if (isInReg) InputRegs.insert(Reg); // Mark reg used.
1362 }
1363
1364 return RegsForValue(Regs, *RC->vt_begin(), VT);
1365 }
1366 }
1367
1368 // Otherwise, we couldn't allocate enough registers for this.
1369 return RegsForValue();
Chris Lattner1558fc62006-02-01 18:59:47 +00001370}
1371
Chris Lattner6f87d182006-02-22 22:37:12 +00001372
Chris Lattner476e67b2006-01-26 22:24:51 +00001373/// visitInlineAsm - Handle a call to an InlineAsm object.
1374///
1375void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
1376 InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
1377
1378 SDOperand AsmStr = DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
1379 MVT::Other);
1380
1381 // Note, we treat inline asms both with and without side-effects as the same.
1382 // If an inline asm doesn't have side effects and doesn't access memory, we
1383 // could not choose to not chain it.
1384 bool hasSideEffects = IA->hasSideEffects();
1385
Chris Lattner3a5ed552006-02-01 01:28:23 +00001386 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
Chris Lattner7ad77df2006-02-22 00:56:39 +00001387 std::vector<MVT::ValueType> ConstraintVTs;
Chris Lattner476e67b2006-01-26 22:24:51 +00001388
1389 /// AsmNodeOperands - A list of pairs. The first element is a register, the
1390 /// second is a bitfield where bit #0 is set if it is a use and bit #1 is set
1391 /// if it is a def of that register.
1392 std::vector<SDOperand> AsmNodeOperands;
1393 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
1394 AsmNodeOperands.push_back(AsmStr);
1395
1396 SDOperand Chain = getRoot();
1397 SDOperand Flag;
1398
Chris Lattner1558fc62006-02-01 18:59:47 +00001399 // We fully assign registers here at isel time. This is not optimal, but
1400 // should work. For register classes that correspond to LLVM classes, we
1401 // could let the LLVM RA do its thing, but we currently don't. Do a prepass
1402 // over the constraints, collecting fixed registers that we know we can't use.
1403 std::set<unsigned> OutputRegs, InputRegs;
Chris Lattner7ad77df2006-02-22 00:56:39 +00001404 unsigned OpNum = 1;
Chris Lattner1558fc62006-02-01 18:59:47 +00001405 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1406 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
1407 std::string &ConstraintCode = Constraints[i].Codes[0];
Chris Lattner7f5880b2006-02-02 00:25:23 +00001408
Chris Lattner7ad77df2006-02-22 00:56:39 +00001409 MVT::ValueType OpVT;
1410
1411 // Compute the value type for each operand and add it to ConstraintVTs.
1412 switch (Constraints[i].Type) {
1413 case InlineAsm::isOutput:
1414 if (!Constraints[i].isIndirectOutput) {
1415 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
1416 OpVT = TLI.getValueType(I.getType());
1417 } else {
Chris Lattner9fed5b62006-02-27 23:45:39 +00001418 const Type *OpTy = I.getOperand(OpNum)->getType();
Chris Lattner7ad77df2006-02-22 00:56:39 +00001419 OpVT = TLI.getValueType(cast<PointerType>(OpTy)->getElementType());
1420 OpNum++; // Consumes a call operand.
1421 }
1422 break;
1423 case InlineAsm::isInput:
1424 OpVT = TLI.getValueType(I.getOperand(OpNum)->getType());
1425 OpNum++; // Consumes a call operand.
1426 break;
1427 case InlineAsm::isClobber:
1428 OpVT = MVT::Other;
1429 break;
1430 }
1431
1432 ConstraintVTs.push_back(OpVT);
1433
Chris Lattner6f87d182006-02-22 22:37:12 +00001434 if (TLI.getRegForInlineAsmConstraint(ConstraintCode, OpVT).first == 0)
1435 continue; // Not assigned a fixed reg.
Chris Lattner7ad77df2006-02-22 00:56:39 +00001436
Chris Lattner6f87d182006-02-22 22:37:12 +00001437 // Build a list of regs that this operand uses. This always has a single
1438 // element for promoted/expanded operands.
1439 RegsForValue Regs = GetRegistersForValue(ConstraintCode, OpVT,
1440 false, false,
1441 OutputRegs, InputRegs);
Chris Lattner1558fc62006-02-01 18:59:47 +00001442
1443 switch (Constraints[i].Type) {
1444 case InlineAsm::isOutput:
1445 // We can't assign any other output to this register.
Chris Lattner6f87d182006-02-22 22:37:12 +00001446 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00001447 // If this is an early-clobber output, it cannot be assigned to the same
1448 // value as the input reg.
Chris Lattner7f5880b2006-02-02 00:25:23 +00001449 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
Chris Lattner6f87d182006-02-22 22:37:12 +00001450 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00001451 break;
Chris Lattner7ad77df2006-02-22 00:56:39 +00001452 case InlineAsm::isInput:
1453 // We can't assign any other input to this register.
Chris Lattner6f87d182006-02-22 22:37:12 +00001454 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner7ad77df2006-02-22 00:56:39 +00001455 break;
Chris Lattner1558fc62006-02-01 18:59:47 +00001456 case InlineAsm::isClobber:
1457 // Clobbered regs cannot be used as inputs or outputs.
Chris Lattner6f87d182006-02-22 22:37:12 +00001458 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
1459 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00001460 break;
Chris Lattner1558fc62006-02-01 18:59:47 +00001461 }
1462 }
Chris Lattner3a5ed552006-02-01 01:28:23 +00001463
Chris Lattner5c79f982006-02-21 23:12:12 +00001464 // Loop over all of the inputs, copying the operand values into the
1465 // appropriate registers and processing the output regs.
Chris Lattner6f87d182006-02-22 22:37:12 +00001466 RegsForValue RetValRegs;
1467 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
Chris Lattner7ad77df2006-02-22 00:56:39 +00001468 OpNum = 1;
Chris Lattner5c79f982006-02-21 23:12:12 +00001469
Chris Lattner2e56e892006-01-31 02:03:41 +00001470 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
Chris Lattner3a5ed552006-02-01 01:28:23 +00001471 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
1472 std::string &ConstraintCode = Constraints[i].Codes[0];
Chris Lattner7ad77df2006-02-22 00:56:39 +00001473
Chris Lattner3a5ed552006-02-01 01:28:23 +00001474 switch (Constraints[i].Type) {
1475 case InlineAsm::isOutput: {
Chris Lattner9fed5b62006-02-27 23:45:39 +00001476 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
1477 if (ConstraintCode.size() == 1) // not a physreg name.
1478 CTy = TLI.getConstraintType(ConstraintCode[0]);
1479
1480 if (CTy == TargetLowering::C_Memory) {
1481 // Memory output.
1482 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
1483
1484 // Check that the operand (the address to store to) isn't a float.
1485 if (!MVT::isInteger(InOperandVal.getValueType()))
1486 assert(0 && "MATCH FAIL!");
1487
1488 if (!Constraints[i].isIndirectOutput)
1489 assert(0 && "MATCH FAIL!");
1490
1491 OpNum++; // Consumes a call operand.
1492
1493 // Extend/truncate to the right pointer type if needed.
1494 MVT::ValueType PtrType = TLI.getPointerTy();
1495 if (InOperandVal.getValueType() < PtrType)
1496 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
1497 else if (InOperandVal.getValueType() > PtrType)
1498 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
1499
1500 // Add information to the INLINEASM node to know about this output.
1501 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
1502 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
1503 AsmNodeOperands.push_back(InOperandVal);
1504 break;
1505 }
1506
1507 // Otherwise, this is a register output.
1508 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
1509
Chris Lattner6f87d182006-02-22 22:37:12 +00001510 // If this is an early-clobber output, or if there is an input
1511 // constraint that matches this, we need to reserve the input register
1512 // so no other inputs allocate to it.
1513 bool UsesInputRegister = false;
1514 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
1515 UsesInputRegister = true;
1516
1517 // Copy the output from the appropriate register. Find a register that
Chris Lattner7ad77df2006-02-22 00:56:39 +00001518 // we can use.
Chris Lattner6f87d182006-02-22 22:37:12 +00001519 RegsForValue Regs =
1520 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
1521 true, UsesInputRegister,
1522 OutputRegs, InputRegs);
1523 assert(!Regs.Regs.empty() && "Couldn't allocate output reg!");
Chris Lattner7ad77df2006-02-22 00:56:39 +00001524
Chris Lattner3a5ed552006-02-01 01:28:23 +00001525 if (!Constraints[i].isIndirectOutput) {
Chris Lattner6f87d182006-02-22 22:37:12 +00001526 assert(RetValRegs.Regs.empty() &&
Chris Lattner3a5ed552006-02-01 01:28:23 +00001527 "Cannot have multiple output constraints yet!");
Chris Lattner3a5ed552006-02-01 01:28:23 +00001528 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
Chris Lattner6f87d182006-02-22 22:37:12 +00001529 RetValRegs = Regs;
Chris Lattner3a5ed552006-02-01 01:28:23 +00001530 } else {
Chris Lattner9fed5b62006-02-27 23:45:39 +00001531 IndirectStoresToEmit.push_back(std::make_pair(Regs,
1532 I.getOperand(OpNum)));
Chris Lattner3a5ed552006-02-01 01:28:23 +00001533 OpNum++; // Consumes a call operand.
1534 }
Chris Lattner2e56e892006-01-31 02:03:41 +00001535
1536 // Add information to the INLINEASM node to know that this register is
1537 // set.
Chris Lattner571d9642006-02-23 19:21:04 +00001538 Regs.AddInlineAsmOperands(2 /*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00001539 break;
1540 }
1541 case InlineAsm::isInput: {
Chris Lattner9fed5b62006-02-27 23:45:39 +00001542 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
Chris Lattner1558fc62006-02-01 18:59:47 +00001543 OpNum++; // Consumes a call operand.
Chris Lattner65ad53f2006-02-04 02:16:44 +00001544
Chris Lattner7f5880b2006-02-02 00:25:23 +00001545 if (isdigit(ConstraintCode[0])) { // Matching constraint?
1546 // If this is required to match an output register we have already set,
1547 // just use its register.
1548 unsigned OperandNo = atoi(ConstraintCode.c_str());
Chris Lattner65ad53f2006-02-04 02:16:44 +00001549
Chris Lattner571d9642006-02-23 19:21:04 +00001550 // Scan until we find the definition we already emitted of this operand.
1551 // When we find it, create a RegsForValue operand.
1552 unsigned CurOp = 2; // The first operand.
1553 for (; OperandNo; --OperandNo) {
1554 // Advance to the next operand.
1555 unsigned NumOps =
1556 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
1557 assert((NumOps & 7) == 2 /*REGDEF*/ &&
1558 "Skipped past definitions?");
1559 CurOp += (NumOps>>3)+1;
1560 }
1561
1562 unsigned NumOps =
1563 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
1564 assert((NumOps & 7) == 2 /*REGDEF*/ &&
1565 "Skipped past definitions?");
1566
1567 // Add NumOps>>3 registers to MatchedRegs.
1568 RegsForValue MatchedRegs;
1569 MatchedRegs.ValueVT = InOperandVal.getValueType();
1570 MatchedRegs.RegVT = AsmNodeOperands[CurOp+1].getValueType();
1571 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
1572 unsigned Reg=cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
1573 MatchedRegs.Regs.push_back(Reg);
1574 }
1575
1576 // Use the produced MatchedRegs object to
1577 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag);
1578 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattner571d9642006-02-23 19:21:04 +00001579 break;
Chris Lattner7f5880b2006-02-02 00:25:23 +00001580 }
Chris Lattner7ef7a642006-02-24 01:11:24 +00001581
1582 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
1583 if (ConstraintCode.size() == 1) // not a physreg name.
1584 CTy = TLI.getConstraintType(ConstraintCode[0]);
1585
1586 if (CTy == TargetLowering::C_Other) {
1587 if (!TLI.isOperandValidForConstraint(InOperandVal, ConstraintCode[0]))
1588 assert(0 && "MATCH FAIL!");
1589
1590 // Add information to the INLINEASM node to know about this input.
1591 unsigned ResOpType = 3 /*IMM*/ | (1 << 3);
1592 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
1593 AsmNodeOperands.push_back(InOperandVal);
1594 break;
1595 } else if (CTy == TargetLowering::C_Memory) {
1596 // Memory input.
1597
1598 // Check that the operand isn't a float.
1599 if (!MVT::isInteger(InOperandVal.getValueType()))
1600 assert(0 && "MATCH FAIL!");
1601
1602 // Extend/truncate to the right pointer type if needed.
1603 MVT::ValueType PtrType = TLI.getPointerTy();
1604 if (InOperandVal.getValueType() < PtrType)
1605 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
1606 else if (InOperandVal.getValueType() > PtrType)
1607 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
1608
1609 // Add information to the INLINEASM node to know about this input.
1610 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
1611 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
1612 AsmNodeOperands.push_back(InOperandVal);
1613 break;
1614 }
1615
1616 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
1617
1618 // Copy the input into the appropriate registers.
1619 RegsForValue InRegs =
1620 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
1621 false, true, OutputRegs, InputRegs);
1622 // FIXME: should be match fail.
1623 assert(!InRegs.Regs.empty() && "Couldn't allocate input reg!");
1624
1625 InRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag);
1626
1627 InRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00001628 break;
1629 }
Chris Lattner571d9642006-02-23 19:21:04 +00001630 case InlineAsm::isClobber: {
1631 RegsForValue ClobberedRegs =
1632 GetRegistersForValue(ConstraintCode, MVT::Other, false, false,
1633 OutputRegs, InputRegs);
1634 // Add the clobbered value to the operand list, so that the register
1635 // allocator is aware that the physreg got clobbered.
1636 if (!ClobberedRegs.Regs.empty())
1637 ClobberedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00001638 break;
1639 }
Chris Lattner571d9642006-02-23 19:21:04 +00001640 }
Chris Lattner2e56e892006-01-31 02:03:41 +00001641 }
Chris Lattner476e67b2006-01-26 22:24:51 +00001642
1643 // Finish up input operands.
1644 AsmNodeOperands[0] = Chain;
1645 if (Flag.Val) AsmNodeOperands.push_back(Flag);
1646
1647 std::vector<MVT::ValueType> VTs;
1648 VTs.push_back(MVT::Other);
1649 VTs.push_back(MVT::Flag);
1650 Chain = DAG.getNode(ISD::INLINEASM, VTs, AsmNodeOperands);
1651 Flag = Chain.getValue(1);
1652
Chris Lattner2e56e892006-01-31 02:03:41 +00001653 // If this asm returns a register value, copy the result from that register
1654 // and set it as the value of the call.
Chris Lattner6f87d182006-02-22 22:37:12 +00001655 if (!RetValRegs.Regs.empty())
1656 setValue(&I, RetValRegs.getCopyFromRegs(DAG, Chain, Flag));
Chris Lattner476e67b2006-01-26 22:24:51 +00001657
Chris Lattner2e56e892006-01-31 02:03:41 +00001658 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
1659
1660 // Process indirect outputs, first output all of the flagged copies out of
1661 // physregs.
1662 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
Chris Lattner6f87d182006-02-22 22:37:12 +00001663 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Chris Lattner2e56e892006-01-31 02:03:41 +00001664 Value *Ptr = IndirectStoresToEmit[i].second;
Chris Lattner6f87d182006-02-22 22:37:12 +00001665 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, Flag);
1666 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner2e56e892006-01-31 02:03:41 +00001667 }
1668
1669 // Emit the non-flagged stores from the physregs.
1670 std::vector<SDOperand> OutChains;
1671 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
1672 OutChains.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
1673 StoresToEmit[i].first,
1674 getValue(StoresToEmit[i].second),
1675 DAG.getSrcValue(StoresToEmit[i].second)));
1676 if (!OutChains.empty())
1677 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains);
Chris Lattner476e67b2006-01-26 22:24:51 +00001678 DAG.setRoot(Chain);
1679}
1680
1681
Chris Lattner7a60d912005-01-07 07:47:53 +00001682void SelectionDAGLowering::visitMalloc(MallocInst &I) {
1683 SDOperand Src = getValue(I.getOperand(0));
1684
1685 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnereccb73d2005-01-22 23:04:37 +00001686
1687 if (IntPtr < Src.getValueType())
1688 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
1689 else if (IntPtr > Src.getValueType())
1690 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner7a60d912005-01-07 07:47:53 +00001691
1692 // Scale the source by the type size.
1693 uint64_t ElementSize = TD.getTypeSize(I.getType()->getElementType());
1694 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
1695 Src, getIntPtrConstant(ElementSize));
1696
1697 std::vector<std::pair<SDOperand, const Type*> > Args;
1698 Args.push_back(std::make_pair(Src, TLI.getTargetData().getIntPtrType()));
Chris Lattner1f45cd72005-01-08 19:26:18 +00001699
1700 std::pair<SDOperand,SDOperand> Result =
Chris Lattner2e77db62005-05-13 18:50:42 +00001701 TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00001702 DAG.getExternalSymbol("malloc", IntPtr),
1703 Args, DAG);
1704 setValue(&I, Result.first); // Pointers always fit in registers
1705 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001706}
1707
1708void SelectionDAGLowering::visitFree(FreeInst &I) {
1709 std::vector<std::pair<SDOperand, const Type*> > Args;
1710 Args.push_back(std::make_pair(getValue(I.getOperand(0)),
1711 TLI.getTargetData().getIntPtrType()));
1712 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner1f45cd72005-01-08 19:26:18 +00001713 std::pair<SDOperand,SDOperand> Result =
Chris Lattner2e77db62005-05-13 18:50:42 +00001714 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00001715 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
1716 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001717}
1718
Chris Lattner13d7c252005-08-26 20:54:47 +00001719// InsertAtEndOfBasicBlock - This method should be implemented by targets that
1720// mark instructions with the 'usesCustomDAGSchedInserter' flag. These
1721// instructions are special in various ways, which require special support to
1722// insert. The specified MachineInstr is created but not inserted into any
1723// basic blocks, and the scheduler passes ownership of it to this method.
1724MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
1725 MachineBasicBlock *MBB) {
1726 std::cerr << "If a target marks an instruction with "
1727 "'usesCustomDAGSchedInserter', it must implement "
1728 "TargetLowering::InsertAtEndOfBasicBlock!\n";
1729 abort();
1730 return 0;
1731}
1732
Chris Lattner58cfd792005-01-09 00:00:49 +00001733void SelectionDAGLowering::visitVAStart(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00001734 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
1735 getValue(I.getOperand(1)),
1736 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner58cfd792005-01-09 00:00:49 +00001737}
1738
1739void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00001740 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
1741 getValue(I.getOperand(0)),
1742 DAG.getSrcValue(I.getOperand(0)));
1743 setValue(&I, V);
1744 DAG.setRoot(V.getValue(1));
Chris Lattner7a60d912005-01-07 07:47:53 +00001745}
1746
1747void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00001748 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
1749 getValue(I.getOperand(1)),
1750 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner7a60d912005-01-07 07:47:53 +00001751}
1752
1753void SelectionDAGLowering::visitVACopy(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00001754 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
1755 getValue(I.getOperand(1)),
1756 getValue(I.getOperand(2)),
1757 DAG.getSrcValue(I.getOperand(1)),
1758 DAG.getSrcValue(I.getOperand(2))));
Chris Lattner7a60d912005-01-07 07:47:53 +00001759}
1760
Chris Lattner58cfd792005-01-09 00:00:49 +00001761// It is always conservatively correct for llvm.returnaddress and
1762// llvm.frameaddress to return 0.
1763std::pair<SDOperand, SDOperand>
1764TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
1765 unsigned Depth, SelectionDAG &DAG) {
1766 return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
Chris Lattner7a60d912005-01-07 07:47:53 +00001767}
1768
Chris Lattner29dcc712005-05-14 05:50:48 +00001769SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner897cd7d2005-01-16 07:28:41 +00001770 assert(0 && "LowerOperation not implemented for this target!");
1771 abort();
Misha Brukman73e929f2005-02-17 21:39:27 +00001772 return SDOperand();
Chris Lattner897cd7d2005-01-16 07:28:41 +00001773}
1774
Nate Begeman595ec732006-01-28 03:14:31 +00001775SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
1776 SelectionDAG &DAG) {
1777 assert(0 && "CustomPromoteOperation not implemented for this target!");
1778 abort();
1779 return SDOperand();
1780}
1781
Chris Lattner58cfd792005-01-09 00:00:49 +00001782void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
1783 unsigned Depth = (unsigned)cast<ConstantUInt>(I.getOperand(1))->getValue();
1784 std::pair<SDOperand,SDOperand> Result =
Chris Lattner4108bb02005-01-17 19:43:36 +00001785 TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
Chris Lattner58cfd792005-01-09 00:00:49 +00001786 setValue(&I, Result.first);
1787 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001788}
1789
Evan Cheng6781b6e2006-02-15 21:59:04 +00001790/// getMemsetValue - Vectorized representation of the memset value
Evan Cheng81fcea82006-02-14 08:22:34 +00001791/// operand.
1792static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
Evan Cheng93e48652006-02-15 22:12:35 +00001793 SelectionDAG &DAG) {
Evan Cheng81fcea82006-02-14 08:22:34 +00001794 MVT::ValueType CurVT = VT;
1795 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
1796 uint64_t Val = C->getValue() & 255;
1797 unsigned Shift = 8;
1798 while (CurVT != MVT::i8) {
1799 Val = (Val << Shift) | Val;
1800 Shift <<= 1;
1801 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00001802 }
1803 return DAG.getConstant(Val, VT);
1804 } else {
1805 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
1806 unsigned Shift = 8;
1807 while (CurVT != MVT::i8) {
1808 Value =
1809 DAG.getNode(ISD::OR, VT,
1810 DAG.getNode(ISD::SHL, VT, Value,
1811 DAG.getConstant(Shift, MVT::i8)), Value);
1812 Shift <<= 1;
1813 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00001814 }
1815
1816 return Value;
1817 }
1818}
1819
Evan Cheng6781b6e2006-02-15 21:59:04 +00001820/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
1821/// used when a memcpy is turned into a memset when the source is a constant
1822/// string ptr.
1823static SDOperand getMemsetStringVal(MVT::ValueType VT,
1824 SelectionDAG &DAG, TargetLowering &TLI,
1825 std::string &Str, unsigned Offset) {
1826 MVT::ValueType CurVT = VT;
1827 uint64_t Val = 0;
1828 unsigned MSB = getSizeInBits(VT) / 8;
1829 if (TLI.isLittleEndian())
1830 Offset = Offset + MSB - 1;
1831 for (unsigned i = 0; i != MSB; ++i) {
1832 Val = (Val << 8) | Str[Offset];
1833 Offset += TLI.isLittleEndian() ? -1 : 1;
1834 }
1835 return DAG.getConstant(Val, VT);
1836}
1837
Evan Cheng81fcea82006-02-14 08:22:34 +00001838/// getMemBasePlusOffset - Returns base and offset node for the
1839static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
1840 SelectionDAG &DAG, TargetLowering &TLI) {
1841 MVT::ValueType VT = Base.getValueType();
1842 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
1843}
1844
Evan Chengdb2a7a72006-02-14 20:12:38 +00001845/// MeetsMaxMemopRequirement - Determines if the number of memory ops required
Evan Chengd5026102006-02-14 09:11:59 +00001846/// to replace the memset / memcpy is below the threshold. It also returns the
1847/// types of the sequence of memory ops to perform memset / memcpy.
Evan Chengdb2a7a72006-02-14 20:12:38 +00001848static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
1849 unsigned Limit, uint64_t Size,
1850 unsigned Align, TargetLowering &TLI) {
Evan Cheng81fcea82006-02-14 08:22:34 +00001851 MVT::ValueType VT;
1852
1853 if (TLI.allowsUnalignedMemoryAccesses()) {
1854 VT = MVT::i64;
1855 } else {
1856 switch (Align & 7) {
1857 case 0:
1858 VT = MVT::i64;
1859 break;
1860 case 4:
1861 VT = MVT::i32;
1862 break;
1863 case 2:
1864 VT = MVT::i16;
1865 break;
1866 default:
1867 VT = MVT::i8;
1868 break;
1869 }
1870 }
1871
Evan Chengd5026102006-02-14 09:11:59 +00001872 MVT::ValueType LVT = MVT::i64;
1873 while (!TLI.isTypeLegal(LVT))
1874 LVT = (MVT::ValueType)((unsigned)LVT - 1);
1875 assert(MVT::isInteger(LVT));
Evan Cheng81fcea82006-02-14 08:22:34 +00001876
Evan Chengd5026102006-02-14 09:11:59 +00001877 if (VT > LVT)
1878 VT = LVT;
1879
Evan Cheng04514992006-02-14 23:05:54 +00001880 unsigned NumMemOps = 0;
Evan Cheng81fcea82006-02-14 08:22:34 +00001881 while (Size != 0) {
1882 unsigned VTSize = getSizeInBits(VT) / 8;
1883 while (VTSize > Size) {
1884 VT = (MVT::ValueType)((unsigned)VT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00001885 VTSize >>= 1;
1886 }
Evan Chengd5026102006-02-14 09:11:59 +00001887 assert(MVT::isInteger(VT));
1888
1889 if (++NumMemOps > Limit)
1890 return false;
Evan Cheng81fcea82006-02-14 08:22:34 +00001891 MemOps.push_back(VT);
1892 Size -= VTSize;
1893 }
Evan Chengd5026102006-02-14 09:11:59 +00001894
1895 return true;
Evan Cheng81fcea82006-02-14 08:22:34 +00001896}
1897
Chris Lattner875def92005-01-11 05:56:49 +00001898void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
Evan Cheng81fcea82006-02-14 08:22:34 +00001899 SDOperand Op1 = getValue(I.getOperand(1));
1900 SDOperand Op2 = getValue(I.getOperand(2));
1901 SDOperand Op3 = getValue(I.getOperand(3));
1902 SDOperand Op4 = getValue(I.getOperand(4));
1903 unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
1904 if (Align == 0) Align = 1;
1905
1906 if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
1907 std::vector<MVT::ValueType> MemOps;
Evan Cheng81fcea82006-02-14 08:22:34 +00001908
1909 // Expand memset / memcpy to a series of load / store ops
1910 // if the size operand falls below a certain threshold.
1911 std::vector<SDOperand> OutChains;
1912 switch (Op) {
Evan Cheng038521e2006-02-14 19:45:56 +00001913 default: break; // Do nothing for now.
Evan Cheng81fcea82006-02-14 08:22:34 +00001914 case ISD::MEMSET: {
Evan Chengdb2a7a72006-02-14 20:12:38 +00001915 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
1916 Size->getValue(), Align, TLI)) {
Evan Chengd5026102006-02-14 09:11:59 +00001917 unsigned NumMemOps = MemOps.size();
Evan Cheng81fcea82006-02-14 08:22:34 +00001918 unsigned Offset = 0;
1919 for (unsigned i = 0; i < NumMemOps; i++) {
1920 MVT::ValueType VT = MemOps[i];
1921 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng93e48652006-02-15 22:12:35 +00001922 SDOperand Value = getMemsetValue(Op2, VT, DAG);
Evan Chenge2038bd2006-02-15 01:54:51 +00001923 SDOperand Store = DAG.getNode(ISD::STORE, MVT::Other, getRoot(),
1924 Value,
Chris Lattner6f87d182006-02-22 22:37:12 +00001925 getMemBasePlusOffset(Op1, Offset, DAG, TLI),
1926 DAG.getSrcValue(I.getOperand(1), Offset));
Evan Chenge2038bd2006-02-15 01:54:51 +00001927 OutChains.push_back(Store);
Evan Cheng81fcea82006-02-14 08:22:34 +00001928 Offset += VTSize;
1929 }
Evan Cheng81fcea82006-02-14 08:22:34 +00001930 }
Evan Chenge2038bd2006-02-15 01:54:51 +00001931 break;
Evan Cheng81fcea82006-02-14 08:22:34 +00001932 }
Evan Chenge2038bd2006-02-15 01:54:51 +00001933 case ISD::MEMCPY: {
1934 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
1935 Size->getValue(), Align, TLI)) {
1936 unsigned NumMemOps = MemOps.size();
Evan Chengc3dcf5a2006-02-16 23:11:42 +00001937 unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
Evan Cheng6781b6e2006-02-15 21:59:04 +00001938 GlobalAddressSDNode *G = NULL;
1939 std::string Str;
Evan Chengc3dcf5a2006-02-16 23:11:42 +00001940 bool CopyFromStr = false;
Evan Cheng6781b6e2006-02-15 21:59:04 +00001941
1942 if (Op2.getOpcode() == ISD::GlobalAddress)
1943 G = cast<GlobalAddressSDNode>(Op2);
1944 else if (Op2.getOpcode() == ISD::ADD &&
1945 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
1946 Op2.getOperand(1).getOpcode() == ISD::Constant) {
1947 G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
Evan Chengc3dcf5a2006-02-16 23:11:42 +00001948 SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
Evan Cheng6781b6e2006-02-15 21:59:04 +00001949 }
1950 if (G) {
1951 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
Evan Chengc3dcf5a2006-02-16 23:11:42 +00001952 if (GV) {
Jim Laskey2698f0d2006-03-08 18:11:07 +00001953 Str = GV->getStringValue();
Evan Chengc3dcf5a2006-02-16 23:11:42 +00001954 if (!Str.empty()) {
1955 CopyFromStr = true;
1956 SrcOff += SrcDelta;
1957 }
1958 }
Evan Cheng6781b6e2006-02-15 21:59:04 +00001959 }
1960
Evan Chenge2038bd2006-02-15 01:54:51 +00001961 for (unsigned i = 0; i < NumMemOps; i++) {
1962 MVT::ValueType VT = MemOps[i];
1963 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng6781b6e2006-02-15 21:59:04 +00001964 SDOperand Value, Chain, Store;
1965
Evan Chengc3dcf5a2006-02-16 23:11:42 +00001966 if (CopyFromStr) {
Evan Cheng6781b6e2006-02-15 21:59:04 +00001967 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
1968 Chain = getRoot();
1969 Store =
1970 DAG.getNode(ISD::STORE, MVT::Other, Chain, Value,
1971 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
1972 DAG.getSrcValue(I.getOperand(1), DstOff));
1973 } else {
1974 Value = DAG.getLoad(VT, getRoot(),
1975 getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
1976 DAG.getSrcValue(I.getOperand(2), SrcOff));
1977 Chain = Value.getValue(1);
1978 Store =
1979 DAG.getNode(ISD::STORE, MVT::Other, Chain, Value,
1980 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
1981 DAG.getSrcValue(I.getOperand(1), DstOff));
1982 }
Evan Chenge2038bd2006-02-15 01:54:51 +00001983 OutChains.push_back(Store);
Evan Cheng6781b6e2006-02-15 21:59:04 +00001984 SrcOff += VTSize;
1985 DstOff += VTSize;
Evan Chenge2038bd2006-02-15 01:54:51 +00001986 }
1987 }
1988 break;
1989 }
1990 }
1991
1992 if (!OutChains.empty()) {
1993 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains));
1994 return;
Evan Cheng81fcea82006-02-14 08:22:34 +00001995 }
1996 }
1997
Chris Lattner875def92005-01-11 05:56:49 +00001998 std::vector<SDOperand> Ops;
Chris Lattner4108bb02005-01-17 19:43:36 +00001999 Ops.push_back(getRoot());
Evan Cheng81fcea82006-02-14 08:22:34 +00002000 Ops.push_back(Op1);
2001 Ops.push_back(Op2);
2002 Ops.push_back(Op3);
2003 Ops.push_back(Op4);
Chris Lattner875def92005-01-11 05:56:49 +00002004 DAG.setRoot(DAG.getNode(Op, MVT::Other, Ops));
Chris Lattner7a60d912005-01-07 07:47:53 +00002005}
2006
Chris Lattner875def92005-01-11 05:56:49 +00002007//===----------------------------------------------------------------------===//
2008// SelectionDAGISel code
2009//===----------------------------------------------------------------------===//
Chris Lattner7a60d912005-01-07 07:47:53 +00002010
2011unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
2012 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
2013}
2014
Chris Lattnerc9950c12005-08-17 06:37:43 +00002015void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner1a908c82005-08-18 17:35:14 +00002016 // FIXME: we only modify the CFG to split critical edges. This
2017 // updates dom and loop info.
Chris Lattnerc9950c12005-08-17 06:37:43 +00002018}
Chris Lattner7a60d912005-01-07 07:47:53 +00002019
Chris Lattner35397782005-12-05 07:10:48 +00002020
2021/// InsertGEPComputeCode - Insert code into BB to compute Ptr+PtrOffset,
2022/// casting to the type of GEPI.
2023static Value *InsertGEPComputeCode(Value *&V, BasicBlock *BB, Instruction *GEPI,
2024 Value *Ptr, Value *PtrOffset) {
2025 if (V) return V; // Already computed.
2026
2027 BasicBlock::iterator InsertPt;
2028 if (BB == GEPI->getParent()) {
2029 // If insert into the GEP's block, insert right after the GEP.
2030 InsertPt = GEPI;
2031 ++InsertPt;
2032 } else {
2033 // Otherwise, insert at the top of BB, after any PHI nodes
2034 InsertPt = BB->begin();
2035 while (isa<PHINode>(InsertPt)) ++InsertPt;
2036 }
2037
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00002038 // If Ptr is itself a cast, but in some other BB, emit a copy of the cast into
2039 // BB so that there is only one value live across basic blocks (the cast
2040 // operand).
2041 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
2042 if (CI->getParent() != BB && isa<PointerType>(CI->getOperand(0)->getType()))
2043 Ptr = new CastInst(CI->getOperand(0), CI->getType(), "", InsertPt);
2044
Chris Lattner35397782005-12-05 07:10:48 +00002045 // Add the offset, cast it to the right type.
2046 Ptr = BinaryOperator::createAdd(Ptr, PtrOffset, "", InsertPt);
2047 Ptr = new CastInst(Ptr, GEPI->getType(), "", InsertPt);
2048 return V = Ptr;
2049}
2050
2051
2052/// OptimizeGEPExpression - Since we are doing basic-block-at-a-time instruction
2053/// selection, we want to be a bit careful about some things. In particular, if
2054/// we have a GEP instruction that is used in a different block than it is
2055/// defined, the addressing expression of the GEP cannot be folded into loads or
2056/// stores that use it. In this case, decompose the GEP and move constant
2057/// indices into blocks that use it.
2058static void OptimizeGEPExpression(GetElementPtrInst *GEPI,
2059 const TargetData &TD) {
Chris Lattner35397782005-12-05 07:10:48 +00002060 // If this GEP is only used inside the block it is defined in, there is no
2061 // need to rewrite it.
2062 bool isUsedOutsideDefBB = false;
2063 BasicBlock *DefBB = GEPI->getParent();
2064 for (Value::use_iterator UI = GEPI->use_begin(), E = GEPI->use_end();
2065 UI != E; ++UI) {
2066 if (cast<Instruction>(*UI)->getParent() != DefBB) {
2067 isUsedOutsideDefBB = true;
2068 break;
2069 }
2070 }
2071 if (!isUsedOutsideDefBB) return;
2072
2073 // If this GEP has no non-zero constant indices, there is nothing we can do,
2074 // ignore it.
2075 bool hasConstantIndex = false;
2076 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
2077 E = GEPI->op_end(); OI != E; ++OI) {
2078 if (ConstantInt *CI = dyn_cast<ConstantInt>(*OI))
2079 if (CI->getRawValue()) {
2080 hasConstantIndex = true;
2081 break;
2082 }
2083 }
Chris Lattnerf1a54c02005-12-11 09:05:13 +00002084 // If this is a GEP &Alloca, 0, 0, forward subst the frame index into uses.
2085 if (!hasConstantIndex && !isa<AllocaInst>(GEPI->getOperand(0))) return;
Chris Lattner35397782005-12-05 07:10:48 +00002086
2087 // Otherwise, decompose the GEP instruction into multiplies and adds. Sum the
2088 // constant offset (which we now know is non-zero) and deal with it later.
2089 uint64_t ConstantOffset = 0;
2090 const Type *UIntPtrTy = TD.getIntPtrType();
2091 Value *Ptr = new CastInst(GEPI->getOperand(0), UIntPtrTy, "", GEPI);
2092 const Type *Ty = GEPI->getOperand(0)->getType();
2093
2094 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
2095 E = GEPI->op_end(); OI != E; ++OI) {
2096 Value *Idx = *OI;
2097 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2098 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
2099 if (Field)
2100 ConstantOffset += TD.getStructLayout(StTy)->MemberOffsets[Field];
2101 Ty = StTy->getElementType(Field);
2102 } else {
2103 Ty = cast<SequentialType>(Ty)->getElementType();
2104
2105 // Handle constant subscripts.
2106 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2107 if (CI->getRawValue() == 0) continue;
2108
2109 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
2110 ConstantOffset += (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
2111 else
2112 ConstantOffset+=TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
2113 continue;
2114 }
2115
2116 // Ptr = Ptr + Idx * ElementSize;
2117
2118 // Cast Idx to UIntPtrTy if needed.
2119 Idx = new CastInst(Idx, UIntPtrTy, "", GEPI);
2120
2121 uint64_t ElementSize = TD.getTypeSize(Ty);
2122 // Mask off bits that should not be set.
2123 ElementSize &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
2124 Constant *SizeCst = ConstantUInt::get(UIntPtrTy, ElementSize);
2125
2126 // Multiply by the element size and add to the base.
2127 Idx = BinaryOperator::createMul(Idx, SizeCst, "", GEPI);
2128 Ptr = BinaryOperator::createAdd(Ptr, Idx, "", GEPI);
2129 }
2130 }
2131
2132 // Make sure that the offset fits in uintptr_t.
2133 ConstantOffset &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
2134 Constant *PtrOffset = ConstantUInt::get(UIntPtrTy, ConstantOffset);
2135
2136 // Okay, we have now emitted all of the variable index parts to the BB that
2137 // the GEP is defined in. Loop over all of the using instructions, inserting
2138 // an "add Ptr, ConstantOffset" into each block that uses it and update the
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00002139 // instruction to use the newly computed value, making GEPI dead. When the
2140 // user is a load or store instruction address, we emit the add into the user
2141 // block, otherwise we use a canonical version right next to the gep (these
2142 // won't be foldable as addresses, so we might as well share the computation).
2143
Chris Lattner35397782005-12-05 07:10:48 +00002144 std::map<BasicBlock*,Value*> InsertedExprs;
2145 while (!GEPI->use_empty()) {
2146 Instruction *User = cast<Instruction>(GEPI->use_back());
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00002147
2148 // If this use is not foldable into the addressing mode, use a version
2149 // emitted in the GEP block.
2150 Value *NewVal;
2151 if (!isa<LoadInst>(User) &&
2152 (!isa<StoreInst>(User) || User->getOperand(0) == GEPI)) {
2153 NewVal = InsertGEPComputeCode(InsertedExprs[DefBB], DefBB, GEPI,
2154 Ptr, PtrOffset);
2155 } else {
2156 // Otherwise, insert the code in the User's block so it can be folded into
2157 // any users in that block.
2158 NewVal = InsertGEPComputeCode(InsertedExprs[User->getParent()],
Chris Lattner35397782005-12-05 07:10:48 +00002159 User->getParent(), GEPI,
2160 Ptr, PtrOffset);
Chris Lattner35397782005-12-05 07:10:48 +00002161 }
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00002162 User->replaceUsesOfWith(GEPI, NewVal);
2163 }
Chris Lattner35397782005-12-05 07:10:48 +00002164
2165 // Finally, the GEP is dead, remove it.
2166 GEPI->eraseFromParent();
2167}
2168
Chris Lattner7a60d912005-01-07 07:47:53 +00002169bool SelectionDAGISel::runOnFunction(Function &Fn) {
2170 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
2171 RegMap = MF.getSSARegMap();
2172 DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
2173
Chris Lattner35397782005-12-05 07:10:48 +00002174 // First, split all critical edges for PHI nodes with incoming values that are
2175 // constants, this way the load of the constant into a vreg will not be placed
2176 // into MBBs that are used some other way.
2177 //
2178 // In this pass we also look for GEP instructions that are used across basic
2179 // blocks and rewrites them to improve basic-block-at-a-time selection.
2180 //
Chris Lattner1a908c82005-08-18 17:35:14 +00002181 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
2182 PHINode *PN;
Chris Lattner35397782005-12-05 07:10:48 +00002183 BasicBlock::iterator BBI;
2184 for (BBI = BB->begin(); (PN = dyn_cast<PHINode>(BBI)); ++BBI)
Chris Lattner1a908c82005-08-18 17:35:14 +00002185 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
2186 if (isa<Constant>(PN->getIncomingValue(i)))
2187 SplitCriticalEdge(PN->getIncomingBlock(i), BB);
Chris Lattner35397782005-12-05 07:10:48 +00002188
2189 for (BasicBlock::iterator E = BB->end(); BBI != E; )
2190 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(BBI++))
2191 OptimizeGEPExpression(GEPI, TLI.getTargetData());
Chris Lattner1a908c82005-08-18 17:35:14 +00002192 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002193
Chris Lattner7a60d912005-01-07 07:47:53 +00002194 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
2195
2196 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
2197 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukman835702a2005-04-21 22:36:52 +00002198
Chris Lattner7a60d912005-01-07 07:47:53 +00002199 return true;
2200}
2201
2202
Chris Lattner718b5c22005-01-13 17:59:43 +00002203SDOperand SelectionDAGISel::
2204CopyValueToVirtualRegister(SelectionDAGLowering &SDL, Value *V, unsigned Reg) {
Chris Lattner613f79f2005-01-11 22:03:46 +00002205 SDOperand Op = SDL.getValue(V);
Chris Lattnere727af02005-01-13 20:50:02 +00002206 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattner33182322005-08-16 21:55:35 +00002207 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattnere727af02005-01-13 20:50:02 +00002208 "Copy from a reg to the same reg!");
Chris Lattner33182322005-08-16 21:55:35 +00002209
2210 // If this type is not legal, we must make sure to not create an invalid
2211 // register use.
2212 MVT::ValueType SrcVT = Op.getValueType();
2213 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
2214 SelectionDAG &DAG = SDL.DAG;
2215 if (SrcVT == DestVT) {
2216 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
2217 } else if (SrcVT < DestVT) {
2218 // The src value is promoted to the register.
Chris Lattnerba28c272005-08-17 06:06:25 +00002219 if (MVT::isFloatingPoint(SrcVT))
2220 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
2221 else
Chris Lattnera66403d2005-09-02 00:19:37 +00002222 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
Chris Lattner33182322005-08-16 21:55:35 +00002223 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
2224 } else {
2225 // The src value is expanded into multiple registers.
2226 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
2227 Op, DAG.getConstant(0, MVT::i32));
2228 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
2229 Op, DAG.getConstant(1, MVT::i32));
2230 Op = DAG.getCopyToReg(SDL.getRoot(), Reg, Lo);
2231 return DAG.getCopyToReg(Op, Reg+1, Hi);
2232 }
Chris Lattner7a60d912005-01-07 07:47:53 +00002233}
2234
Chris Lattner16f64df2005-01-17 17:15:02 +00002235void SelectionDAGISel::
2236LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
2237 std::vector<SDOperand> &UnorderedChains) {
2238 // If this is the entry block, emit arguments.
2239 Function &F = *BB->getParent();
Chris Lattnere3c2cf42005-01-17 17:55:19 +00002240 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattner6871b232005-10-30 19:42:35 +00002241 SDOperand OldRoot = SDL.DAG.getRoot();
2242 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner16f64df2005-01-17 17:15:02 +00002243
Chris Lattner6871b232005-10-30 19:42:35 +00002244 unsigned a = 0;
2245 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
2246 AI != E; ++AI, ++a)
2247 if (!AI->use_empty()) {
2248 SDL.setValue(AI, Args[a]);
Chris Lattnerd4382f02005-09-13 19:30:54 +00002249
Chris Lattner6871b232005-10-30 19:42:35 +00002250 // If this argument is live outside of the entry block, insert a copy from
2251 // whereever we got it to the vreg that other BB's will reference it as.
2252 if (FuncInfo.ValueMap.count(AI)) {
2253 SDOperand Copy =
2254 CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
2255 UnorderedChains.push_back(Copy);
2256 }
Chris Lattnere3c2cf42005-01-17 17:55:19 +00002257 }
Chris Lattner6871b232005-10-30 19:42:35 +00002258
2259 // Next, if the function has live ins that need to be copied into vregs,
2260 // emit the copies now, into the top of the block.
2261 MachineFunction &MF = SDL.DAG.getMachineFunction();
2262 if (MF.livein_begin() != MF.livein_end()) {
2263 SSARegMap *RegMap = MF.getSSARegMap();
2264 const MRegisterInfo &MRI = *MF.getTarget().getRegisterInfo();
2265 for (MachineFunction::livein_iterator LI = MF.livein_begin(),
2266 E = MF.livein_end(); LI != E; ++LI)
2267 if (LI->second)
2268 MRI.copyRegToReg(*MF.begin(), MF.begin()->end(), LI->second,
2269 LI->first, RegMap->getRegClass(LI->second));
Chris Lattner16f64df2005-01-17 17:15:02 +00002270 }
Chris Lattner6871b232005-10-30 19:42:35 +00002271
2272 // Finally, if the target has anything special to do, allow it to do so.
2273 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner16f64df2005-01-17 17:15:02 +00002274}
2275
2276
Chris Lattner7a60d912005-01-07 07:47:53 +00002277void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
2278 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
2279 FunctionLoweringInfo &FuncInfo) {
2280 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattner718b5c22005-01-13 17:59:43 +00002281
2282 std::vector<SDOperand> UnorderedChains;
Misha Brukman835702a2005-04-21 22:36:52 +00002283
Chris Lattner6871b232005-10-30 19:42:35 +00002284 // Lower any arguments needed in this block if this is the entry block.
2285 if (LLVMBB == &LLVMBB->getParent()->front())
2286 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner7a60d912005-01-07 07:47:53 +00002287
2288 BB = FuncInfo.MBBMap[LLVMBB];
2289 SDL.setCurrentBasicBlock(BB);
2290
2291 // Lower all of the non-terminator instructions.
2292 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
2293 I != E; ++I)
2294 SDL.visit(*I);
2295
2296 // Ensure that all instructions which are used outside of their defining
2297 // blocks are available as virtual registers.
2298 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Chris Lattner613f79f2005-01-11 22:03:46 +00002299 if (!I->use_empty() && !isa<PHINode>(I)) {
Chris Lattnera2c5d912005-01-09 01:16:24 +00002300 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner7a60d912005-01-07 07:47:53 +00002301 if (VMI != FuncInfo.ValueMap.end())
Chris Lattner718b5c22005-01-13 17:59:43 +00002302 UnorderedChains.push_back(
2303 CopyValueToVirtualRegister(SDL, I, VMI->second));
Chris Lattner7a60d912005-01-07 07:47:53 +00002304 }
2305
2306 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
2307 // ensure constants are generated when needed. Remember the virtual registers
2308 // that need to be added to the Machine PHI nodes as input. We cannot just
2309 // directly add them, because expansion might result in multiple MBB's for one
2310 // BB. As such, the start of the BB might correspond to a different MBB than
2311 // the end.
Misha Brukman835702a2005-04-21 22:36:52 +00002312 //
Chris Lattner7a60d912005-01-07 07:47:53 +00002313
2314 // Emit constants only once even if used by multiple PHI nodes.
2315 std::map<Constant*, unsigned> ConstantsOut;
2316
2317 // Check successor nodes PHI nodes that expect a constant to be available from
2318 // this block.
2319 TerminatorInst *TI = LLVMBB->getTerminator();
2320 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
2321 BasicBlock *SuccBB = TI->getSuccessor(succ);
2322 MachineBasicBlock::iterator MBBI = FuncInfo.MBBMap[SuccBB]->begin();
2323 PHINode *PN;
2324
2325 // At this point we know that there is a 1-1 correspondence between LLVM PHI
2326 // nodes and Machine PHI nodes, but the incoming operands have not been
2327 // emitted yet.
2328 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner8ea875f2005-01-07 21:34:19 +00002329 (PN = dyn_cast<PHINode>(I)); ++I)
2330 if (!PN->use_empty()) {
2331 unsigned Reg;
2332 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
2333 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
2334 unsigned &RegOut = ConstantsOut[C];
2335 if (RegOut == 0) {
2336 RegOut = FuncInfo.CreateRegForValue(C);
Chris Lattner718b5c22005-01-13 17:59:43 +00002337 UnorderedChains.push_back(
2338 CopyValueToVirtualRegister(SDL, C, RegOut));
Chris Lattner8ea875f2005-01-07 21:34:19 +00002339 }
2340 Reg = RegOut;
2341 } else {
2342 Reg = FuncInfo.ValueMap[PHIOp];
Chris Lattnera2c5d912005-01-09 01:16:24 +00002343 if (Reg == 0) {
Misha Brukman835702a2005-04-21 22:36:52 +00002344 assert(isa<AllocaInst>(PHIOp) &&
Chris Lattnera2c5d912005-01-09 01:16:24 +00002345 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
2346 "Didn't codegen value into a register!??");
2347 Reg = FuncInfo.CreateRegForValue(PHIOp);
Chris Lattner718b5c22005-01-13 17:59:43 +00002348 UnorderedChains.push_back(
2349 CopyValueToVirtualRegister(SDL, PHIOp, Reg));
Chris Lattnera2c5d912005-01-09 01:16:24 +00002350 }
Chris Lattner7a60d912005-01-07 07:47:53 +00002351 }
Misha Brukman835702a2005-04-21 22:36:52 +00002352
Chris Lattner8ea875f2005-01-07 21:34:19 +00002353 // Remember that this register needs to added to the machine PHI node as
2354 // the input for this MBB.
2355 unsigned NumElements =
2356 TLI.getNumElements(TLI.getValueType(PN->getType()));
2357 for (unsigned i = 0, e = NumElements; i != e; ++i)
2358 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
Chris Lattner7a60d912005-01-07 07:47:53 +00002359 }
Chris Lattner7a60d912005-01-07 07:47:53 +00002360 }
2361 ConstantsOut.clear();
2362
Chris Lattner718b5c22005-01-13 17:59:43 +00002363 // Turn all of the unordered chains into one factored node.
Chris Lattner24516842005-01-13 19:53:14 +00002364 if (!UnorderedChains.empty()) {
Chris Lattnerb7cad902005-11-09 05:03:03 +00002365 SDOperand Root = SDL.getRoot();
2366 if (Root.getOpcode() != ISD::EntryToken) {
2367 unsigned i = 0, e = UnorderedChains.size();
2368 for (; i != e; ++i) {
2369 assert(UnorderedChains[i].Val->getNumOperands() > 1);
2370 if (UnorderedChains[i].Val->getOperand(0) == Root)
2371 break; // Don't add the root if we already indirectly depend on it.
2372 }
2373
2374 if (i == e)
2375 UnorderedChains.push_back(Root);
2376 }
Chris Lattner718b5c22005-01-13 17:59:43 +00002377 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, UnorderedChains));
2378 }
2379
Chris Lattner7a60d912005-01-07 07:47:53 +00002380 // Lower the terminator after the copies are emitted.
2381 SDL.visit(*LLVMBB->getTerminator());
Chris Lattner4108bb02005-01-17 19:43:36 +00002382
2383 // Make sure the root of the DAG is up-to-date.
2384 DAG.setRoot(SDL.getRoot());
Chris Lattner7a60d912005-01-07 07:47:53 +00002385}
2386
2387void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
2388 FunctionLoweringInfo &FuncInfo) {
Jim Laskey219d5592006-01-04 22:28:25 +00002389 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
Chris Lattner7a60d912005-01-07 07:47:53 +00002390 CurDAG = &DAG;
2391 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
2392
2393 // First step, lower LLVM code to some DAG. This DAG may use operations and
2394 // types that are not supported by the target.
2395 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
2396
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00002397 // Run the DAG combiner in pre-legalize mode.
2398 DAG.Combine(false);
Nate Begeman007c6502005-09-07 00:15:36 +00002399
Chris Lattner7a60d912005-01-07 07:47:53 +00002400 DEBUG(std::cerr << "Lowered selection DAG:\n");
2401 DEBUG(DAG.dump());
2402
2403 // Second step, hack on the DAG until it only uses operations and types that
2404 // the target supports.
Chris Lattnerffcb0ae2005-01-23 04:36:26 +00002405 DAG.Legalize();
Chris Lattner7a60d912005-01-07 07:47:53 +00002406
2407 DEBUG(std::cerr << "Legalized selection DAG:\n");
2408 DEBUG(DAG.dump());
2409
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00002410 // Run the DAG combiner in post-legalize mode.
2411 DAG.Combine(true);
Nate Begeman007c6502005-09-07 00:15:36 +00002412
Evan Cheng739a6a42006-01-21 02:32:06 +00002413 if (ViewISelDAGs) DAG.viewGraph();
Chris Lattner6bd8fd02005-10-05 06:09:10 +00002414
Chris Lattner5ca31d92005-03-30 01:10:47 +00002415 // Third, instruction select all of the operations to machine code, adding the
2416 // code to the MachineBasicBlock.
Chris Lattner7a60d912005-01-07 07:47:53 +00002417 InstructionSelectBasicBlock(DAG);
2418
Chris Lattner7a60d912005-01-07 07:47:53 +00002419 DEBUG(std::cerr << "Selected machine code:\n");
2420 DEBUG(BB->dump());
2421
Chris Lattner5ca31d92005-03-30 01:10:47 +00002422 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner7a60d912005-01-07 07:47:53 +00002423 // PHI nodes in successors.
2424 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
2425 MachineInstr *PHI = PHINodesToUpdate[i].first;
2426 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
2427 "This is not a machine PHI node that we are updating!");
2428 PHI->addRegOperand(PHINodesToUpdate[i].second);
2429 PHI->addMachineBasicBlockOperand(BB);
2430 }
Chris Lattner5ca31d92005-03-30 01:10:47 +00002431
2432 // Finally, add the CFG edges from the last selected MBB to the successor
2433 // MBBs.
2434 TerminatorInst *TI = LLVMBB->getTerminator();
2435 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
2436 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[TI->getSuccessor(i)];
2437 BB->addSuccessor(Succ0MBB);
2438 }
Chris Lattner7a60d912005-01-07 07:47:53 +00002439}
Evan Cheng739a6a42006-01-21 02:32:06 +00002440
2441//===----------------------------------------------------------------------===//
2442/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
2443/// target node in the graph.
2444void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
2445 if (ViewSchedDAGs) DAG.viewGraph();
Evan Chengc1e1d972006-01-23 07:01:07 +00002446 ScheduleDAG *SL = NULL;
2447
2448 switch (ISHeuristic) {
2449 default: assert(0 && "Unrecognized scheduling heuristic");
Evan Chenga6eff8a2006-01-25 09:12:57 +00002450 case defaultScheduling:
2451 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency)
2452 SL = createSimpleDAGScheduler(noScheduling, DAG, BB);
2453 else /* TargetLowering::SchedulingForRegPressure */
2454 SL = createBURRListDAGScheduler(DAG, BB);
2455 break;
Evan Chengc1e1d972006-01-23 07:01:07 +00002456 case noScheduling:
Chris Lattner5255d042006-03-10 07:49:12 +00002457 SL = createBFS_DAGScheduler(DAG, BB);
2458 break;
Evan Chengc1e1d972006-01-23 07:01:07 +00002459 case simpleScheduling:
Chris Lattner5255d042006-03-10 07:49:12 +00002460 SL = createSimpleDAGScheduler(false, DAG, BB);
2461 break;
Evan Chengc1e1d972006-01-23 07:01:07 +00002462 case simpleNoItinScheduling:
Chris Lattner5255d042006-03-10 07:49:12 +00002463 SL = createSimpleDAGScheduler(true, DAG, BB);
Evan Chengc1e1d972006-01-23 07:01:07 +00002464 break;
Evan Cheng31272342006-01-23 08:26:10 +00002465 case listSchedulingBURR:
2466 SL = createBURRListDAGScheduler(DAG, BB);
Chris Lattner98ecb8e2006-03-05 21:10:33 +00002467 break;
Chris Lattner47639db2006-03-06 00:22:00 +00002468 case listSchedulingTD:
Chris Lattner543832d2006-03-08 04:25:59 +00002469 SL = createTDListDAGScheduler(DAG, BB, CreateTargetHazardRecognizer());
Chris Lattner98ecb8e2006-03-05 21:10:33 +00002470 break;
Evan Chengc1e1d972006-01-23 07:01:07 +00002471 }
Chris Lattnere23928c2006-01-21 19:12:11 +00002472 BB = SL->Run();
Evan Chengf9adce92006-02-04 06:49:00 +00002473 delete SL;
Evan Cheng739a6a42006-01-21 02:32:06 +00002474}
Chris Lattnerdcf785b2006-02-24 02:13:54 +00002475
Chris Lattner543832d2006-03-08 04:25:59 +00002476HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
2477 return new HazardRecognizer();
Chris Lattner47639db2006-03-06 00:22:00 +00002478}
2479
Chris Lattnerdcf785b2006-02-24 02:13:54 +00002480/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
2481/// by tblgen. Others should not call it.
2482void SelectionDAGISel::
2483SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
2484 std::vector<SDOperand> InOps;
2485 std::swap(InOps, Ops);
2486
2487 Ops.push_back(InOps[0]); // input chain.
2488 Ops.push_back(InOps[1]); // input asm string.
2489
2490 const char *AsmStr = cast<ExternalSymbolSDNode>(InOps[1])->getSymbol();
2491 unsigned i = 2, e = InOps.size();
2492 if (InOps[e-1].getValueType() == MVT::Flag)
2493 --e; // Don't process a flag operand if it is here.
2494
2495 while (i != e) {
2496 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
2497 if ((Flags & 7) != 4 /*MEM*/) {
2498 // Just skip over this operand, copying the operands verbatim.
2499 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
2500 i += (Flags >> 3) + 1;
2501 } else {
2502 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
2503 // Otherwise, this is a memory operand. Ask the target to select it.
2504 std::vector<SDOperand> SelOps;
2505 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
2506 std::cerr << "Could not match memory address. Inline asm failure!\n";
2507 exit(1);
2508 }
2509
2510 // Add this to the output node.
2511 Ops.push_back(DAG.getConstant(4/*MEM*/ | (SelOps.size() << 3), MVT::i32));
2512 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
2513 i += 2;
2514 }
2515 }
2516
2517 // Add the flag input back if present.
2518 if (e != InOps.size())
2519 Ops.push_back(InOps.back());
2520}